@popovych.co/witness 0.26.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +9 -4
  2. package/dist/battery.js +2 -1
  3. package/dist/cli.js +22 -2
  4. package/dist/contain.js +132 -0
  5. package/dist/deferral.js +5 -4
  6. package/dist/design.js +534 -1
  7. package/dist/drift.js +2 -1
  8. package/dist/drive-presence.js +5 -0
  9. package/dist/drive.js +24 -8
  10. package/dist/gate.js +155 -46
  11. package/dist/gates/decompose.js +1 -0
  12. package/dist/gates/design.js +6 -9
  13. package/dist/gates/implement.js +3 -0
  14. package/dist/gates/plan.js +1 -0
  15. package/dist/gates/ship.js +1 -0
  16. package/dist/harness.js +13 -4
  17. package/dist/review.js +74 -0
  18. package/dist/reviewer.js +12 -3
  19. package/dist/rounds.js +7 -2
  20. package/dist/runner-lock.js +12 -0
  21. package/dist/runner.js +40 -5
  22. package/dist/spawn.js +1 -1
  23. package/dist/verbs/next.js +1 -1
  24. package/dist/verbs/read.js +5 -1
  25. package/dist/verbs/review.js +127 -0
  26. package/dist/verbs/turn.js +46 -0
  27. package/package.json +1 -1
  28. package/plugin/.claude-plugin/plugin.json +1 -1
  29. package/plugin/commands/witness.md +4 -2
  30. package/plugin/hooks/session-dashboard.sh +3 -1
  31. package/plugin/skills/witness-brainstorm/SKILL.md +1 -1
  32. package/plugin/skills/witness-decompose/SKILL.md +1 -1
  33. package/plugin/skills/witness-design/SKILL.md +20 -5
  34. package/plugin/skills/witness-implement/SKILL.md +5 -3
  35. package/plugin/skills/witness-plan/SKILL.md +2 -2
  36. package/plugin/skills/witness-ship/SKILL.md +4 -2
  37. package/prompts/arbiter.md +1 -1
  38. package/prompts/code-reviewer.md +4 -2
  39. package/prompts/design-critic.md +8 -4
  40. package/prompts/design-reviewer.md +4 -2
  41. package/prompts/drift-reviewer.md +5 -3
  42. package/prompts/plan-critic.md +5 -3
  43. package/prompts/pr-test.md +4 -2
  44. package/prompts/silent-failure-hunter.md +4 -2
  45. package/prompts/slicing-critic.md +5 -3
  46. package/prompts/type-design.md +4 -2
package/dist/gate.js CHANGED
@@ -11,13 +11,13 @@ import { criteriaOwner, loadCanon, findById } from './scan.js';
11
11
  import { deferralsBlock, openDeferrals } from './deferral.js';
12
12
  import { newRunId } from './drift.js';
13
13
  import { resolveJudge } from './harness.js';
14
- import { ok, renderRefusal, v } from './refusal.js';
15
- import { cmd, kv, rows } from './toon.js';
14
+ import { ok, refuse, renderRefusal, v } from './refusal.js';
15
+ import { cmd, kv, logSafe, rows } from './toon.js';
16
16
  import { stageModel, unansweredPin } from './model.js';
17
- import { docKeysFor, docsBlock, loadLensDocs, pinsBlock, promptsSha, resolvePrompt } from './reviewer.js';
17
+ import { docKeysFor, docsBlock, loadLensDocs, pinsBlock, promptsSha, resolvePrompt, } from './reviewer.js';
18
18
  import { runBattery } from './battery.js';
19
19
  import { anchorFromKey, anchorKey, anchorMenu } from './verdict.js';
20
- import { basisSha, deltaBlock, demote, demotionsBlock, outstandingDemotions, planDelta, reportedBy } from './delta.js';
20
+ import { basisSha, deltaBlock, demote, demotionsBlock, outstandingDemotions, planDelta, reportedBy, } from './delta.js';
21
21
  import { ROUND_BOUND, appendKind, boundReached, lastGateRun, liveExits, roundBudget, roundsSinceApprove, runsSinceReset, } from './rounds.js';
22
22
  export { liveExits } from './rounds.js';
23
23
  import { gateSettled, owedRun } from './verbs/next.js';
@@ -28,6 +28,138 @@ import { reportHandover, slicesLine } from './slice.js';
28
28
  const GATES = new Map();
29
29
  export function registerGate(spec) { GATES.set(spec.gate, spec); }
30
30
  export function gateSpec(name) { return GATES.get(name); }
31
+ // Row 216. What a lens at a gate reads: its override's kind, else the gate's. Undefined for a
32
+ // gate nobody registered.
33
+ export function readsOf(gate, lens) {
34
+ const spec = GATES.get(gate);
35
+ if (!spec)
36
+ return undefined;
37
+ return (lens !== undefined ? spec.lensReads?.[lens] : undefined) ?? spec.reads;
38
+ }
39
+ // Row 216. The declaration is checked against what `resolve` actually handed over: a gate whose
40
+ // content and declaration disagree would ask the wrong lenses about debts, so it is a witness
41
+ // bug and fails loudly, before any lens runs.
42
+ export function assertReads(spec, reviewed, overrides) {
43
+ if (reviewed.kind !== spec.reads) {
44
+ throw new Error(`gate ${spec.gate} declares it reads ${spec.reads}, but resolve handed over ${reviewed.kind}`);
45
+ }
46
+ for (const [lens, ov] of Object.entries(overrides ?? {})) {
47
+ if (ov.reviewed !== undefined && ov.reviewed.kind !== spec.lensReads?.[lens]) {
48
+ throw new Error(`gate ${spec.gate} declares ${lens} reads ${String(spec.lensReads?.[lens])}, but its override hands over ${ov.reviewed.kind}`);
49
+ }
50
+ }
51
+ }
52
+ // Row 216 (K2). A debt is of the kinds its raising lenses read, which neither a move nor a rename
53
+ // changes: find the stream that minted it, the round there that raised it, and what each lens
54
+ // with a blocking finding at its anchor read. `home` is the stream being judged — an unmoved
55
+ // debt's minting stream, read from the entries in hand because `rename` leaves `artifact` stale.
56
+ // A moved debt is walked back through each stream's FIRST entry for it, which names where it
57
+ // arrived from: a take-back hands a debt home to a stream it already visited. Anything that will
58
+ // not read, repeats or is missing falls back to the minting gate's kind.
59
+ export function debtKinds(root, d, home) {
60
+ const fallback = () => { const k = readsOf(d.gate); return k === undefined ? [] : [k]; };
61
+ try {
62
+ let minting = home;
63
+ if (d.moved_from !== undefined) {
64
+ const seen = new Set();
65
+ let stream = d.moved_from;
66
+ for (;;) {
67
+ if (seen.has(stream))
68
+ return fallback();
69
+ seen.add(stream);
70
+ const entries = readStream(root, stream);
71
+ const first = entries.find((e) => e.t === 'deferral' && e.id === d.id);
72
+ if (first === undefined)
73
+ return fallback();
74
+ if (first.moved_from === undefined) {
75
+ minting = entries;
76
+ break;
77
+ }
78
+ stream = first.moved_from;
79
+ }
80
+ }
81
+ const round = minting.find((e) => e.t === 'gate-run' && e.run_id === d.caused_by_run);
82
+ if (round === undefined)
83
+ return fallback();
84
+ const kinds = new Set();
85
+ for (const rv of round.verdicts ?? []) {
86
+ if (!rv.findings.some((f) => f.blocking && anchorKey(f.anchor) === d.anchor))
87
+ continue;
88
+ const k = readsOf(round.gate, rv.reviewer);
89
+ if (k !== undefined)
90
+ kinds.add(k);
91
+ }
92
+ return kinds.size > 0 ? [...kinds] : fallback();
93
+ }
94
+ catch {
95
+ return fallback();
96
+ }
97
+ }
98
+ // Row 216 (K3). Some lens in this battery reads one of the debt's kinds, so its silence is evidence.
99
+ export function judgeable(root, d, home, gate, lenses) {
100
+ const kinds = debtKinds(root, d, home);
101
+ return lenses.some((l) => { const k = readsOf(gate, l); return k !== undefined && kinds.includes(k); });
102
+ }
103
+ // The gate's lenses for these battery names: each prompt, with the docs configured for it at this
104
+ // gate and an override's living docs (which join prompts_sha). One home for the gate and a review.
105
+ export function gateLenses(root, cfg, gate, names, overrides) {
106
+ const lenses = [];
107
+ for (const name of names) {
108
+ const lensR = resolvePrompt(name);
109
+ if (!lensR.ok)
110
+ return lensR;
111
+ const lens = lensR.value;
112
+ const docPaths = docKeysFor(gate, name).flatMap((k) => cfg.docs[k] ?? []);
113
+ let docs = [];
114
+ if (docPaths.length > 0) {
115
+ const docsR = loadLensDocs(root, docPaths);
116
+ if (!docsR.ok)
117
+ return refuse(docsR.violations);
118
+ docs = docsR.value;
119
+ }
120
+ const ov = overrides?.[name];
121
+ if (ov?.docs?.length)
122
+ docs = [...docs, ...ov.docs]; // living design joins prompts_sha
123
+ if (docs.length)
124
+ lens.docs = docs;
125
+ lenses.push(lens);
126
+ }
127
+ return ok(lenses);
128
+ }
129
+ // Row 216 (K3). Each lens's own setup: the pins, then the open debts it can read, then the
130
+ // backstop. D122: what a lens is asked joins `prompts_sha` — `text` is every lens's setup under
131
+ // its name, sorted by name so the sha, like `promptsSha`, does not depend on battery order — so a
132
+ // debt minted for a lens re-invokes the battery.
133
+ export function gateSetup(root, spec, entries, lenses) {
134
+ const pins = pinsBlock(policyPins(entries));
135
+ const debts = openDeferrals(entries).map((d) => ({ d, kinds: debtKinds(root, d, entries) }));
136
+ const backstopped = spec.backstops ? outstandingDemotions(entries, spec.backstops) : [];
137
+ const backstop = spec.backstops ? demotionsBlock(spec.backstops, backstopped) : '';
138
+ const forLens = (name) => {
139
+ const reads = spec.lensReads?.[name] ?? spec.reads;
140
+ return pins + deferralsBlock(debts.filter((x) => x.kinds.includes(reads)).map((x) => x.d)) + backstop;
141
+ };
142
+ const each = [...lenses].sort().map((n) => ({ n, s: forLens(n) }));
143
+ const text = each.every((x) => x.s === '') ? '' : each.map((x) => `### Lens ${x.n}\n\n${x.s}`).join('');
144
+ return { forLens, text, backstopped };
145
+ }
146
+ // One prompt assembly for the gate and a review (row 215): the lens, its docs, its setup, the
147
+ // anchor menu, the content.
148
+ export function lensPrompt(lens, setup, menu, body) {
149
+ return `${lens.contents}\n\n${docsBlock(lens.docs ?? [])}${setup}${menu ? `${menu}\n\n` : ''}## Reviewed content\n\n${body}\n`;
150
+ }
151
+ // A finding's anchor and claim are a reviewer's free text, printed on a human's terminal: spelled
152
+ // out (`logSafe`) so an escape sequence or bidi override cannot paint over the row (row 215).
153
+ export function findingRows(verdicts) {
154
+ return verdicts.flatMap((rv) => rv.findings.map((f) => ({
155
+ reviewer: rv.reviewer, blocking: String(f.blocking),
156
+ pin: f.contradicts_pin !== undefined ? `#${f.contradicts_pin}` : '',
157
+ anchor: logSafe(typeof f.anchor === 'string' ? f.anchor : `omission:${f.anchor.scope}`), claim: logSafe(f.claim),
158
+ })));
159
+ }
160
+ export function malformedRows(malformed) {
161
+ return malformed.flatMap((m) => m.violations.map((x) => ({ reviewer: m.reviewer, field: x.field, rule: x.rule })));
162
+ }
31
163
  // The gate's own reviewers for this class. Their shape — a non-empty list, or a map naming
32
164
  // every class — is refused when the file loads (row 13, amended by 193), so nothing is left
33
165
  // to refuse here.
@@ -62,11 +194,7 @@ export function renderGateRun(ctx, entry, mode, opts = {}) {
62
194
  // Row 179: what the lane did not run, beside the row that passed without it.
63
195
  for (const h of entry.checks.flatMap((c) => c.held ?? []))
64
196
  ctx.out(`held: ${h.criterion} — ${h.need} unmet · ${h.satisfy}`);
65
- const findings = (entry.verdicts ?? []).flatMap((rv) => rv.findings.map((f) => ({
66
- reviewer: rv.reviewer, blocking: String(f.blocking),
67
- pin: f.contradicts_pin !== undefined ? `#${f.contradicts_pin}` : '',
68
- anchor: typeof f.anchor === 'string' ? f.anchor : `omission:${f.anchor.scope}`, claim: f.claim,
69
- })));
197
+ const findings = findingRows(entry.verdicts ?? []);
70
198
  if (findings.length)
71
199
  ctx.out(rows('findings', ['reviewer', 'blocking', 'pin', 'anchor', 'claim'], findings).join('\n'));
72
200
  for (const f of (entry.verdicts ?? []).flatMap((rv) => rv.findings)) {
@@ -74,7 +202,7 @@ export function renderGateRun(ctx, entry, mode, opts = {}) {
74
202
  ctx.out(kv('demoted', `${anchorKey(f.anchor)} — unchanged since round ${f.demoted}`));
75
203
  }
76
204
  if (entry.malformed?.length) {
77
- ctx.out(rows('malformed', ['reviewer', 'field', 'rule'], entry.malformed.flatMap((m) => m.violations.map((x) => ({ reviewer: m.reviewer, field: x.field, rule: x.rule })))).join('\n'));
205
+ ctx.out(rows('malformed', ['reviewer', 'field', 'rule'], malformedRows(entry.malformed)).join('\n'));
78
206
  }
79
207
  if (entry.standing)
80
208
  ctx.out(kv('standing-stop', entry.standing));
@@ -201,6 +329,7 @@ async function judge(ctx, gateName, target, flags) {
201
329
  return EXIT.REFUSED;
202
330
  }
203
331
  const input = inputR.value;
332
+ assertReads(spec, input.reviewed, input.lensOverrides); // row 216, before any lens runs
204
333
  // Resolved once for every render this run performs — the entry renderers stay pure
205
334
  // formatters (they take the id, they never look it up).
206
335
  const upstreamId = spec.upstreamOf?.(root, canon, target);
@@ -213,38 +342,18 @@ async function judge(ctx, gateName, target, flags) {
213
342
  const active = batteryR.value.filter((n) => !skip.has(n));
214
343
  const dropped = batteryR.value.filter((n) => skip.has(n)).map((n) => `${n} — ${skip.get(n)}`);
215
344
  const entries = readStream(root, target);
216
- const pins = policyPins(entries);
217
- const pinsText = pinsBlock(pins);
345
+ const lensesR = gateLenses(root, cfgR.value, spec.gate, active, input.lensOverrides);
346
+ if (!lensesR.ok) {
347
+ renderRefusal(lensesR.violations).forEach((l) => ctx.err(l));
348
+ return EXIT.REFUSED;
349
+ }
350
+ const lenses = lensesR.value;
218
351
  // D122. Open obligations join the prompt exactly as pins do, and join `prompts_sha` for
219
352
  // the same reason: an obligation the battery did not see is an obligation nothing can
220
353
  // discharge. Minting one therefore guarantees the next round re-invokes the battery,
221
354
  // which is the intended cost of an override rather than an accident of the cache.
222
- const deferralsText = deferralsBlock(openDeferrals(entries));
223
- const lenses = [];
224
- for (const name of active) {
225
- const lensR = resolvePrompt(name);
226
- if (!lensR.ok) {
227
- renderRefusal(lensR.violations).forEach((l) => ctx.err(l));
228
- return EXIT.REFUSED;
229
- }
230
- const lens = lensR.value;
231
- const docPaths = docKeysFor(spec.gate, name).flatMap((k) => cfgR.value.docs[k] ?? []);
232
- let docs = [];
233
- if (docPaths.length > 0) {
234
- const docsR = loadLensDocs(root, docPaths);
235
- if (!docsR.ok) {
236
- renderRefusal(docsR.violations).forEach((l) => ctx.err(l));
237
- return EXIT.REFUSED;
238
- }
239
- docs = docsR.value;
240
- }
241
- const ov = input.lensOverrides?.[name];
242
- if (ov?.docs?.length)
243
- docs = [...docs, ...ov.docs]; // living design joins prompts_sha
244
- if (docs.length)
245
- lens.docs = docs;
246
- lenses.push(lens);
247
- }
355
+ // Row 216: each lens is asked only about the debts it can read.
356
+ const setup = gateSetup(root, spec, entries, active);
248
357
  const hxR = resolveJudge(ctx.env, cfgR.value.harness);
249
358
  if (!hxR.ok) {
250
359
  renderRefusal(hxR.violations).forEach((l) => ctx.err(l));
@@ -270,10 +379,8 @@ async function judge(ctx, gateName, target, flags) {
270
379
  // `model` may name a stand-in, so the brake below compares `pin`.
271
380
  const pin = modelR.value;
272
381
  const basis = basisSha(lenses, input.snapshot?.context ?? '', pin, harness.name);
273
- const backstopped = spec.backstops ? outstandingDemotions(entries, spec.backstops) : [];
274
- const backstopText = spec.backstops ? demotionsBlock(spec.backstops, backstopped) : '';
275
- const setupText = [pinsText, deferralsText, backstopText].filter((t) => t !== '').join('');
276
- const setupSha = promptsSha(lenses, setupText || undefined); // the full-review prompts_sha
382
+ const backstopped = setup.backstopped;
383
+ const setupSha = promptsSha(lenses, setup.text || undefined); // the full-review prompts_sha
277
384
  const fullKey = {
278
385
  reviewed_sha: input.reviewedSha, gate: spec.gate, prompts_sha: setupSha, pin, witness: version(),
279
386
  harness: harness.name,
@@ -378,7 +485,7 @@ async function judge(ctx, gateName, target, flags) {
378
485
  ? planDelta(root, entries, spec.gate, { reviewedSha: input.reviewedSha, snapshot: input.snapshot, basis, reviewed: input.reviewed, inDelta })
379
486
  : undefined;
380
487
  const block = delta ? deltaBlock(delta) : '';
381
- const askedSha = delta ? promptsSha(lenses, setupText + block) : setupSha;
488
+ const askedSha = delta ? promptsSha(lenses, setup.text + block) : setupSha;
382
489
  // Row 209. A repair carries verdicts only when the question is the same: a moved delta base
383
490
  // (git gc pruned it, a judged round landed) asks every lens what the malformed round did not.
384
491
  if (kind.kind === 'repair' && kind.from.prompts_sha !== askedSha)
@@ -405,10 +512,9 @@ async function judge(ctx, gateName, target, flags) {
405
512
  const reviewed = ov?.reviewed ?? (delta?.paths && input.reviewed.kind === 'tree'
406
513
  ? { ...input.reviewed, floor: { round: delta.baseRound, paths: delta.paths } } : input.reviewed);
407
514
  const body = ov?.promptBody ?? input.promptBody;
408
- const menu = anchorMenu(reviewed);
409
515
  return {
410
516
  name: lens.name, reviewed,
411
- prompt: `${lens.contents}\n\n${docsBlock(lens.docs ?? [])}${pinsText}${deferralsText}${backstopText}${delta && inDelta(lens.name) ? block : ''}${menu ? `${menu}\n\n` : ''}## Reviewed content\n\n${body}\n`,
517
+ prompt: lensPrompt(lens, setup.forLens(lens.name) + (delta && inDelta(lens.name) ? block : ''), anchorMenu(reviewed), body),
412
518
  };
413
519
  });
414
520
  // Row 209. A repair asks only the lenses with no verdict in the malformed round. Both runs
@@ -511,8 +617,11 @@ async function judge(ctx, gateName, target, flags) {
511
617
  // its silence discharges only an obligation whose unit the change touched. Silence on an
512
618
  // unchanged unit, or on context, is not evidence that anything was fixed.
513
619
  const silenceCounts = (anchor) => !replayedDelta && (delta === undefined || delta.view.state(anchorFromKey(anchor)) === 'changed');
620
+ // Row 216. And only a debt some lens in this battery could read: silence on content no lens
621
+ // was handed is not evidence either.
514
622
  const discharged = entry.outcome === 'malformed' ? []
515
- : openDeferrals(entriesNow).filter((d) => !reported.has(d.anchor) && silenceCounts(d.anchor))
623
+ : openDeferrals(entriesNow).filter((d) => !reported.has(d.anchor) && silenceCounts(d.anchor)
624
+ && judgeable(root, d, entriesNow, spec.gate, active))
516
625
  .map((d) => ({ v: 1, t: 'deferral-discharged', id: d.id, artifact: target, by_run: entry.run_id }));
517
626
  const files = [
518
627
  journalRel(target), ...stamps.flatMap((s) => [s.rel, journalRel(s.stream)]),
@@ -17,6 +17,7 @@ function stampsFor(docs) {
17
17
  registerGate({
18
18
  gate: 'decompose',
19
19
  targetKind: 'effort',
20
+ reads: 'docs', // row 216
20
21
  async resolve(root, _ctx, canon, _cfg, effort) {
21
22
  if (!streamExists(root, effort)) {
22
23
  return refuse([v('effort', 'unknown-effort', effort, 'an effort born by witness recap')]);
@@ -1,7 +1,6 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { serializeDoc } from '../fm.js';
4
- import { designCurrentSha, designGateSha, designRel, designUnseen, elementIds, htmlSha, validateDesignArtifact } from '../design.js';
3
+ import { designCurrentSha, designGateSha, designRel, designReviewed, designUnseen, htmlSha, validateDesignArtifact } from '../design.js';
5
4
  import { registerGate } from '../gate.js';
6
5
  import { latestRecap } from '../journal.js';
7
6
  import { ok, refuse, v } from '../refusal.js';
@@ -13,6 +12,7 @@ import { snapshotFiles } from '../snapshot.js';
13
12
  registerGate({
14
13
  gate: 'design',
15
14
  targetKind: 'spec',
15
+ reads: 'design', // row 216
16
16
  async resolve(root, _ctx, canon, cfg, specId) {
17
17
  const spec = findById(canon, specId);
18
18
  if (!spec || spec.meta.type !== 'spec') {
@@ -44,19 +44,16 @@ registerGate({
44
44
  checks.push({ name: 'template', ok: html !== undefined && template.length === 0,
45
45
  detail: template.length ? template.map((x) => x.rule).join(' · ') : 'self-contained, id-attributed' });
46
46
  // With no artifact, reviewer input is empty ids + the spec — the checks already
47
- // fail-stop; still produce a well-formed GateInput so the gate stops cleanly.
48
- const ids = html !== undefined ? elementIds(html) : [];
49
- const promptBody = [
50
- `### Design artifact: ${rel}`, html ?? '(missing — no artifact to review)',
51
- `### Parent spec: ${specId}`, serializeDoc({ meta: spec.meta, body: spec.body }),
52
- ].join('\n\n');
47
+ // fail-stop; still produce a well-formed GateInput so the gate stops cleanly. Row 215: the
48
+ // same question `witness review design` asks.
49
+ const { reviewed, promptBody } = designReviewed(html, spec);
53
50
  const tree = html !== undefined ? snapshotFiles(root, [{ name: 'design.html', content: html }]) : undefined;
54
51
  return ok({
55
52
  class: (recap?.class ?? 'feature'),
56
53
  reviewedSha: designGateSha(html, spec),
57
54
  ...(tree ? { snapshot: { tree, context: contextDigest(canonicalSha(spec.meta, spec.body)) } } : {}),
58
55
  artifactSha: html !== undefined ? htmlSha(html) : undefined,
59
- reviewed: { kind: 'design', artifact: { ids }, spec: { id: specId, body: spec.body } },
56
+ reviewed,
60
57
  promptBody,
61
58
  checks,
62
59
  standingStop: 'design always stops — a human approves every screen (same footing as ship)',
@@ -70,6 +70,9 @@ registerGate({
70
70
  gate: 'implement',
71
71
  targetKind: 'plan',
72
72
  demotes: true,
73
+ // Row 216. The design-reviewer reads the screens override `resolve` builds for it below.
74
+ reads: 'tree',
75
+ lensReads: { 'design-reviewer': 'screens' },
73
76
  async resolve(root, ctx, canon, cfg, planId) {
74
77
  const plan = findById(canon, planId);
75
78
  if (!plan || plan.meta.type !== 'plan') {
@@ -20,6 +20,7 @@ const draftApproval = (plan) => String(plan.meta.status) === 'draft' ? [{ artifa
20
20
  registerGate({
21
21
  gate: 'plan',
22
22
  targetKind: 'plan',
23
+ reads: 'docs', // row 216
23
24
  async resolve(root, _ctx, canon, _cfg, planId) {
24
25
  const plan = findById(canon, planId);
25
26
  if (!plan || plan.meta.type !== 'plan') {
@@ -31,6 +31,7 @@ registerGate({
31
31
  targetKind: 'plan',
32
32
  demotes: true,
33
33
  backstops: 'implement',
34
+ reads: 'tree', // row 216
34
35
  async resolve(root, ctx, canon, cfg, planId) {
35
36
  const plan = findById(canon, planId);
36
37
  if (!plan || plan.meta.type !== 'plan') {
package/dist/harness.js CHANGED
@@ -89,8 +89,14 @@ const REGISTRY = {
89
89
  ],
90
90
  skills: { project: '.claude/skills', global: '.claude/skills' },
91
91
  reviewer: {
92
- spawn(pin, _extensions) {
93
- const args = ['-p', '--output-format', 'json'];
92
+ // Row 217. Sealed off from the repo it judges: --safe-mode loads none of its hooks, CLAUDE.md
93
+ // or plugins (P11; settings `env` and permissions survive it, P14), --strict-mcp-config none
94
+ // of its MCP servers, --no-session-persistence saves no session, and --tools names every
95
+ // tool the reviewer has. `--tools` is variadic, so nothing positional may follow it — the
96
+ // prompt rides stdin (P12).
97
+ spawn(pin, _extensions, tools = 'none') {
98
+ const args = ['-p', '--output-format', 'json', '--safe-mode', '--strict-mcp-config', '--no-session-persistence',
99
+ '--tools', tools === 'read' ? 'Read,Grep,Glob' : ''];
94
100
  const env = {};
95
101
  if (pin !== undefined) {
96
102
  args.push('--model', pin.model);
@@ -148,14 +154,17 @@ const REGISTRY = {
148
154
  // worker below keeps full discovery on purpose: skills and context files are what
149
155
  // the implement seed measures; auth extensions ride along with everything else there.
150
156
  reviewer: {
151
- spawn(pin, extensions) {
157
+ spawn(pin, extensions, tools = 'none') {
152
158
  const args = ['-p', '--mode', 'json', '--no-session', '--no-extensions'];
153
159
  // Declared machine extensions ride INSIDE the hermetic set (row 89): pi's
154
160
  // --no-extensions disables discovery but explicit -e paths still load, so
155
161
  // auth-supplying adapters work without readmitting ambient machine state.
156
162
  for (const e of extensions ?? [])
157
163
  args.push('-e', e);
158
- args.push('--no-skills', '--no-context-files', '--thinking', pin?.thinking ?? 'off');
164
+ args.push('--no-skills', '--no-context-files');
165
+ // Row 217: with no flag pi hands every session read, bash, edit and write, unapproved.
166
+ args.push(...(tools === 'read' ? ['--tools', 'read,grep,find,ls'] : ['--no-tools']));
167
+ args.push('--thinking', pin?.thinking ?? 'off');
159
168
  if (pin !== undefined)
160
169
  args.push('--model', `${pin.provider ?? 'anthropic'}/${pin.model}`);
161
170
  return { cmd: 'pi', args, env: {} };
package/dist/review.js ADDED
@@ -0,0 +1,74 @@
1
+ import { loadLocalConfig } from './config.js';
2
+ import { runBattery } from './battery.js';
3
+ import { assertReads, batteryFor, gateLenses, gateSetup, gateSpec, lensPrompt, } from './gate.js';
4
+ import { resolveJudge } from './harness.js';
5
+ import { readStream } from './journal.js';
6
+ import { stageModel, unansweredPin } from './model.js';
7
+ import { ok, refuse } from './refusal.js';
8
+ import { promptsSha } from './reviewer.js';
9
+ import { answersKey, fellBack, gateRuns, keyOf, } from './rounds.js';
10
+ import { anchorMenu } from './verdict.js';
11
+ import { version } from './version.js';
12
+ const blockingIn = (verdicts) => verdicts.flatMap((rv) => rv.findings).filter((f) => f.blocking).length;
13
+ export async function reviewOnce(ctx, root, cfg, gate, target, input) {
14
+ const spec = gateSpec(gate);
15
+ if (!spec)
16
+ throw new Error(`review: no gate named ${gate} is registered`);
17
+ const batteryR = batteryFor(cfg, gate, input.cls);
18
+ if (!batteryR.ok)
19
+ return refuse(batteryR.violations);
20
+ const battery = batteryR.value;
21
+ const lensesR = gateLenses(root, cfg, gate, battery);
22
+ if (!lensesR.ok)
23
+ return refuse(lensesR.violations);
24
+ const lenses = lensesR.value;
25
+ assertReads(spec, input.reviewed); // row 216, before any lens runs
26
+ const entries = readStream(root, target);
27
+ const setup = gateSetup(root, spec, entries, battery);
28
+ const hxR = resolveJudge(ctx.env, cfg.harness);
29
+ if (!hxR.ok)
30
+ return refuse(hxR.violations);
31
+ const harness = hxR.value.harness;
32
+ const localR = loadLocalConfig(root);
33
+ if (!localR.ok)
34
+ return refuse(localR.violations);
35
+ const modelR = stageModel(cfg, gate);
36
+ if (!modelR.ok)
37
+ return refuse(modelR.violations);
38
+ const pin = modelR.value;
39
+ // D3. The gate's own key for these bytes under this setup. A full answer on it is not asked
40
+ // again; a delta round, or a cached replay of one, answered a narrower question.
41
+ const key = {
42
+ reviewed_sha: input.reviewedSha, gate, prompts_sha: promptsSha(lenses, setup.text || undefined), pin,
43
+ witness: version(), harness: harness.name,
44
+ };
45
+ const runs = gateRuns(entries, gate).reverse();
46
+ const replay = runs.find((r) => answersKey(r, key) && r.delta === undefined);
47
+ if (replay) {
48
+ return ok({ model: replay.model, verdicts: replay.verdicts ?? [], malformed: [], answered: { round: replay.round, run: replay.run_id } });
49
+ }
50
+ const judged = runs.find((r) => r.reviewed_sha === input.reviewedSha && r.outcome !== 'malformed' && (r.verdicts?.length ?? 0) > 0);
51
+ let earlier;
52
+ if (judged) {
53
+ const k = keyOf(judged);
54
+ const fields = [
55
+ k.witness !== key.witness ? 'witness' : '', k.pin !== key.pin ? 'pin' : '',
56
+ k.harness !== key.harness ? 'harness' : '', k.prompts_sha !== key.prompts_sha ? 'prompts' : '',
57
+ ].filter((f) => f !== '').join(' · ');
58
+ const why = judged.delta !== undefined ? 'in delta mode'
59
+ : fellBack(judged) ? 'under another setup (pin)' : `under another setup (${fields})`;
60
+ earlier = { round: judged.round, why, blocking: blockingIn(judged.verdicts ?? []) };
61
+ }
62
+ // A review is always a full review (row 185): no delta block, whatever the journal holds.
63
+ const composed = lenses.map((lens) => ({
64
+ name: lens.name, reviewed: input.reviewed,
65
+ prompt: lensPrompt(lens, setup.forLens(lens.name), anchorMenu(input.reviewed), input.promptBody),
66
+ }));
67
+ const pinField = `gates.${gate}.model`;
68
+ const ranR = await runBattery(ctx, harness, pin, composed, {
69
+ cwd: root, pinField, timeoutMs: cfg.gates.reviewerTimeoutMs, extensions: localR.value.reviewerExtensions,
70
+ });
71
+ if (!ranR.ok)
72
+ return refuse(unansweredPin(ranR.violations, pinField, pin, harness.name));
73
+ return ok({ model: pin, verdicts: ranR.value.verdicts, malformed: ranR.value.malformed, ...(earlier ? { earlier } : {}) });
74
+ }
package/dist/reviewer.js CHANGED
@@ -5,8 +5,12 @@ import { fileURLToPath } from 'node:url';
5
5
  import { validatePin } from './harness.js';
6
6
  import { ok, refuse, v } from './refusal.js';
7
7
  import { resolveSpawn, spawn, spawnSync } from './spawn.js';
8
+ import { contained, jobHost } from './contain.js';
8
9
  import { DRIVE_DEADLINE_ENV, driveChild } from './drive-presence.js';
9
10
  import { duration, limitIn, realClock, SINGLE_WAIT_MAX_MS, waitFor } from './usage.js';
11
+ export function toolsFor(reviewed) {
12
+ return reviewed.kind === 'screens' ? 'read' : 'none';
13
+ }
10
14
  export const PROMPT_NAMES = [
11
15
  'slicing-critic', 'plan-critic', 'code-reviewer', 'silent-failure-hunter',
12
16
  'type-design', 'pr-test', 'drift-reviewer', 'design-critic', 'design-reviewer',
@@ -111,7 +115,7 @@ function prepareInvocation(ctx, harness, opts) {
111
115
  return refuse(pinR.violations);
112
116
  pin = pinR.value;
113
117
  }
114
- const { cmd, args, env } = harness.reviewer.spawn(pin, opts.extensions);
118
+ const { cmd, args, env } = harness.reviewer.spawn(pin, opts.extensions, opts.tools ?? 'none');
115
119
  // Row 164: on Windows the CLI may be a `.cmd` shim, which only cmd.exe can start. The
116
120
  // prompt rides stdin, so the shim's second parse of the command line never sees it. A
117
121
  // reviewer that cannot be started is an invocation failure on every platform: the
@@ -123,9 +127,14 @@ function prepareInvocation(ctx, harness, opts) {
123
127
  });
124
128
  if (!run.ok)
125
129
  return refuse(run.violations.map((x) => ({ ...x, rule: 'reviewer-invocation' })));
130
+ // Row 218. On Windows a stop — spawnSync's timeout, the async invoker's kill — ends one process,
131
+ // which was the `cmd.exe` shim: the agent under it kept running, and spending, and the piped
132
+ // spawnSync returned only when it exited on its own. Started in a job, the stop is the host's,
133
+ // and the job takes the agent and whatever it started with it.
134
+ const spawned = contained(run.value, jobHost(ctx.env));
126
135
  return ok({
127
- cmd, file: run.value.file, args: run.value.args, env: run.value.env,
128
- windowsVerbatimArguments: run.value.windowsVerbatimArguments,
136
+ cmd, file: spawned.file, args: spawned.args, env: spawned.env,
137
+ windowsVerbatimArguments: spawned.windowsVerbatimArguments,
129
138
  timeout: opts.timeoutMs ?? REVIEWER_TIMEOUT_MS,
130
139
  });
131
140
  }
package/dist/rounds.js CHANGED
@@ -267,6 +267,12 @@ export function repairsOnRegate(entries, gate) {
267
267
  }
268
268
  return false;
269
269
  }
270
+ // Row 215 (D3). Does this journaled run answer `key` — the one evidence rule for the gate's
271
+ // cache and for a review's replay? A malformed round judged nothing; a fallen-back one was asked
272
+ // of another model; a run with no verdicts said nothing.
273
+ export function answersKey(run, key) {
274
+ return run.outcome !== 'malformed' && !fellBack(run) && (run.verdicts?.length ?? 0) > 0 && sameKey(keyOf(run), key);
275
+ }
270
276
  export function appendKind(entries, gate, key) {
271
277
  let lastRunIdx = -1;
272
278
  for (let i = entries.length - 1; i >= 0; i--) {
@@ -303,9 +309,8 @@ export function appendKind(entries, gate, key) {
303
309
  // clean one over the same content share a key, so edit-then-revert would replay an
304
310
  // unpinned verdict into a passing run. Beside the malformed filter, which is here
305
311
  // for the identical reason — a round witness could not complete is not evidence.
306
- if (run.outcome !== 'malformed' && !fellBack(run) && run.verdicts && sameKey(keyOf(run), key)) {
312
+ if (answersKey(run, key))
307
313
  return { kind: 'cached', from: run };
308
- }
309
314
  }
310
315
  return { kind: 'fresh' };
311
316
  }
@@ -109,6 +109,18 @@ function takeTurn(root, ctx, label) {
109
109
  pause(POLL_MS);
110
110
  }
111
111
  }
112
+ // Row 218. A holder killed mid-run skips its `finally` and leaves its pid behind. The next taker
113
+ // steals such a turn anyway, but Windows reuses pids within minutes, and a reused pid reads as a
114
+ // live holder that every later run waits on. Drive calls this when it starts and after every
115
+ // session, so the leftover goes before its pid is likely to name another process. Only a dead
116
+ // holder's turn goes: a live one, one being written, or none at all is left alone.
117
+ export function releaseDeadTurn(root) {
118
+ const p = runnerLockPath(root);
119
+ const holder = holderOf(p);
120
+ if (typeof holder !== 'number' || isAlive(holder))
121
+ return false;
122
+ return drop(p, (text) => pidOf(text) === holder) === 'taken';
123
+ }
112
124
  function suitesMayOverlap(root) {
113
125
  const cfg = loadConfig(root);
114
126
  return cfg.ok && cfg.value.drive.parallelSuites;
package/dist/runner.js CHANGED
@@ -3,8 +3,9 @@ import { join } from 'node:path';
3
3
  import { ensureTrusted } from './allowlist.js';
4
4
  import { mergeReports, reportFiles } from './junit.js';
5
5
  import { ok, refuse, v } from './refusal.js';
6
+ import { contained, JOB_HOST_ENV, jobHost } from './contain.js';
6
7
  import { withRunnerTurn } from './runner-lock.js';
7
- import { execSync } from './spawn.js';
8
+ import { execFileSync, execSync, system32 } from './spawn.js';
8
9
  // The values' own shapes (a runner with {id}, a junit: report) are refused when the file loads
9
10
  // (row 193); what is left is what only a combination says, and what an older file never set.
10
11
  export function runnerConfig(cfg) {
@@ -31,12 +32,46 @@ export function criteriaExcludes(cfg) {
31
32
  export function execCommand(runRoot, ctx, cmd) {
32
33
  return withRunnerTurn(runRoot, ctx, cmd, (env) => runCommand(runRoot, { ...ctx, env }, cmd));
33
34
  }
35
+ // Row 218. Said once per process, by every run that starts on win32 without a job host.
36
+ let saidNoJob = false;
37
+ export function sayNoJob(ctx, host) {
38
+ if (host.ok || saidNoJob)
39
+ return;
40
+ saidNoJob = true;
41
+ ctx.err(`runner: no job (${host.why}) — what this run starts may outlive it`);
42
+ }
43
+ // D158. Suite stdout is unbounded and only the last 4000 chars are kept — but at
44
+ // Node's 1 MiB default a chatty GREEN suite threw ENOBUFS into the catch and read
45
+ // as a failed lane. 64 MiB: the same bound the reviewer spawn uses.
46
+ const MAX_BUFFER = 64 * 1024 * 1024;
47
+ // Row 218. On win32 the run starts in a job (src/contain.ts), so whatever the suite starts —
48
+ // its app detached, an installer that starts it and exits — ends when the run does, and with
49
+ // the turn's holder if that is killed alone: libuv's own job takes the host, the host's job
50
+ // the rest. The shell is System32's cmd.exe with Node's own argv for execSync, never ComSpec,
51
+ // which may name a shell with other syntax (row 164). Elsewhere the run is execSync's.
34
52
  function runCommand(runRoot, ctx, cmd) {
35
53
  try {
36
- // D158. Suite stdout is unbounded and only the last 4000 chars are kept — but at
37
- // Node's 1 MiB default a chatty GREEN suite threw ENOBUFS into the catch and read
38
- // as a failed lane. 64 MiB: the same bound the reviewer spawn uses.
39
- const out = execSync(cmd, { cwd: runRoot, env: ctx.env, stdio: 'pipe', maxBuffer: 64 * 1024 * 1024 });
54
+ let out;
55
+ if (process.platform === 'win32') {
56
+ const host = jobHost(ctx.env);
57
+ sayNoJob(ctx, host);
58
+ const run = contained({
59
+ file: system32(ctx.env, 'cmd.exe'),
60
+ args: ['/d', '/s', '/c', `"${cmd}"`],
61
+ env: { ...ctx.env, [JOB_HOST_ENV]: host.ok ? 'job' : 'none' },
62
+ windowsVerbatimArguments: true,
63
+ }, host);
64
+ // execFileSync hands its options to spawnSync, which reads windowsVerbatimArguments;
65
+ // @types/node leaves it off ExecFileSyncOptions, so they travel as a variable
66
+ const opts = {
67
+ cwd: runRoot, env: run.env, stdio: 'pipe', maxBuffer: MAX_BUFFER,
68
+ windowsVerbatimArguments: run.windowsVerbatimArguments,
69
+ };
70
+ out = execFileSync(run.file, run.args, opts);
71
+ }
72
+ else {
73
+ out = execSync(cmd, { cwd: runRoot, env: ctx.env, stdio: 'pipe', maxBuffer: MAX_BUFFER });
74
+ }
40
75
  return { exitZero: true, output: String(out).slice(-4000) };
41
76
  }
42
77
  catch (e) {
package/dist/spawn.js CHANGED
@@ -55,7 +55,7 @@ function whichWin32(cmd, env) {
55
55
  // The C runtime's rules (CommandLineToArgvW; node's own argv parser follows them): inside
56
56
  // quotes a backslash is literal unless a quote follows it, where the run doubles and the
57
57
  // quote takes one more.
58
- function crtQuote(arg) {
58
+ export function crtQuote(arg) {
59
59
  let out = '"';
60
60
  let slashes = 0;
61
61
  for (const ch of arg) {
@@ -543,7 +543,7 @@ export function readyChoice(canon, ready) {
543
543
  }
544
544
  // D122. Orientation, never a ladder tier: routing the human to the dismissal verb would
545
545
  // teach closure-by-assertion at the one place the design means closure-by-evidence. The real
546
- // bite is the battery injection, which no round can skip. Applied once where the action is
546
+ // bite is the injection into every lens that can read the debt (row 216). Applied once where the action is
547
547
  // finally produced rather than at each routing site — a per-branch copy would drift, and
548
548
  // there are eleven branches.
549
549
  export function withDeferralNote(root, canon, action) {