Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions .ai/contexts/fast-check.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,18 +91,33 @@ requirement.
`node scripts/doc-staleness.js` reports tracked coverage docs from the working
tree, using the exported `coverageMap` and `isCoverageDoc` from
`scripts/check-docs.js`. The coverage map also returns each doc's optional stamp.
The report matches the same coverage patterns against the current tracked-file
The report works from the top level of the repository that contains the start
directory (`git rev-parse --show-toplevel`), so a `--repo-root` inside a
subdirectory gives the same report as the top level.
It matches the same coverage patterns against the current tracked-file
list, then passes the matching paths as literal Git pathspecs to
`git rev-list --count <verified-sha>..HEAD -- <paths>`. Each commit counts once
even if it changes several covered files or patterns overlap. Empty coverage
counts zero; deleted files absent from the current tracked list are not counted.
Uncommitted code changes are outside the commit count.
counts zero. Only paths in the current tracked list are counted: a commit that
touched a file since renamed counts only through the new path, and a deleted
file counts nothing, including the commit that deleted it. A doc whose only
covered files are deleted fails the shared coverage validation (`covers pattern
matches no tracked file`). Uncommitted code changes are outside the commit count.

Unstamped docs and unresolved commit SHAs rank first, labelled `unstamped` and
A stamp is `unknown sha` unless it resolves to exactly one commit that is an
ancestor of `HEAD` (`git merge-base --is-ancestor`). An unmatched or ambiguous
prefix, a SHA naming an object that does not peel to a commit (a tree or a blob),
and a commit on a diverged branch all rank as `unknown sha`; an annotated tag
that points at an ancestor commit resolves to that commit.

Unstamped docs and `unknown sha` docs rank first, labelled `unstamped` and
`unknown sha`, with an unknown count rather than zero. Remaining docs sort by
descending count; ties sort by doc path. `--json` emits rows with `doc`, `stamp`,
`status` and `commitsSince` (null for unknown counts); `--limit N` selects the
first N rows, and `--repo-root <dir>` selects a checkout (default: current
directory). Staleness exits zero; invalid arguments, malformed metadata and
Git failures exit nonzero. The report is advisory and does not run in the PR gate.
directory). The exit code is zero for a report. It is nonzero (2) for invalid
arguments, malformed coverage metadata, and any Git failure other than a stamp
that does not resolve to one ancestor commit, such as a directory outside a
repository or a repository without commits. The report is advisory and does not
run in the PR gate.
The weekly procedure is in [agent-practices.md](../agent-practices.md#doc-verification-audit).
41 changes: 31 additions & 10 deletions scripts/doc-staleness.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,35 @@ function parseArgs(argv) {
return opts;
}

function collectStaleness(repoRoot) {
const git = args => execFileSync('git', args, {
cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024,
function runGit(cwd, args) {
return execFileSync('git', args, {
cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024,
}).trim();
}

// see .ai/contexts/fast-check.md, "Documentation verification stamps"
function resolveStampCommit(git, sha) {
try {
return git(['rev-parse', '--verify', '--quiet', sha + '^{commit}']) || null;
} catch (err) {
if (err.status === 1 || (err.status === 128 && /ambiguous/i.test(String(err.stderr)))) return null;
throw err;
}
}

function isAncestor(git, commit) {
try {
git(['merge-base', '--is-ancestor', commit, 'HEAD']);
return true;
} catch (err) {
if (err.status === 1) return false;
throw err;
}
}

function collectStaleness(startDir) {
const repoRoot = runGit(startDir, ['rev-parse', '--show-toplevel']);
const git = args => runGit(repoRoot, args);
git(['rev-parse', '--verify', 'HEAD^{commit}']);
const trackedFiles = git(['ls-files', '-z', '--cached']).split('\0').filter(Boolean);
const documents = Object.fromEntries(trackedFiles.filter(isCoverageDoc)
Expand All @@ -46,12 +71,8 @@ function collectStaleness(repoRoot) {
let status = 'unstamped';
let commitsSince = null;
if (stamp !== null) {
let commit;
try {
commit = git(['rev-parse', '--verify', '--quiet', stamp.split(' ')[0] + '^{commit}']);
} catch (err) {
if (err.status !== 1) throw err;
}
let commit = resolveStampCommit(git, stamp.split(' ')[0]);
if (commit && !isAncestor(git, commit)) commit = null;
status = commit ? 'verified' : 'unknown sha';
if (commit) {
const files = trackedFiles.filter(file => patterns.some(pattern => pattern.test(file)));
Expand Down Expand Up @@ -87,4 +108,4 @@ if (require.main === module) {
}
}

module.exports = { collectStaleness };
module.exports = { collectStaleness, resolveStampCommit };
123 changes: 123 additions & 0 deletions test/doc-staleness.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,126 @@ test('GIVEN invalid coverage metadata WHEN reporting THEN shared validation name
fs.writeFileSync(file, original);
}
});

const withRepo = fn => {
const saved = repo;
repo = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-staleness-case-'));
try {
git('init');
return fn();
} finally {
fs.rmSync(repo, { recursive: true, force: true });
repo = saved;
}
};
const report = () => Object.fromEntries(load().collectStaleness(repo).map(row => [row.doc, row]));

test('GIVEN a stamp that is not an ancestor of HEAD WHEN reporting THEN it ranks as unknown sha', () => {
withRepo(() => {
write('src/a.js', 'base');
commit('baseline');
const main = git('rev-parse', 'HEAD');
git('checkout', '-b', 'diverged');
write('src/a.js', 'diverged');
commit('diverged work');
const stamp = git('rev-parse', 'HEAD');
git('checkout', main);
write('src/a.js', 'main one');
commit('main one');
write('src/a.js', 'main two');
commit('main two');
write('docs/diverged.md', doc(['src/a.js'], stamp + ' 2026-11-29'));
write('docs/ancestor.md', doc(['src/a.js'], main + ' 2026-11-29'));
commit('docs');
const rows = report();
assert.equal(rows['docs/diverged.md'].status, 'unknown sha');
assert.equal(rows['docs/diverged.md'].commitsSince, null);
assert.equal(rows['docs/ancestor.md'].status, 'verified');
assert.equal(rows['docs/ancestor.md'].commitsSince, 2);
});
});

test('GIVEN a sha git cannot resolve to one commit WHEN resolving THEN it is unknown, and other git failures throw', () => {
const { resolveStampCommit } = load();
assert.equal(typeof resolveStampCommit, 'function');
const failing = (status, stderr) => () => {
throw Object.assign(new Error('git failed'), { status, stderr });
};
assert.equal(resolveStampCommit(failing(1, ''), 'abcd'), null);
assert.equal(resolveStampCommit(failing(128, 'error: short SHA1 abcd is ambiguous'), 'abcd'), null);
assert.throws(() => resolveStampCommit(failing(128, 'fatal: not a git repository'), 'abcd'), /git failed/);
assert.throws(() => resolveStampCommit(failing(null, ''), 'abcd'), /git failed/);
withRepo(() => {
const emptyTree = execFileSync('git', ['hash-object', '-t', 'tree', '-w', '--stdin'],
{ cwd: repo, input: '', encoding: 'utf8' }).trim();
const fixedDate = '1700000000 +0000';
const env = { ...process.env, GIT_AUTHOR_NAME: 'A', GIT_AUTHOR_EMAIL: 'a@example.com', GIT_AUTHOR_DATE: fixedDate,
GIT_COMMITTER_NAME: 'A', GIT_COMMITTER_EMAIL: 'a@example.com', GIT_COMMITTER_DATE: fixedDate };
const commitTree = (input, ...parents) => execFileSync('git', ['-c', 'i18n.commitEncoding=UTF-8', 'commit-tree',
emptyTree, ...parents.flatMap(parent => ['-p', parent])], { cwd: repo, env, input, encoding: 'utf8' }).trim();
const colliding = [19170, 22379].map(n => commitTree('collision ' + n + '\n'));
assert.deepEqual(colliding, ['585bc065a4f9004617843a4d6194a7313862db7c', '585bc06e5e7e1b1922cd01af449e2c640335d3b9']);
git('update-ref', 'HEAD', commitTree('join\n', ...colliding));
const runGit = args => git(...args);
assert.equal(resolveStampCommit(runGit, '585bc06'), null);
assert.equal(resolveStampCommit(runGit, colliding[0]), colliding[0]);
write('src/a.js', 'base');
write('docs/ambiguous.md', doc(['src/a.js'], '585bc06 2026-11-29'));
commit('ambiguous stamp');
assert.equal(report()['docs/ambiguous.md'].status, 'unknown sha');
});
});

test('GIVEN --repo-root inside a subdirectory WHEN reporting THEN the top level is used', () => {
const { collectStaleness } = load();
const sub = path.join(repo, 'src', 'deep');
assert.deepEqual(collectStaleness(sub), collectStaleness(repo));
const result = cli(['--repo-root', sub, '--json'], path.dirname(repo));
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(JSON.parse(result.stdout), collectStaleness(repo));
});

test('GIVEN a covered file with glob characters WHEN counting THEN the pathspec is literal', () => {
withRepo(() => {
write('src/a[1].js', 'base');
write('src/a1.js', 'base');
commit('baseline');
const stamp = git('rev-parse', 'HEAD');
write('docs/glob.md', doc(['src/*.js'], stamp + ' 2026-11-29'));
commit('doc');
write('src/a1.js', 'changed');
commit('touch a1');
git('rm', 'src/a1.js');
commit('delete a1');
assert.equal(report()['docs/glob.md'].commitsSince, 0);
write('src/a[1].js', 'changed');
commit('touch a[1]');
assert.equal(report()['docs/glob.md'].commitsSince, 1);
});
});

test('GIVEN a renamed and a deleted covered file WHEN counting THEN only commits on current paths count', () => {
withRepo(() => {
write('src/old.js', 'base');
write('src/gone.js', 'base');
write('src/keep.js', 'base');
commit('baseline');
const stamp = git('rev-parse', 'HEAD');
write('docs/rename.md', doc(['src/*.js'], stamp + ' 2026-11-29'));
write('docs/deleted.md', doc(['src/gone.js'], stamp + ' 2026-11-29'));
commit('docs');
write('src/old.js', 'edited before rename');
commit('edit old');
git('mv', 'src/old.js', 'src/new.js');
commit('rename');
write('src/gone.js', 'edited before delete');
commit('edit gone');
git('rm', 'src/gone.js');
commit('delete gone');
assert.throws(() => report(), /docs\/deleted.md: covers pattern matches no tracked file: src\/gone.js/);
fs.rmSync(path.join(repo, 'docs/deleted.md'));
git('rm', '--cached', 'docs/deleted.md');
commit('drop doc covering only the deleted file');
assert.equal(report()['docs/rename.md'].commitsSince, 1);
});
});
Loading