From a4d058b0782353b91651864534bd1ccb3f62f264 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 4 Nov 2026 20:13:13 -0800 Subject: [PATCH] feat(review): enforce the reader fetch rule with a per-stage sweep (GST-1322 B) (#4011) * feat(review): enforce the reader fetch rule with a per-stage sweep (GST-1322 B) Split of #4008 onto current main: the squashed product diff at cf34a43. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes (GST-1322 B, ship-c-p1) A start sweep that hit its bounds is a partial note, never a violation (sweepResult). The sweep tests remove their fixture repos. A stage's rerun dispatches no reader while a path its first attempt found still exists (FETCH_RERUN_BLOCKED, the Captain's ruling C on #4011). Review-Finding: p1/specialist-batched#1 reader=state-machines Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: sweep strips remote userinfo; a spent or blocked rerun stops every later stage (GST-1322 B, grant a-7b63e4cad37c) outside-voice#1: remote URLs are recorded and printed without user:token@. outside-voice#2: resuming after FETCH_RERUN_SPENT stops before any later stage and returns no reader output; while a kept path blocks one stage's rerun, no stage's start (Step 11's voices included) dispatches a reader. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: sweep reads remotes through git config and redacts fail-closed (GST-1322 B, GSTA-297) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes Review-Finding: p1/specialist-batched#1 reader=security Review-Finding: p1/red-team#2 reader=red-team Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: quarantine every collection of a dispatch; classify remotes on the raw value (GST-1322 B, GSTA-297) Review-Finding: p1/outside-voice#1 reader=outside-voice Review-Finding: p1/outside-voice#2 reader=outside-voice 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> --- bin/gstack-doctor-components.sh | 3 + bin/gstack-review-dispatch | 60 +++++++- changelog.d/gst-1322-fetch-sweep.md | 1 + docs/review-policy.md | 28 +++- docs/troubleshooting.md | 52 +++++++ lib/capy-review-pass.js | 23 ++- lib/result-codes-release.ts | 16 ++ lib/review-ledger.ts | 35 ++++- lib/review-pass.ts | 9 +- lib/review-scope.ts | 5 +- lib/review-sweep.ts | 221 ++++++++++++++++++++++++++++ test/review-pass.test.ts | 157 +++++++++++++++++++- test/review-sweep.test.ts | 194 ++++++++++++++++++++++++ 13 files changed, 787 insertions(+), 17 deletions(-) create mode 100644 changelog.d/gst-1322-fetch-sweep.md create mode 100644 lib/review-sweep.ts create mode 100644 test/review-sweep.test.ts diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh index e3843b635..fc9f2e2a1 100644 --- a/bin/gstack-doctor-components.sh +++ b/bin/gstack-doctor-components.sh @@ -361,6 +361,9 @@ gstack_result_anchor() { REVIEW_DIFF_TOO_LARGE) printf '%s' 'review-diff-too-large' ;; REVIEW_DIFF_UNREADABLE) printf '%s' 'review-diff-unreadable' ;; REVIEW_EXCLUDE_REFERENCE) printf '%s' 'review-exclude-reference' ;; + FETCH_VIOLATION) printf '%s' 'fetch-violation' ;; + FETCH_RERUN_BLOCKED) printf '%s' 'fetch-rerun-blocked' ;; + FETCH_RERUN_SPENT) printf '%s' 'fetch-rerun-spent' ;; APPROVAL_RECORD_INVALID) printf '%s' 'approval-record-invalid' ;; APPROVAL_RECORD_SECRET) printf '%s' 'approval-record-secret' ;; APPROVAL_RECORD_NO_BRANCH) printf '%s' 'approval-record-no-branch' ;; diff --git a/bin/gstack-review-dispatch b/bin/gstack-review-dispatch index 2cc9fa31d..3232fa4ba 100755 --- a/bin/gstack-review-dispatch +++ b/bin/gstack-review-dispatch @@ -12,6 +12,7 @@ * gstack-review-dispatch show|stage|chunk|mark --manifest ... one manifest step * gstack-review-dispatch program [--ledger ] the checked-in Capy pass program * gstack-review-dispatch audit-fetch --events [--manifest --reader ] what a reader fetched (GST-1322) + * gstack-review-dispatch sweep --manifest --stage --phase start|end what a stage fetched; quarantine and rerun * * Logic: lib/review-brief.ts (rendering from the sections), lib/review-ledger.ts (ledger, collect, judge, verify), * lib/review-pass.ts (the staged manifest) and lib/capy-review-pass.js (the Capy program that runs it). @@ -30,6 +31,7 @@ import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedRead } from ' import { resolveBaseBranch } from '../lib/ship-policy'; import { auditVerdict, eventsDigest, loadReaders, readersLine, scanEvents, type ToolEvent } from '../lib/review-fetch'; import { effectiveReaders, READERS_POLICY_DEFAULT, type EffectiveReaders } from '../lib/ship-policy-readers'; +import { defaultRoots, foundLines, inventory, quarantineStage, rerunBlocked, sweepResult, type Inventory } from '../lib/review-sweep'; import { REVIEW_DIFF_MAX_BYTES, ceilingContext, disclosureDigest, disclosureLine, parseTail, readSelection, tooLargeLine, unreadableLine, type PlanExclude, type ReaderDiff } from '../lib/review-exclude'; const HELP = `gstack-review-dispatch — verbatim reviewer briefs and loss-free collection for /ship @@ -102,6 +104,14 @@ const HELP = `gstack-review-dispatch — verbatim reviewer briefs and loss-free readers policy (the manifest's, else the base's): one FETCH_HIT: line per hit, then FETCH_AUDIT: verdict=clean|violation hits= notes= events= sha256=. With --manifest it records the result on the reader as fetch_audit. A note only: it exits 0 whatever it finds (docs/review-policy.md#what-readers-may-fetch) + sweep --manifest --stage --phase start|end + the fetch rule's enforcement, per stage. start records an inventory of git repositories and files of 100 MB or more under + the roots (the checkout's parent, home and the temp dir, or GSTACK_SWEEP_ROOTS; bounded in depth, entries and time) before the stage's readers + start. end, once the stage's readers are collected, diffs against it: a new repository with a network remote or a new big file + prints FETCH_VIOLATION: per path with a KEEP: line (never a delete command: no transcript attributes the path), + quarantines every reader of the stage (reply to /quarantine/, findings out of merged.jsonl), plans one rerun per slot as + #2 (RERUN:, not a review round) and exits 0; the same on a rerun prints FETCH_RERUN_SPENT (exit 3). A sweep that hit + its bounds prints FETCH_SWEEP: partial, a note. Each end appends a fetch-sweep ledger event that verify replays program [--ledger ] PROGRAM: v sha256=… bytes=…, then lib/capy-review-pass.js as one JSON string line (see the gstack Capy skill) ${exitTableHelp()}`; @@ -212,10 +222,56 @@ function auditFetch(): number { writeManifest(file, m); } for (const h of hits) process.stdout.write(`FETCH_HIT: ${h.severity} rule=${h.rule} tool=${h.tool} target=${JSON.stringify(h.target)}\n`); - process.stdout.write(`FETCH_AUDIT: verdict=${verdict} hits=${hits.filter(h => h.severity === 'violation').length} notes=${hits.filter(h => h.severity === 'note').length} events=${parsed.length} sha256=${audit.events_sha256.slice(0, 12)} ${readersLine(readers)} (recorded as a note; enforcement lands with GST-1322 PR B)\n`); + process.stdout.write(`FETCH_AUDIT: verdict=${verdict} hits=${hits.filter(h => h.severity === 'violation').length} notes=${hits.filter(h => h.severity === 'note').length} events=${parsed.length} sha256=${audit.events_sha256.slice(0, 12)} ${readersLine(readers)} (a note: the per-stage sweep enforces the rule, gstack-review-dispatch sweep)\n`); return EXIT.ok; } +/** The stage's fetch sweep: the start inventory, or the end diff with quarantine and one rerun per slot (lib/review-sweep.ts). */ +function sweep(): number { + const file = flag('--manifest'); + const stage = flag('--stage') as Stage | undefined; + const phase = flag('--phase'); + if (!file || !stage || !STAGES.includes(stage) || (phase !== 'start' && phase !== 'end')) { process.stderr.write(`gstack-review-dispatch sweep: --manifest --stage ${STAGES.join('|')} --phase start|end\n`); return EXIT.usage; } + const m = readManifest(file); + const checkout = checkoutRoot(); + const s = ((m.sweeps ??= {})[stage] ??= { attempt: 1 }); + if (phase === 'start') { + if (!s.start) { + const blocked = Object.entries(m.sweeps).flatMap(([x, sx]) => (sx.start ? [] : rerunBlocked(x as Stage, sx))); + if (blocked.length) { process.stdout.write(blocked.join('\n') + '\n'); return EXIT.refused; } + const inv = inventory(defaultRoots(checkout), checkout); + const dir = path.join(m.out, 'sweep'); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + const f = path.join(dir, `${stage}-${s.attempt}-start.json`); + fs.writeFileSync(f, JSON.stringify(inv) + '\n', { mode: 0o600 }); + s.start = { at: new Date(inv.at).toISOString(), file: f, ...(inv.partial ? { partial: inv.partial } : {}) }; + writeManifest(file, m); + } + process.stdout.write(`FETCH_SWEEP: start stage=${stage} attempt=${s.attempt} file=${s.start.file}${s.start.partial ? ` partial=${JSON.stringify(s.start.partial)}` : ''}\n`); + return EXIT.ok; + } + const readers = m.readers.filter(r => r.stage === stage && (r.attempt ?? 1) === s.attempt).map(r => r.reader); + if (s.end) { process.stdout.write(`FETCH_SWEEP: ${s.end.verdict} stage=${stage} attempt=${s.attempt} found=${s.end.found.length} (recorded)\n`); return EXIT.ok; } + let start: Inventory | null = null; + try { start = s.start ? JSON.parse(fs.readFileSync(s.start.file, 'utf8')) as Inventory : null; } catch { start = null; } + const { found, verdict, partial } = sweepResult(start, start ? inventory(start.roots, checkout) : null); + s.end = { at: new Date().toISOString(), verdict, found, ...(partial ? { partial } : {}) }; + appendEvent(m.ledger, { event: 'fetch-sweep', pass: m.pass, stage, attempt: s.attempt, verdict, found, readers, ...(partial ? { partial } : {}) }); + const lines = [`FETCH_SWEEP: ${verdict} stage=${stage} attempt=${s.attempt} found=${found.length}${partial ? ` partial=${JSON.stringify(partial)} (a note: the sweep could not cover every root)` : ''}`]; + if (verdict !== 'violation') { writeManifest(file, m); process.stdout.write(lines.join('\n') + '\n'); return EXIT.ok; } + lines.push(...foundLines(stage, s.attempt, found, readers)); + const q = quarantineStage(m, stage, s.attempt); + lines.push(...q.lines); + const spent = s.attempt > 1; + if (!spent) m.sweeps[stage] = { attempt: s.attempt + 1, history: [...(s.history ?? []), { attempt: s.attempt, start: s.start, end: s.end }] }; + writeManifest(file, m); + lines.push(spent + ? `FETCH_RERUN_SPENT: stage=${stage} (its one rerun fetched too, so the pass stops; deal with the paths above, then start a fresh pass under a new --pass and --out; docs/troubleshooting.md#fetch-rerun-spent)` + : `RERUN: stage=${stage} readers=${q.reruns.map(r => r.reader).join(',')} (one fresh attempt per slot, not a review round; verify refuses until they are collected and the stage sweeps clean)`); + process.stdout.write(lines.join('\n') + '\n'); + return spent ? EXIT.refused : EXIT.ok; +} + const quote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`; const wrongTree = (reader: string, t: TreeCheck) => `${t.moved ? 'COLLECT_TREE_MOVED' : 'COLLECT_WRONG_TREE'}: reader=${reader} reported=${JSON.stringify(t.reported)} expected=${JSON.stringify(t.expected)} (${t.moved ? 'the checkout moved after this brief was rendered' : 'the reply did not review the checkout its brief named'}; nothing merged; restore it with a fresh pass under a new --pass and --out)\n`; @@ -434,6 +490,7 @@ function main(): number { if (cmd === 'pass') return pass(); if (cmd === 'program') return program(); if (cmd === 'audit-fetch') return auditFetch(); + if (cmd === 'sweep') return sweep(); if (['show', 'stage', 'chunk', 'mark'].includes(cmd)) return passStep(cmd); const ledger = flag('--ledger'); if (!ledger) { process.stderr.write(`gstack-review-dispatch ${cmd}: --ledger is required\n`); return EXIT.usage; } @@ -502,6 +559,7 @@ function main(): number { if (flag('--targeted-out')) fs.rmSync(flag('--targeted-out')!, { force: true }); const v = verify(ledger); for (const r of v.rows) process.stdout.write(`${r.kind} ${r.reader} ${r.status} ${r.detail}\n`); + for (const r of v.rows.filter(x => x.kind === 'FETCH' && x.status === 'VIOLATION')) process.stdout.write(`FETCH_VIOLATION: ${r.reader} ${r.detail} (a reader of that stage fetched; its replies are quarantined and the pass cannot certify until the stage reruns clean; docs/troubleshooting.md#fetch-violation)\n`); if (!v.briefs) { process.stdout.write('VERIFY: no brief records (this run\'s ledger kept no prompts; dispatched-vs-rendered cannot be checked)\n'); return EXIT.refused; } const record = targetedRecord(ledger, v.rows); if (record) { diff --git a/changelog.d/gst-1322-fetch-sweep.md b/changelog.d/gst-1322-fetch-sweep.md new file mode 100644 index 000000000..9b86344aa --- /dev/null +++ b/changelog.d/gst-1322-fetch-sweep.md @@ -0,0 +1 @@ +- **/ship now enforces the reviewer fetch rule: a review stage that downloads another repository is thrown out and rerun once.** Before each review stage starts, /ship lists the git repositories and files of 100 MB or more under the workspace, home and the temp dir, and lists them again when the stage's last reader is done. A new repository with a network remote, or a new big file, quarantines every reader of that stage. Their replies move under `/quarantine/`, their findings never reach the Red Team, the judge or PR text, and `gstack-review-dispatch verify` refuses with `FETCH_VIOLATION`. Each reader reruns once as `#2` (not a review round), and a second fetch stops the pass with `FETCH_RERUN_SPENT`; running it again starts no later stage. The rerun starts only after every path the first attempt found is gone. While one is still there, no reader of any stage starts, Step 11's voices included, and the pass stops with `FETCH_RERUN_BLOCKED`, so no reader can read what the first attempt downloaded. Nothing is deleted for you, and no delete command is printed. Each path it finds is listed for you to inspect and leave alone, and a remote URL is shown without its `user:token@` part or query (or as `` when it doesn't parse as a URL). Capy doesn't tell a pass which reader did what, so blame lands on the whole stage, not one reader. The sweep only sees repositories that keep a network remote and files of 100 MB or more; an extracted archive, a smaller download, or a clone nested in another repository or deleted before the stage ends is not caught yet. (GST-1322) diff --git a/docs/review-policy.md b/docs/review-policy.md index 882cd2004..35b62cda2 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -545,8 +545,32 @@ It splits each command into words and flags only a known download tool aimed at a network target, so a reader that greps for `git clone` or reads the scanner's source is not a hit, while `bash -c`, wrappers such as `timeout` and `command:` strings inside a program are read through. A fetch of the checkout's own remote -by name is a note. Today the result is recorded on the reader in the pass -manifest as a note (`fetch_audit`, `enforced: false`). +by name is a note. The result is recorded on the reader in the pass manifest as +a note (`fetch_audit`, `enforced: false`): Capy gives a pass no way to read a +reader's own tool calls, so the scanner serves hosts that can hand it a +transcript. + +The rule is enforced per stage. Before a stage's readers start, the pass program +runs `gstack-review-dispatch sweep --phase start`, an inventory of git +repositories and files of 100 MB or more under the workspace, home and the temp +dir (bounded at depth 6, 200,000 entries and 20 seconds; past a bound the sweep +is `partial`, a note). After the stage's last reader is collected, +`--phase end` diffs against it. A new repository with a network remote, or a +new big file, is a violation. Every reader of that stage is quarantined (reply +under `/quarantine/`, findings out of `merged.jsonl`, never shown to the +Red Team or returned), `verify` refuses with `FETCH_VIOLATION`, and each slot +reruns once as `#2`, which is not a review round. The rerun starts only +once every path the first attempt found is gone: while one exists, a rerun reader +could open it and still sweep clean, so no reader of any stage, Step 11's voices included, starts and the pass stops +(`FETCH_RERUN_BLOCKED`). A fetch on the rerun stops the pass (`FETCH_RERUN_SPENT`), and resuming it starts no later stage. Nothing is deleted for you, and no delete +command is printed: each found path gets a `KEEP:` line to inspect and leave alone. A remote URL is read through git's own config parser and printed and recorded without its `user:token@` part or query; a value that does not parse as a URL reads ``. +Attribution is per stage until the platform exposes reader ids: a violation +names the stage and its readers, never the one reader that fetched, and a clean +reader of that stage reruns with the rest. The sweep sees only repositories that +keep a network remote and files of 100 MB or more, outside `node_modules` and +outside other repositories. An extracted archive, a smaller raw download, a fetch +with no remote, a clone nested in another repository and a clone deleted before +the stage ends all go unseen until the platform exposes reader transcripts. What this protects: the readers' findings, the merged review and PR text never carry a sealed file a reader fetched or opened. What it cannot protect: data that diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index bb61f5b92..b64bbd1e6 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -3531,6 +3531,58 @@ does, so readers see that code without the files it reads. **Fix.** Nothing for the review itself. If the code's correctness depends on the excluded files, narrow the pattern on the base so they stay in the diff. + +### `FETCH_VIOLATION` + +**Meaning.** A reader broke [the fetch rule](review-policy.md#what-readers-may-fetch): +between the start and the end of one review stage, a git repository with a +network remote, or a file of 100 MB or more, appeared under the workspace, home +or the temp dir. `gstack-review-dispatch sweep --phase end` prints one line per +path (`kind=repo|download`, the remote, the size and the stage's readers). Capy +exposes no reader id, so the stage is the unit: every reader of that stage is +quarantined. Its reply moves to `/quarantine/` (mode 0600), its findings +leave `merged.jsonl`, and it never reaches the Red Team, the judge, the +returned output or PR text. `verify` prints `FETCH_VIOLATION:` and refuses +until the stage has rerun and swept clean. + +**Fix.** Nothing to rerun by hand: the pass plans one fresh attempt per slot +(`RERUN:`, readers named `#2`; not a review round) and the pass program +dispatches them next. Each path gets a `KEEP:` line and never a delete command: +the sweep goes by time alone, and no transcript can tie a path to a reader, so a +clone another process on the machine made in the same window looks the same. +Inspect each path and leave it alone, then write a decision-trail row and tell +your Captain. A sweep that hit its bounds (depth 6, 200,000 entries or 20 seconds) +prints `FETCH_SWEEP: partial`, a note that is never a refusal. + + +### `FETCH_RERUN_BLOCKED` + +**Meaning.** A path a stage's first attempt found (a `FETCH_VIOLATION:` line) +still exists when that stage's rerun, or any other stage of the same pass +(Step 11's voices included), starts. A reader could open that clone or +download and still sweep clean, so no reader is dispatched, the pass stops +(exit 3) and `verify` keeps refusing with the first attempt's +`FETCH_VIOLATION`. + +**Fix.** Stop and report the printed path to your Captain. Leave it alone: no +transcript ties it to a reader, so never move or delete it yourself. Once the +path is gone, rerunning the same pass program resumes the rerun from its +manifest. + + +### `FETCH_RERUN_SPENT` + +**Meaning.** The stage's one rerun fetched too, so the pass stopped (exit 3). +Its readers are quarantined like the first attempt's, nothing they wrote is +merged, and `verify` refuses. Running the same pass program again stops at +once: it starts no later stage (no Red Team beside the kept paths) and returns +no reader output. + +**Fix.** Deal with the paths the `FETCH_VIOLATION:` lines name as above. Then +find out why readers keep fetching (a brief or a checklist that sends them to +another repository, or a sealed path the policy does not list yet) and start a +fresh pass under a new `--pass` and `--out`. A third attempt is never automatic. + ### `EXECUTION_UNKNOWN` diff --git a/lib/capy-review-pass.js b/lib/capy-review-pass.js index 0fe143498..7b1752a6c 100644 --- a/lib/capy-review-pass.js +++ b/lib/capy-review-pass.js @@ -10,6 +10,9 @@ // Once Phase 2 has started /parts (the parent of input.out), each poll or finished pass also // returns the next phase's section parts that fit its 32 KB (`gstack-ship-parts next`, GSTA-167 C5); // after a return that never reached the parent, rerun with input.resendParts to get that batch again. +// The fetch rule is enforced per stage (GST-1322): `gstack-review-dispatch sweep` inventories repositories and big files before a +// stage's readers start and diffs after its last is collected. A fetch quarantines the whole stage and plans one `#2` per +// slot, which this program dispatches next; a fetch on that rerun returns STOP:. const T0 = input.startedAt ?? (await now()); const deadline = T0 + (input.budgetMs ?? 200000); const tick = input.tickMs ?? 20000; @@ -24,6 +27,7 @@ const sh = async (cmd) => { return { code: r.exit_code, out: r.output || '' }; }; const bin = 'gstack-review-dispatch'; +const sweepCmd = (stage, phase) => bin + ' sweep --manifest ' + q(input.out.replace(/\/+$/, '') + '/pass-manifest.json') + ' --stage ' + stage + ' --phase ' + phase; const finish = (tail) => { const all = [...lines, ...tail]; let text = all.join('\n'); @@ -246,6 +250,14 @@ try { } } m = await load(); + for (const s of active.filter((x) => ((m.sweeps || {})[x] || {}).start && !m.sweeps[x].end && m.readers.every((r) => r.stage !== x || r.state === 'collected'))) { + const w = await sh(sweepCmd(s, 'end')); + lines.push(...w.out.trim().split('\n')); + if (w.code !== 0) return stop('gstack-review-dispatch sweep --stage ' + s + ' --phase end exited ' + w.code + ' (its lines above say why); nothing a quarantined reader wrote is merged or returned'); + m = await load(); + } + const spent = Object.keys(m.sweeps || {}).find((s) => m.sweeps[s].attempt > 1 && (m.sweeps[s].end || {}).verdict === 'violation'); + if (spent) return stop('FETCH_RERUN_SPENT is recorded for stage ' + spent + ', so this pass starts no later stage and returns no reader output; deal with its KEEP paths, then start a fresh pass under a new --pass and --out (docs/troubleshooting.md#fetch-rerun-spent)'); const stage = active.find((s) => m.readers.some((r) => r.stage === s && r.state !== 'collected')); if (!stage) break; if (m.readers.some((r) => r.stage === stage && r.state === 'planned')) { @@ -256,6 +268,12 @@ try { } const unmapped = m.readers.find((x) => x.stage === stage && x.state === 'rendered' && REASONING[x.effort] && !modelOf(x)); if (unmapped) return stop(unmapped.reader + ' runs at effort=' + unmapped.effort + ', which needs input.laneModel (your model id) or input.models; none was given'); + if (m.readers.some((x) => x.stage === stage && x.state === 'rendered') && !((m.sweeps || {})[stage] || {}).start) { + const w = await sh(sweepCmd(stage, 'start')); + if (w.code !== 0) return stop('gstack-review-dispatch sweep --stage ' + stage + ' --phase start exited ' + w.code + ': ' + w.out.slice(-500) + '; no reader of the stage was dispatched'); + lines.push(w.out.trim()); + m = await load(); + } for (const r of m.readers.filter((x) => x.stage === stage && x.state === 'rendered')) { const model = modelOf(r); const text = await briefText(r); @@ -289,12 +307,13 @@ try { } await sleep(tick); } - const done = m.readers.filter((r) => active.includes(r.stage)); + const ran = m.readers.filter((r) => active.includes(r.stage)); + const done = ran.filter((r) => !r.quarantined); const after = await reading(); let noteExit = 0; const before = m[beforeKey]; if (after && before && input.record && input.step) { - const n = await sh('gstack-ship-budget note --step ' + q(input.step) + ' --reading ' + after.tokens + ' --credits ' + after.credits + ' --record ' + q(input.record) + ' --dispatched-at ' + before.tokens + ' --dispatched-credits ' + before.credits + ' --readers ' + done.length); + const n = await sh('gstack-ship-budget note --step ' + q(input.step) + ' --reading ' + after.tokens + ' --credits ' + after.credits + ' --record ' + q(input.record) + ' --dispatched-at ' + before.tokens + ' --dispatched-credits ' + before.credits + ' --readers ' + ran.length); lines.push(n.out.trim()); noteExit = n.code; } diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index f50581020..1f1c0e6e6 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -546,4 +546,20 @@ export const RELEASE_RESULT_CODES = { summary: 'informational: a kept code file names an excluded folder (a directory reference, not a full file path), so its files stay excluded and readers see that code without the files it reads', fix: 'nothing to do for the review; if that code\'s correctness depends on the excluded files, narrow review_exclude_paths on the base so they stay in the diff', }, + // The fetch rule's per-stage sweep (lib/review-sweep.ts, GST-1322). + FETCH_VIOLATION: { + anchor: 'fetch-violation', + summary: 'a git repository with a network remote or a file of 100 MB or more appeared during one review stage, so every reader of that stage was quarantined and verify refuses until the stage reruns clean', + fix: 'the pass reruns each slot once as #2 by itself; inspect each printed KEEP: path and leave it alone (nothing attributes it to a reader, so never delete it), then write a decision-trail row and tell your Captain', + }, + FETCH_RERUN_BLOCKED: { + anchor: 'fetch-rerun-blocked', + summary: 'a path a stage\'s first attempt found still exists, so no stage of the pass, Step 11\'s voices included, dispatched a reader (one could read that path and sweep clean) and verify keeps refusing', + fix: 'stop and report the printed path to your Captain; leave it alone (nothing attributes it to a reader, so never move or delete it yourself)', + }, + FETCH_RERUN_SPENT: { + anchor: 'fetch-rerun-spent', + summary: 'the stage\'s one rerun fetched too, so the pass stopped with its readers quarantined, resuming it starts no later stage and returns no reader output, and verify refuses', + fix: 'deal with the printed paths, find out why readers keep fetching, then start a fresh pass under a new --pass and --out; a third attempt is never automatic', + }, } as const satisfies Record; diff --git a/lib/review-ledger.ts b/lib/review-ledger.ts index d010c8fb1..37a8e8c04 100644 --- a/lib/review-ledger.ts +++ b/lib/review-ledger.ts @@ -19,7 +19,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { checkReviewedTree, isReviewedTreeLine, promptHash, type TreeCheck } from './review-brief'; -export interface LedgerEvent { event: 'rendered' | 'sent' | 'output' | 'judgment' | 'judge' | 'program'; [k: string]: unknown } +export interface LedgerEvent { event: 'rendered' | 'sent' | 'output' | 'judgment' | 'judge' | 'program' | 'quarantined' | 'fetch-sweep'; [k: string]: unknown } export const readerKey = (role: string, name?: string) => (name ? `${role}/${name}` : role); export function appendEvent(ledger: string, e: LedgerEvent): void { @@ -415,9 +415,10 @@ export function ledgerBlockers(ledger: string): LedgerBlocker[] { const raws = new Map(); const readers = new Map(); const loci = new Map(); - for (const o of events.filter(e => e.event === 'output' && Array.isArray(e.ids) && e.ids.length)) { + const gone = quarantinedIds(events); + for (const o of events.filter(e => e.event === 'output' && idsOf(e).some(id => !gone.has(id)))) { const lines = jsonLines(read(o.merged, `merged file of ${String(o.reader)}`), String(o.merged)) as MergedLine[]; - for (const id of o.ids as string[]) { + for (const id of idsOf(o).filter(id => !gone.has(id))) { const line = lines.find(l => l.id === id) ?? fail(`collected id ${id} is missing from ${String(o.merged)}`); ranks.set(id, rank(line.label) ?? 0); if (statesNoBlocks(line.raw)) unblocking.set(id, rank(line.label) ?? 0); @@ -454,9 +455,16 @@ function reviewed(o: LedgerEvent, render?: LedgerEvent): boolean { } /** Every id collect recorded, in order. */ -const collectedIds = (events: LedgerEvent[]) => events.filter(e => e.event === 'output').flatMap(e => (Array.isArray(e.ids) ? (e.ids as string[]) : [])); +const idsOf = (e: LedgerEvent) => (Array.isArray(e.ids) ? (e.ids as string[]) : []); +/** Ids a fetch violation quarantined (lib/review-sweep.ts): they left merged.jsonl and no consumer of the ledger counts them. */ +export const quarantinedIds = (events: LedgerEvent[]) => new Set(events.filter(e => e.event === 'quarantined').flatMap(idsOf)); +/** Ids collect recorded, less the quarantined ones. */ +const collectedIds = (events: LedgerEvent[]) => { + const gone = quarantinedIds(events); + return events.filter(e => e.event === 'output').flatMap(idsOf).filter(id => !gone.has(id)); +}; -export interface VerifyRow { kind: 'BRIEF' | 'OUTPUT' | 'JUDGE'; reader: string; status: string; detail: string } +export interface VerifyRow { kind: 'BRIEF' | 'OUTPUT' | 'JUDGE' | 'FETCH'; reader: string; status: string; detail: string } /** Replay every check from a finished run's ledger: briefs dispatched as rendered, outputs merged as returned, judgment without loss. */ export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; briefs: number; voided: number; unavailable: number } { @@ -497,12 +505,18 @@ export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; bri let payloadNow: string | null = null; if (!overwritten && payload && typeof payload.file === 'string') { try { payloadNow = createHash('sha256').update(fs.readFileSync(payload.file)).digest('hex'); } catch { payloadNow = ''; } } const tampered = (fileNow && fileNow !== r.sha256 ? ' file_changed_since_render' : '') + (payloadNow !== null && payloadNow !== payload!.sha256 ? ' payload_changed_since_render' : ''); - rows.push({ kind: 'BRIEF', reader: p.label, status: tampered ? 'MISMATCH' : status, detail: `rendered=${short(r.sha256)} sent=${sent.map(({ e }) => short(e.sha256)).join(',') || '-'}${epVoided ? ` voided=${epVoided}` : ''}${outputs.length && !collected && !unavailable ? ' not_reviewed' : ''}${tampered}` }); + // A fetch violation quarantined this dispatch; it counts only once a later render of the same reader replaced it. + const quarantine = inside.some(({ e }) => e.event === 'quarantined') ? (p.next < events.length ? 'SUPERSEDED' : 'QUARANTINED') : null; + rows.push({ kind: 'BRIEF', reader: p.label, status: quarantine ?? (tampered ? 'MISMATCH' : status), detail: `rendered=${short(r.sha256)} sent=${sent.map(({ e }) => short(e.sha256)).join(',') || '-'}${epVoided ? ` voided=${epVoided}` : ''}${outputs.length && !collected && !unavailable ? ' not_reviewed' : ''}${tampered}${quarantine ? ' quarantined' : ''}` }); } for (const [i, o] of events.entries()) { if (o.event !== 'output') continue; const reader = String(o.reader); const p = episodes.find(q => q.reader === reader && q.at < i && i < q.next); + if (p && events.slice(i + 1, p.next).some(e => e.event === 'quarantined' && e.reader === reader)) { + rows.push({ kind: 'OUTPUT', reader: p.label, status: p.next < events.length ? 'SUPERSEDED' : 'QUARANTINED', detail: `sha=${short(o.sha256)} findings=${idsOf(o).length} quarantined` }); + continue; + } let status = 'MATCH'; const notes: string[] = []; const lastSent = p ? events.slice(p.at + 1, i).filter(e => e.event === 'sent' && e.reader === reader).at(-1) : undefined; @@ -572,6 +586,13 @@ export function verify(ledger: string): { rows: VerifyRow[]; clean: boolean; bri const status = !v.ok ? 'REJECTED' : notes.length ? 'MISMATCH' : 'OK'; rows.push({ kind: 'JUDGE', reader: '-', status, detail: `dropped=${JSON.stringify(v.dropped)} downgraded=${JSON.stringify(v.downgraded)} added=${v.added} promoted=${v.promoted} folded=${v.folded}${v.dismissed ? ` dismissed=${v.dismissed}` : ''}${notes.length ? ' ' + notes.join(' ') : ''}` }); } else if (events.some(e => e.event === 'output')) rows.push({ kind: 'JUDGE', reader: '-', status: 'MISSING', detail: 'outputs were collected but no judged set was checked' }); - const clean = episodes.length > 0 && rows.every(r => ['MATCH', 'OK', 'VOIDED', 'UNAVAILABLE'].includes(r.status)); + // Each stage sweep's verdict; a violation stays open until a later attempt of the same stage swept clean or partial. + const sweeps = events.filter(e => e.event === 'fetch-sweep'); + for (const s of sweeps) { + const resolved = s.verdict === 'violation' && sweeps.some(t => t.pass === s.pass && t.stage === s.stage && Number(t.attempt) > Number(s.attempt) && t.verdict !== 'violation'); + const found = Array.isArray(s.found) ? (s.found as Array<{ path: string }>) : []; + rows.push({ kind: 'FETCH', reader: `${String(s.pass)}/${String(s.stage)}#${String(s.attempt)}`, status: s.verdict === 'violation' ? (resolved ? 'RESOLVED' : 'VIOLATION') : String(s.verdict).toUpperCase(), detail: `found=${found.length}${found.length ? ` paths=${JSON.stringify(found.map(x => x.path))}` : ''}${s.partial ? ` partial=${JSON.stringify(s.partial)}` : ''}` }); + } + const clean = episodes.length > 0 && rows.every(r => ['MATCH', 'OK', 'VOIDED', 'UNAVAILABLE', 'SUPERSEDED', 'CLEAN', 'PARTIAL', 'RESOLVED'].includes(r.status)); return { rows, clean, briefs: episodes.length, voided, unavailable: rows.filter(r => r.kind === 'BRIEF' && r.status === 'UNAVAILABLE').length }; } diff --git a/lib/review-pass.ts b/lib/review-pass.ts index 00b14d186..cf988c4c7 100644 --- a/lib/review-pass.ts +++ b/lib/review-pass.ts @@ -21,6 +21,7 @@ import { diffCommand, type Dispatch } from './review-depth'; import { TARGETED_RULES, parseClassList, targetedBriefSha, targetedRead } from './review-targeted'; import type { FetchHit } from './review-fetch'; import type { EffectiveReaders } from './ship-policy-readers'; +import type { StageSweep } from './review-sweep'; export const STAGES = ['first', 'specialists', 'red-team', 'voices'] as const; export type Stage = typeof STAGES[number]; @@ -43,6 +44,10 @@ export interface PassReader { tree?: string | null; /** What the reader fetched, from its own tool calls (gstack-review-dispatch audit-fetch, lib/review-fetch.ts). */ fetch_audit?: { policy_digest: string; events: number; events_sha256: string; hits: FetchHit[]; verdict: 'clean' | 'violation'; enforced: boolean }; + /** A stage rerun after a fetch violation (lib/review-sweep.ts): attempt 2 of the slot, and the reader it replaced points at it. */ + attempt?: number; superseded_by?: string; + /** Set when the stage's sweep found a fetch: the reply's new home under /quarantine/; it is never merged, judged or returned. */ + quarantined?: { file: string; at: string }; path?: string; output?: string; error?: string; state_at?: string; } export interface Manifest { @@ -60,6 +65,8 @@ export interface Manifest { voices_only?: true; /** The plan's readers policy (lib/review-fetch.ts): what every brief says readers may not fetch or open; absent means the default rule. */ fetch_policy?: EffectiveReaders; + /** Each stage's fetch sweep (gstack-review-dispatch sweep): the start inventory, then the end verdict. */ + sweeps?: Partial>; } export interface FixCheckFiles { fix_list: string; hunks: string; tests: string; callers?: string } export interface Extra { name: string; prompt_file: string; first?: boolean; model?: PassModel } @@ -217,7 +224,7 @@ export function renderStage(m: Manifest, stage: Stage, t: SectionTexts, diffFor: fs.writeFileSync(file, text, { mode: 0o600 }); const sha = promptHash(text); const bytes = Buffer.byteLength(text); - appendEvent(m.ledger, { event: 'rendered', reader: r.reader, role, name: r.name ?? null, file, sha256: sha, bytes, pass: m.pass, stage, workdir, tree, ...(findingsSha ? { findings_sha256: findingsSha } : {}), ...targeted, ...slice, ...(disclosureDigest(m.disclosure) ? { exclude: disclosureDigest(m.disclosure) } : {}), ...(m.fetch_policy ? { readers: m.fetch_policy.digest } : {}) }); + appendEvent(m.ledger, { event: 'rendered', reader: readerKey(role, r.name), role, name: r.name ?? null, file, sha256: sha, bytes, pass: m.pass, stage, workdir, tree, ...(findingsSha ? { findings_sha256: findingsSha } : {}), ...targeted, ...slice, ...(disclosureDigest(m.disclosure) ? { exclude: disclosureDigest(m.disclosure) } : {}), ...(m.fetch_policy ? { readers: m.fetch_policy.digest } : {}) }); Object.assign(r, { file, sha256: sha, bytes, chunks: chunkCount(text), state: 'rendered', tree, ...(findingsSha ? { findings_sha256: findingsSha } : {}) }); done.push(r); } diff --git a/lib/review-scope.ts b/lib/review-scope.ts index ec15bce11..35cbe206d 100644 --- a/lib/review-scope.ts +++ b/lib/review-scope.ts @@ -15,7 +15,7 @@ */ import * as path from 'node:path'; import { SPECIALISTS } from './review-depth'; -import { rank, readLedger, type LedgerBlocker } from './review-ledger'; +import { quarantinedIds, rank, readLedger, type LedgerBlocker } from './review-ledger'; import { parseSpecialistOutput } from './state-matrix'; export type Locus = 'diff' | 'fix-range' | 'outside'; @@ -389,7 +389,8 @@ export function ledgerPass(ledger: string, key = (id: string) => id): LedgerPass const events = readLedger(ledger); const started = Date.parse(String(events[0]?.at ?? '')); const fixCheck = events.some(e => e.event === 'output' && e.reader === 'fix-check' && e.tree_ok !== false && ((Array.isArray(e.ids) && e.ids.length > 0) || e.review === true)); - const ids = events.flatMap(e => (e.event === 'output' && Array.isArray(e.ids) ? (e.ids as string[]) : e.event === 'judgment' && e.kind === 'added' && typeof e.id === 'string' ? [e.id] : [])).map(key); + const gone = quarantinedIds(events); + const ids = events.flatMap(e => (e.event === 'output' && Array.isArray(e.ids) ? (e.ids as string[]).filter(id => !gone.has(id)) : e.event === 'judgment' && e.kind === 'added' && typeof e.id === 'string' ? [e.id] : [])).map(key); return { started: Number.isFinite(started) ? started : NaN, fixCheck, ids, name: path.basename(path.dirname(path.resolve(ledger))), judged: events.some(e => e.event === 'judge') }; } diff --git a/lib/review-sweep.ts b/lib/review-sweep.ts new file mode 100644 index 000000000..35f371680 --- /dev/null +++ b/lib/review-sweep.ts @@ -0,0 +1,221 @@ +/** + * review-sweep — the per-stage sweep that enforces the fetch rule (GST-1322 PR B, docs/review-policy.md#what-readers-may-fetch). + * + * Capy exposes no reader's jam id, so a pass cannot read a reader's own tool calls. Instead the pass program takes an + * inventory of git repositories and big files under fixed roots before a stage's readers start, and again after the last + * of them is collected. A repository that is new and has a network remote, or a new file of BIG_BYTES or more, is a fetch + * that stage made. Attribution is per stage: every reader of the stage is quarantined (its reply moved under + * /quarantine/, its findings taken out of merged.jsonl), verify refuses, and the stage reruns once, each slot as + * `#2`. A second violation stops the pass. A sweep that hit its bounds is `partial`: a note, never a refusal. + * + * Nothing here deletes anything, and nothing prints a delete command: no transcript can attribute a path to a reader today, + * so every found path is reported as KEEP for the lane to inspect and leave alone. + */ +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { networkTarget } from './review-fetch'; +import { appendEvent, readLedger, readerKey } from './review-ledger'; +import type { Manifest, PassReader, Stage } from './review-pass'; + +export const SWEEP_DEPTH = 6; +export const SWEEP_MAX_ENTRIES = 200_000; +export const SWEEP_BUDGET_MS = 20_000; +export const BIG_BYTES = 100 * 1024 * 1024; +const SKIP = new Set(['node_modules', '.git']); +const SCP = /^(?:[\w.-]+@)?[\w.-]+:(?!\/\/)[\w./-]+$/; + +export interface Inventory { at: number; roots: string[]; repos: Record; big: Record; partial?: string } +export interface Found { path: string; kind: 'repo' | 'download'; remote?: string; bytes: number | null } +export type SweepVerdict = 'clean' | 'violation' | 'partial'; +export interface StageSweep { + attempt: number; + start?: { at: string; file: string; partial?: string }; + end?: { at: string; verdict: SweepVerdict; found: Found[]; partial?: string }; + /** Earlier attempts of this stage, newest last. */ + history?: Array>; +} + +/** The workspace (the checkout's parent), home and the temp dir, or GSTACK_SWEEP_ROOTS (path-delimited; tests); drives are never walked. */ +export const defaultRoots = (checkout: string) => process.env.GSTACK_SWEEP_ROOTS?.split(path.delimiter).filter(Boolean) ?? [path.dirname(checkout), os.homedir(), os.tmpdir()]; +export const defaultSkip = () => [path.join(os.homedir(), '.capy', 'drive')]; + +/** + * A remote URL with nothing that can carry a credential: userinfo removed and a query read as `?` + * (`https://user:PASSWORD@host/r.git#x` reads `https://host/r.git#x`). git's `[user@]host:path` form has no password and stays + * as it is. Anything else, a value the URL parser rejects included, reads ``: it is never recorded or printed raw. + */ +export function redactUrl(v: string): string { + if (SCP.test(v)) return v; + if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) return ''; + try { + const u = new URL(v); + if (!u.username && !u.password && !u.search) return v; + return `${u.protocol}//${u.host}${u.pathname}${u.search ? '?' : ''}${u.hash}`; + } catch { return ''; } +} + +/** + * Whether git would reach a remote over the network: any `scheme://` but `file:`, a `::` helper, or git's + * `[user@]host:path` form (a colon with no slash before it; one letter before it is a Windows drive). + */ +export function networkRemote(v: string): boolean { + if (/^file:/i.test(v)) return false; + return networkTarget(v) !== null || /^[a-z][a-z0-9+.-]*:(?::|\/\/)/i.test(v) || /^(?:[^@/]+@)?(?:\[[^\]/]+\]|[^/:@[]{2,}):(?!\/\/)/.test(v); +} + +/** + * A repository's network remotes as git itself reads its config (quoted values, escapes and `#` included), classified on + * the raw value and recorded only through redactUrl. + */ +function remotes(gitDir: string): string[] { + const r = spawnSync('git', ['config', '--file', path.join(gitDir, 'config'), '--null', '--get-regexp', '\\.url$'], { encoding: 'utf8', timeout: 5_000 }); + if (r.status !== 0 || !r.stdout) return []; + return r.stdout.split('\0').flatMap(e => { const i = e.indexOf('\n'); const v = e.slice(i + 1); return i >= 0 && networkRemote(v) ? [redactUrl(v)] : []; }); +} + +/** The git directory a directory holds: its `.git` (a directory, or a file naming one), or itself when it is a bare repository. */ +function gitDirOf(dir: string, names: Set): string | null { + if (names.has('.git')) { + const g = path.join(dir, '.git'); + try { + if (fs.statSync(g).isDirectory()) return g; + const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(g, 'utf8')); + return m ? path.resolve(dir, m[1]!.trim()) : null; + } catch { return null; } + } + return names.has('HEAD') && names.has('objects') && names.has('refs') ? dir : null; +} + +/** + * Git repositories (with their redacted network remotes) and files of BIG_BYTES or more under the roots, to SWEEP_DEPTH, without following + * symlinks or entering node_modules, .git or a repository other than the checkout. Past SWEEP_MAX_ENTRIES entries or + * SWEEP_BUDGET_MS the inventory stops and says so in `partial`. + */ +export function inventory(roots: readonly string[], checkout: string, skip: readonly string[] = defaultSkip(), now = Date.now()): Inventory { + const inv: Inventory = { at: now, roots: roots.map(r => realOr(r)), repos: {}, big: {} }; + const deadline = Date.now() + SWEEP_BUDGET_MS; + const home = realOr(checkout); + const seen = new Set(); + let entries = 0; + const walk = (dir: string, depth: number) => { + if (inv.partial || seen.has(dir) || skip.some(s => dir === s || dir.startsWith(s + path.sep))) return; + seen.add(dir); + let list: fs.Dirent[]; + try { list = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } + entries += list.length; + if (entries > SWEEP_MAX_ENTRIES) { inv.partial = `more than ${SWEEP_MAX_ENTRIES} entries`; return; } + if (Date.now() > deadline) { inv.partial = `past ${SWEEP_BUDGET_MS / 1000}s`; return; } + const gitDir = gitDirOf(dir, new Set(list.map(d => d.name))); + if (gitDir) { inv.repos[dir] = remotes(gitDir); if (dir !== home) return; } + for (const d of list) { + const p = path.join(dir, d.name); + if (d.isFile()) { try { const s = fs.statSync(p); if (s.size >= BIG_BYTES) inv.big[p] = s.size; } catch { /* gone */ } continue; } + if (d.isDirectory() && !SKIP.has(d.name) && depth < SWEEP_DEPTH) walk(p, depth + 1); + } + }; + for (const r of inv.roots) walk(r, 0); + return inv; +} + +function realOr(p: string): string { try { return fs.realpathSync(p); } catch { return path.resolve(p); } } +function du(p: string): number | null { + const r = spawnSync('du', ['-sk', p], { encoding: 'utf8', timeout: 10_000 }); + const kb = Number(/^(\d+)/.exec(r.stdout ?? '')?.[1]); + return r.status === 0 && Number.isFinite(kb) ? kb * 1024 : null; +} + +/** What the stage fetched: repositories new since the start inventory with a network remote, and new big files outside them. */ +export function sweepDiff(start: Inventory, end: Inventory): Found[] { + const found: Found[] = []; + for (const [p, urls] of Object.entries(end.repos)) { + const remote = urls[0]; + if (p in start.repos || !remote) continue; + found.push({ path: p, kind: 'repo', remote, bytes: du(p) }); + } + for (const [p, bytes] of Object.entries(end.big)) { + if (p in start.big || found.some(f => p.startsWith(f.path + path.sep))) continue; + found.push({ path: p, kind: 'download', bytes }); + } + return found; +} + +/** + * The end of a stage. With no start inventory, or one that stopped at its bounds, the sweep cannot tell a path the start + * never reached from a new one, so what it finds is a `partial` note, never a violation. + */ +export function sweepResult(start: Inventory | null, end: Inventory | null): { found: Found[]; verdict: SweepVerdict; partial?: string } { + const found = start && end ? sweepDiff(start, end) : []; + const partial = !start ? 'no start inventory' : start.partial ?? end?.partial; + const verdict = found.length && !start?.partial ? 'violation' : partial ? 'partial' : 'clean'; + return { found, verdict, ...(partial ? { partial } : {}) }; +} + +const q = (s: string) => `'${s.replace(/'/g, "'\\''")}'`; +const safe = (reader: string) => reader.replace(/[^a-zA-Z0-9._-]/g, '_'); + +/** + * The lines a violation prints for each found path: what it is, then KEEP (never a delete command). A path or remote with a + * control character prints JSON-quoted, so it can never start a line of its own. + */ +const control = (s: string) => /[\x00-\x1f\x7f]/.test(s); +const shownPath = (p: string) => (control(p) ? JSON.stringify(p) : q(p)); + +export function foundLines(stage: Stage, attempt: number, found: readonly Found[], readers: readonly string[]): string[] { + return found.flatMap(f => { + const unsafe = control(f.path) || control(f.remote ?? ''); + const shown = unsafe ? JSON.stringify(f.path) : q(f.path); + return [ + `FETCH_VIOLATION: stage=${stage} attempt=${attempt} kind=${f.kind} path=${shown}${f.remote ? ` remote=${unsafe ? JSON.stringify(f.remote) : f.remote}` : ''} bytes=${f.bytes ?? 'unknown'} readers=${readers.join(',')} (attributed to the stage: Capy exposes no reader id; docs/troubleshooting.md#fetch-violation)`, + `KEEP: ${shown} (no transcript attributes it to a reader: inspect it and leave it alone)`, + ]; + }); +} + +/** + * A stage's pending rerun: while a path an earlier attempt of the stage found still exists, a reader could read it and + * sweep clean, so no stage's start dispatches a reader (and the violation stays unresolved). Nothing is moved or deleted. + */ +export function rerunBlocked(stage: Stage, s: StageSweep): string[] { + const kept = (s.history ?? []).flatMap(h => (h.end?.found ?? []).map(f => ({ f, attempt: h.attempt }))).filter(({ f }) => fs.existsSync(f.path)); + return kept.map(({ f, attempt }) => `FETCH_RERUN_BLOCKED: stage=${stage} attempt=${s.attempt} path=${shownPath(f.path)} (attempt ${attempt} found it and it still exists, so no rerun reader starts beside it and verify refuses; stop and report the path to your Captain, and leave it alone; docs/troubleshooting.md#fetch-rerun-blocked)`); +} + +/** + * Quarantine every reader of the stage's current attempt: its reply moves to /quarantine/ (0600), its findings leave + * merged.jsonl, and the ledger records which ids left. On the first attempt each slot gets a planned `#2`. + */ +export function quarantineStage(m: Manifest, stage: Stage, attempt: number): { quarantined: PassReader[]; reruns: PassReader[]; lines: string[] } { + const dir = path.join(m.out, 'quarantine'); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + const quarantined = m.readers.filter(r => r.stage === stage && !r.quarantined && (r.attempt ?? 1) === attempt); + const reruns: PassReader[] = []; + const lines: string[] = []; + const events = readLedger(m.ledger); + for (const r of quarantined) { + const file = path.join(dir, `${safe(r.reader)}.txt`); + if (r.output && fs.existsSync(r.output)) { fs.renameSync(r.output, file); fs.chmodSync(file, 0o600); } + let ids: string[] = []; + if (!r.prompt_file && r.role) { + const key = readerKey(r.role, r.name); + const mine = events.filter(e => e.reader === key && (e.event === 'output' || e.event === 'rendered')); + ids = mine.slice(mine.findLastIndex(e => e.event === 'rendered') + 1).flatMap(e => (Array.isArray(e.ids) ? (e.ids as string[]) : [])); + const gone = new Set(ids); + if (gone.size && fs.existsSync(m.merged)) { + const kept = fs.readFileSync(m.merged, 'utf8').split('\n').filter(l => { if (!l.trim()) return false; try { return !gone.has((JSON.parse(l) as { id: string }).id); } catch { return true; } }); + fs.writeFileSync(m.merged, kept.map(l => l + '\n').join(''), { mode: 0o600 }); + } + appendEvent(m.ledger, { event: 'quarantined', reader: key, pass: m.pass, stage, attempt, ids, file }); + } + Object.assign(r, { quarantined: { file, at: new Date().toISOString() }, output: undefined }); + lines.push(`QUARANTINED: reader=${r.reader} file=${file} findings_removed=${ids.length}`); + if (attempt > 1) continue; + const { file: _f, sha256: _s, bytes: _b, chunks: _c, findings_sha256: _fs, tree: _t, path: _p, output: _o, error: _e, state_at: _a, quarantined: _q, fetch_audit: _fa, ...plan } = r; + const next: PassReader = { ...plan, reader: `${r.reader}#2`, title: `${r.title}#2`, state: 'planned', attempt: 2 }; + r.superseded_by = next.reader; + reruns.push(next); + } + m.readers.push(...reruns); + return { quarantined, reruns, lines }; +} diff --git a/test/review-pass.test.ts b/test/review-pass.test.ts index f039f9ba9..2cca6d6ec 100644 --- a/test/review-pass.test.ts +++ b/test/review-pass.test.ts @@ -2,7 +2,7 @@ * GSTA-167 calls PR 2: the staged pass manifest (lib/review-pass.ts), its bin commands, and the * checked-in Capy pass program (lib/capy-review-pass.js) run against a fake host whose shell is real. */ -import { describe, expect, test } from 'bun:test'; +import { afterAll, describe, expect, test } from 'bun:test'; import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; @@ -129,7 +129,7 @@ function writeManifestFile(m: Manifest): string { /** A repository on a feature branch with enough runtime lines for a full plan. */ function repo(): { dir: string; env: NodeJS.ProcessEnv } { const dir = tmp('rp-repo-'); - const env = { ...process.env, PATH: BIN + path.delimiter + process.env.PATH, GSTACK_STATE_ROOT: path.join(dir, '.state'), GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' }; + const env = { ...process.env, PATH: BIN + path.delimiter + process.env.PATH, GSTACK_STATE_ROOT: path.join(dir, '.state'), GSTACK_SWEEP_ROOTS: dir, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' }; const sh = (c: string) => { const r = spawnSync('bash', ['-c', c], { cwd: dir, env, encoding: 'utf8', timeout: 60_000 }); if (r.status !== 0) throw new Error(r.stderr); }; sh("git init -q -b main && echo '{}' > package.json && mkdir src && echo 'export const a = 1;' > src/a.ts && echo .state > .gitignore && git add -A && git commit -qm base && git checkout -qb feat"); sh('for i in $(seq 1 80); do echo "export const v$i = $i;" >> src/a.ts; done && git commit -qam feat'); @@ -1253,4 +1253,157 @@ describe('readers on a shared machine review the checkout the pass ships (GST-48 expect(v).toMatch(/^BRIEF outside-voice UNAVAILABLE /m); }, 240_000); }); + +describe('the fetch sweep quarantines a stage that fetched (GST-1322 PR B)', () => { + const clone = (at: string) => { fs.mkdirSync(at, { recursive: true }); expect(spawnSync('bash', ['-c', 'git init -q && git remote add origin https://github.com/sealed-org/BEAM.git'], { cwd: at, encoding: 'utf8', timeout: 30_000 }).status).toBe(0); }; + const made: string[] = []; + afterAll(() => { for (const d of made) fs.rmSync(d, { recursive: true, force: true }); }); + // Value: protects=a stage whose reader cloned a network repository is quarantined (reply out of merged.jsonl and the Red Team brief), reruns once as #2, and verifies clean only after the rerun sweeps clean; fails_when=the sweep runs outside the stage window, the quarantined findings reach the Red Team, or verify certifies the first attempt; + // why_new=gbrain-evals #362 (an unprompted 4.2 GB clone by a reader); seam=lib/capy-review-pass.js stage boundaries; no_claim=which reader of the stage fetched (Capy exposes no reader id) + test('a clone during the specialists stage quarantines it, blocks the rerun while the clone exists, then reruns each slot once and verifies clean', async () => { + const { dir, env } = repo(); + made.push(dir); + const out = path.join(dir, '.state/run/p1'); + const beam = path.join(dir, '.state/BEAM'); + const h = host(dir, env, { output: t => { if (t === 'ship f1p1 specialist-batched') { clone(beam); return 'High: src/a.ts:3 SEALED-QUOTE leaked from the clone'; } return 'NO FINDINGS'; } }); + const blocked = await runPass(h, { base: 'main', out, pass: 'f1p1', planFlags: ['--depth-floor', 'full'] }); + expect(blocked).toContain('FETCH_VIOLATION: stage=specialists attempt=1 kind=repo path=' + "'" + fs.realpathSync(beam) + "'"); + expect(blocked).toContain('KEEP: ' + "'" + fs.realpathSync(beam) + "'"); + expect(blocked).toMatch(/^RERUN: stage=specialists readers=\S*specialist-batched#2/m); + expect(blocked).toContain('FETCH_RERUN_BLOCKED: stage=specialists attempt=2 path=' + "'" + fs.realpathSync(beam) + "'"); + expect(h.creates.map(c => c.title)).not.toContain('ship f1p1 specialist-batched#2'); + fs.rmSync(beam, { recursive: true, force: true }); + const res = await runPass(h, { base: 'main', out, pass: 'f1p1', planFlags: ['--depth-floor', 'full'] }); + expect(res).toContain('NEXT: judge (Phase 4)'); + const m = JSON.parse(fs.readFileSync(path.join(out, 'pass-manifest.json'), 'utf8')) as Manifest; + const first = m.readers.find(r => r.reader === 'specialist-batched')!; + expect(first.superseded_by).toBe('specialist-batched#2'); + expect(fs.statSync(first.quarantined!.file).mode & 0o777).toBe(0o600); + expect(h.creates.map(c => c.title)).toContain('ship f1p1 specialist-batched#2'); + expect(fs.existsSync(m.merged) ? fs.readFileSync(m.merged, 'utf8') : '').not.toContain('SEALED-QUOTE'); + expect(h.creates.find(c => c.title === 'ship f1p1 red-team')!.prompt).not.toContain('SEALED-QUOTE'); + expect(res).not.toContain('SEALED-QUOTE'); + expect(m.sweeps?.specialists).toMatchObject({ attempt: 2, end: { verdict: 'clean' } }); + expect(bin(dir, env, ['judge', '--ledger', m.ledger, '--merged', m.merged, '--judged', path.join(out, 'judged.jsonl')]).status).toBe(0); + const v = bin(dir, env, ['verify', '--ledger', m.ledger]); + expect(v.stdout).toMatch(/^FETCH f1p1\/specialists#1 RESOLVED found=1/m); + expect(v.stdout).toMatch(/^BRIEF specialist-batched SUPERSEDED .* quarantined$/m); + expect(v.stdout, v.stdout).toContain('VERIFY: clean'); + }, 240_000); + + // Value: protects=a rerun reader can never read what attempt 1 fetched and sweep clean: while any path attempt 1 found exists, the rerun dispatches no reader and verify keeps refusing; + // fails_when=the #2 readers start beside the kept clone, sweep clean, and their findings (read from the clone) reach merged.jsonl with verify RESOLVED; why_new=ship-c-p1 red-team#2 (CRITICAL; the Captain's ruling C on #4011); + // seam=gstack-review-dispatch sweep --phase start; no_claim=that the kept path is safe to keep + test('a rerun reader cannot open attempt 1\'s kept clone: the rerun start refuses, dispatches nothing and verify stays dirty', async () => { + const { dir, env } = repo(); + made.push(dir); + const out = path.join(dir, '.state/run/p1'); + const beam = path.join(dir, '.state/BEAM'); + const h = host(dir, env, { output: t => { if (t === 'ship f3p1 specialist-batched') clone(beam); if (t === 'ship f3p1 specialist-batched#2' && fs.existsSync(beam)) return 'High: src/a.ts:3 SEALED-QUOTE read from the kept clone'; return 'NO FINDINGS'; } }); + let res = await runPass(h, { base: 'main', out, pass: 'f3p1', planFlags: ['--depth-floor', 'full'] }); + for (let i = 0; i < 4 && res.includes('NEXT: poll'); i++) res = await runPass(h, { base: 'main', out, pass: 'f3p1', planFlags: ['--depth-floor', 'full'] }); + const kept = fs.realpathSync(beam); + expect(res).toContain("FETCH_RERUN_BLOCKED: stage=specialists attempt=2 path='" + kept + "'"); + expect(res).toMatch(/STOP: gstack-review-dispatch sweep --stage specialists --phase start exited 3/); + expect(res).not.toContain('NEXT: judge'); + expect(res).not.toContain('SEALED-QUOTE'); + expect(h.creates.map(c => c.title)).not.toContain('ship f3p1 specialist-batched#2'); + expect(fs.existsSync(beam)).toBe(true); + const m = JSON.parse(fs.readFileSync(path.join(out, 'pass-manifest.json'), 'utf8')) as Manifest; + expect(fs.existsSync(m.merged) ? fs.readFileSync(m.merged, 'utf8') : '').not.toContain('SEALED-QUOTE'); + const v = bin(dir, env, ['verify', '--ledger', m.ledger]); + expect(v.status).toBe(1); + expect(v.stdout).toMatch(/^FETCH_VIOLATION: f3p1\/specialists#1 found=1/m); + expect(v.stdout).toContain('VERIFY: dirty'); + }, 240_000); + + // Value: protects=a fetch on the stage's one rerun stops the pass and verify refuses with FETCH_VIOLATION; a path that holds an older one is reported, never given a delete command; fails_when=the program reruns again, returns NEXT: judge, or prints rm -rf for the sweep root; + // why_new=GST-1322 d3 (no unattended rm -rf) and d5 (one rerun per slot); seam=gstack-review-dispatch sweep --phase end; no_claim=who created the reported path + test('a fetch on the rerun stops the pass, verify refuses, and a root-level repository gets KEEP, never a delete command', async () => { + const { dir, env } = repo(); + made.push(dir); + const out = path.join(dir, '.state/run/p1'); + const h = host(dir, env, { output: t => { if (t === 'ship f2p1 specialist-batched') clone(path.join(dir, '.state/BEAM')); if (t === 'ship f2p1 specialist-batched#2') clone(path.join(dir, '.state')); return 'NO FINDINGS'; } }); + let res = await runPass(h, { base: 'main', out, pass: 'f2p1', planFlags: ['--depth-floor', 'full'] }); + expect(res).toContain('FETCH_RERUN_BLOCKED: stage=specialists attempt=2'); + fs.rmSync(path.join(dir, '.state/BEAM'), { recursive: true, force: true }); + res = await runPass(h, { base: 'main', out, pass: 'f2p1', planFlags: ['--depth-floor', 'full'] }); + for (let i = 0; i < 4 && res.includes('NEXT: poll'); i++) res = await runPass(h, { base: 'main', out, pass: 'f2p1', planFlags: ['--depth-floor', 'full'] }); + expect(res).toContain('FETCH_RERUN_SPENT: stage=specialists'); + expect(res).toMatch(/STOP: gstack-review-dispatch sweep --stage specialists --phase end exited 3/); + expect(res).not.toContain('NEXT: judge'); + const state = fs.realpathSync(path.join(dir, '.state')); + expect(res).toContain("KEEP: '" + state + "' (no transcript attributes it to a reader"); + expect(res).not.toContain("rm -rf -- '" + state + "'"); + expect(h.creates.filter(c => c.title.endsWith('#3'))).toHaveLength(0); + expect(h.creates.some(c => c.title === 'ship f2p1 red-team')).toBe(false); + const m = JSON.parse(fs.readFileSync(path.join(out, 'pass-manifest.json'), 'utf8')) as Manifest; + const v = bin(dir, env, ['verify', '--ledger', m.ledger]); + expect(v.status).toBe(1); + expect(v.stdout).toMatch(/^FETCH_VIOLATION: f2p1\/specialists#2 found=1/m); + expect(v.stdout).toContain('VERIFY: dirty'); + }, 240_000); + + // Value: protects=once a stage's rerun fetched too, resuming the same pass dispatches no later stage and returns no reader output; + // fails_when=the resumed program skips the recorded end, dispatches the Red Team beside the kept clone and returns NEXT: judge; why_new=ship-c-p1 outside-voice#2 (High; the Captain's grant on #4011); + // seam=lib/capy-review-pass.js stage selection; no_claim=that the kept path is safe to keep + test('resuming after FETCH_RERUN_SPENT stops before any later stage starts', async () => { + const { dir, env } = repo(); + made.push(dir); + const out = path.join(dir, '.state/run/p1'); + const input = { base: 'main', out, pass: 'f4p1', planFlags: ['--depth-floor', 'full'] }; + const h = host(dir, env, { output: t => { if (t === 'ship f4p1 specialist-batched') clone(path.join(dir, '.state/BEAM')); if (t === 'ship f4p1 specialist-batched#2') clone(path.join(dir, '.state/BEAM2')); if (t === 'ship f4p1 red-team') return 'High: src/a.ts:3 SEALED-QUOTE read beside the kept clone'; return 'NO FINDINGS'; } }); + let res = await runPass(h, input); + expect(res).toContain('FETCH_RERUN_BLOCKED: stage=specialists attempt=2'); + fs.rmSync(path.join(dir, '.state/BEAM'), { recursive: true, force: true }); + res = await runPass(h, input); + for (let i = 0; i < 4 && res.includes('NEXT: poll'); i++) res = await runPass(h, input); + expect(res).toContain('FETCH_RERUN_SPENT: stage=specialists'); + const again = await runPass(h, input); + expect(again).toMatch(/STOP: .*FETCH_RERUN_SPENT/); + expect(again).not.toContain('NEXT: judge'); + expect(again).not.toContain('SEALED-QUOTE'); + expect(h.creates.some(c => c.title === 'ship f4p1 red-team')).toBe(false); + }, 240_000); + + // Value: protects=while a path an earlier attempt found still exists, no reader of any stage, Step 11's voices included, starts beside it; + // fails_when=the voices run on the same manifest dispatches its readers beside the kept clone while the specialists rerun is blocked; why_new=ship-c-p1 outside-voice#2 (High; the Captain's grant on #4011); + // seam=gstack-review-dispatch sweep --phase start; no_claim=that the kept path is safe to keep + test('Step 11 voices dispatch nothing while another stage\'s rerun is blocked by a kept clone', async () => { + const { dir, env } = repo(); + made.push(dir); + const out = path.join(dir, '.state/run/p1'); + const base = { base: 'main', out, pass: 'f5p1', planFlags: ['--depth-floor', 'full'] }; + const h = host(dir, env, { output: t => { if (t === 'ship f5p1 specialist-batched') clone(path.join(dir, '.state/BEAM')); return 'NO FINDINGS'; } }); + expect(await runPass(h, base)).toContain('FETCH_RERUN_BLOCKED: stage=specialists attempt=2'); + const before = h.creates.length; + const models = { 'outside-voice': { model_id: 'openai/gpt-6.1-sol' }, 'adversarial-native': { model_id: 'anthropic/claude-opus-5-5', reasoning_mode: 'high' } }; + const res = await runPass(h, { ...base, stage: 'voices', models }); + expect(res).toContain("FETCH_RERUN_BLOCKED: stage=specialists attempt=2 path='" + fs.realpathSync(path.join(dir, '.state/BEAM')) + "'"); + expect(res).toMatch(/STOP: gstack-review-dispatch sweep --stage voices --phase start exited 3/); + expect(h.creates.length).toBe(before); + }, 240_000); +// Value: protects=a remote URL git writes quoted (one holding '#') with credentials never reaches the printed FETCH_VIOLATION, the start inventory, the manifest or the ledger, while a remote without userinfo prints exactly as configured; + // fails_when=the sweep scans raw config text, so the quoted value skips the userinfo strip and FAKETOKEN is printed and recorded; why_new=ship-c-v2 outside-voice#1 (High, lib/review-sweep.ts:45; GSTA-297 on #4011); + // seam=lib/review-sweep.ts remotes (git config --null); no_claim=that other tools print remotes safely + test('a quoted remote URL with userinfo prints and records without it; a remote without userinfo prints unchanged', async () => { + const { dir, env } = repo(); + made.push(dir); + const out = path.join(dir, '.state/run/p1'); + const FAKE = 'FAKETOKEN'; + const OLD = 'FAKETOKEN-old'; + const at = (p: string, url: string) => { fs.mkdirSync(p, { recursive: true }); expect(spawnSync('bash', ['-c', 'git init -q && git remote add origin "$1"', '_', url], { cwd: p, encoding: 'utf8', timeout: 30_000 }).status).toBe(0); }; + at(path.join(dir, '.state/OLD'), `https://ci-bot:${OLD}@github.com/me/old.git#main`); + expect(fs.readFileSync(path.join(dir, '.state/OLD/.git/config'), 'utf8')).toContain(`url = "https://ci-bot:${OLD}@github.com/me/old.git#main"`); + const h = host(dir, env, { output: t => { if (t === 'ship f6p1 specialist-batched') { at(path.join(dir, '.state/BEAM'), `https://bot:${FAKE}@github.com/sealed-org/BEAM.git#x`); at(path.join(dir, '.state/PLAIN'), 'https://github.com/sealed-org/PLAIN.git#x'); } return 'NO FINDINGS'; } }); + const res = await runPass(h, { base: 'main', out, pass: 'f6p1', planFlags: ['--depth-floor', 'full'] }); + expect(res).toMatch(/^FETCH_VIOLATION: stage=specialists attempt=1 kind=repo path='[^']*\/BEAM' remote=https:\/\/github\.com\/sealed-org\/BEAM\.git#x bytes=/m); + expect(res).toMatch(/^FETCH_VIOLATION: stage=specialists attempt=1 kind=repo path='[^']*\/PLAIN' remote=https:\/\/github\.com\/sealed-org\/PLAIN\.git#x bytes=/m); + const m = JSON.parse(fs.readFileSync(path.join(out, 'pass-manifest.json'), 'utf8')) as Manifest; + const inventories = fs.readdirSync(path.join(out, 'sweep')).map(f => fs.readFileSync(path.join(out, 'sweep', f), 'utf8')); + expect(inventories.join('')).toContain('https://github.com/me/old.git#main'); + const v = bin(dir, env, ['verify', '--ledger', m.ledger]); + for (const text of [res, v.stdout, ...inventories, fs.readFileSync(m.ledger, 'utf8'), fs.readFileSync(path.join(out, 'pass-manifest.json'), 'utf8')]) expect(text).not.toMatch(/FAKETOKEN|ci-bot|bot:/); + }, 240_000); +}); const briefDirOf = (h: ReturnType, title: string) => briefDir(h.creates.find(c => c.title === title)?.prompt ?? ''); diff --git a/test/review-sweep.test.ts b/test/review-sweep.test.ts new file mode 100644 index 000000000..eb9ab53f8 --- /dev/null +++ b/test/review-sweep.test.ts @@ -0,0 +1,194 @@ +/** + * GST-1322 PR B: the per-stage inventory-diff sweep (lib/review-sweep.ts) that enforces the fetch rule. + */ +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { BIG_BYTES, foundLines, inventory, networkRemote, quarantineStage, redactUrl, sweepDiff, sweepResult } from '../lib/review-sweep'; +import { collect, ledgerBlockers } from '../lib/review-ledger'; +import { ledgerPass } from '../lib/review-scope'; +import type { Manifest } from '../lib/review-pass'; +import { RELEASE_RESULT_CODES } from '../lib/result-codes-release'; + +const made: string[] = []; +const FAKE = 'FAKETOKEN'; +const tmp = () => { const d = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'sweep-'))); made.push(d); return d; }; +afterAll(() => { for (const d of made) fs.rmSync(d, { recursive: true, force: true }); }); +const repoAt = (dir: string, remote?: string) => { + fs.mkdirSync(dir, { recursive: true }); + const r = spawnSync('bash', ['-c', 'git init -q' + (remote ? ' && git remote add origin "$1"' : ''), '_', remote ?? ''], { cwd: dir, encoding: 'utf8', timeout: 30_000 }); + expect(r.status, r.stderr).toBe(0); +}; + +describe('review-sweep inventory diff', () => { + // Value: protects=only a new repository with a network remote, or a new big file, counts as a fetch; a local clone, a file:// remote and anything present at the start do not; fails_when=the diff flags local work or misses a network clone or a download; + // why_new=GST-1322 PR B (Capy exposes no reader transcript, so the sweep is the enforcement); seam=none; no_claim=which reader made the path + test('a new network repository and a new big file are found; local and pre-existing repositories are not', async () => { + const root = tmp(); + const checkout = path.join(root, 'checkout'); + repoAt(checkout, 'https://github.com/me/app.git'); + repoAt(path.join(root, 'old'), 'https://github.com/x/old.git'); + const start = inventory([root], checkout, []); + await Bun.sleep(30); + repoAt(path.join(root, 'BEAM'), 'https://github.com/sealed-org/BEAM.git'); + repoAt(path.join(root, 'scp'), 'git@github.com:sealed-org/BEAM.git'); + repoAt(path.join(root, 'scp-nouser'), 'github.com:sealed-org/BEAM.git'); + repoAt(path.join(root, 'local')); + repoAt(path.join(root, 'filecopy'), 'file:///srv/mirror/app.git'); + repoAt(path.join(checkout, 'vendor', 'nested'), 'https://example.com/n.git'); + fs.mkdirSync(path.join(root, 'dl')); + fs.writeFileSync(path.join(root, 'dl', 'chats.tar'), ''); + fs.truncateSync(path.join(root, 'dl', 'chats.tar'), BIG_BYTES); + const found = sweepDiff(start, inventory([root], checkout, [])); + expect(found.map(f => [path.relative(root, f.path), f.kind]).sort()).toEqual([ + ['BEAM', 'repo'], ['checkout/vendor/nested', 'repo'], ['dl/chats.tar', 'download'], ['scp', 'repo'], ['scp-nouser', 'repo'], + ]); + expect(found.find(f => f.path.endsWith('scp-nouser'))!.remote).toBe('github.com:sealed-org/BEAM.git'); + expect(found.find(f => f.path.endsWith('BEAM'))!.remote).toBe('https://github.com/sealed-org/BEAM.git'); + }); + + // Value: protects=no found path gets a delete command, including one the start inventory missed or one holding the checkout (GST-1322 d3); fails_when=any of them gets rm -rf; + // why_new=GST-1322 autoplan Critical d3 (no unattended rm -rf); seam=none; no_claim=that a KEEP path is safe to keep + test('a path older than the start, a root, or a parent of the checkout gets KEEP, never DELETE', async () => { + const root = tmp(); + const checkout = path.join(root, 'ws', 'checkout'); + repoAt(checkout); + repoAt(path.join(root, 'missed'), 'https://github.com/x/missed.git'); + await Bun.sleep(30); + const start = inventory([root], checkout, []); + delete start.repos[path.join(root, 'missed')]; + repoAt(path.join(root, 'ws'), 'https://github.com/x/ws.git'); + const found = sweepDiff(start, inventory([root], checkout, [])); + expect(found.map(f => path.relative(root, f.path)).sort()).toEqual(['missed', 'ws']); + const lines = foundLines('specialists', 1, found, ['specialist/security']); + expect(lines.filter(l => l.startsWith('DELETE:'))).toEqual([]); + expect(lines.filter(l => l.startsWith('KEEP:'))).toHaveLength(2); + expect(lines[0]).toMatch(/^FETCH_VIOLATION: stage=specialists attempt=1 kind=repo .* readers=specialist\/security \(attributed to the stage/); + }); + + // Value: protects=a start walk that stopped at its bounds cannot tell a repository it never reached from a new one, so what the end walk finds past it is a note, never a quarantine; + // fails_when=a partial start turns pre-existing repositories into FETCH_VIOLATION and FETCH_RERUN_SPENT on runs where nobody fetched; why_new=ship-c-p1 specialist-batched#1 (CRITICAL); seam=sweepResult; no_claim=that a partial sweep sees every fetch + test('a partial start inventory makes what the end walk finds a partial note, not a violation', () => { + const root = tmp(); + const checkout = path.join(root, 'checkout'); + repoAt(checkout); + repoAt(path.join(root, 'old'), 'https://github.com/x/old.git'); + const start = { ...inventory([root], checkout, []), partial: 'past 20s' }; + delete start.repos[path.join(root, 'old')]; + const end = inventory([root], checkout, []); + expect(sweepDiff(start, end).map(f => path.relative(root, f.path))).toEqual(['old']); + const r = sweepResult(start, end); + expect([r.verdict, r.partial, r.found.length]).toEqual(['partial', 'past 20s', 1]); + expect(sweepResult({ ...start, partial: undefined }, end).verdict).toBe('violation'); + expect(sweepResult(null, null)).toEqual({ found: [], verdict: 'partial', partial: 'no start inventory' }); + }); +}); + +describe('review-sweep quarantine and printed paths (GST-1322 PR B /ship pass 1)', () => { + // Value: protects=a quarantined reader's findings leave every consumer of the ledger's ids, so review-scope summary (REVIEW_LOOP) still runs after a fetch violation; + // fails_when=ledgerBlockers throws "collected id … is missing from merged.jsonl" or ledgerPass still counts the quarantined ids; why_new=ship-b-p1 red-team#1 (CRITICAL, reproduced); + // seam=collect, quarantineStage, ledgerBlockers, ledgerPass; no_claim=that the rerun's findings are judged + test('a quarantined reader with a CRITICAL leaves ledgerBlockers and ledgerPass', () => { + const out = tmp(); + const ledger = path.join(out, 'review-ledger.jsonl'); + const merged = path.join(out, 'merged.jsonl'); + const reply = path.join(out, 'security.txt'); + fs.writeFileSync(reply, '1. **CRITICAL**: a.ts:3 leaks a token\nBlocks: yes\n'); + const c = collect(ledger, 'specialist/security', fs.readFileSync(reply, 'utf8'), merged, reply); + expect(c.lines.map(l => l.id)).toEqual(['specialist/security#1']); + expect(ledgerBlockers(ledger).map(b => b.id)).toEqual(['specialist/security#1']); + const m = { pass: 'p1', out, ledger, merged, readers: [{ reader: 'specialist/security', role: 'specialist', name: 'security', title: 'security', stage: 'specialists', state: 'collected', output: reply }] } as unknown as Manifest; + quarantineStage(m, 'specialists', 1); + expect(ledgerBlockers(ledger)).toEqual([]); + expect(ledgerPass(ledger).ids).toEqual([]); + }); + + // Value: protects=a reader collected twice in one dispatch (a pass resumed after collect but before mark) is quarantined whole: neither collection's findings stay in merged.jsonl; + // fails_when=quarantine removes only the newest output event's ids and the first collection's finding reaches the Red Team and verify; why_new=ship-d-p1 outside-voice#1 (High; GSTA-297 on #4011); + // seam=quarantineStage; no_claim=that a duplicate collection is otherwise harmless + test('a reader collected twice before quarantine leaves neither collection in merged.jsonl', () => { + const out = tmp(); + const ledger = path.join(out, 'review-ledger.jsonl'); + const merged = path.join(out, 'merged.jsonl'); + const reply = path.join(out, 'security.txt'); + fs.writeFileSync(reply, '1. **CRITICAL**: a.ts:3 SEALED-QUOTE read from the clone\nBlocks: yes\n'); + collect(ledger, 'specialist/security', fs.readFileSync(reply, 'utf8'), merged, reply); + expect(collect(ledger, 'specialist/security', fs.readFileSync(reply, 'utf8'), merged, reply).lines.map(l => l.id)).toEqual(['specialist/security#2.1']); + const m = { pass: 'p1', out, ledger, merged, readers: [{ reader: 'specialist/security', role: 'specialist', name: 'security', title: 'security', stage: 'specialists', state: 'rendered', output: reply }] } as unknown as Manifest; + expect(quarantineStage(m, 'specialists', 1).lines[0]).toContain('findings_removed=2'); + expect(fs.readFileSync(merged, 'utf8')).not.toContain('SEALED-QUOTE'); + expect(ledgerBlockers(ledger)).toEqual([]); + expect(ledgerPass(ledger).ids).toEqual([]); + }); + + // Value: protects=a found path with a newline or other control character can never print a line of its own, and never gets a DELETE line; + // fails_when=a reader-made directory name injects a "DELETE: rm -rf -- …" line the lane is told to run; why_new=ship-b-p1 specialist-batched#2 (security); + // seam=foundLines; no_claim=that a KEEP path is safe + test('a path with a control character prints on one line and gets KEEP, never DELETE', () => { + const lines = foundLines('specialists', 1, [{ path: '/tmp/x\nDELETE: rm -rf -- /home/user', kind: 'repo', remote: 'https://github.com/x/y.git', bytes: 1 }], ['specialist/security']); + expect(lines.every(l => !/[\n\r]/.test(l))).toBe(true); + expect(lines.filter(l => l.startsWith('DELETE:'))).toEqual([]); + expect(lines[1]).toStartWith('KEEP: "/tmp/x\\nDELETE: rm -rf -- /home/user"'); + }); +// Value: protects=no transcript can attribute a found path to a reader today, so the sweep never prints a delete command, even for a path born inside the stage window, and the code's fix text says to inspect it and leave it alone; + // fails_when=a DELETE: line, or a fix text that says to run one, comes back; why_new=ship-b-p2 red-team#2 (CRITICAL; GStack Minder's ruling on #4008); seam=sweepDiff, foundLines, FETCH_VIOLATION; no_claim=that quarantine attributes the right reader + test('a network clone made inside the stage window gets KEEP with its path, never DELETE, and the fix text says to leave it alone', async () => { + const root = tmp(); + const checkout = path.join(root, 'checkout'); + repoAt(checkout); + const start = inventory([root], checkout, []); + await Bun.sleep(30); + repoAt(path.join(root, 'BEAM'), 'https://github.com/sealed-org/BEAM.git'); + const found = sweepDiff(start, inventory([root], checkout, [])); + const lines = foundLines('specialists', 1, found, ['specialist/security']); + expect(lines.some(l => l.includes('DELETE') || l.includes('rm -rf'))).toBe(false); + expect(lines[1]).toStartWith(`KEEP: '${path.join(root, 'BEAM')}'`); + const fix = RELEASE_RESULT_CODES.FETCH_VIOLATION.fix; + expect([fix.includes('DELETE'), /inspect/.test(fix), /leave it alone/.test(fix)]).toEqual([false, true, true]); + }); + + // Value: protects=a clone whose remote URL carries credentials (https://user:PASSWORD@host/…) never puts them in a FETCH_VIOLATION line, the found record verify replays, or the start inventory; + // fails_when=the sweep prints or records the remote verbatim and the token reaches the transcript; why_new=ship-c-p1 outside-voice#1 (High; the Captain's grant on #4011); seam=remotes, sweepDiff, foundLines; no_claim=that other tools print remotes safely + test('a remote with user:token@ prints and records without its userinfo', async () => { + const root = tmp(); + const checkout = path.join(root, 'checkout'); + repoAt(checkout, `https://ci-bot:${FAKE}@github.com/me/app.git`); + const start = inventory([root], checkout, []); + await Bun.sleep(30); + repoAt(path.join(root, 'BEAM'), `https://x-access-token:${FAKE}@github.com/sealed-org/BEAM.git`); + const end = inventory([root], checkout, []); + const found = sweepDiff(start, end); + const lines = foundLines('specialists', 1, found, ['specialist/security']); + expect(lines[0]).toContain(' remote=https://github.com/sealed-org/BEAM.git '); + expect(JSON.stringify([start, end, found, lines])).not.toMatch(/FAKETOKEN|ci-bot|x-access-token/); + }); +// Value: protects=a remote value that is not a URL (or git's user@host:path form) is recorded and printed as , never raw; + // fails_when=an unparseable value with credentials (a git transport form, a broken authority) is stored verbatim; why_new=GSTA-297 (fail-closed redaction on #4011); seam=redactUrl; no_claim=that remotes are detected as network clones + test('remote values redact fail-closed: userinfo and query go, unparseable values read , plain URLs and scp forms stay', () => { + expect(redactUrl(`https://bot:${FAKE}@github.com/sealed-org/BEAM.git#x`)).toBe('https://github.com/sealed-org/BEAM.git#x'); + expect(redactUrl('https://FAKETOKEN@github.com/x/y.git')).toBe('https://github.com/x/y.git'); + expect(redactUrl(`ssh://git:${FAKE}@example.com:2222/x/y.git`)).toBe('ssh://example.com:2222/x/y.git'); + expect(redactUrl('https://github.com/x/y.git?private_token=FAKETOKEN')).toBe('https://github.com/x/y.git?'); + expect(redactUrl(`persistent-https::https://bot:${FAKE}@github.com/x/y.git`)).toBe(''); + expect(redactUrl(`https://bot:${FAKE}@x@[bad/x`)).toBe(''); + expect(redactUrl('/srv/mirror/app.git')).toBe(''); + for (const plain of ['https://github.com/sealed-org/BEAM.git', 'https://github.com/sealed-org/PLAIN.git#x', 'git@github.com:sealed-org/BEAM.git', 'github.com:sealed-org/BEAM.git', 'file:///srv/mirror/app.git']) expect(redactUrl(plain)).toBe(plain); + }); + + // Value: protects=a remote is classified as network on its raw value, so a form redaction shows as still counts as a fetch; + // fails_when=a clone whose remote is `user@host:~/repo`, `host:path`, `[::1]:path`, a `::` helper or an unlisted scheme is treated as local; why_new=ship-d-p1 outside-voice#2 (High) and adversarial-native#5; seam=networkRemote, remotes; no_claim=that every git transport is listed + test('remotes are classified on the raw value: every ssh, helper and scheme form is network, local paths and file: are not', async () => { + for (const net of ['github.com:sealed-org/BEAM.git', 'git@host:~/repo', `bot:${FAKE}@host:r.git`, '[::1]:r.git', 'persistent-https::https://github.com/x/y.git', 'git+ssh://host/r.git', 'https://github.com/x/y.git']) expect([net, networkRemote(net)]).toEqual([net, true]); + for (const local of ['/srv/mirror/app.git', '../app.git', './a:b', 'C:/repos/app.git', 'file:///srv/mirror/app.git', 'FILE:/x']) expect([local, networkRemote(local)]).toEqual([local, false]); + const root = tmp(); + const checkout = path.join(root, 'checkout'); + repoAt(checkout); + const start = inventory([root], checkout, []); + await Bun.sleep(30); + repoAt(path.join(root, 'tilde'), `bot:${FAKE}@host:~/sealed.git`); + const found = sweepDiff(start, inventory([root], checkout, [])); + expect(found.map(f => [path.relative(root, f.path), f.remote])).toEqual([['tilde', '']]); + }); +});