@popovych.co/witness 0.28.3 → 0.29.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 (57) hide show
  1. package/README.md +14 -2
  2. package/dist/act.d.ts +2 -1
  3. package/dist/act.js +9 -0
  4. package/dist/busy.d.ts +38 -0
  5. package/dist/busy.js +274 -0
  6. package/dist/caps.d.ts +3 -2
  7. package/dist/caps.js +24 -3
  8. package/dist/decide-view.d.ts +6 -0
  9. package/dist/decide-view.js +21 -3
  10. package/dist/drive-presence.d.ts +3 -0
  11. package/dist/drive-presence.js +18 -6
  12. package/dist/drive.d.ts +18 -1
  13. package/dist/drive.js +264 -48
  14. package/dist/evidence.d.ts +2 -0
  15. package/dist/evidence.js +8 -2
  16. package/dist/gate.js +37 -4
  17. package/dist/gates/implement.js +11 -3
  18. package/dist/gates/ship.js +10 -5
  19. package/dist/gitio.d.ts +5 -0
  20. package/dist/gitio.js +27 -2
  21. package/dist/journal.d.ts +1 -1
  22. package/dist/live.d.ts +6 -1
  23. package/dist/live.js +15 -3
  24. package/dist/needs-you.d.ts +18 -2
  25. package/dist/needs-you.js +55 -17
  26. package/dist/progress.js +2 -0
  27. package/dist/reviewed.d.ts +4 -0
  28. package/dist/reviewed.js +9 -0
  29. package/dist/rounds.d.ts +6 -2
  30. package/dist/rounds.js +43 -10
  31. package/dist/settle.d.ts +25 -2
  32. package/dist/settle.js +120 -11
  33. package/dist/ship-outcome.d.ts +24 -0
  34. package/dist/ship-outcome.js +76 -0
  35. package/dist/ship.d.ts +12 -1
  36. package/dist/ship.js +306 -73
  37. package/dist/stamp.d.ts +6 -0
  38. package/dist/stamp.js +17 -7
  39. package/dist/steps.d.ts +1 -0
  40. package/dist/steps.js +31 -7
  41. package/dist/verbs/dashboard.js +9 -3
  42. package/dist/verbs/decide.d.ts +12 -0
  43. package/dist/verbs/decide.js +77 -23
  44. package/dist/verbs/evidence.js +40 -3
  45. package/dist/verbs/next.d.ts +20 -3
  46. package/dist/verbs/next.js +272 -58
  47. package/dist/verbs/wait.js +30 -5
  48. package/package.json +1 -1
  49. package/plugin/.claude-plugin/plugin.json +1 -1
  50. package/plugin/commands/witness.md +8 -2
  51. package/plugin/hooks/session-dashboard.sh +1 -1
  52. package/plugin/skills/witness-brainstorm/SKILL.md +1 -1
  53. package/plugin/skills/witness-decompose/SKILL.md +1 -1
  54. package/plugin/skills/witness-design/SKILL.md +1 -1
  55. package/plugin/skills/witness-implement/SKILL.md +4 -4
  56. package/plugin/skills/witness-plan/SKILL.md +2 -2
  57. package/plugin/skills/witness-ship/SKILL.md +2 -2
package/dist/drive.js CHANGED
@@ -12,18 +12,23 @@ import { findById, loadCanon } from './scan.js';
12
12
  import { NO_CONSOLE_ENV, resolveSpawn, spawn, treeStop } from './spawn.js';
13
13
  import { contained, containmentLine, JOB_HOST_ENV, jobHost } from './contain.js';
14
14
  import { releaseDeadTurn } from './runner-lock.js';
15
- import { computeNext, conversationStage } from './verbs/next.js';
15
+ import { computeNext, conversationStage, heldPlan } from './verbs/next.js';
16
16
  import { shownView } from './verbs/decide.js';
17
17
  import { decideViewLines } from './decide-view.js';
18
18
  import { renderDecision } from './recommend.js';
19
19
  import { entryDetail } from './verbs/log.js';
20
20
  import { DRIVE_DEADLINE_ENV, DRIVE_ENV, DRIVE_LOG, DRIVE_LOG_ENV, TARGETLESS, driveHolder } from './drive-presence.js';
21
- import { isAlive, pause } from './lock.js';
21
+ import { LOCK_WAIT_MS, isAlive, pause } from './lock.js';
22
+ import { BUSY_DIR, busyHolder, sweepDeadBusy } from './busy.js';
23
+ import { unparkAt } from './rounds.js';
24
+ import { latestOutcome } from './ship-outcome.js';
25
+ import { stateFloor } from './floor.js';
26
+ import { compareTriple, version } from './version.js';
22
27
  import { ASK_STREAM } from './ask.js';
23
28
  import { KEPT_STOP_NAMES, unmetNeedLine } from './autonomy.js';
24
29
  import { unmetNeeds } from './needs.js';
25
30
  import { capHit, parkAtCap } from './caps.js';
26
- import { effortStreams, journalRel, readStream } from './journal.js';
31
+ import { effortStreams, journalActs, journalRel, readStream } from './journal.js';
27
32
  import { movesFlow } from './progress.js';
28
33
  import { sourced } from './allowlist.js';
29
34
  import { effortOf } from './reviewed.js';
@@ -73,9 +78,10 @@ export function classifyAction(action, root, opts = {}) {
73
78
  // agent to do. In practice this line arrives in the spawned ship session's OUTPUT
74
79
  // (ship.ts:277) rather than in a routing row, which is why the loop reads the child's
75
80
  // stream for it too; both readers exist because either surface can carry it.
76
- if (line.includes('merge PR') || (action.note?.includes('merge PR') ?? false)) {
77
- return { kind: 'merge', line: action.note?.includes('merge PR') ? action.note : line };
78
- }
81
+ // Row 242. A hold is classified from its record (`held`), never from ship's words: the merge sniff
82
+ // that read `merge PR` retired with it.
83
+ if (action.held !== undefined)
84
+ return { kind: action.held.outcome === 'fix' ? 'fix' : 'merge', line };
79
85
  // `witness check` is computeNext's terminal answer in two states: canon errors that
80
86
  // stopped routing early (bare line), and an exhausted ladder (line + a "nothing is
81
87
  // owed" note, D157). Idle PRINTS the line rather than swallowing it: a human who sees
@@ -430,7 +436,9 @@ const idleMaxOf = (env) => {
430
436
  export function watchSignature(root) {
431
437
  const p = canonPaths(root);
432
438
  const files = [];
433
- for (const dir of [join(root, '.witness', 'journal'), join(root, p.specs), join(root, p.plans), join(root, p.designs)]) {
439
+ // Row 240: the busy folder too — a take or a release is what frees a target drive skipped. The
440
+ // repo lock is not watched: it is taken and released by every state write.
441
+ for (const dir of [join(root, '.witness', 'journal'), join(root, p.specs), join(root, p.plans), join(root, p.designs), join(root, BUSY_DIR)]) {
434
442
  try {
435
443
  for (const n of readdirSync(dir, { recursive: true }))
436
444
  files.push(join(dir, n));
@@ -450,8 +458,16 @@ export function watchSignature(root) {
450
458
  });
451
459
  return createHash('sha1').update(parts.join('\n')).digest('hex');
452
460
  }
453
- // What `mergeOwnPr` prints when it leaves the merge to a human (ship.ts), and nothing else.
454
- const MERGE_LINE = /^ship: "?merge PR #(\d+) on GitHub when ready/;
461
+ // Row 240 (design §4.1.4). A refused settle is tried again one lock wait later; the third door
462
+ // refusal in a row sets the stop aside for the human. A busy lock never reaches the door.
463
+ export const RETRY_DUE_MS = LOCK_WAIT_MS;
464
+ export const RETRY_MAX = 3;
465
+ // Row 242 (design §4.3.4). A transient ship hold is checked again 5 minutes after the first, the
466
+ // wait doubling to at most an hour; constants (n3), each re-check a session counted against the caps.
467
+ export const RECHECK_FIRST_MS = 300_000;
468
+ export const RECHECK_MAX_MS = 3_600_000;
469
+ // The kinds that are drive's own timers, never the human's: a settle's retry, a hold's re-check.
470
+ const isTimer = (a) => a.kind === 'retry' || a.kind === 'recheck';
455
471
  const streamLines = (root, id) => readStream(root, id).length;
456
472
  // Row 181. Did anything happen for THIS target? A whole-journal count is satisfied by any
457
473
  // other lane's progress, so a stalled flow beside a busy one would spawn until the ceiling.
@@ -480,6 +496,18 @@ function progressKey(root, action, family) {
480
496
  // Final review F2. A lane holds its whole flow: a spec and the plans written for it. Pure over the
481
497
  // canon it is given: drive's fill reads it from the canon of this fill, the journal watch from a
482
498
  // fresh one (row 214).
499
+ // Row 240 (design §4.1.2). Which owed stops drive's own settle pass judges: one in its scope (the
500
+ // `--flow` claim, else every target), not itself a lane (a session settles its own target), not
501
+ // set aside, and not busy to another live process. A lane's family members are admitted, which the
502
+ // fill's `admits` keeps out: a spec's stop would otherwise wait for every lane of its plans (P18).
503
+ export function settleAdmitsFor(t, s) {
504
+ const k = t ?? TARGETLESS;
505
+ if (s.lanes.has(k) || s.aside.has(k))
506
+ return false;
507
+ if (s.flow !== undefined && t !== s.flow)
508
+ return false;
509
+ return t === undefined || !s.busy(t);
510
+ }
483
511
  export function flowOf(canon, t) {
484
512
  const doc = findById(canon, t);
485
513
  if (doc?.meta.type === 'plan')
@@ -622,6 +650,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
622
650
  const aside = new Map();
623
651
  const progress = new Map();
624
652
  const use = new Map(); // row 183: this run's sessions and time, per target
653
+ const unparksSeen = new Map(); // row 241: human un-parks counted per target
625
654
  let spawns = 0;
626
655
  let stop;
627
656
  let idle;
@@ -666,16 +695,52 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
666
695
  // this fill, so a plan written a moment ago belongs to its spec's lane at once.
667
696
  let canonNow = loadCanon(root);
668
697
  const family = (t) => flowOf(canonNow, t);
698
+ // Row 240. This round's targets another live process holds — a settle lock or a ship marker —
699
+ // skipped by the settle pass, the fill, `waitingNeed`, `capped` and `unmoved` alike, so none
700
+ // reads it as a cap or as no progress. While one waits and no lane runs, drive polls.
701
+ const busySeen = new Set();
702
+ const busyOther = (t) => {
703
+ if (busyHolder(root, 'settle', t) === undefined && busyHolder(root, 'ship', t) === undefined)
704
+ return false;
705
+ busySeen.add(t);
706
+ return true;
707
+ };
669
708
  const admits = (t) => {
670
709
  const k = t ?? TARGETLESS;
671
- if (lanes.has(k) || aside.has(k) || (flags.flow !== undefined && t !== flags.flow))
710
+ if (lanes.has(k) || aside.has(k) || busySeen.has(k) || (flags.flow !== undefined && t !== flags.flow))
672
711
  return false;
673
712
  if (t === undefined)
674
713
  return true;
675
714
  const mine = family(t);
676
- return ![...lanes.keys()].some((l) => mine.includes(l) || family(l).includes(t));
715
+ if ([...lanes.keys()].some((l) => mine.includes(l) || family(l).includes(t)))
716
+ return false;
717
+ // Row 242: a plan whose merge ship journaled is over for drive, whatever its status says yet.
718
+ if (ended(t) === 'merged')
719
+ return false;
720
+ return !busyOther(t);
677
721
  };
722
+ const settleAdmits = (t) => !busySeen.has(t ?? TARGETLESS) && settleAdmitsFor(t, { lanes, aside, ...(flags.flow !== undefined ? { flow: flags.flow } : {}), busy: busyOther });
678
723
  const setAside = (key, a) => { aside.set(key, { target: key, ...a }); };
724
+ // Row 240. Drive's timers: the earliest due time, and each timer whose time came — only its aside
725
+ // is deleted (row 207's release resets a target's use and must not be used), its kept act handed
726
+ // to this round's settle pass.
727
+ const nextDue = () => {
728
+ let at;
729
+ for (const a of aside.values())
730
+ if (isTimer(a) && a.due !== undefined && (at === undefined || a.due < at))
731
+ at = a.due;
732
+ return at;
733
+ };
734
+ const releaseDue = () => {
735
+ for (const [k, a] of [...aside]) {
736
+ if (!isTimer(a) || a.due === undefined || a.due > clock.now())
737
+ continue;
738
+ aside.delete(k);
739
+ if (a.kept !== undefined)
740
+ dueKept.set(k, a.kept);
741
+ }
742
+ };
743
+ const humanAsides = () => [...aside.values()].filter((a) => !isTimer(a));
679
744
  // Row 196. A target's own next action, read with every other target filtered out: how the
680
745
  // settle pass, which holds no action, and `takeBack` derive the key a human may move.
681
746
  const ownNext = (key) => computeNext(root, ctx, canonNow, cfg, { scope: key === TARGETLESS ? (t) => t === undefined : (t) => t === key });
@@ -705,12 +770,27 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
705
770
  const ended = (key) => {
706
771
  const doc = findById(canonNow, key);
707
772
  const status = String(doc?.meta.status);
708
- return doc?.meta.type === 'plan' && (status === 'done' || status === 'abandoned') ? status : undefined;
773
+ if (doc?.meta.type === 'plan' && (status === 'done' || status === 'abandoned'))
774
+ return status;
775
+ // Row 242: a merge ship journaled ends the plan for drive at once, as a done plan does — no
776
+ // session runs only to reach the lazy stamp.
777
+ return doc?.meta.type === 'plan' && latestOutcome(readStream(root, key))?.outcome === 'merged' ? 'merged' : undefined;
778
+ };
779
+ // Row 242. A merge or fix aside is drive's again the moment the plan stops being held — a later
780
+ // entry, or a moved HEAD, which changes no progress key.
781
+ const heldNow = (key) => {
782
+ const doc = findById(canonNow, key);
783
+ return doc?.meta.type === 'plan' ? heldPlan(root, cfg, doc) : undefined;
709
784
  };
710
785
  const takeBack = () => {
711
786
  for (const [key, a] of aside) {
712
787
  if (a.key0 === undefined)
713
788
  continue;
789
+ if ((a.kind === 'merge' || a.kind === 'fix') && ended(key) === undefined && heldNow(key) === undefined) {
790
+ release(key);
791
+ ctx.out(`drive: taken back — ${key} · no longer held`);
792
+ continue;
793
+ }
714
794
  const over = ended(key);
715
795
  if (over !== undefined) {
716
796
  release(key);
@@ -745,7 +825,18 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
745
825
  aside.delete(key);
746
826
  }
747
827
  };
828
+ // Row 242 (R15). A target whose plan is held is the human's stop, never stuck.
829
+ const asHeld = (key) => {
830
+ const rec = heldNow(key);
831
+ if (rec === undefined)
832
+ return false;
833
+ ctx.out(`drive: ${rec.outcome} — ${key} · ${logSafe(String(rec.reason))}`);
834
+ setAside(key, { kind: rec.outcome === 'fix' ? 'fix' : 'merge', line: cliAct('ship', key).line, why: rec.reason, key0: keyOf(ownNext(key)) });
835
+ return true;
836
+ };
748
837
  const stuck = (key, action) => {
838
+ if (asHeld(key))
839
+ return;
749
840
  ctx.out(`drive: no progress — ${action.line}`);
750
841
  ctx.out(action.target !== undefined
751
842
  ? `help: ${action.target} is set aside until its record moves — read its stream above · after a fix witness cannot see: ${cliAct('retry', action.target).line}`
@@ -778,9 +869,9 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
778
869
  setAside(key, { kind: 'conversation', line: step.line, why: 'an exchange with a human', key0: keyOf(action) });
779
870
  return;
780
871
  }
781
- if (step.kind === 'merge') {
782
- ctx.out(`drive: merge — ${step.line}`);
783
- setAside(key, { kind: 'merge', line: step.line, why: 'the merge is a human\'s', key0: keyOf(action) });
872
+ if (step.kind === 'merge' || step.kind === 'fix') {
873
+ ctx.out(`drive: ${step.kind} — ${action.target ?? 'untargeted work'} · ${action.held !== undefined ? logSafe(String(action.held.reason)) : 'the merge is a human\'s'}`);
874
+ setAside(key, { kind: step.kind, line: step.line, why: action.held?.reason ?? 'the merge is a human\'s', key0: keyOf(action) });
784
875
  return;
785
876
  }
786
877
  // Under autonomy a `witness decide` line still reaching the fill is a stop the settle
@@ -801,23 +892,16 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
801
892
  };
802
893
  // `next` is the line the session takes (D13): the action's, or the re-run a settle routed.
803
894
  const launch = (step, action, n, next) => {
804
- const lane = { action, end: Promise.resolve(undefined) };
805
- // The merge is announced by the SHIP SESSION's own output (ship.ts), not by a routing
806
- // row — a flow whose PR is open routes to `witness ship` forever, and only the child
807
- // knows it printed "merge PR". `mergeOwnPr` prints it only when it leaves the merge to a
808
- // human, so under autonomy this fires only where a human merges.
809
- // Final review F10: only the CLI's own line counts, and only for a flow with a PR — agent
810
- // prose that mentions a merge must never hand a human `gh pr merge` for a flow without one.
811
- // Row 214: the line is read wherever the CLI printed it. The ship skill runs `witness ship` in
812
- // the agent's bash tool, so in production it is a tool's output, which drive hears and never
813
- // prints — the session's printed lines alone met it only when an agent happened to quote it.
814
- const pr = action.target !== undefined ? findById(canonNow, action.target)?.meta.pr : undefined;
815
- const hear = (line) => { if (pr !== undefined && MERGE_LINE.exec(line)?.[1] === String(pr))
816
- lane.merged = line; };
895
+ const lane = {
896
+ action, end: Promise.resolve(undefined),
897
+ streamAt: action.target !== undefined ? readStream(root, action.target).length : 0,
898
+ };
899
+ // Row 242: a merge or fix left to the human is read from the record ship journals, so drive no
900
+ // longer listens for ship's words (the merge sniff of rows 180 and 214 retired).
817
901
  // Row 214: what the session journals for its flow. Target-less work has no stream of its own
818
902
  // to watch (row 181 keys it on counts).
819
903
  const progress = action.target !== undefined ? journalWatch(root, action.target) : undefined;
820
- lane.end = spawnSession(step, cfg, ctx, n, { manual: flags.manual, signal: abort.signal, hear, root, next, progress });
904
+ lane.end = spawnSession(step, cfg, ctx, n, { manual: flags.manual, signal: abort.signal, root, next, progress });
821
905
  return lane;
822
906
  };
823
907
  // Every wait drive takes goes through here: printed, bounded and counted toward the total.
@@ -867,9 +951,18 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
867
951
  return; // the signal's, reported once at the end
868
952
  if (limited(key, end))
869
953
  return;
954
+ // Row 240. A target another live process holds when its lane ends — a human started `witness
955
+ // ship` after drive spawned — ends like a usage-limited lane: its progress cleared, no cap
956
+ // counted, never stuck. Read from the busy folder, never from the session's words.
957
+ if (key !== TARGETLESS && busyOther(key)) {
958
+ progress.delete(key);
959
+ return;
960
+ }
870
961
  const u = use.get(key) ?? { spawns: 0, ms: 0 };
871
962
  use.set(key, { spawns: u.spawns + 1, ms: u.ms + end.ms });
872
963
  if (end.outcome === 'timeout') {
964
+ if (asHeld(key))
965
+ return;
873
966
  ctx.out(`drive: spawn-timeout — ${lane.action.line}`);
874
967
  setAside(key, { kind: 'stuck', line: lane.action.line, why: `spawn-timeout on ${lane.action.line}`, key0: keyAfter(key) });
875
968
  return;
@@ -879,9 +972,29 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
879
972
  stop ??= 'spawn-failed'; // this machine can spawn nothing
880
973
  return;
881
974
  }
882
- if (lane.merged !== undefined) {
883
- ctx.out(`drive: merge — ${lane.merged}`);
884
- setAside(key, { kind: 'merge', line: lane.merged, why: 'the merge is a human\'s', key0: keyAfter(key) });
975
+ // Row 242 (design §4.3.4). A lane that journaled a transient or pending record — now the
976
+ // stream's latest entry — is re-checked by drive itself; one that wrote nothing takes the
977
+ // no-progress path below and ends stuck: a session that never reached ship is no re-check.
978
+ if (key !== TARGETLESS) {
979
+ const entries = readStream(root, key);
980
+ const rec = latestOutcome(entries);
981
+ if (rec !== undefined && (rec.outcome === 'transient' || rec.outcome === 'pending') && entries.length > lane.streamAt) {
982
+ const reason = logSafe(String(rec.reason));
983
+ if (!autonomous) {
984
+ // The human is at the terminal: the hold is theirs to look at, as stuck.
985
+ ctx.out(`drive: ${rec.outcome} — ${key} · ${reason}`);
986
+ setAside(key, { kind: 'stuck', line: lane.action.line, why: `${rec.outcome}: ${String(rec.reason)}`, key0: keyAfter(key) });
987
+ return;
988
+ }
989
+ const prev = recheckDelay.get(key);
990
+ const delay = prev === undefined ? RECHECK_FIRST_MS : Math.min(prev * 2, RECHECK_MAX_MS);
991
+ recheckDelay.set(key, delay);
992
+ progress.delete(key); // the unchanged line never reads as stuck
993
+ ctx.out(`drive: recheck — ${key} · ${reason} · again in ${duration(delay)}`);
994
+ setAside(key, { kind: 'recheck', line: lane.action.line, why: String(rec.reason), due: clock.now() + delay });
995
+ return;
996
+ }
997
+ recheckDelay.delete(key);
885
998
  }
886
999
  };
887
1000
  // Row 180. Under autonomy each round starts with one settle pass over every target no
@@ -890,11 +1003,39 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
890
1003
  // the pass leaves for a human, drive sets aside. The pass never waits inside a reviewer
891
1004
  // (F6: that wait was silent, uncounted and deaf to a signal): an arbiter refused by a usage
892
1005
  // limit becomes drive's own pause, and the stop is judged again after it.
893
- const routed = new Map(); // target → the re-run its settle routed (row 239: its act)
1006
+ // target → the re-run its settle routed (row 239: its act; row 241: a plan step's whole row)
1007
+ const routed = new Map();
1008
+ const recheckDelay = new Map(); // row 242: each target's last re-check wait
1009
+ // Row 240 (§4.1.4). Door refusals with exit 3 in a row, per target, and the acts kept from them
1010
+ // whose retry fell due this round.
1011
+ const retries = new Map();
1012
+ const dueKept = new Map();
894
1013
  const settlePass = async () => {
895
1014
  const { settleOwed, settledLine } = await import('./settle.js');
896
- for (const r of await settleOwed(ctx, root, cfg, { scope: admits })) {
1015
+ const reports = await settleOwed(ctx, root, cfg, { scope: settleAdmits, kept: dueKept });
1016
+ // A kept act stays until a settle of its target uses it: one busy this round is judged next.
1017
+ for (const r of reports)
1018
+ dueKept.delete(r.target);
1019
+ for (const r of reports) {
897
1020
  const s = r.settled;
1021
+ // Row 240: another process took the stop's settle lock after the scope was read.
1022
+ if (s.kind === 'busy') {
1023
+ busySeen.add(r.target);
1024
+ continue;
1025
+ }
1026
+ if (s.kind === 'left' && s.code === EXIT.BLOCKED && s.limit === undefined) {
1027
+ const tries = (retries.get(r.target) ?? 0) + 1;
1028
+ retries.set(r.target, tries);
1029
+ if (tries < RETRY_MAX) {
1030
+ ctx.out(`drive: retry — ${r.target} · ${s.why} · again in ${duration(RETRY_DUE_MS)}`);
1031
+ setAside(r.target, {
1032
+ kind: 'retry', line: cliAct('decide', r.gate, r.target, '--show').line, why: s.why, gate: r.gate,
1033
+ due: clock.now() + RETRY_DUE_MS, tries, ...(s.paid === true && s.act !== undefined ? { kept: s.act } : {}),
1034
+ });
1035
+ continue;
1036
+ }
1037
+ }
1038
+ retries.delete(r.target);
898
1039
  if (s.kind === 'left' && s.limit !== undefined) {
899
1040
  pauseFor(limitIn(s.limit, clock.now()) ?? { kind: 'usage', text: s.limit });
900
1041
  continue;
@@ -915,7 +1056,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
915
1056
  setAside(r.target, { kind: 'decision', line: cliAct('decide', r.gate, r.target, '--show').line, why: s.why, gate: r.gate, key0: keyOf(ownNext(r.target)) });
916
1057
  }
917
1058
  else if (s.kind === 'routed') {
918
- routed.set(r.target, s.act);
1059
+ routed.set(r.target, { act: s.act, ...(s.row !== undefined ? { row: s.row } : {}) });
919
1060
  }
920
1061
  }
921
1062
  };
@@ -943,14 +1084,23 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
943
1084
  return false;
944
1085
  // A parked cap carries its gate and the report reads it from the journal; an
945
1086
  // unparkable one carries none and is reported with what it is, beside the stuck.
946
- const parked = await parkAtCap(ctx, root, action.target, hit);
1087
+ const parked = await parkAtCap(ctx, root, action.target, hit, cfg);
1088
+ // Row 240: another process is deciding that stop now — nothing is set aside, and the target
1089
+ // is tried again next round.
1090
+ if (!parked.parked && parked.busy === true) {
1091
+ busySeen.add(key);
1092
+ return true;
1093
+ }
947
1094
  if (parked.parked) {
948
1095
  ctx.out(`drive: parked — ${action.target} · ${hit.note}`);
949
1096
  const gate = hit.gate ?? lastRunGate(readStream(root, action.target));
950
1097
  setAside(key, { kind: 'capped', line: action.line, why: hit.note, ...(gate ? { gate } : {}), key0: keyOf(action) });
951
1098
  }
952
1099
  else {
953
- const why = `${hit.note} · ${parked.why}`;
1100
+ // Row 242: a hold drive kept re-checking until the cap names its last reason — the first wake it makes.
1101
+ const last = latestOutcome(readStream(root, action.target));
1102
+ const held = last !== undefined && (last.outcome === 'transient' || last.outcome === 'pending') ? ` · ${logSafe(String(last.reason))}` : '';
1103
+ const why = `${hit.note} · ${parked.why}${held}`;
954
1104
  ctx.out(`drive: capped — ${action.target} · ${why}`);
955
1105
  setAside(key, { kind: 'capped', line: action.line, why, key0: keyOf(action) });
956
1106
  }
@@ -989,10 +1139,15 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
989
1139
  const publish = (ended) => {
990
1140
  if (!autonomous)
991
1141
  return;
992
- const asides = [...aside.values()].filter((a) => !notice(a)).map((a) => ({
1142
+ const asides = humanAsides().filter((a) => !notice(a)).map((a) => ({
993
1143
  target: a.target, kind: a.kind, ...(a.gate !== undefined ? { gate: a.gate } : {}), ...(a.stop !== undefined ? { stop: a.stop } : {}),
994
1144
  }));
995
- writeLive(root, { pid: process.pid, asides, ...(ended !== undefined ? { ended } : {}) });
1145
+ // Row 240: drive's scope, and whether it still settles stops — false once it stopped for good.
1146
+ writeLive(root, {
1147
+ pid: process.pid, asides, ...(ended !== undefined ? { ended } : {}),
1148
+ ...(flags.flow !== undefined ? { scope: { flow: flags.flow } } : {}),
1149
+ deciding: ended === undefined && stop === undefined && signalled === undefined,
1150
+ });
996
1151
  };
997
1152
  // Row 203 (Q2). Each item that newly needs the human is notified once per run (n5), a burst
998
1153
  // as one notification, started in the background so no round waits on it. Mid-run, an item
@@ -1010,7 +1165,10 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1010
1165
  const local = loadLocalConfig(root);
1011
1166
  notify(local.ok ? local.value.notify : undefined, 'witness drive', `witness · ${basename(root)}: ${named.join(' · ')}${fresh.length > 3 ? ` (+${fresh.length - 3})` : ''}`, process.platform, { wait: false });
1012
1167
  };
1013
- const owed = () => needsYou(root, ctx, cfg, loadCanon(root), [...aside.values()]);
1168
+ // Row 240: drive applies its own scope rule — a stop it will decide is no item for the human.
1169
+ const owed = () => needsYou(root, ctx, cfg, loadCanon(root), humanAsides(), {
1170
+ ...(flags.flow !== undefined ? { flow: flags.flow } : {}), deciding: stop === undefined && signalled === undefined,
1171
+ });
1014
1172
  // Row 202. Everything left waits on the human: say what, notify, let the machine sleep, and
1015
1173
  // watch for the act. A change runs a round as usual (take-back, settle pass, fill); a change
1016
1174
  // that releases nothing re-enters the pause silently. True to run a round, false to end.
@@ -1036,12 +1194,17 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1036
1194
  for (;;) {
1037
1195
  if (watchSignature(root) !== signature)
1038
1196
  return true;
1039
- if (clock.now() - pauseSince >= idleMax) {
1197
+ // Row 240: drive's own timers wake it at their due times (the repo lock is outside the signature).
1198
+ const due = nextDue();
1199
+ if (due !== undefined && clock.now() >= due)
1200
+ return true;
1201
+ // Row 242: drive's own timers are its own work — the idle limit does not run while one waits.
1202
+ if (due === undefined && clock.now() - pauseSince >= idleMax) {
1040
1203
  ctx.out(`drive: idle limit — waited ${duration(idleMax)} on you · the run ends`);
1041
1204
  stop = 'idle-limit';
1042
1205
  return false;
1043
1206
  }
1044
- await Promise.race([clock.sleep(PAUSE_POLL_MS), aborted]);
1207
+ await Promise.race([clock.sleep(due !== undefined ? Math.max(0, Math.min(PAUSE_POLL_MS, due - clock.now())) : PAUSE_POLL_MS), aborted]);
1045
1208
  if (signalled !== undefined)
1046
1209
  return false;
1047
1210
  }
@@ -1063,20 +1226,42 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1063
1226
  process.on('SIGTERM', onSignal);
1064
1227
  publish();
1065
1228
  // Row 218. A runner turn whose holder died — a session drive stopped mid-run — is released
1066
- // now and after every session, before Windows hands its pid to another process.
1229
+ // now and after every session, before Windows hands its pid to another process. Row 240: so are
1230
+ // the busy locks of dead holders, and this drive's own leftovers.
1067
1231
  releaseDeadTurn(root);
1232
+ sweepDeadBusy(root, { pid: process.pid });
1068
1233
  try {
1069
1234
  for (;;) {
1070
1235
  if (autonomous)
1071
1236
  roundSignature = watchSignature(root);
1237
+ busySeen.clear();
1072
1238
  stillAutonomous();
1239
+ // Row 240. Once a newer CLI has journaled, the state floor refuses this one at dispatch — and
1240
+ // this drive's sessions run its own bin. It ends rather than work beside its successor.
1241
+ const floor = stateFloor(root);
1242
+ if (stop === undefined && floor !== undefined && (compareTriple(floor.pin, version()) ?? 0) > 0) {
1243
+ ctx.out('drive: superseded — a newer witness CLI took over');
1244
+ stop = 'superseded';
1245
+ }
1073
1246
  canonNow = loadCanon(root);
1074
1247
  // A run that is stopping fills nothing more, so a target released now would be set aside
1075
1248
  // by nobody and drop out of the report; it stays where it is, and the report derives it.
1076
1249
  if (!stop && !signalled)
1077
1250
  takeBack();
1251
+ if (autonomous && !stop && !signalled)
1252
+ releaseDue();
1078
1253
  if (autonomous && !stop && !signalled && clock.now() >= pausedUntil)
1079
1254
  await settlePass();
1255
+ // Row 242 (design §4.3.2, Drive). Beside the settle pass: each held plan in scope is set aside as
1256
+ // its merge or fix stop, so a run left with only such stops pauses for the human (row 202).
1257
+ if (autonomous && !stop && !signalled) {
1258
+ for (const d of canonNow.docs.filter((x) => x.meta.type === 'plan')) {
1259
+ const t = String(d.meta.id);
1260
+ if (lanes.has(t) || aside.has(t) || (flags.flow !== undefined && t !== flags.flow))
1261
+ continue;
1262
+ asHeld(t);
1263
+ }
1264
+ }
1080
1265
  while (!stop && !signalled && lanes.size < parallel && clock.now() >= pausedUntil) {
1081
1266
  canonNow = loadCanon(root);
1082
1267
  const action = computeNext(root, ctx, canonNow, cfg, { scope: admits });
@@ -1097,8 +1282,12 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1097
1282
  // Only then: `routed` keeps a target's re-run for the whole run.
1098
1283
  let next = action.line;
1099
1284
  if (step.kind === 'decision' && autonomous && rerun !== undefined) {
1100
- step = conversationStage({ line: rerun.line }) ? { kind: 'conversation', line: rerun.line } : { kind: 'spawn', home: root, target: action.target };
1101
- next = rerun.line;
1285
+ // Row 241 (R12): a plan step's re-run runs at its row's home (the worktree), on its model.
1286
+ step = conversationStage({ line: rerun.act.line }) ? { kind: 'conversation', line: rerun.act.line }
1287
+ : rerun.row !== undefined
1288
+ ? { kind: 'spawn', home: rerun.row.home ?? root, stage: rerun.row.stage, target: action.target, model: rerun.row.model }
1289
+ : { kind: 'spawn', home: root, target: action.target };
1290
+ next = rerun.act.line;
1102
1291
  }
1103
1292
  if (step.kind !== 'spawn') {
1104
1293
  await standAside(step, action, key);
@@ -1112,6 +1301,19 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1112
1301
  }
1113
1302
  if (waitingNeed(action, key))
1114
1303
  continue;
1304
+ // Row 241 (R11). A human un-park restarts the target's per-run spawns and wall clock, as
1305
+ // row 207's release does: an arbiter's park sets no aside, so no take-back would. Only an
1306
+ // un-park witness journaled counts — committed by a state commit, a human's, right after a
1307
+ // park — so a line a session merely appended to the journal restarts no cap.
1308
+ if (action.target !== undefined) {
1309
+ const acts = journalActs(root, action.target);
1310
+ const es = acts.map((a) => a.entry);
1311
+ const n = acts.filter((a, i) => !/^0+$/.test(a.commit) && unparkAt(es, i)).length;
1312
+ const seen = unparksSeen.get(key);
1313
+ if (seen !== undefined && n > seen)
1314
+ use.delete(key);
1315
+ unparksSeen.set(key, n);
1316
+ }
1115
1317
  // A cap outranks a stall in the report, and no session is spent past it.
1116
1318
  if (await capped(action, key))
1117
1319
  continue;
@@ -1124,22 +1326,36 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1124
1326
  }
1125
1327
  if (autonomous) {
1126
1328
  publish();
1127
- notifyNew(owed().filter((i) => i.kind !== 'pending-txn' && !busy(i.target)));
1329
+ notifyNew(owed().filter((i) => i.kind !== 'pending-txn' && !busy(i.target) && !busySeen.has(i.target)));
1128
1330
  }
1129
1331
  if (lanes.size === 0) {
1130
1332
  if (!stop && !signalled && pausedUntil > clock.now()) {
1131
1333
  await Promise.race([clock.sleep(pausedUntil - clock.now()), aborted]);
1132
1334
  continue;
1133
1335
  }
1336
+ // Row 240. A target another process holds is work in flight, not the human's: drive polls on
1337
+ // its pause cadence — no pause, no notification — until a take or a release frees it.
1338
+ if (!stop && !signalled && busySeen.size > 0) {
1339
+ await Promise.race([clock.sleep(PAUSE_POLL_MS), aborted]);
1340
+ continue;
1341
+ }
1134
1342
  // Row 202. Not --manual: there the human is at drive's prompt, and the run ends as before.
1135
- if (autonomous && !stop && !signalled && [...aside.values()].some((a) => !notice(a)) && await pauseForHuman())
1343
+ const forHuman = humanAsides().some((a) => !notice(a));
1344
+ if (autonomous && !stop && !signalled && forHuman && await pauseForHuman())
1136
1345
  continue;
1346
+ // Row 240. Only drive's own timers wait: it sleeps until the earliest is due.
1347
+ const due = nextDue();
1348
+ if (autonomous && !stop && !signalled && !forHuman && due !== undefined) {
1349
+ await Promise.race([clock.sleep(Math.max(0, due - clock.now())), aborted]);
1350
+ continue;
1351
+ }
1137
1352
  break;
1138
1353
  }
1139
1354
  const { key, end } = await Promise.race([...lanes].map(([k, l]) => l.end.then((e) => ({ key: k, end: e }))));
1140
1355
  settle(key, lanes.get(key), end); // a usage limit pauses every lane here
1141
1356
  lanes.delete(key);
1142
1357
  releaseDeadTurn(root);
1358
+ sweepDeadBusy(root, { pid: process.pid });
1143
1359
  }
1144
1360
  if (signalled !== undefined)
1145
1361
  ctx.out(`drive: stopped — signal ${signalled}`);
@@ -1150,7 +1366,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1150
1366
  // The idle limit is no failure: the run waited on the human as long as it could.
1151
1367
  const stopped = signalled !== undefined ? `signal ${signalled}` : stop === 'idle-limit' ? undefined : stop;
1152
1368
  refreshAside();
1153
- const report = driveReport(root, ctx, cfg, start, [...aside.values()], { autonomous, ...(stopped ? { stopped } : {}) });
1369
+ const report = driveReport(root, ctx, cfg, start, humanAsides(), { autonomous, ...(stopped ? { stopped } : {}) });
1154
1370
  report.lines.forEach((l) => ctx.out(l));
1155
1371
  if (autonomous) {
1156
1372
  const local = loadLocalConfig(root);
@@ -55,6 +55,8 @@ export interface EvidenceRequirement {
55
55
  red: boolean;
56
56
  green: boolean;
57
57
  vacuous: boolean;
58
+ present?: true;
59
+ presentStep?: string;
58
60
  }
59
61
  export interface EvidenceReport {
60
62
  plan: string;
package/dist/evidence.js CHANGED
@@ -356,12 +356,18 @@ export function evidenceForDiff(runRoot, stateRoot, plan, base) {
356
356
  }
357
357
  const lastRed = lastRedIdx >= 0 ? entries[lastRedIdx] : undefined;
358
358
  const lastGreen = lastGreenIdx >= 0 ? entries[lastGreenIdx] : undefined;
359
+ // Row 241 (R10): a reconstructed red that came back vacuous ran with the change set aside —
360
+ // the behavior is already present — unlike a plain vacuous red, which cannot tell that from a
361
+ // test that asserts nothing. The reviewers judge which it is (the gate's note).
362
+ // Final review: it closes a step, so it names one — a fix round's reconstructed red names none.
363
+ const present = lastRed?.vacuous === true && lastRed.reconstructed === true && typeof lastRed.step === 'string';
359
364
  return {
360
365
  tag,
361
- red: lastRed !== undefined && matching(lastRed, tag).some((t) => !t.ok),
366
+ red: present || (lastRed !== undefined && matching(lastRed, tag).some((t) => !t.ok)),
362
367
  green: lastGreen !== undefined && lastGreenIdx > lastRedIdx &&
363
368
  matching(lastGreen, tag).every((t) => t.ok),
364
- vacuous: lastRed?.vacuous === true,
369
+ vacuous: lastRed?.vacuous === true && !present,
370
+ ...(present ? { present: true, ...(typeof lastRed.step === 'string' ? { presentStep: lastRed.step } : {}) } : {}),
365
371
  };
366
372
  });
367
373
  return {