@popovych.co/witness 0.24.2 → 0.25.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.
package/dist/drive.js CHANGED
@@ -1,27 +1,32 @@
1
- import { closeSync, constants, fstatSync, mkdirSync, openSync, writeSync } from 'node:fs';
2
- import { dirname, join } from 'node:path';
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, mkdirSync, openSync, readdirSync, statSync, writeSync } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
4
5
  import { EXIT, main } from './cli.js';
5
- import { loadConfig, loadLocalConfig } from './config.js';
6
+ import { canonPaths, loadConfig, loadLocalConfig } from './config.js';
6
7
  import { withoutSession } from './context.js';
7
8
  import { detectionVariables, resolveJudge } from './harness.js';
8
9
  import { ok, refuse, renderRefusal, v } from './refusal.js';
9
10
  import { findById, loadCanon } from './scan.js';
10
11
  import { NO_CONSOLE_ENV, resolveSpawn, spawn, treeStop } from './spawn.js';
11
12
  import { computeNext, conversationStage } from './verbs/next.js';
12
- import { DRIVE_DEADLINE_ENV, DRIVE_ENV, DRIVE_LOG, DRIVE_LOG_ENV, TARGETLESS } from './drive-presence.js';
13
+ import { DRIVE_DEADLINE_ENV, DRIVE_ENV, DRIVE_LOG, DRIVE_LOG_ENV, TARGETLESS, driveHolder } from './drive-presence.js';
14
+ import { isAlive, pause } from './lock.js';
13
15
  import { ASK_STREAM } from './ask.js';
14
16
  import { KEPT_STOP_NAMES, unmetNeedLine } from './autonomy.js';
15
17
  import { unmetNeeds } from './needs.js';
16
18
  import { capHit, parkAtCap } from './caps.js';
17
19
  import { effortStreams, readStream } from './journal.js';
20
+ import { movesFlow } from './progress.js';
21
+ import { sourced } from './allowlist.js';
18
22
  import { effortOf } from './reviewed.js';
19
- import { vacuousEvidence } from './steps.js';
20
23
  import { pendingTxn } from './txn.js';
21
24
  import { duration, limitIn, realClock, sessionLimit, SINGLE_WAIT_MAX_MS, TOTAL_WAIT_MAX_MS, waitFor, } from './usage.js';
22
25
  import { keepAwake } from './awake.js';
23
26
  import { driveReport, runStart } from './drive-report.js';
24
27
  import { notify } from './notify.js';
28
+ import { writeLive } from './live.js';
29
+ import { needsYou, needsYouToken, WAIT_LABEL } from './needs-you.js';
25
30
  // The rule table is an ORDERED FIRST-MATCH list, on `recommend.ts`'s precedent: a
26
31
  // misrouted action is attributable to one line here rather than to a weighting. Pure over
27
32
  // the NextAction shape — no I/O — so every branch is one `expect` away.
@@ -43,6 +48,11 @@ export function classifyAction(action, root, opts = {}) {
43
48
  const [, , gate, target] = line.split(' ');
44
49
  return { kind: 'decision', gate, target: target ?? action.target };
45
50
  }
51
+ // Row 205 (issue #56). A step whose runner, ship lanes or cmd: need this machine does not
52
+ // trust would only be refused inside the session — the refusal journaled nothing, so drive
53
+ // respawned it to the cap. In both modes it waits for the human, and no session is spent.
54
+ if (action.trust !== undefined && action.trust.length > 0)
55
+ return { kind: 'kept', stop: 'trust-grant', line };
46
56
  // D121: a block is the CLI saying the human is choosing, not being told — so a runnable
47
57
  // line under a block (the recovery fork, `N ready — ranked below`) is still a stop.
48
58
  // Below the decide rule so a gate decision keeps its gate/target rather than its block.
@@ -270,14 +280,48 @@ export const DEFAULT_MAX_SPAWNS = 20;
270
280
  // against accounting bugs: 200 is the 203 sessions fewhats ran in the whole 33-day evidence
271
281
  // window (design §2).
272
282
  export const AUTONOMY_MAX_SPAWNS = 200;
283
+ // Row 202 (issue #56). When everything left waits on the human, an autonomous drive pauses
284
+ // instead of quitting: it polls what a human act writes every 5 s and gives up after 12 h with
285
+ // nothing moving. Constants, not settings (no `migrate` for an upgrade); the suite reaches them
286
+ // through the Clock seam, and a CLI-level test bounds the idle limit through an undocumented
287
+ // seam on WITNESS_KEEP_AWAKE_BIN's precedent.
288
+ export const PAUSE_POLL_MS = 5_000;
289
+ const DETACH_LOCK_WAIT_MS = 10_000;
290
+ export const PAUSE_IDLE_MAX_MS = 43_200_000;
291
+ const idleMaxOf = (env) => {
292
+ const v = env.WITNESS_DRIVE_IDLE_MAX_MS;
293
+ return v !== undefined && /^\d+$/.test(v) ? Number(v) : PAUSE_IDLE_MAX_MS;
294
+ };
295
+ // What a human act writes: the journal, canon, the committed config, the trust list and the
296
+ // machine config — each file's size and mtime, hashed. Never drive's own log or its live
297
+ // folder, which it writes itself while paused.
298
+ export function watchSignature(root) {
299
+ const p = canonPaths(root);
300
+ const files = [];
301
+ for (const dir of [join(root, '.witness', 'journal'), join(root, p.specs), join(root, p.plans), join(root, p.designs)]) {
302
+ try {
303
+ for (const n of readdirSync(dir, { recursive: true }))
304
+ files.push(join(dir, n));
305
+ }
306
+ catch { /* absent: nothing to watch there yet */ }
307
+ }
308
+ for (const f of ['witness.config.yaml', join('.witness', 'allow.json'), join('.witness', 'config.local.yaml')])
309
+ files.push(join(root, f));
310
+ const parts = files.sort().map((f) => {
311
+ try {
312
+ const st = statSync(f);
313
+ return st.isFile() ? `${f}:${st.size}:${st.mtimeMs}` : '';
314
+ }
315
+ catch {
316
+ return `${f}:-`;
317
+ }
318
+ });
319
+ return createHash('sha1').update(parts.join('\n')).digest('hex');
320
+ }
273
321
  const STREAM_PREFIX = /^\[\d+ [^\]]*\] /;
274
322
  // What `mergeOwnPr` prints when it leaves the merge to a human (ship.ts), and nothing else.
275
323
  const MERGE_LINE = /^ship: "?merge PR #(\d+) on GitHub when ready/;
276
324
  const streamLines = (root, id) => readStream(root, id).length;
277
- // A refused write is the CLI saying no: it moves nothing (F5). Nor does a vacuous red (row 191,
278
- // final review I3): a session that only re-runs one has done nothing, and counted, it read as
279
- // progress, so the target was respawned until its spawn cap.
280
- const moved = (e) => e.t !== 'write-refused' && !vacuousEvidence(e);
281
325
  // Row 181. Did anything happen for THIS target? A whole-journal count is satisfied by any
282
326
  // other lane's progress, so a stalled flow beside a busy one would spawn until the ceiling.
283
327
  // A target's key is its line, its stream, and the entries in its owning effort's stream that
@@ -296,9 +340,9 @@ function progressKey(root, action, family) {
296
340
  const target = action.target;
297
341
  const effort = effortOf(root, target);
298
342
  const flow = family(target);
299
- const own = readStream(root, target).filter(moved).length;
343
+ const own = readStream(root, target).filter(movesFlow).length;
300
344
  const inEffort = effort !== undefined && effort !== target
301
- ? readStream(root, effort).filter((e) => moved(e) && flow.includes(String(e.artifact))).length
345
+ ? readStream(root, effort).filter((e) => movesFlow(e) && flow.includes(String(e.artifact))).length
302
346
  : 0;
303
347
  return [action.line, own, inEffort].join('\u0000');
304
348
  }
@@ -391,14 +435,39 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
391
435
  // (an ask answered or queued, a need satisfied, a stop decided in a chat) leaves the aside
392
436
  // set and competes for a slot again. One whose next act is the human's again is set aside
393
437
  // anew, under its new key, by the settle pass or the fill that meets it.
438
+ // Row 207: a release is a new chance, so the target's per-run use and its last key go too.
439
+ const release = (key) => {
440
+ aside.delete(key);
441
+ use.delete(key);
442
+ progress.delete(key);
443
+ pauseSince = undefined; // a human act: the idle clock starts over
444
+ // What this target needs of the human next is news (final review): a second trust grant,
445
+ // a stuck again after a retry. Keys are `<kind>:<target>[:…]`, and ids carry no colon.
446
+ for (const k of [...notified])
447
+ if (k.split(':')[1] === key)
448
+ notified.delete(k);
449
+ };
450
+ // A plan that reached its end — merged, abandoned — is no flow any more: its scoped ladder
451
+ // answers with a global rung, so `ownAnswer` would hold its aside forever.
452
+ const ended = (key) => {
453
+ const doc = findById(canonNow, key);
454
+ const status = String(doc?.meta.status);
455
+ return doc?.meta.type === 'plan' && (status === 'done' || status === 'abandoned') ? status : undefined;
456
+ };
394
457
  const takeBack = () => {
395
458
  for (const [key, a] of aside) {
396
459
  if (a.key0 === undefined)
397
460
  continue;
461
+ const over = ended(key);
462
+ if (over !== undefined) {
463
+ release(key);
464
+ ctx.out(`drive: released — ${key} · ${over}`);
465
+ continue;
466
+ }
398
467
  const now = ownNext(key);
399
468
  if (!ownAnswer(key, now) || keyOf(now) === a.key0)
400
469
  continue;
401
- aside.delete(key);
470
+ release(key);
402
471
  ctx.out(`drive: taken back — ${key === TARGETLESS ? 'untargeted work' : key} · ${now.line}`);
403
472
  }
404
473
  };
@@ -410,6 +479,10 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
410
479
  for (const [key, a] of aside) {
411
480
  if (a.key0 === undefined)
412
481
  continue;
482
+ if (ended(key) !== undefined) {
483
+ aside.delete(key);
484
+ continue;
485
+ }
413
486
  const now = ownNext(key);
414
487
  if (!ownAnswer(key, now) || keyOf(now) === a.key0)
415
488
  continue;
@@ -421,8 +494,10 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
421
494
  };
422
495
  const stuck = (key, action) => {
423
496
  ctx.out(`drive: no progress — ${action.line}`);
424
- ctx.out(`help: ${action.target ?? 'untargeted work'} is set aside for this run — read its stream above`);
425
- setAside(key, { kind: 'stuck', line: action.line, why: `no progress on ${action.line}` });
497
+ ctx.out(action.target !== undefined
498
+ ? `help: ${action.target} is set aside until its record moves — read its stream above · after a fix witness cannot see: witness retry ${action.target}`
499
+ : 'help: untargeted work is set aside until its record moves — read its stream above');
500
+ setAside(key, { kind: 'stuck', line: action.line, why: `no progress on ${action.line}`, key0: keyOf(action) });
426
501
  };
427
502
  // A decision is an act too, and it gets the same convergence guard as a spawn: a decision
428
503
  // that executes and journals nothing would otherwise re-render its own block forever.
@@ -436,6 +511,14 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
436
511
  return false;
437
512
  };
438
513
  const standAside = async (step, action, key) => {
514
+ if (step.kind === 'kept') {
515
+ ctx.out(`drive: waits on you — ${action.target ?? 'untargeted work'} · ${KEPT_STOP_NAMES[step.stop]}`);
516
+ setAside(key, {
517
+ kind: 'kept', line: step.line, why: KEPT_STOP_NAMES[step.stop], stop: step.stop,
518
+ ...(action.trust !== undefined ? { trust: action.trust } : {}), key0: keyOf(action),
519
+ });
520
+ return;
521
+ }
439
522
  if (step.kind === 'conversation') {
440
523
  ctx.out(`drive: conversation — ${step.line}`);
441
524
  ctx.out('help: run /witness in a chat — drive takes it back when you are done');
@@ -444,7 +527,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
444
527
  }
445
528
  if (step.kind === 'merge') {
446
529
  ctx.out(`drive: merge — ${step.line}`);
447
- setAside(key, { kind: 'merge', line: step.line, why: 'the merge is a human\'s' });
530
+ setAside(key, { kind: 'merge', line: step.line, why: 'the merge is a human\'s', key0: keyOf(action) });
448
531
  return;
449
532
  }
450
533
  // Under autonomy a `witness decide` line still reaching the fill is a stop the settle
@@ -461,7 +544,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
461
544
  if (r === 'stands')
462
545
  setAside(key, { kind: 'decision', line: action.line, why: action.line, ...(step.gate ? { gate: step.gate } : {}), key0: keyOf(action) });
463
546
  if (r === 'refused')
464
- setAside(key, { kind: 'stuck', line: action.line, why: `decision refused on ${action.line}` });
547
+ setAside(key, { kind: 'stuck', line: action.line, why: `decision refused on ${action.line}`, key0: keyOf(action) });
465
548
  };
466
549
  const launch = (step, action, n) => {
467
550
  const lane = { action, end: Promise.resolve(undefined) };
@@ -519,6 +602,13 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
519
602
  pauseFor(limit);
520
603
  return true;
521
604
  };
605
+ // Final review I3: an aside set when a lane ends keys on the target's state after the session,
606
+ // as the settle pass's do — the line the lane started with may be one the session moved past,
607
+ // which would read as a human's move at the next take-back.
608
+ const keyAfter = (key) => {
609
+ canonNow = loadCanon(root);
610
+ return keyOf(ownNext(key));
611
+ };
522
612
  const settle = (key, lane, end) => {
523
613
  if (end.outcome === 'stopped')
524
614
  return; // the signal's, reported once at the end
@@ -528,7 +618,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
528
618
  use.set(key, { spawns: u.spawns + 1, ms: u.ms + end.ms });
529
619
  if (end.outcome === 'timeout') {
530
620
  ctx.out(`drive: spawn-timeout — ${lane.action.line}`);
531
- setAside(key, { kind: 'stuck', line: lane.action.line, why: `spawn-timeout on ${lane.action.line}` });
621
+ setAside(key, { kind: 'stuck', line: lane.action.line, why: `spawn-timeout on ${lane.action.line}`, key0: keyAfter(key) });
532
622
  return;
533
623
  }
534
624
  if (end.outcome === 'spawn-failed') {
@@ -538,7 +628,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
538
628
  }
539
629
  if (lane.merged !== undefined) {
540
630
  ctx.out(`drive: merge — ${lane.merged}`);
541
- setAside(key, { kind: 'merge', line: lane.merged, why: 'the merge is a human\'s' });
631
+ setAside(key, { kind: 'merge', line: lane.merged, why: 'the merge is a human\'s', key0: keyAfter(key) });
542
632
  }
543
633
  };
544
634
  // Row 180. Under autonomy each round starts with one settle pass over every target no
@@ -561,7 +651,11 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
561
651
  ctx.out(line);
562
652
  if (s.kind === 'kept') {
563
653
  ctx.out(`drive: waits on you — ${r.target} · ${KEPT_STOP_NAMES[s.stop]}`);
564
- setAside(r.target, { kind: 'kept', line: s.line, why: KEPT_STOP_NAMES[s.stop], gate: r.gate, stop: s.stop, key0: keyOf(ownNext(r.target)) });
654
+ const trust = s.untrusted !== undefined ? sourced(cfg, canonNow, r.target, s.untrusted) : undefined;
655
+ setAside(r.target, {
656
+ kind: 'kept', line: s.line, why: KEPT_STOP_NAMES[s.stop], gate: r.gate, stop: s.stop,
657
+ ...(trust !== undefined ? { trust } : {}), key0: keyOf(ownNext(r.target)),
658
+ });
565
659
  }
566
660
  else if (s.kind === 'left') {
567
661
  ctx.out(`drive: waits on you — ${r.target} · decision · ${s.why}`);
@@ -600,20 +694,98 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
600
694
  if (parked.parked) {
601
695
  ctx.out(`drive: parked — ${action.target} · ${hit.note}`);
602
696
  const gate = hit.gate ?? lastRunGate(readStream(root, action.target));
603
- setAside(key, { kind: 'capped', line: action.line, why: hit.note, ...(gate ? { gate } : {}) });
697
+ setAside(key, { kind: 'capped', line: action.line, why: hit.note, ...(gate ? { gate } : {}), key0: keyOf(action) });
604
698
  }
605
699
  else {
606
700
  const why = `${hit.note} · ${parked.why}`;
607
701
  ctx.out(`drive: capped — ${action.target} · ${why}`);
608
- setAside(key, { kind: 'capped', line: action.line, why });
702
+ setAside(key, { kind: 'capped', line: action.line, why, key0: keyOf(action) });
609
703
  }
610
704
  return true;
611
705
  };
612
706
  const start = runStart(root);
613
- const awake = keepAwake(ctx.env, process.platform, process.pid);
707
+ let awake = keepAwake(ctx.env, process.platform, process.pid);
708
+ let awakeHeld = true;
614
709
  ctx.out(awake.command !== undefined
615
710
  ? `keep-awake: ${awake.command} — a closed lid on battery still sleeps`
616
711
  : `keep-awake: none on ${process.platform} — keep the host awake yourself`);
712
+ // Row 182, amended by row 202: held while a session runs, released while drive waits on the
713
+ // human — a paused drive lets the machine sleep — and taken again before the next spawn.
714
+ const holdAwake = () => {
715
+ if (awakeHeld)
716
+ return;
717
+ awake = keepAwake(ctx.env, process.platform, process.pid);
718
+ awakeHeld = true;
719
+ };
720
+ const releaseAwake = () => {
721
+ if (!awakeHeld)
722
+ return;
723
+ awake.stop();
724
+ awakeHeld = false;
725
+ };
726
+ // Row 203. Drive's set-asides, published for a chat waiting beside it: ids and kinds only. A
727
+ // grill with nothing queued waits on nobody and is not published.
728
+ const notice = (a) => a.target === TARGETLESS && a.kind === 'conversation' && !/ --ask /.test(a.line);
729
+ const publish = (ended) => {
730
+ if (!autonomous)
731
+ return;
732
+ const asides = [...aside.values()].filter((a) => !notice(a)).map((a) => ({
733
+ target: a.target, kind: a.kind, ...(a.gate !== undefined ? { gate: a.gate } : {}), ...(a.stop !== undefined ? { stop: a.stop } : {}),
734
+ }));
735
+ writeLive(root, { pid: process.pid, asides, ...(ended !== undefined ? { ended } : {}) });
736
+ };
737
+ // Row 203 (Q2). Each item that newly needs the human is notified once per run (n5), a burst
738
+ // as one notification, started in the background so no round waits on it. Mid-run, an item
739
+ // whose flow a session is working on is that session's to settle, and a crash is drive's own
740
+ // to recover; both are said only once drive pauses.
741
+ const notified = new Set();
742
+ const busy = (t) => [...lanes.keys()].some((l) => l === t || family(l).includes(t) || family(t).includes(l));
743
+ const notifyNew = (items) => {
744
+ const fresh = items.filter((i) => i.notice !== true && !notified.has(i.key));
745
+ if (fresh.length === 0)
746
+ return;
747
+ for (const i of fresh)
748
+ notified.add(i.key);
749
+ const named = fresh.slice(0, 3).map((i) => i.kind === 'pending-txn' ? WAIT_LABEL[i.kind] : `${WAIT_LABEL[i.kind]} · ${i.target}`);
750
+ const local = loadLocalConfig(root);
751
+ notify(local.ok ? local.value.notify : undefined, 'witness drive', `witness · ${basename(root)}: ${named.join(' · ')}${fresh.length > 3 ? ` (+${fresh.length - 3})` : ''}`, process.platform, { wait: false });
752
+ };
753
+ const owed = () => needsYou(root, ctx, cfg, loadCanon(root), [...aside.values()]);
754
+ // Row 202. Everything left waits on the human: say what, notify, let the machine sleep, and
755
+ // watch for the act. A change runs a round as usual (take-back, settle pass, fill); a change
756
+ // that releases nothing re-enters the pause silently. True to run a round, false to end.
757
+ const idleMax = idleMaxOf(ctx.env);
758
+ let pauseSince;
759
+ let pausePrinted;
760
+ // Final review (b) I3: the signature the round began with. A human act that lands during the
761
+ // round — after its take-back, before the pause — differs from it, and resumes at once.
762
+ let roundSignature = '';
763
+ const pauseForHuman = async () => {
764
+ const items = owed().filter((i) => i.notice !== true);
765
+ const token = needsYouToken(items);
766
+ if (token !== pausePrinted) {
767
+ ctx.out(`drive: waiting on you — ${items.length} item(s)`);
768
+ items.flatMap((i) => i.rows).forEach((l) => ctx.out(l));
769
+ pausePrinted = token;
770
+ }
771
+ notifyNew(items);
772
+ releaseAwake();
773
+ publish();
774
+ pauseSince ??= clock.now();
775
+ const signature = roundSignature;
776
+ for (;;) {
777
+ if (watchSignature(root) !== signature)
778
+ return true;
779
+ if (clock.now() - pauseSince >= idleMax) {
780
+ ctx.out(`drive: idle limit — waited ${duration(idleMax)} on you · the run ends`);
781
+ stop = 'idle-limit';
782
+ return false;
783
+ }
784
+ await Promise.race([clock.sleep(PAUSE_POLL_MS), aborted]);
785
+ if (signalled !== undefined)
786
+ return false;
787
+ }
788
+ };
617
789
  // Final review F9. Autonomy is re-read from the committed config before every round, on
618
790
  // A1's precedent (ship re-reads it at merge time): a human who turns it off mid-run takes
619
791
  // the wheel at once — no stop of theirs is settled, and no new session starts.
@@ -629,8 +801,11 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
629
801
  };
630
802
  process.on('SIGINT', onSignal);
631
803
  process.on('SIGTERM', onSignal);
804
+ publish();
632
805
  try {
633
806
  for (;;) {
807
+ if (autonomous)
808
+ roundSignature = watchSignature(root);
634
809
  stillAutonomous();
635
810
  canonNow = loadCanon(root);
636
811
  // A run that is stopping fills nothing more, so a target released now would be set aside
@@ -676,13 +851,22 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
676
851
  if (unmoved(key, action))
677
852
  continue;
678
853
  spawns += 1;
854
+ holdAwake();
855
+ pauseSince = undefined;
679
856
  lanes.set(key, launch(step, action, spawns));
680
857
  }
858
+ if (autonomous) {
859
+ publish();
860
+ notifyNew(owed().filter((i) => i.kind !== 'pending-txn' && !busy(i.target)));
861
+ }
681
862
  if (lanes.size === 0) {
682
863
  if (!stop && !signalled && pausedUntil > clock.now()) {
683
864
  await Promise.race([clock.sleep(pausedUntil - clock.now()), aborted]);
684
865
  continue;
685
866
  }
867
+ // Row 202. Not --manual: there the human is at drive's prompt, and the run ends as before.
868
+ if (autonomous && !stop && !signalled && [...aside.values()].some((a) => !notice(a)) && await pauseForHuman())
869
+ continue;
686
870
  break;
687
871
  }
688
872
  const { key, end } = await Promise.race([...lanes].map(([k, l]) => l.end.then((e) => ({ key: k, end: e }))));
@@ -695,7 +879,8 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
695
879
  ctx.out(`drive: idle — ${idle}`);
696
880
  // Row 184. One report when nothing else can move, and for an autonomous run one
697
881
  // notification — a human at a TTY prompt is already watching.
698
- const stopped = signalled !== undefined ? `signal ${signalled}` : stop;
882
+ // The idle limit is no failure: the run waited on the human as long as it could.
883
+ const stopped = signalled !== undefined ? `signal ${signalled}` : stop === 'idle-limit' ? undefined : stop;
699
884
  refreshAside();
700
885
  const report = driveReport(root, ctx, cfg, start, [...aside.values()], { autonomous, ...(stopped ? { stopped } : {}) });
701
886
  report.lines.forEach((l) => ctx.out(l));
@@ -712,7 +897,8 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
712
897
  finally {
713
898
  process.removeListener('SIGINT', onSignal);
714
899
  process.removeListener('SIGTERM', onSignal);
715
- awake.stop();
900
+ publish(signalled !== undefined ? 'signal' : stop ?? 'done');
901
+ releaseAwake();
716
902
  }
717
903
  }
718
904
  // Row 180. `--detach`: this CLI again, as `witness drive <args>`, in the background at the
@@ -749,6 +935,14 @@ export function detachDrive(root, ctx, args) {
749
935
  return refuse([v('--detach', 'spawn-failed', file, 'a runnable witness CLI')]);
750
936
  child.on('error', () => { });
751
937
  child.unref();
938
+ // Final review: return once the child holds the drive lock (or has died, or a bound passed),
939
+ // so a chat's `wait` started right after it never reads the drive as stopped — the previous
940
+ // run's end record would otherwise answer for a drive that is only starting.
941
+ const deadline = Date.now() + DETACH_LOCK_WAIT_MS;
942
+ // Any live holder is this child's (detach refuses while a drive runs); under a WITNESS_BIN
943
+ // wrapper the lock's pid may be a process the wrapper started.
944
+ while (Date.now() < deadline && driveHolder(root) === undefined && isAlive(child.pid))
945
+ pause(50);
752
946
  return ok({ pid: child.pid, log });
753
947
  }
754
948
  finally {
package/dist/gitio.js CHANGED
@@ -114,7 +114,8 @@ const LOCAL_STATE_FILES = new Set([
114
114
  // and the exemption is load-bearing for the same reason: init writes its .gitignore block only
115
115
  // when scaffolding, so on every repo older than the row a draft is untracked-but-visible under a
116
116
  // state dir, and an unrelated-dirty refusal there would block the very recap the grill lands.
117
- const LOCAL_STATE_DIRS = ['.witness/drafts/'];
117
+ // Row 203: drive's live folder (what needs the human, the waiting chat's lock) is the same tier.
118
+ const LOCAL_STATE_DIRS = ['.witness/drafts/', '.witness/live/'];
118
119
  export function dirtyStatePaths(root) {
119
120
  const res = tryGit(root, 'status', '--porcelain', '--untracked-files=all', '--', ...stateDirs(root));
120
121
  if (!res.ok || res.out === '')
package/dist/harness.js CHANGED
@@ -75,6 +75,7 @@ const REGISTRY = {
75
75
  launch: 'claude',
76
76
  relay: '/clear',
77
77
  session: 'CLAUDE_CODE_SESSION_ID',
78
+ waitMode: 'background',
78
79
  settings: '.claude/settings.json',
79
80
  bundled: true,
80
81
  payload: [
@@ -116,6 +117,7 @@ const REGISTRY = {
116
117
  defaultProvider: 'anthropic',
117
118
  relay: '/new',
118
119
  session: 'PI_SESSION_ID',
120
+ waitMode: 'add-on',
119
121
  bundled: false,
120
122
  payload: [
121
123
  { from: 'plugin/commands/witness.md', to: '.pi/prompts/witness.md' },
package/dist/install.js CHANGED
@@ -132,6 +132,21 @@ export function payloadHomes(root) {
132
132
  .map((e) => join(dir, e.name))
133
133
  .sort()];
134
134
  }
135
+ // Row 102: content, not pins — every installed payload file, in every home, that differs from
136
+ // what this CLI ships. A shipped file that cannot be read is a packaging failure, not staleness,
137
+ // and is skipped. Read by `check` (payload-stale) and by `next`, whose waiting Pi chat falls
138
+ // back to the foreground when its add-on is older than this CLI (row 204).
139
+ export function payloadStale(root, harness) {
140
+ const installed = harness.payload.filter((p) => existsSync(join(root, p.to)));
141
+ return payloadHomes(root).flatMap((home) => installed
142
+ .filter((p) => {
143
+ const src = join(packageRoot(), p.from);
144
+ if (!existsSync(src) || !existsSync(join(home, p.to)))
145
+ return false;
146
+ return readFileSync(join(home, p.to), 'utf8') !== readFileSync(src, 'utf8');
147
+ })
148
+ .map((p) => (home === root ? p.to : `${home}: ${p.to}`)));
149
+ }
135
150
  // Preflight EVERY home before writing ANY. install.ts's standing doctrine is that a
136
151
  // refusal leaves nothing half-installed; across homes that matters more, not less — a
137
152
  // half-upgraded set of homes IS the skew row 116 refuses and this row prevents.
package/dist/live.js ADDED
@@ -0,0 +1,143 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { KEPT_STOP_NAMES } from './autonomy.js';
5
+ import { TARGETLESS, driveHolder } from './drive-presence.js';
6
+ import { effortStreams } from './journal.js';
7
+ import { GATE_NAMES } from './settings.js';
8
+ import { ensureExcluded } from './worktree.js';
9
+ // Row 203. Drive's set-asides — stuck and capped above all — live only in its memory (D145),
10
+ // and a chat waiting beside it must know them. So drive publishes what needs the human here,
11
+ // machine-local and never committed (excluded the three ways the drafts are). Row 145: a killed
12
+ // drive leaves no cleanup, so a reader trusts the file only while the drive it names holds the
13
+ // drive lock. And it is display data at most: only ids and kinds survive the read, never text,
14
+ // and every line a reader prints is rendered by the CLI (`drive-presence.ts`'s doctrine).
15
+ export const LIVE_DIR = '.witness/live';
16
+ const DRIVE_FILE = 'drive.json';
17
+ const WAITER_FILE = 'waiter.json';
18
+ const END_REASONS = ['done', 'idle-limit', 'ceiling', 'usage', 'autonomy-off', 'spawn-failed', 'signal'];
19
+ const ASIDE_KINDS = ['kept', 'decision', 'conversation', 'merge', 'stuck', 'capped'];
20
+ // A folder a repo committed as a symlink would aim drive's writes anywhere: refused, as
21
+ // `detachDrive` refuses a linked log. Absent is fine — the first write makes it.
22
+ function liveDir(root, create) {
23
+ const dir = join(root, LIVE_DIR);
24
+ try {
25
+ if (!lstatSync(dir).isDirectory())
26
+ return undefined;
27
+ }
28
+ catch (e) {
29
+ if (e.code !== 'ENOENT' || !create)
30
+ return undefined;
31
+ mkdirSync(dir, { recursive: true });
32
+ }
33
+ return dir;
34
+ }
35
+ // Written to a temp name and renamed, so a reader never sees half a file. The temp name is
36
+ // random and created exclusively without following a link: a repo can commit files inside a
37
+ // real .witness/live/, and a link at a name drive would write through could aim it anywhere.
38
+ // The rename replaces whatever entry holds the final name, a link included, never its target.
39
+ function put(root, file, value) {
40
+ // Spec c2 (final review I1): a repo whose ignore rules predate this folder must never show it,
41
+ // and drive may run without starting the session whose worktree would exclude it — so the
42
+ // write excludes it first, as a draft's does. Best effort: a write is never refused for it.
43
+ try {
44
+ ensureExcluded(root);
45
+ }
46
+ catch { /* not a git checkout we can write to */ }
47
+ const dir = liveDir(root, true);
48
+ if (dir === undefined)
49
+ return;
50
+ const tmp = join(dir, `.${file}.${randomBytes(8).toString('hex')}.tmp`);
51
+ let fd;
52
+ try {
53
+ fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o644);
54
+ writeSync(fd, JSON.stringify(value));
55
+ closeSync(fd);
56
+ fd = undefined;
57
+ renameSync(tmp, join(dir, file));
58
+ }
59
+ catch {
60
+ // best effort: a reader with no file reads "unknown", never a wrong answer
61
+ if (fd !== undefined)
62
+ closeSync(fd);
63
+ rmSync(tmp, { force: true });
64
+ }
65
+ }
66
+ function get(root, file) {
67
+ const dir = liveDir(root, false);
68
+ if (dir === undefined)
69
+ return undefined;
70
+ try {
71
+ const p = join(dir, file);
72
+ if (!lstatSync(p).isFile())
73
+ return undefined;
74
+ return JSON.parse(readFileSync(p, 'utf8'));
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ const isPid = (x) => Number.isInteger(x) && x > 0;
81
+ export function writeLive(root, state) {
82
+ put(root, DRIVE_FILE, state);
83
+ }
84
+ // Every field is checked against what this CLI knows: a target that is no canon id or effort, a kind,
85
+ // gate or stop this CLI does not name, is dropped whole. No free text is kept.
86
+ export function readLive(root, canon) {
87
+ const raw = get(root, DRIVE_FILE);
88
+ if (raw === undefined || raw === null || typeof raw !== 'object' || !isPid(raw.pid))
89
+ return undefined;
90
+ // Canon ids and effort slugs: drive sets aside effort-level work too (final review b-I4).
91
+ const ids = new Set([...canon.docs.map((d) => String(d.meta.id)), ...effortStreams(root)]);
92
+ const stops = Object.keys(KEPT_STOP_NAMES);
93
+ const asides = [];
94
+ for (const a of Array.isArray(raw.asides) ? raw.asides : []) {
95
+ if (a === null || typeof a !== 'object')
96
+ continue;
97
+ const { target, kind, gate, stop } = a;
98
+ if (typeof target !== 'string' || (target !== TARGETLESS && !ids.has(target)))
99
+ continue;
100
+ if (!ASIDE_KINDS.includes(kind))
101
+ continue;
102
+ if (gate !== undefined && !GATE_NAMES.includes(gate))
103
+ continue;
104
+ if (stop !== undefined && !stops.includes(stop))
105
+ continue;
106
+ asides.push({
107
+ target, kind: kind,
108
+ ...(gate !== undefined ? { gate: gate } : {}), ...(stop !== undefined ? { stop: stop } : {}),
109
+ });
110
+ }
111
+ const ended = END_REASONS.includes(raw.ended) ? { ended: raw.ended } : {};
112
+ return { pid: raw.pid, asides, ...ended };
113
+ }
114
+ // The live drive's state: only while the drive the file names holds the drive lock.
115
+ export function liveDrive(root, canon) {
116
+ const state = readLive(root, canon);
117
+ return state !== undefined && driveHolder(root)?.pid === state.pid ? state : undefined;
118
+ }
119
+ // How the last drive ended, once it no longer holds the lock — read even while its process is
120
+ // still on its way out, which is when a waiter first sees the lock gone.
121
+ export function lastEnd(root, canon) {
122
+ const state = readLive(root, canon);
123
+ return state !== undefined && driveHolder(root)?.pid !== state.pid ? state.ended : undefined;
124
+ }
125
+ // Row 204. One waiting chat per repo: the newest takes over, and the one it displaced learns so
126
+ // on its next poll. Final review C2: the waiter names its chat too (the harness's session, hashed
127
+ // — the raw id never lands on disk), so a chat whose human typed while it waited, and whose new
128
+ // turn started a second wait, reads as replaced by itself rather than taken over by another.
129
+ const chatKey = (session) => session === undefined || session === '' ? undefined : createHash('sha1').update(session).digest('hex').slice(0, 12);
130
+ export function takeWaiter(root, pid, session) {
131
+ const chat = chatKey(session);
132
+ put(root, WAITER_FILE, { pid, ...(chat !== undefined ? { chat } : {}) });
133
+ }
134
+ export function waiterState(root, pid, session) {
135
+ const raw = get(root, WAITER_FILE);
136
+ if (raw !== undefined && raw !== null && raw.pid === pid)
137
+ return 'mine';
138
+ const chat = chatKey(session);
139
+ return chat !== undefined && raw !== undefined && raw !== null && raw.chat === chat ? 'replaced' : 'taken';
140
+ }
141
+ export function waiterIs(root, pid) {
142
+ return waiterState(root, pid) === 'mine';
143
+ }