From 81f825147fc6223e3bfe50248db5a5b447bfde6c Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Date: Sun, 29 Nov 2026 12:43:45 +0100 Subject: [PATCH] feat(docs): record when each doc was last verified and list the stalest (#1354) Coverage docs may carry verified: ; check-docs validates its shape without resolving the SHA. scripts/doc-staleness.js ranks docs by the commits that touched their covered files since that stamp, unstamped docs first. The 18 contexts rewritten under #1355 are stamped at their merge commits; the others stay unstamped. The weekly audit is documented in .ai/agent-practices.md. --- .ai/agent-practices.md | 21 ++++ .ai/contexts/activitywatch.md | 1 + .ai/contexts/app-dialogs.md | 1 + .ai/contexts/bg-agents.md | 1 + .ai/contexts/changes-view.md | 1 + .ai/contexts/cli-session-state.md | 1 + .ai/contexts/fast-check.md | 31 +++++- .ai/contexts/panel-terminal.md | 1 + .ai/contexts/plain-terminal.md | 1 + .ai/contexts/project-delete.md | 1 + .ai/contexts/schedule-runner.md | 1 + .ai/contexts/session-state.md | 1 + .ai/contexts/subagent-observability.md | 1 + .ai/contexts/terminal-path-links.md | 1 + .ai/contexts/theme.md | 1 + .ai/contexts/tool-bar.md | 1 + .ai/contexts/touched-files.md | 1 + .ai/contexts/updater-relaunch.md | 1 + .ai/contexts/viewer-panel.md | 1 + .ai/contexts/window-frame.md | 1 + scripts/check-docs.js | 14 ++- scripts/doc-staleness.js | 90 ++++++++++++++++ test/check-docs.test.js | 38 +++++++ test/doc-staleness.test.js | 139 +++++++++++++++++++++++++ 24 files changed, 345 insertions(+), 6 deletions(-) create mode 100644 scripts/doc-staleness.js create mode 100644 test/doc-staleness.test.js diff --git a/.ai/agent-practices.md b/.ai/agent-practices.md index 0859273b0..26529aa73 100644 --- a/.ai/agent-practices.md +++ b/.ai/agent-practices.md @@ -122,3 +122,24 @@ the check). If it's stale, correct or delete it in the same pass rather than rep Fix exactly what was asked. When a task names N specific findings, apply N fixes — no unrelated cleanup, no rewriting adjacent prose "while you're in there". If you notice something else that's wrong, say so in the HANDOFF; don't fix it silently. + +## Doc verification audit + +Every week, an agent runs `node scripts/doc-staleness.js --limit 3` from the +repository root and audits the listed docs against the current main commit. +For each doc, inventory every statement as TRUE, FALSE or UNVERIFIABLE. +Trace the whole flow, including callers and downstream effects, before calling +a statement false. Describe current behaviour only; do not add historical notes. + +Search existing issues first with `gh issue list --repo devsuitup/switchboard --state all --search ""`. +Open one issue per wrong statement with `gh issue create --repo devsuitup/switchboard`, +or reuse the matching issue. Include the statement, the code evidence and the +correct current behaviour. An UNVERIFIABLE statement needs evidence or corrected +wording before the doc can be marked verified. + +Once every statement is verified or corrected, open a PR limited to the necessary +doc fixes and advancing `verified: ` in front matter. Use the +main commit actually checked and its commit date, not the future PR commit. +Keep unrelated docs unstamped. If the doc is already correct, change only its +stamp. Have the other engine cross-review the audit and corrections (Claude for +Codex work, Codex for Claude work). Repeat weekly, independently of releases. diff --git a/.ai/contexts/activitywatch.md b/.ai/contexts/activitywatch.md index 72ae48694..a09f6e65a 100644 --- a/.ai/contexts/activitywatch.md +++ b/.ai/contexts/activitywatch.md @@ -1,4 +1,5 @@ --- +verified: f9e691b7 2026-11-29 covers: - "public/activity-reporting-panel.js" - "src/main/integrations/activitywatch/activitywatch-client.js" diff --git a/.ai/contexts/app-dialogs.md b/.ai/contexts/app-dialogs.md index bd29a72ed..acf3f7270 100644 --- a/.ai/contexts/app-dialogs.md +++ b/.ai/contexts/app-dialogs.md @@ -1,4 +1,5 @@ --- +verified: ece9003a 2026-11-29 covers: - "public/choice-dialog.js" - "public/resume-guard.js" diff --git a/.ai/contexts/bg-agents.md b/.ai/contexts/bg-agents.md index bf6de24c4..0007f73e5 100644 --- a/.ai/contexts/bg-agents.md +++ b/.ai/contexts/bg-agents.md @@ -1,4 +1,5 @@ --- +verified: d56a4ae3 2026-11-29 covers: - "claude-binary.js" - "delete-session-guard.js" diff --git a/.ai/contexts/changes-view.md b/.ai/contexts/changes-view.md index ef60188f5..6078b3b84 100644 --- a/.ai/contexts/changes-view.md +++ b/.ai/contexts/changes-view.md @@ -1,4 +1,5 @@ --- +verified: 7156c294 2026-11-29 covers: - "public/file-panel.js" - "src/main/changes/git-changes-file.js" diff --git a/.ai/contexts/cli-session-state.md b/.ai/contexts/cli-session-state.md index 696f5ac33..9442f4d5b 100644 --- a/.ai/contexts/cli-session-state.md +++ b/.ai/contexts/cli-session-state.md @@ -1,4 +1,5 @@ --- +verified: d6587dae 2026-11-29 covers: - "bridge-session-id.js" - "cli-session-state.js" diff --git a/.ai/contexts/fast-check.md b/.ai/contexts/fast-check.md index 634393f0b..403696998 100644 --- a/.ai/contexts/fast-check.md +++ b/.ai/contexts/fast-check.md @@ -2,8 +2,7 @@ covers: - ".husky/pre-commit" - "Taskfile.yaml" - - "scripts/check-doc-refs.js" - - "scripts/check-docs.js" + - "scripts/*doc*.js" - "scripts/check-fast.js" - "scripts/run-tests.js" --- @@ -79,3 +78,31 @@ The hub owner sets are deliberately narrow: The PR template and checker accept `- no docs: ` on its own line with the exact `no-docs` label. Replace the placeholder with a nonempty reason. + +## Documentation verification stamps + +Coverage front matter accepts `covers` and an optional `verified` string: +`verified: a024e9ef 2026-11-29`. The SHA is 7–40 hexadecimal characters, followed +by one space and a date in YYYY-MM-DD form. The checker validates the shape, +without resolving the SHA, so shallow CI checkouts can validate docs. Other keys +remain errors. Adding or moving a stamp never satisfies the PR gate's body-change +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 +list, then passes the matching paths as literal Git pathspecs to +`git rev-list --count ..HEAD -- `. 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. + +Unstamped docs and unresolved commit SHAs 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 ` 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. +The weekly procedure is in [agent-practices.md](../agent-practices.md#doc-verification-audit). diff --git a/.ai/contexts/panel-terminal.md b/.ai/contexts/panel-terminal.md index 834b24567..edd3761fc 100644 --- a/.ai/contexts/panel-terminal.md +++ b/.ai/contexts/panel-terminal.md @@ -1,4 +1,5 @@ --- +verified: a0d43823 2026-11-29 covers: - "public/panel-terminal.js" - "public/file-panel.js" diff --git a/.ai/contexts/plain-terminal.md b/.ai/contexts/plain-terminal.md index 02ef449b9..9d00dd30a 100644 --- a/.ai/contexts/plain-terminal.md +++ b/.ai/contexts/plain-terminal.md @@ -1,4 +1,5 @@ --- +verified: 688565ff 2026-11-29 covers: - "src/main/terminals/plain-terminal-shell.js" - "src/main/terminals/shell-profiles.js" diff --git a/.ai/contexts/project-delete.md b/.ai/contexts/project-delete.md index 1f367d5dd..96f3bfc9c 100644 --- a/.ai/contexts/project-delete.md +++ b/.ai/contexts/project-delete.md @@ -1,4 +1,5 @@ --- +verified: 93b54955 2026-11-29 covers: - "derive-project-path.js" - "public/archived-manager.js" diff --git a/.ai/contexts/schedule-runner.md b/.ai/contexts/schedule-runner.md index be8422304..1d3c07b74 100644 --- a/.ai/contexts/schedule-runner.md +++ b/.ai/contexts/schedule-runner.md @@ -1,4 +1,5 @@ --- +verified: 2217ee18 2026-11-29 covers: - "src/main/shared/normalize-project-path.js" - "public/schedules-view.js" diff --git a/.ai/contexts/session-state.md b/.ai/contexts/session-state.md index 9fefafcfb..af95b353a 100644 --- a/.ai/contexts/session-state.md +++ b/.ai/contexts/session-state.md @@ -1,4 +1,5 @@ --- +verified: 944791ad 2026-11-29 covers: - "public/index.html" - "cli-session-state.js" diff --git a/.ai/contexts/subagent-observability.md b/.ai/contexts/subagent-observability.md index 916aa04c4..7fb365f0f 100644 --- a/.ai/contexts/subagent-observability.md +++ b/.ai/contexts/subagent-observability.md @@ -1,4 +1,5 @@ --- +verified: e52cc6ec 2026-11-29 covers: - "public/grid-view.js" - "public/jsonl-viewer.js" diff --git a/.ai/contexts/terminal-path-links.md b/.ai/contexts/terminal-path-links.md index 7a52266b7..2d7922f96 100644 --- a/.ai/contexts/terminal-path-links.md +++ b/.ai/contexts/terminal-path-links.md @@ -1,4 +1,5 @@ --- +verified: 9df983e1 2026-11-29 covers: - "public/terminal-path-links.js" - "src/main/terminals/terminal-path-target.js" diff --git a/.ai/contexts/theme.md b/.ai/contexts/theme.md index 1446e9fe6..4b50f0c50 100644 --- a/.ai/contexts/theme.md +++ b/.ai/contexts/theme.md @@ -1,4 +1,5 @@ --- +verified: a024e9ef 2026-11-29 covers: - "public/setting-defaults.js" - "public/style.css" diff --git a/.ai/contexts/tool-bar.md b/.ai/contexts/tool-bar.md index beb1d162c..ccef21634 100644 --- a/.ai/contexts/tool-bar.md +++ b/.ai/contexts/tool-bar.md @@ -1,4 +1,5 @@ --- +verified: a1d6d37a 2026-11-29 covers: - "public/style.css" - "public/tool-bar.js" diff --git a/.ai/contexts/touched-files.md b/.ai/contexts/touched-files.md index 8f1135693..2a93e0a18 100644 --- a/.ai/contexts/touched-files.md +++ b/.ai/contexts/touched-files.md @@ -1,4 +1,5 @@ --- +verified: 32983283 2026-11-29 covers: - "public/file-panel.js" - "public/touched-files-view.js" diff --git a/.ai/contexts/updater-relaunch.md b/.ai/contexts/updater-relaunch.md index 8054df49b..d19e065f0 100644 --- a/.ai/contexts/updater-relaunch.md +++ b/.ai/contexts/updater-relaunch.md @@ -1,4 +1,5 @@ --- +verified: 65989837 2026-11-29 covers: - "src/main/app/linux-startup.js" - "src/main/app/relaunch.js" diff --git a/.ai/contexts/viewer-panel.md b/.ai/contexts/viewer-panel.md index 4aefe3eb7..495586d46 100644 --- a/.ai/contexts/viewer-panel.md +++ b/.ai/contexts/viewer-panel.md @@ -1,4 +1,5 @@ --- +verified: 8d7792bc 2026-11-29 covers: - "file-lists-worker-client.js" - "file-lists.js" diff --git a/.ai/contexts/window-frame.md b/.ai/contexts/window-frame.md index fdc936788..4f24bbc31 100644 --- a/.ai/contexts/window-frame.md +++ b/.ai/contexts/window-frame.md @@ -1,4 +1,5 @@ --- +verified: 62134edb 2026-11-29 covers: - "main.js" - "preload.js" diff --git a/scripts/check-docs.js b/scripts/check-docs.js index 56cfbda9a..9e068c510 100644 --- a/scripts/check-docs.js +++ b/scripts/check-docs.js @@ -44,6 +44,7 @@ function coverPattern(glob) { function coverageMap(documents, trackedFiles) { const coverage = new Map(); + const verified = new Map(); const errors = []; for (const [doc, text] of Object.entries(documents)) { if (!isCoverageDoc(doc)) continue; @@ -58,8 +59,12 @@ function coverageMap(documents, trackedFiles) { if (!front) throw new Error('unterminated front matter'); const data = yaml.load(front[1], { schema: yaml.JSON_SCHEMA }); if (!data || typeof data !== 'object' || Array.isArray(data) - || Object.keys(data).some(key => key !== 'covers') || !Array.isArray(data.covers)) { - throw new Error('front matter must contain only covers: an array of source paths/globs'); + || Object.keys(data).some(key => key !== 'covers' && key !== 'verified') || !Array.isArray(data.covers)) { + throw new Error('front matter must contain only covers: an array of source paths/globs and optional verified'); + } + if (Object.hasOwn(data, 'verified') && (typeof data.verified !== 'string' + || !/^[0-9a-fA-F]{7,40} [0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(data.verified))) { + throw new Error('verified must be a string matching with one space'); } const patterns = data.covers.map(glob => { const pattern = coverPattern(glob); @@ -67,6 +72,7 @@ function coverageMap(documents, trackedFiles) { return pattern; }); coverage.set(doc, patterns); + verified.set(doc, data.verified ?? null); } catch (err) { errors.push(doc + ': ' + err.message); } @@ -75,7 +81,7 @@ function coverageMap(documents, trackedFiles) { const owners = [...coverage].filter(([, patterns]) => patterns.some(pattern => pattern.test(file))).map(([doc]) => doc); if (owners.length > 4) errors.push(file + ': covered by ' + owners.length + ' docs (maximum 4): ' + owners.join(', ')); } - return { coverage, errors }; + return { coverage, verified, errors }; } function checkDocs({ files, labels, body = '', documents = {}, previousDocuments = {}, trackedFiles = files }) { @@ -170,4 +176,4 @@ if (require.main === module) { } } -module.exports = { checkDocs, coverageMap }; +module.exports = { checkDocs, coverageMap, isCoverageDoc }; diff --git a/scripts/doc-staleness.js b/scripts/doc-staleness.js new file mode 100644 index 000000000..b8df0798b --- /dev/null +++ b/scripts/doc-staleness.js @@ -0,0 +1,90 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); +const { coverageMap, isCoverageDoc } = require('./check-docs'); + +const USAGE = 'usage: doc-staleness.js [--json] [--limit ] [--repo-root ]'; + +function parseArgs(argv) { + const opts = { repoRoot: process.cwd(), json: false }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--json') { + opts.json = true; + } else if (arg === '--limit') { + const value = argv[++i]; + if (!/^[1-9][0-9]*$/.test(value) || !Number.isSafeInteger(Number(value))) throw new Error(USAGE); + opts.limit = Number(value); + } else if (arg === '--repo-root') { + const value = argv[++i]; + if (!value || value.startsWith('--')) throw new Error(USAGE); + opts.repoRoot = path.resolve(value); + } else { + throw new Error(USAGE); + } + } + return opts; +} + +function collectStaleness(repoRoot) { + const git = args => execFileSync('git', args, { + cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024, + }).trim(); + git(['rev-parse', '--verify', 'HEAD^{commit}']); + const trackedFiles = git(['ls-files', '-z', '--cached']).split('\0').filter(Boolean); + const documents = Object.fromEntries(trackedFiles.filter(isCoverageDoc) + .filter(file => fs.existsSync(path.join(repoRoot, file))) + .map(file => [file, fs.readFileSync(path.join(repoRoot, file), 'utf8')])); + const { coverage, verified, errors } = coverageMap(documents, trackedFiles); + if (errors.length) throw new Error(errors.join('\n')); + const rows = []; + for (const [doc, patterns] of coverage) { + const stamp = verified.get(doc); + 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; + } + status = commit ? 'verified' : 'unknown sha'; + if (commit) { + const files = trackedFiles.filter(file => patterns.some(pattern => pattern.test(file))); + commitsSince = files.length + ? Number(git(['rev-list', '--count', commit + '..HEAD', '--', ...files.map(file => ':(literal)' + file)])) + : 0; + } + } + rows.push({ doc, stamp, status, commitsSince }); + } + return rows.sort((a, b) => Number(a.commitsSince !== null) - Number(b.commitsSince !== null) + || (b.commitsSince ?? 0) - (a.commitsSince ?? 0) + || (a.doc < b.doc ? -1 : a.doc > b.doc ? 1 : 0)); +} + +function formatTable(rows) { + const cells = [['Doc', 'Stamp', 'Commits since'], ...rows.map(row => [ + row.doc, row.stamp ?? 'unstamped', row.commitsSince === null ? row.status : String(row.commitsSince), + ])]; + const widths = [0, 1].map(column => Math.max(...cells.map(row => row[column].length))); + return cells.map(row => row[0].padEnd(widths[0]) + ' ' + row[1].padEnd(widths[1]) + ' ' + row[2]).join('\n'); +} + +if (require.main === module) { + try { + const opts = parseArgs(process.argv.slice(2)); + const rows = collectStaleness(opts.repoRoot).slice(0, opts.limit); + console.log(opts.json ? JSON.stringify(rows, null, 2) : formatTable(rows)); + process.exitCode = 0; + } catch (err) { + console.error(err.message); + process.exitCode = 2; + } +} + +module.exports = { collectStaleness }; diff --git a/test/check-docs.test.js b/test/check-docs.test.js index b9b9d846e..2e3863382 100644 --- a/test/check-docs.test.js +++ b/test/check-docs.test.js @@ -554,3 +554,41 @@ test('GIVEN replay 3f382b5f WHEN checking current owners THEN its documentation const result = checkDocs({ files, labels: [], documents: realDocuments, trackedFiles: realFiles }); assert.equal(result.ok, true, result.message); }); + +for (const stamp of ['abcdef0 2026-11-29', 'ABCDEF01'.repeat(5) + ' 2026-01-02']) { + test('GIVEN valid verified stamp ' + stamp + ' WHEN validating THEN it is accepted without resolving git', () => { + const result = checkDocs({ files: [], labels: [], trackedFiles: ['main.js'], + documents: { 'docs/stamped.md': '---\ncovers: ["main.js"]\nverified: ' + stamp + '\n---\n# Doc' } }); + assert.equal(result.ok, true, result.message); + }); +} + +for (const value of ['null', 'true', '123', '[]', '{}', '""', '"abcdef 2026-11-29"', + '"' + 'a'.repeat(41) + ' 2026-11-29"', '"ghijklm 2026-11-29"', '"abcdef0 2026-1-29"', + '"abcdef0 2026-11-29"', '"abcdef0\\t2026-11-29"', '"abcdef0 2026-11-29 extra"', '" abcdef0 2026-11-29"', '"abcdef0 2026-11-29\\n"']) { + test('GIVEN malformed verified ' + value + ' WHEN validating THEN the doc and stamp reason are reported', () => { + const result = checkDocs({ files: [], labels: [], trackedFiles: ['main.js'], + documents: { 'docs/stamped.md': '---\ncovers: ["main.js"]\nverified: ' + value + '\n---\n# Doc' } }); + assert.equal(result.ok, false); + assert.match(result.message, /docs\/stamped\.md: verified must be a string/); + }); +} + +test('GIVEN a valid verified stamp WHEN another unknown key is present THEN it is still rejected', () => { + const result = checkDocs({ files: [], labels: [], trackedFiles: ['main.js'], + documents: { 'docs/stamped.md': '---\ncovers: ["main.js"]\nverified: abcdef0 2026-11-29\nother: true\n---\n# Doc' } }); + assert.equal(result.ok, false); + assert.match(result.message, /docs\/stamped\.md:.*only covers.*verified/); +}); + +test('GIVEN a stamp-only edit WHEN covered code changes THEN the DoD gate still requires a body change', () => { + const doc = 'docs/terminal.md'; + const previousDocuments = { [doc]: TERMINAL_DOC.replace('covers:', 'verified: abcdef0 2026-11-28\ncovers:') }; + const documents = { [doc]: previousDocuments[doc].replace('abcdef0 2026-11-28', '1234567 2026-11-29') }; + const options = { files: ['public/terminal.js', doc], trackedFiles: ['public/terminal.js', doc], documents, previousDocuments }; + const result = runCli([...REFS, '--labels', '[]'], options); + assert.equal(result.code, 1); + assert.match(result.output, /This PR changes the app without documentation/); + assert.doesNotMatch(result.output, /front matter must/); + assert.equal(runCli([...REFS, '--labels', '[]'], { ...options, documents: { [doc]: documents[doc] + '\nCorrected behavior.' } }).code, 0); +}); diff --git a/test/doc-staleness.test.js b/test/doc-staleness.test.js new file mode 100644 index 000000000..d6d900337 --- /dev/null +++ b/test/doc-staleness.test.js @@ -0,0 +1,139 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { execFileSync, spawnSync } = require('node:child_process'); + +const SCRIPT = path.join(__dirname, '..', 'scripts', 'doc-staleness.js'); +let repo; +let base; +let head; +const git = (...args) => execFileSync('git', [ + '-c', 'user.name=Doc test', '-c', 'user.email=doc-test@example.invalid', + '-c', 'commit.gpgSign=false', '-c', 'core.hooksPath=/dev/null', ...args, +], { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); +const write = (file, text) => { + fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true }); + fs.writeFileSync(path.join(repo, file), text); +}; +const commit = message => { git('add', '.'); git('commit', '-m', message); }; +const doc = (covers, stamp) => '---\ncovers: ' + JSON.stringify(covers) + + (stamp ? '\nverified: ' + stamp : '') + '\n---\n# Documentation\n'; +const load = () => { + assert.ok(fs.existsSync(SCRIPT), 'doc-staleness report must exist'); + return require(SCRIPT); +}; +const cli = (args, cwd = repo) => { + load(); + return spawnSync(process.execPath, [SCRIPT, ...args], { cwd, encoding: 'utf8' }); +}; + +test.before(() => { + repo = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-staleness-test-')); + git('init'); + write('src/a.js', 'base'); + write('src/b.js', 'base'); + write('src/deep/c.js', 'base'); + write('src/literal[1].js', 'base'); + write('src/literal1.js', 'base'); + write('other.txt', 'base'); + commit('baseline'); + base = git('rev-parse', 'HEAD'); + write('docs/stamped.md', doc(['src/a.js'], base.slice(0, 7) + ' 2026-11-29')); + write('docs/glob.md', doc(['src/**/*.js', 'src/a.js'], base + ' 2026-11-29')); + write('docs/shallow.md', doc(['src/*.js'], base + ' 2026-11-29')); + write('docs/unstamped.md', doc(['other.txt'])); + write('docs/unknown.md', doc(['other.txt'], '0000000000000000000000000000000000000000 2026-11-29')); + write('docs/empty.md', doc([], base + ' 2026-11-29')); + write('docs/plain.md', '# No coverage'); + write('src/a.js', 'first'); + write('src/b.js', 'first'); + commit('two covered files in one commit'); + write('other.txt', 'uncovered by stamped docs'); + commit('uncovered change'); + write('src/deep/c.js', 'nested'); + commit('nested covered change'); + write('src/a.js', 'second'); + commit('second direct change'); + head = git('rev-parse', 'HEAD'); + write('docs/current.md', doc(['other.txt'], head + ' 2026-11-29')); + git('add', 'docs/current.md'); +}); + +test.after(() => { + if (repo) fs.rmSync(repo, { recursive: true, force: true }); +}); + +test('GIVEN real history WHEN reporting THEN unknown stamps rank first and covered commits are counted once', () => { + const { collectStaleness } = load(); + const rows = collectStaleness(repo); + assert.deepEqual(rows.map(row => [row.doc, row.status, row.commitsSince]), [ + ['docs/unknown.md', 'unknown sha', null], + ['docs/unstamped.md', 'unstamped', null], + ['docs/glob.md', 'verified', 3], + ['docs/shallow.md', 'verified', 2], + ['docs/stamped.md', 'verified', 2], + ['docs/current.md', 'verified', 0], + ['docs/empty.md', 'verified', 0], + ]); + assert.equal(rows.find(row => row.doc === 'docs/stamped.md').stamp, base.slice(0, 7) + ' 2026-11-29'); + assert.equal(rows.find(row => row.doc === 'docs/unstamped.md').stamp, null); +}); + +test('GIVEN stale docs WHEN invoking CLI THEN cwd, repo-root, JSON, table and limit work without failing the gate', () => { + const { collectStaleness } = load(); + const result = cli(['--json']); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(JSON.parse(result.stdout), collectStaleness(repo)); + const limited = cli(['--repo-root', repo, '--limit', '3', '--json'], path.dirname(repo)); + assert.equal(limited.status, 0, limited.stderr); + assert.deepEqual(JSON.parse(limited.stdout), collectStaleness(repo).slice(0, 3)); + const table = cli(['--limit', '2']); + assert.equal(table.status, 0, table.stderr); + assert.match(table.stdout, /Doc\s+Stamp\s+Commits since/); + assert.match(table.stdout, /docs\/unknown.md.*unknown sha/); + assert.match(table.stdout, /docs\/unstamped.md.*unstamped/); + assert.equal(table.stdout.trim().split('\n').length, 3); +}); + +test('GIVEN malformed arguments WHEN invoking CLI THEN usage fails with no report', () => { + load(); + for (const args of [['--limit'], ['--limit', '0'], ['--limit', '-1'], ['--limit', '1.5'], + ['--limit', 'NaN'], ['--limit', '9007199254740992'], ['--repo-root'], ['--repo-root', ''], + ['--other'], ['--json', 'true']]) { + const result = cli(args); + assert.equal(result.status, 2, JSON.stringify(args)); + assert.match(result.stderr, /usage:/); + assert.equal(result.stdout, ''); + } +}); + +test('GIVEN invalid git context WHEN reporting THEN errors propagate instead of becoming zero counts', () => { + const { collectStaleness } = load(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'doc-staleness-outside-')); + try { + assert.throws(() => collectStaleness(outside), /git|repository|HEAD/i); + assert.equal(cli(['--repo-root', outside]).status, 2); + execFileSync('git', ['init'], { cwd: outside, stdio: 'pipe' }); + assert.throws(() => collectStaleness(outside), /git|HEAD/i); + } finally { + fs.rmSync(outside, { recursive: true, force: true }); + } +}); + +test('GIVEN invalid coverage metadata WHEN reporting THEN shared validation names the offending doc', () => { + const { collectStaleness } = load(); + const file = path.join(repo, 'docs/stamped.md'); + const original = fs.readFileSync(file); + try { + write('docs/stamped.md', doc(['src/a.js'], 'bad')); + assert.throws(() => collectStaleness(repo), /docs\/stamped.md: verified/); + write('docs/stamped.md', doc(['src/missing*.js'])); + assert.throws(() => collectStaleness(repo), /docs\/stamped.md: covers pattern matches no tracked file/); + } finally { + fs.writeFileSync(file, original); + } +});