Files
gstack/bin/gstack-docs-candidate
Garry Tanandcapy-ai[bot] a2ce5bd888 v1.92.24.0 fix(ship): finish accepts an owner-accepted documentation exception (GST-713) (#3776)
* fix(ship): base merges, adjacent base edits, test-only and audit-requested fixes no longer force a second review loop (GST-407, GST-384, GST-391)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* ship driver: trim two phrases for headroom with #3662

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* ship driver: keep the Next steps heading phrase the handoff check reads; trim elsewhere

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: regenerate ship goldens

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes

comparePath returns same only when every hunk sits where the base change puts it (patch-ids ignore positions) and treats a file-mode change as changed; the scoped-review packet says when a fence is truncated; --docs-result must be the posted audit's result; the --context-reviewed record goes beside the packet, outside the worktree. Negative controls for each.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pass-2 review fixes

A test edit routes as tests= only when it adds lines with no gate tag; a removed or changed line or an unreadable test diff goes through the full loop. Diffs skip textconv. A hunkless patch (binary, empty, mode-only) is same when its patch-id matches. Without --reviewed-base test files route as before. finish's packet path and attempt's state directory have fallbacks.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: Step 11 review fixes; a version-only stamp_files edit after review is release metadata (GBRA-251)

gateEditedPaths reads removed lines only inside hunks; carry refuses when a path listing fails; docs freshness stops on a failed listing; attempt counts an unreadable state file. releasePaths includes stamp_files paths whose edit is a version swap under stamp_patterns.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: no test edit skips review; guard packet writes; exclusive attempt state

A test-only edit with no gate tag gets the scoped fix-check of its test hunks instead of a lanes-only rerun. Packet write failures print a STOP or RECEIPT_CARRY_REFUSED. attempt's allowance uses an exclusive create.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: attempt prints gstack's install command; carry checks the product diff outside context paths

The attempt STOP no longer echoes the audit child's fix text. A scoped-review carry now requires the product patch-id without the context paths to match at both heads.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: oversized packets take the full loop; exact --docs-requested match; name-only test globs only in test dirs

A scoped-review packet section over 200 lines sends that path to the full loop instead of a truncated packet. The docs-result path match is exact. test_*.py, *Test.java and similar count as test code only under a test directory.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(unattended): carry's scoped-review refusal and what it keeps

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: carry's scoped-review route in ship-policy, review-policy and troubleshooting (docs-a-1)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(windows): curate ship-rereview-triggers out of the Windows lane like ship-release (run 41193336209)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: restore bin/gstack-ship-receipt after the main merge

The merge commit b10e2db wrote a truncated copy of the file. This is the
three-way merge of both sides with the refused() union: main's codes plus
RECEIPT_CARRY_SCOPED_REVIEW.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(ship): finish runs after an owner-accepted Step 14.5 documentation exception (GST-713)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(ship): the exception match and every snapshot --exception refusal are covered (GST-713)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(ship): the exception snapshot uses the receipt's docs parser; finish also matches scope and stops on a corrupt docs-audit record (GST-713)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: DOCS_AUDIT_BLOCKED names the --exception snapshot finish needs (GST-713)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore(changelog): drop #3684's fragment, already stamped into CHANGELOG.md on main

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-11-01 10:13:55 +00:00

224 lines
13 KiB
TypeScript
Executable File

#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
* gstack-docs-candidate — /ship's documentation-audit snapshot and its later check.
*
* Usage (run inside the repository):
* gstack-docs-candidate snapshot --out <candidate.json> --audit-id <id> --mode edit|read-only
* --base <rev> [--select <path>]... [--docs <path>]... [--exception <docs-audit.json>]
* gstack-docs-candidate compare <candidate.json>
* gstack-docs-candidate attempt <child-output> --state <attempts.json>
* gstack-docs-candidate [snapshot|compare] --help
*
* snapshot saves, NUL-safely and without writing to the repository: base SHA,
* HEAD, branch, index entries, committed (base..HEAD), staged, unstaged and
* untracked paths, and git blob hashes of the working-tree content of every
* selected path, docs path and dirty/untracked path. Without --select, the
* selected paths are the committed, staged, unstaged and untracked paths.
* --docs takes files or directories (directories expand to their tracked and
* untracked files). It prints a short summary; the JSON file is the record.
* --exception names the blocked .gstack/tmp/docs-audit.json an owner accepted
* (Step 14.5 Blocked recovery): the record then carries that exception, so
* Step 16 can tell an accepted risk from a skipped audit.
*
* compare re-reads the same state and prints one JSON object: whether HEAD or
* the index changed, which recorded paths' content changed or disappeared, and
* which paths are newly dirty or untracked. It never decides whether a change
* was permitted; the caller checks those paths against the child's report.
*
* attempt reads one audit child's output and says whether the launch counts
* against Step 14.5's attempt budget. A launch the child's install check refused
* (an `INSTALL: fail` row, its last GSTACK_RESULT line a document-release
* refusal, and no audit JSON) never audited, so it is not counted, once per
* invocation (--state, the invocation's record); a second refusal is counted
* and stops for the install fix (GST-391, gbrain #8084).
*/
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { parseReceiptDocs, type ReceiptDocs } from '../lib/ship-receipt-docs';
function git(args: string[]): string {
const r = spawnSync('git', args, { encoding: 'utf8', env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' }, maxBuffer: 256 * 1024 * 1024 });
if (r.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${(r.stderr || '').trim()}`);
return r.stdout;
}
const nul = (text: string) => text.split('\0').filter(Boolean);
function state(base: string) {
const head = git(['rev-parse', 'HEAD']).trim();
return {
head,
branch: git(['branch', '--show-current']).trim(),
index: nul(git(['ls-files', '-s', '-z'])),
committed: nul(git(['diff', '--name-only', '-z', base, head])),
staged: nul(git(['diff', '--cached', '--name-only', '-z'])),
unstaged: nul(git(['diff', '--name-only', '-z'])),
untracked: nul(git(['ls-files', '-z', '--others', '--exclude-standard'])),
};
}
function expand(listed: string[], paths: string[]): string[] {
const out = new Set<string>();
for (const p of paths) {
const rel = p.replace(/^\.\//, '').replace(/\/+$/, '');
const under = listed.filter(f => f === rel || f.startsWith(rel + '/'));
if (under.length) under.forEach(f => out.add(f)); else out.add(rel);
}
return [...out].sort();
}
/** Git blob ids of working-tree content, computed in-process (any path bytes, nothing written); null when absent. */
function hashes(paths: string[]): Record<string, string | null> {
const out: Record<string, string | null> = {};
for (const p of paths) {
if (!fs.existsSync(p) || !fs.statSync(p).isFile()) { out[p] = null; continue; }
const content = fs.readFileSync(p);
out[p] = new Bun.CryptoHasher('sha1').update(`blob ${content.length}\0`).update(content).digest('hex');
}
return out;
}
function flag(args: string[], name: string): string[] {
const values: string[] = [];
for (let i = 0; i < args.length; i++) if (args[i] === name) {
const value = args[i + 1];
if (value === undefined || value.startsWith('--')) throw new Error(`${name} needs a value`);
values.push(value); i++;
}
return values;
}
function one(args: string[], name: string): string {
const values = flag(args, name);
if (values.length !== 1) throw new Error(`${name} is required exactly once`);
return values[0]!;
}
const USAGE = `usage: gstack-docs-candidate snapshot --out <candidate.json> --audit-id <id> --mode edit|read-only --base <rev> [--select <path>]... [--docs <path>]... [--exception <docs-audit.json>]
gstack-docs-candidate compare <candidate.json>
gstack-docs-candidate attempt <child-output> --state <attempts.json>`;
/** The owner's accepted Step 14.5 exception from the blocked .gstack/tmp/docs-audit.json record, read by the receipt's own parser; throws when the record is not blocked or names no complete exception. */
function acceptedException(file: string): NonNullable<ReceiptDocs['exception']> & { scope: string } {
let audit: unknown;
try { audit = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (error) { throw new Error(`--exception ${file} is not readable JSON: ${(error as Error).message}`); }
const parsed = parseReceiptDocs(audit);
const problem = !parsed.ok ? parsed.message : parsed.docs.status !== 'blocked' ? `its status is ${parsed.docs.status}, not blocked` : !parsed.docs.exception ? 'it names no accepted exception' : null;
if (problem || !parsed.ok || !parsed.docs.exception) throw new Error(`--exception ${file}: ${problem}. Only an owner-accepted documentation risk writes this snapshot (ship/sections/documentation.md, Blocked recovery step 3)`);
return { ...parsed.docs.exception, scope: parsed.docs.scope };
}
/** Each field compare needs that the record lacks or types wrongly; empty for a valid record. */
function recordProblems(record: any): string[] {
if (!record || typeof record !== 'object' || Array.isArray(record)) return ['not a JSON object'];
const problems: string[] = [];
if (record.schema_version !== 1) problems.push('missing or wrong schema_version (want 1)');
if (typeof record.base !== 'string') problems.push('missing or wrong base (want the base commit SHA string)');
if (!record.hashes || typeof record.hashes !== 'object' || Array.isArray(record.hashes)) problems.push('missing or wrong hashes (want an object of path -> blob id)');
return problems;
}
function main(argv: string[]): void {
const [command, ...args] = argv;
const topHelp = (command === '--help' || command === '-h') && !args.length;
const commandHelp = (command === 'snapshot' || command === 'compare' || command === 'attempt') && args.length === 1 && args[0] === '--help';
if (topHelp || commandHelp) {
console.log(USAGE);
return;
}
if (command === 'snapshot') {
const known = new Set(['--out', '--audit-id', '--mode', '--base', '--select', '--docs', '--exception']);
for (let i = 0; i < args.length; i += 2) if (!known.has(args[i]!)) throw new Error(`unknown argument: ${args[i]}`);
const out = path.resolve(one(args, '--out'));
const top = fs.realpathSync(git(['rev-parse', '--show-toplevel']).trim());
if (out === top || out.startsWith(top + path.sep)) throw new Error('--out must be outside the repository');
const mode = one(args, '--mode');
if (mode !== 'edit' && mode !== 'read-only') throw new Error('--mode must be edit or read-only');
const base = git(['rev-parse', '--verify', one(args, '--base') + '^{commit}']).trim();
const exceptionFile = flag(args, '--exception')[0];
const exception = exceptionFile === undefined ? undefined : acceptedException(exceptionFile);
process.chdir(top);
const now = state(base);
const listed = nul(git(['ls-files', '-z', '--cached', '--others', '--exclude-standard']));
const selected = flag(args, '--select').length ? expand(listed, flag(args, '--select'))
: [...new Set([...now.committed, ...now.staged, ...now.unstaged, ...now.untracked])].sort();
const docs = expand(listed, flag(args, '--docs'));
const tracked = [...new Set([...selected, ...docs, ...now.staged, ...now.unstaged, ...now.untracked])].sort();
const record = { schema_version: 1, audit_id: one(args, '--audit-id'), mode, base, ...now, selected, docs, hashes: hashes(tracked), ...(exception ? { exception } : {}) };
fs.writeFileSync(out, JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
console.log(`CANDIDATE: ${out}`);
console.log(`base=${base} head=${now.head} branch=${now.branch || '(detached)'} mode=${mode}`);
if (exception) console.log(`EXCEPTION: accepted by ${exception.accepted_by} ${exception.date} via ${exception.via}`);
console.log(`committed=${now.committed.length} staged=${now.staged.length} unstaged=${now.unstaged.length} untracked=${now.untracked.length} selected=${selected.length} docs=${docs.length} hashed=${tracked.length}`);
for (const [label, list] of [['committed', now.committed], ['staged', now.staged], ['unstaged', now.unstaged], ['untracked', now.untracked], ['docs', docs]] as const) {
if (list.length) console.log(`${label}: ${list.map(p => JSON.stringify(p)).join(' ')}`);
}
return;
}
if (command === 'compare') {
if (args.length !== 1) throw new Error('compare takes exactly one candidate path');
const file = args[0]!;
let record: any;
try { record = JSON.parse(fs.readFileSync(file, 'utf8')); }
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw error; record = undefined; }
const problems = record === undefined ? ['not valid JSON'] : recordProblems(record);
if (problems.length) {
throw new Error(`${file} is not a gstack-docs-candidate record: ${problems.join('; ')}. `
+ 'Fix: the candidate must be the record the Prepare snapshot wrote. To rebuild it, rerun the Prepare snapshot '
+ '(gstack-docs-candidate snapshot --out <path> --audit-id <id> --mode edit --base <rev> ...) only before dispatching '
+ 'the child audit. After the audit, never snapshot over it: the post-child snapshot uses a different --out '
+ '(<audit-id>-post.json).');
}
process.chdir(fs.realpathSync(git(['rev-parse', '--show-toplevel']).trim()));
const now = state(record.base);
const current = hashes(Object.keys(record.hashes));
const content_changed = Object.keys(record.hashes).filter(p => current[p] !== record.hashes[p]).sort();
const dirty = (s: { staged: string[]; unstaged: string[]; untracked: string[] }) => new Set([...s.staged, ...s.unstaged, ...s.untracked]);
const before = dirty(record);
const newly_dirty = [...dirty(now)].filter(p => !before.has(p) && !(p in record.hashes)).sort();
const sameList = (a: string[], b: string[]) => a.length === b.length && a.every((v, i) => v === b[i]);
console.log(JSON.stringify({
audit_id: record.audit_id,
head_changed: now.head !== record.head,
index_changed: !sameList(now.index, record.index),
content_changed,
newly_dirty,
}));
return;
}
if (command === 'attempt') {
const INSTALL_FIX = 'run the Capy skill installer (scripts/install.sh --for document-release), then launch with its GSTACK_LAUNCH line';
const [file, ...rest] = args;
if (!file || file.startsWith('--')) throw new Error('attempt takes the child output file, then --state <attempts.json>');
const state = one(rest, '--state');
const lines = fs.readFileSync(file, 'utf8').split('\n').map(l => l.trim()).filter(Boolean);
const last = lines.filter(l => l.startsWith('GSTACK_RESULT: ')).pop();
const install = lines.find(l => /^INSTALL: fail\b/.test(l));
const audited = lines.some(l => { try { const v = JSON.parse(l); return !!v && typeof v === 'object' && 'schema_version' in v; } catch { return false; } });
if (!last || !/^GSTACK_RESULT: skill=document-release status=refused\b/.test(last) || !install || audited) { console.log('ATTEMPT: counted'); return; }
let seen = 0;
try { seen = Number(JSON.parse(fs.readFileSync(state, 'utf8')).not_counted) || 0; } catch { seen = fs.existsSync(state) ? 1 : 0; }
if (seen >= 1) {
console.log('ATTEMPT: counted (a second install refusal in this invocation)');
console.log(`STOP: ${INSTALL_FIX} and confirm its gstack: ok trailer before another launch`);
process.exit(3);
}
fs.mkdirSync(path.dirname(path.resolve(state)), { recursive: true });
try { fs.writeFileSync(state, JSON.stringify({ not_counted: 1 }) + '\n', { mode: 0o600, flag: 'wx' }); } catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
console.log('ATTEMPT: counted (another launch in this invocation already used the allowance)');
console.log(`STOP: ${INSTALL_FIX} and confirm its gstack: ok trailer before another launch`);
process.exit(3);
}
console.log('ATTEMPT: not-counted (the audit child\'s install check refused document-release)');
return;
}
throw new Error(USAGE);
}
try { main(process.argv.slice(2)); }
catch (error) {
console.error(`gstack-docs-candidate: ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
}