@popovych.co/witness 0.26.0 → 0.26.2

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/README.md CHANGED
@@ -293,7 +293,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
293
293
  | `design <spec-id> --file <html>\|--open\|--reconfirm\|--preview <html>` | register/show a `ui` spec's approved look; `--preview` opens a page and records nothing |
294
294
  | `start <plan-id>` | create/re-attach the plan's worktree (`.witness/worktrees/<id>`) — code only: the canon dirs are excluded from it, so a plan cannot go stale in there |
295
295
  | `next` | the one next action across every effort |
296
- | `drive [--flow <plan-id>] [--max-spawns <n>] [--manual] [--detach]` | runs every session itself · under autonomy it needs no terminal and reports when nothing else can move. Up to `drive.parallel` targets at once, one session per target; usage limits are waited out; a target past a cap is parked. `--detach` (autonomy only) runs it in the background into `.witness/drive.log`; `--manual` runs serially and asks you at every stop. One drive per repo. A session drive spawned is refused — agents are what drive spawns, never what spawns drive |
296
+ | `drive [--flow <plan-id>] [--max-spawns <n>] [--manual] [--detach]` | runs every session itself · under autonomy it needs no terminal and reports when nothing else can move. Up to `drive.parallel` targets at once, one session per target; usage limits are waited out; a target past a cap is parked. `--detach` (autonomy only) runs it in the background into `.witness/drive.log` — each session's start, every command and file its agent touches, every act it journals for its flow, a `still running` line after 5 quiet minutes, and how it ended; drive's pi sessions are kept in pi's session store under `witness-drive/`; `--manual` runs serially and asks you at every stop. One drive per repo. A session drive spawned is refused — agents are what drive spawns, never what spawns drive |
297
297
  | `ship <plan-id> [--manual]` | lanes → ship gate → PR → CI watch → under autonomy: merge on green · `--manual` keeps that run's stop and merge for a human |
298
298
  | `test-evidence <plan-id> --phase red\|green [--step <id>]` / `verify-red <plan-id> [--base <ref>] [--step <id>]` | journal red/green criteria evidence from a worktree; `--step` names the plan step the cycle closes — required before the plan's first implement gate (on a plan with a criteria step), left off for a fix round after it. A green that closes a step prints `context:`, `steps:` and `slice:` |
299
299
  | `step-close <plan-id> --step <id>` | close a scaffolding step, which has no red→green to witness; prints `context:`, `steps:` and `slice:` as a closing green does, and closing it again changes nothing |
package/dist/arbiter.js CHANGED
@@ -94,8 +94,8 @@ export async function arbitrate(ctx, root, cfg, req) {
94
94
  // and every approve over a failed deterministic check — it may overrule a reviewer, never a
95
95
  // check. `amendment-ack` alone is the exception: approving IS its acknowledgement.
96
96
  // The design gate is the exception that holds whatever the evidence says: the look is the
97
- // human's (§3 G2), so no approve of it is ever offered — at the bound, on a fallback round or
98
- // past a spent ladder the arbiter may revise, reset upstream, repair or park, never stamp.
97
+ // human's (§3 G2), so no approve of it is ever offered — at the bound or past a spent ladder
98
+ // the arbiter may revise, reset upstream, repair or park, never stamp.
99
99
  export function menuFor(block, run) {
100
100
  const failed = run.checks.filter((c) => !c.ok);
101
101
  const approveBarred = run.gate === 'design' || (failed.length > 0 && !failed.every((c) => c.name === 'amendment-ack'));
package/dist/awake.js CHANGED
@@ -44,14 +44,21 @@ export function awakeArgv(env, platform, pid) {
44
44
  const nameOf = (file) => file.split(/[\\/]/).pop() ?? file;
45
45
  // Why a helper that ended before drive let go of it no longer holds the host, or undefined when
46
46
  // its end is no news: a signal (drive's own group stop, the terminal's Ctrl+C), a clean exit
47
- // (caffeinate's `-w` pid ended), or win32's Ctrl+C status.
48
- export function lostWhy(platform, file, code, signal) {
47
+ // (caffeinate's `-w` pid ended), or win32's Ctrl+C status. The cause is named: exit 3 is
48
+ // AWAKE_SCRIPT's own, and otherwise `said` — the helper's first stderr line, which in Windows
49
+ // PowerShell 5.1's error view is the message of the error that stopped it, ahead of its
50
+ // `At line`, `~~~`, `+ CategoryInfo` and `+ FullyQualifiedErrorId` lines.
51
+ export function lostWhy(platform, file, code, signal, said = '') {
49
52
  if (signal !== null || code === null || code === 0)
50
53
  return undefined;
51
54
  if (platform === 'win32' && code === CTRL_C_EXIT)
52
55
  return undefined;
53
- return `${nameOf(file)} exited ${code}`;
56
+ if (platform === 'win32' && code === 3)
57
+ return `${nameOf(file)} exited 3 — SetThreadExecutionState refused the request`;
58
+ return said ? `${nameOf(file)} exited ${code}: ${said}` : `${nameOf(file)} exited ${code}`;
54
59
  }
60
+ // The first non-empty line a helper wrote to stderr, capped: one row's worth for the warning.
61
+ const firstLine = (text) => text.trim().split(/\r?\n/)[0]?.trim().slice(0, 200) ?? '';
55
62
  export function keepAwake(env, platform, pid, onLost = () => { }) {
56
63
  const a = awakeArgv(env, platform, pid);
57
64
  if (a === undefined)
@@ -63,10 +70,15 @@ export function keepAwake(env, platform, pid, onLost = () => { }) {
63
70
  done = true;
64
71
  onLost(why);
65
72
  };
66
- const child = spawn(a.file, a.args, { stdio: 'ignore', ...(a.env ? { env: { ...env, ...a.env } } : {}) });
67
- // A helper that cannot hold the host costs the guard, never the run — but it says so.
73
+ const child = spawn(a.file, a.args, { stdio: ['ignore', 'ignore', 'pipe'], ...(a.env ? { env: { ...env, ...a.env } } : {}) });
74
+ // A helper that cannot hold the host costs the guard, never the run — but it says so, and why.
75
+ let said = '';
76
+ child.stderr?.setEncoding('utf8').on('data', (d) => { if (said.length < 4096)
77
+ said += d; });
78
+ child.stderr?.unref?.(); // the pipe never holds drive open
68
79
  child.on('error', (e) => lost(`${nameOf(a.file)} failed to start (${e.code ?? e.message})`));
69
- child.on('exit', (code, signal) => lost(lostWhy(platform, a.file, code, signal)));
80
+ // 'close', not 'exit': the helper's stderr has been read in full only once its pipe closed.
81
+ child.on('close', (code, signal) => lost(lostWhy(platform, a.file, code, signal, firstLine(said))));
70
82
  child.unref();
71
83
  return {
72
84
  shown: a.shown,
@@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { isAlive, pause, pidOf, releaseIfMine, takeStale } from './lock.js';
4
4
  import { ok, refuse, v } from './refusal.js';
5
- import { shellArg } from './toon.js';
5
+ import { psArg, shellArg } from './toon.js';
6
6
  // Row 180. What a process knows about the drive it runs under. Drive marks every child
7
7
  // session with WITNESS_DRIVE=<target>: the marker is the recursion guard (a marked session's
8
8
  // `witness drive` refuses) and the child's scope (its `next` answers for that target alone).
@@ -106,9 +106,15 @@ export function acquireDriveLock(root, info, pid = process.pid) {
106
106
  }
107
107
  }
108
108
  // Row 201: `kill` is not a Windows command, and PowerShell's alias ends drive alone.
109
+ //
110
+ // Row 214: nor is `tail -f`. PowerShell's reader is `Get-Content -Wait`, with `-LiteralPath`
111
+ // because `-Path` reads `[ ]` in a path as a wildcard, `-Tail 50` so it starts at the end rather
112
+ // than replaying the whole log, and `-Encoding UTF8` because Windows PowerShell 5.1 reads a
113
+ // BOM-less file as ANSI and would garble drive's `·` and `—`.
109
114
  export function watchLine(h, platform = process.platform) {
110
- const stop = platform === 'win32' ? `taskkill /PID ${h.pid} /T /F` : `kill ${h.pid}`;
111
- return h.log !== undefined
112
- ? `tail -f ${shellArg(h.log)} · stop it: ${stop}`
113
- : `the terminal running witness drive · pid ${h.pid}`;
115
+ if (h.log === undefined)
116
+ return `the terminal running witness drive · pid ${h.pid}`;
117
+ return platform === 'win32'
118
+ ? `Get-Content -LiteralPath ${psArg(h.log)} -Wait -Tail 50 -Encoding UTF8 · stop it: taskkill /PID ${h.pid} /T /F`
119
+ : `tail -f ${shellArg(h.log)} · stop it: kill ${h.pid}`;
114
120
  }
package/dist/drive.js CHANGED
@@ -4,23 +4,26 @@ import { basename, dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { EXIT, main } from './cli.js';
6
6
  import { canonPaths, loadConfig, loadLocalConfig } from './config.js';
7
- import { withoutSession } from './context.js';
7
+ import { sessionHash, withoutSession } from './context.js';
8
8
  import { detectionVariables, resolveJudge } from './harness.js';
9
9
  import { ok, refuse, renderRefusal, v } from './refusal.js';
10
10
  import { findById, loadCanon } from './scan.js';
11
11
  import { NO_CONSOLE_ENV, resolveSpawn, spawn, treeStop } from './spawn.js';
12
12
  import { computeNext, conversationStage } from './verbs/next.js';
13
+ import { entryDetail } from './verbs/log.js';
13
14
  import { DRIVE_DEADLINE_ENV, DRIVE_ENV, DRIVE_LOG, DRIVE_LOG_ENV, TARGETLESS, driveHolder } from './drive-presence.js';
14
15
  import { isAlive, pause } from './lock.js';
15
16
  import { ASK_STREAM } from './ask.js';
16
17
  import { KEPT_STOP_NAMES, unmetNeedLine } from './autonomy.js';
17
18
  import { unmetNeeds } from './needs.js';
18
19
  import { capHit, parkAtCap } from './caps.js';
19
- import { effortStreams, readStream } from './journal.js';
20
+ import { effortStreams, journalRel, readStream } from './journal.js';
20
21
  import { movesFlow } from './progress.js';
21
22
  import { sourced } from './allowlist.js';
22
23
  import { effortOf } from './reviewed.js';
23
24
  import { pendingTxn } from './txn.js';
25
+ import { logSafe } from './toon.js';
26
+ import { passthrough } from './worker-stream.js';
24
27
  import { duration, limitIn, realClock, sessionLimit, SINGLE_WAIT_MAX_MS, TOTAL_WAIT_MAX_MS, waitFor, } from './usage.js';
25
28
  import { keepAwake } from './awake.js';
26
29
  import { monotonicTicker, sessionClock } from './session-clock.js';
@@ -94,6 +97,12 @@ const TERM_GRACE_MS = 5_000;
94
97
  // before drive itself goes, so nothing a session started outlives the run.
95
98
  const LIVE_GROUPS = new Set();
96
99
  const EXIT_GRACE_MS = 2_000;
100
+ // Row 214. How long a session may print nothing before drive says it still runs, and what on —
101
+ // then again after each further stretch as long. Awake time, on the session's own clock (row
102
+ // 210). A constant, not a setting, on row 202's precedent: no `migrate` for an upgrade.
103
+ export const SESSION_QUIET_MS = 300_000;
104
+ // Local wall-clock time, `HH:MM:SS`: what a human at the terminal reads `started` and `ended` by.
105
+ const clockTime = () => new Date().toTimeString().slice(0, 8);
97
106
  // This CLI, for the child. A spawned session shells out to `witness` through
98
107
  // ${WITNESS_BIN:-npx …} in every stage skill, and an unset value means the child resolves
99
108
  // the PUBLISHED version while its parent runs an unpublished one — which the state floor
@@ -104,21 +113,29 @@ function localBin(ctx) {
104
113
  }
105
114
  // Line-buffered because a pipe's chunks split wherever the kernel felt like it: printing
106
115
  // chunks would interleave two streams mid-word and prefix half a line. Every complete
107
- // line is prefixed and forwarded as it arrives — drive is a terminal a human is watching,
108
- // and the child's own output IS the progress report (addendum §4).
109
- function lineSink(prefix, emit) {
116
+ // record is forwarded as it arrives — drive is a terminal a human is watching (addendum §4).
117
+ //
118
+ // Row 214: one record per LF, a trailing CR dropped — the harnesses' JSON records end at LF alone,
119
+ // and a CRLF would leave a CR on every line. A chunk with no LF is only appended: one record can
120
+ // be megabytes (pi's agent_end carries the whole conversation), and splitting the whole buffer
121
+ // again on every 64 KiB chunk was quadratic in it.
122
+ export function lineSink(emit) {
110
123
  let buf = '';
124
+ const record = (r) => emit(r.endsWith('\r') ? r.slice(0, -1) : r);
111
125
  return {
112
- push: (chunk) => {
113
- buf += chunk;
114
- const parts = buf.split('\n');
115
- buf = parts.pop() ?? '';
116
- for (const line of parts)
117
- emit(prefix + line);
126
+ push(chunk) {
127
+ const at = chunk.lastIndexOf('\n');
128
+ if (at === -1) {
129
+ buf += chunk;
130
+ return;
131
+ }
132
+ const records = (buf + chunk.slice(0, at)).split('\n');
133
+ buf = chunk.slice(at + 1);
134
+ records.forEach(record);
118
135
  },
119
- flush: () => {
136
+ flush() {
120
137
  if (buf !== '') {
121
- emit(prefix + buf);
138
+ record(buf);
122
139
  buf = '';
123
140
  }
124
141
  },
@@ -147,9 +164,17 @@ export function signalSession(child, grouped, env, sig) {
147
164
  // the driver's: this is a programmatic spawn like the reviewer battery, not a statement
148
165
  // about which CLI a human is typing at. Ambient detection deciding what drive spawns would
149
166
  // make the same repo drive differently from two terminals.
167
+ //
168
+ // Row 214: `next` is the line drive derived for this session, shown on its `started` line; `hear`
169
+ // gets every line the child wrote, shown or not — what the CLI printed, wherever it landed;
170
+ // `progress` is what its flow journaled since the last poll (journalWatch), as lines, asked with
171
+ // the session's id once its stream has named it; `root`
172
+ // is the repo, whose drive sessions a harness that can be told where to keep them keeps in a
173
+ // folder of their own (D2); `stream` replaces the harness's renderer, a test seam on `ticker`'s
174
+ // precedent.
150
175
  export async function spawnSession(step, cfg, ctx, spawnN, opts = {}) {
151
176
  const t0 = Date.now();
152
- const end = (outcome, code = null, tail = []) => ({ outcome, code, tail, ms: Math.max(1, Date.now() - t0) });
177
+ const end = (outcome, code = null, tail = []) => ({ outcome, code, tail, ms: Math.max(1, Date.now() - t0), failed: false });
153
178
  if (opts.signal?.aborted)
154
179
  return end('stopped');
155
180
  const hxR = resolveJudge(ctx.env, cfg.harness);
@@ -157,7 +182,9 @@ export async function spawnSession(step, cfg, ctx, spawnN, opts = {}) {
157
182
  renderRefusal(hxR.violations).forEach((l) => ctx.err(l));
158
183
  return end('spawn-failed');
159
184
  }
160
- const { cmd, args, env } = hxR.value.harness.worker.spawn(opts.manual ? MANUAL_PROMPT : SESSION_PROMPT, step.model);
185
+ const { harness } = hxR.value;
186
+ const transcripts = opts.root !== undefined ? harness.worker.transcripts?.(ctx.env, opts.root) : undefined;
187
+ const { cmd, args, env } = harness.worker.spawn(opts.manual ? MANUAL_PROMPT : SESSION_PROMPT, step.model, transcripts);
161
188
  // Test-only seam, on WITNESS_TRUST_CMDS' precedent (decide.ts): the suite points this at
162
189
  // a scripted fake that performs real CLI acts. Never documented for users — a spawn
163
190
  // binary chosen by ambient env is exactly the identity confusion row 90 removed.
@@ -190,16 +217,84 @@ export async function spawnSession(step, cfg, ctx, spawnN, opts = {}) {
190
217
  }
191
218
  const prefix = `[${spawnN} ${step.stage ?? 'drive'}/${step.target ?? step.home.split('/').pop() ?? '-'}] `;
192
219
  const tail = [];
193
- const emit = (l) => {
220
+ // Row 214. Three readers of one stream: the human (every shown line, under the prefix), the
221
+ // merge sniff (`hear`: shown lines, each line of a tool's output and stderr, unprefixed — what
222
+ // the CLI printed, wherever it landed) and row 182's limit check (the tail: the child's own
223
+ // lines, never drive's about it). Every line a child wrote is spelled out before anyone reads
224
+ // it (logSafe): the stream's lines by the renderer, stderr by `passthrough`.
225
+ const stream = opts.stream ?? harness.worker.stream(step.home);
226
+ // Awake time on the session's clock once the child runs: what the quiet line measures in (row
227
+ // 210). `started` prints before the clock exists, at 0.
228
+ let awakeNow = () => 0;
229
+ // The id the session's stream named last: whose journal entries are its own.
230
+ let session;
231
+ // When a line was last printed, in awake time, and how many quiet lines followed it.
232
+ let lastHeard = 0;
233
+ let quiet = 0;
234
+ // D7. The one place a line is printed under the session's prefix, so the one place it is spelled
235
+ // out (logSafe: a renderer's lines already are, and spelling twice changes nothing). Any line
236
+ // but the quiet line itself ends the quiet. Drive's own lines (started, session, still running,
237
+ // ended, host slept) never enter the tail: only `show` puts the child's there.
238
+ const emit = (l, quietLine = false) => {
239
+ ctx.out(prefix + logSafe(l));
240
+ if (!quietLine) {
241
+ lastHeard = awakeNow();
242
+ quiet = 0;
243
+ }
244
+ };
245
+ // The child's own lines: into the tail row 182 reads, and to the merge sniff.
246
+ const show = (l) => {
194
247
  if (l.trim() !== '') {
195
248
  tail.push(l);
196
249
  if (tail.length > TAIL_LINES)
197
250
  tail.shift();
198
251
  }
199
- ctx.out(prefix + l);
252
+ emit(l);
253
+ opts.hear?.(l);
254
+ };
255
+ // A renderer never throws (row 214), and drive holds it to that: a throw here is in a pipe's
256
+ // 'data' listener, which takes drive down and leaves the session running unwatched (P16). The
257
+ // record is then shown as any record that is no event is.
258
+ const out = lineSink((record) => {
259
+ let said;
260
+ try {
261
+ said = stream.line(record);
262
+ }
263
+ catch {
264
+ said = [{ kind: 'show', text: passthrough(record) }];
265
+ }
266
+ for (const w of said) {
267
+ if (w.kind === 'show')
268
+ show(w.text);
269
+ else if (w.kind === 'heard')
270
+ opts.hear?.(w.text);
271
+ else {
272
+ session = w.id;
273
+ emit(`session ${w.id}${transcripts !== undefined ? ` · ${transcripts}` : ''}`);
274
+ }
275
+ }
276
+ });
277
+ const err = lineSink((record) => show(passthrough(record)));
278
+ // D8. A session that printed nothing for SESSION_QUIET_MS of awake time says it still runs, how
279
+ // long of its limit, and what it waits on — its oldest open call, else the model — then again
280
+ // after each further SESSION_QUIET_MS. `quiet` names the stretch it crossed, never the measured
281
+ // time, which drifts with how late each check fires. A harness whose events this CLI no longer
282
+ // reads still gets the line. The check runs in the clock's timer, so it catches everything: a
283
+ // throw there takes drive down and leaves the session unwatched (P16). The clock is re-armed
284
+ // before it runs, so a check that failed costs one line, never the limit.
285
+ const tick = (awake) => {
286
+ try {
287
+ for (const l of opts.progress?.(session) ?? [])
288
+ emit(l);
289
+ const n = Math.floor((awake - lastHeard) / SESSION_QUIET_MS);
290
+ if (n <= quiet)
291
+ return;
292
+ quiet = n;
293
+ const what = stream.inFlight();
294
+ emit(`still running · ${duration(awake)} of ${duration(cfg.drive.sessionTimeoutMs)} · quiet ${duration(n * SESSION_QUIET_MS)}${what !== undefined ? ` · in: ${what}` : ''}`, true);
295
+ }
296
+ catch { /* the next check says it */ }
200
297
  };
201
- const out = lineSink('', emit);
202
- const err = lineSink('', emit);
203
298
  return await new Promise((resolve) => {
204
299
  // Final review F11: its own process group, so a stop reaches the tools, shells and gates
205
300
  // the session started, not just the agent — an orphan would keep writing state after
@@ -216,6 +311,9 @@ export async function spawnSession(step, cfg, ctx, spawnN, opts = {}) {
216
311
  const signal = (sig) => signalSession(child, grouped, run.value.env, sig);
217
312
  if (grouped && child.pid !== undefined)
218
313
  LIVE_GROUPS.add(child.pid);
314
+ // Only a session that started says so: a binary that is not there reports spawn-failed alone.
315
+ if (child.pid !== undefined)
316
+ emit(`started ${clockTime()}${opts.next !== undefined ? ` · next: ${opts.next}` : ''}`);
219
317
  let outcome = 'exited';
220
318
  let code = null;
221
319
  let settled = false;
@@ -242,12 +340,29 @@ export async function spawnSession(step, cfg, ctx, spawnN, opts = {}) {
242
340
  err.flush();
243
341
  child.stdout.destroy();
244
342
  child.stderr.destroy();
245
- resolve({ outcome: o, code, tail: [...tail], ms: Math.max(1, clock.awakeMs()) });
343
+ const ms = Math.max(1, clock.awakeMs());
344
+ // How it ended, in awake time. A spawn that failed never started, and said so already.
345
+ // `(error)`: the stream says its last answer was an error, which pi's JSON mode reports at
346
+ // exit 0 (D5).
347
+ if (o !== 'spawn-failed') {
348
+ // What it journaled since the last check, before how it ended.
349
+ try {
350
+ for (const l of opts.progress?.(session) ?? [])
351
+ emit(l);
352
+ }
353
+ catch { /* what it journaled is in its stream; `ended` still says how it went */ }
354
+ const how = o === 'timeout' ? 'timed out' : o === 'stopped' ? 'stopped'
355
+ : code === null ? 'killed' : `exit ${code}${stream.failed() ? ' (error)' : ''}`;
356
+ emit(`ended ${clockTime()} · ${how} · ${duration(ms)}`);
357
+ }
358
+ resolve({ outcome: o, code, tail: [...tail], ms, failed: stream.failed() });
246
359
  };
247
360
  const clock = sessionClock(cfg.drive.sessionTimeoutMs, opts.ticker ?? monotonicTicker, {
248
361
  expire: () => stop('timeout'),
249
- slept: (ms) => ctx.out(`${prefix}host slept ${duration(ms)} — not counted against drive.sessionTimeoutMs`),
362
+ slept: (ms) => emit(`host slept ${duration(ms)} — not counted against drive.sessionTimeoutMs`),
363
+ tick,
250
364
  });
365
+ awakeNow = () => clock.awakeMs();
251
366
  opts.signal?.addEventListener('abort', onAbort, { once: true });
252
367
  child.stdout.setEncoding('utf8');
253
368
  child.stderr.setEncoding('utf8');
@@ -322,7 +437,6 @@ export function watchSignature(root) {
322
437
  });
323
438
  return createHash('sha1').update(parts.join('\n')).digest('hex');
324
439
  }
325
- const STREAM_PREFIX = /^\[\d+ [^\]]*\] /;
326
440
  // What `mergeOwnPr` prints when it leaves the merge to a human (ship.ts), and nothing else.
327
441
  const MERGE_LINE = /^ship: "?merge PR #(\d+) on GitHub when ready/;
328
442
  const streamLines = (root, id) => readStream(root, id).length;
@@ -350,6 +464,128 @@ function progressKey(root, action, family) {
350
464
  : 0;
351
465
  return [action.line, own, inEffort].join('\u0000');
352
466
  }
467
+ // Final review F2. A lane holds its whole flow: a spec and the plans written for it. Pure over the
468
+ // canon it is given: drive's fill reads it from the canon of this fill, the journal watch from a
469
+ // fresh one (row 214).
470
+ export function flowOf(canon, t) {
471
+ const doc = findById(canon, t);
472
+ if (doc?.meta.type === 'plan')
473
+ return [t, String(doc.meta.parent)];
474
+ if (doc?.meta.type === 'spec') {
475
+ return [t, ...canon.docs.filter((d) => d.meta.type === 'plan' && String(d.meta.parent) === t).map((d) => String(d.meta.id))];
476
+ }
477
+ return [t];
478
+ }
479
+ // Row 214 (D9). What a session journals for its flow, as it lands: the target and its family
480
+ // (flowOf), each member's own stream, and the owning effort's entries about a member. The flow is
481
+ // read again from a fresh canon whenever the effort's stream moves, so the plan a spec's session
482
+ // writes mid-session joins it, from its first entry. Polled on the session clock's check and once
483
+ // before `ended`; drive journals nothing (row 145), so this only reads, and it never throws.
484
+ //
485
+ // Each stream has its own position, counted on all its entries — the filter (row 206's acts, the
486
+ // effort's about the flow) applies only to what is printed — and its own gate, size and mtime
487
+ // taken before the read: a stream caught mid-append fails to parse and keeps its old gate, so it
488
+ // is read again at the next check, once its line is whole. A stream that shrank starts over from
489
+ // where it stands. What the repo held before the session is the baseline, taken at creation, or
490
+ // for a stream that could not be read then, at the first check that can. The efforts read are
491
+ // every one that wrote a flow member — a fix routes to the spec it amends, so a later effort writes
492
+ // the spec again and plans it — collected again whenever a watched stream moves, so an amendment
493
+ // or an adopted target's first effort joins, from where its stream then stands. Once the
494
+ // session's id is known, an act it did not journal says so (its `ctx.session`, row 191 §4.8,
495
+ // absent or another's). An entry that cannot be rendered — a hand-edited line — is skipped, and
496
+ // costs no other entry its line.
497
+ export function journalWatch(root, target) {
498
+ const at = new Map();
499
+ let moved = false; // a watched stream's gate moved this poll
500
+ let flow = [target];
501
+ let efforts = []; // the efforts that wrote a flow member, read apart
502
+ const derive = () => {
503
+ try {
504
+ flow = flowOf(loadCanon(root), target);
505
+ }
506
+ catch { /* the flow it had stands */ }
507
+ };
508
+ const gateOf = (id) => {
509
+ try {
510
+ const st = statSync(join(root, journalRel(id)));
511
+ return `${st.size}:${st.mtimeMs}`;
512
+ }
513
+ catch {
514
+ return '-'; // no stream yet
515
+ }
516
+ };
517
+ // The entries a stream gained since it was last read; [] when its gate stands or it cannot be
518
+ // read yet. `from0`: a member that joined the flow now, whose every entry is new.
519
+ const read = (id, from0) => {
520
+ const gate = gateOf(id);
521
+ const was = at.get(id);
522
+ if (was?.gate === gate)
523
+ return [];
524
+ moved = true;
525
+ let entries;
526
+ try {
527
+ entries = readStream(root, id);
528
+ }
529
+ catch {
530
+ return []; // an append in flight
531
+ }
532
+ at.set(id, { gate, seen: entries.length });
533
+ const from = was === undefined ? (from0 ? 0 : entries.length) : Math.min(was.seen, entries.length);
534
+ return entries.slice(from);
535
+ };
536
+ // An effort that is itself a flow member (a lane whose target is it) is read as one.
537
+ const collect = () => {
538
+ try {
539
+ return effortStreams(root).filter((id) => !flow.includes(id) && readStream(root, id)
540
+ .some((e) => e.t === 'write' && flow.includes(String(e.artifact))));
541
+ }
542
+ catch {
543
+ return efforts; // collected again when a stream moves
544
+ }
545
+ };
546
+ derive();
547
+ efforts = collect();
548
+ const members = new Set(flow); // the flow at creation: a baseline, never news
549
+ for (const id of [...flow, ...efforts])
550
+ read(id, false);
551
+ const render = (e, mine, about) => {
552
+ try {
553
+ if (!movesFlow(e))
554
+ return [];
555
+ if (about !== undefined && !about.includes(String(e.artifact)))
556
+ return [];
557
+ const by = e.ctx?.session;
558
+ return [`journal: ${String(e.t)} ${entryDetail(e)}${mine !== undefined && by !== mine ? ' · not this session' : ''}`];
559
+ }
560
+ catch {
561
+ return [];
562
+ }
563
+ };
564
+ return (session) => {
565
+ try {
566
+ const mine = session !== undefined ? sessionHash(session) : undefined;
567
+ moved = false;
568
+ const inEffort = efforts.flatMap((id) => read(id, false));
569
+ if (moved)
570
+ derive();
571
+ const out = inEffort.flatMap((e) => render(e, mine, flow));
572
+ for (const id of flow) {
573
+ out.push(...read(id, !members.has(id) && !at.has(id)).flatMap((e) => render(e, mine)));
574
+ }
575
+ if (moved) {
576
+ const now = collect();
577
+ for (const id of now)
578
+ if (!efforts.includes(id))
579
+ read(id, false); // a new effort's baseline
580
+ efforts = now;
581
+ }
582
+ return out;
583
+ }
584
+ catch {
585
+ return []; // the next check reads it
586
+ }
587
+ };
588
+ }
353
589
  const lastRunGate = (entries) => {
354
590
  const run = [...entries].reverse().find((e) => e.t === 'gate-run');
355
591
  return typeof run?.gate === 'string' ? run.gate : undefined;
@@ -408,15 +644,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
408
644
  // a free target meanwhile — nor a spec while one of its plans runs. Read from the canon of
409
645
  // this fill, so a plan written a moment ago belongs to its spec's lane at once.
410
646
  let canonNow = loadCanon(root);
411
- const family = (t) => {
412
- const doc = findById(canonNow, t);
413
- if (doc?.meta.type === 'plan')
414
- return [t, String(doc.meta.parent)];
415
- if (doc?.meta.type === 'spec') {
416
- return [t, ...canonNow.docs.filter((d) => d.meta.type === 'plan' && String(d.meta.parent) === t).map((d) => String(d.meta.id))];
417
- }
418
- return [t];
419
- };
647
+ const family = (t) => flowOf(canonNow, t);
420
648
  const admits = (t) => {
421
649
  const k = t ?? TARGETLESS;
422
650
  if (lanes.has(k) || aside.has(k) || (flags.flow !== undefined && t !== flags.flow))
@@ -550,7 +778,8 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
550
778
  if (r === 'refused')
551
779
  setAside(key, { kind: 'stuck', line: action.line, why: `decision refused on ${action.line}`, key0: keyOf(action) });
552
780
  };
553
- const launch = (step, action, n) => {
781
+ // `next` is the line the session takes (D13): the action's, or the re-run a settle routed.
782
+ const launch = (step, action, n, next) => {
554
783
  const lane = { action, end: Promise.resolve(undefined) };
555
784
  // The merge is announced by the SHIP SESSION's own output (ship.ts), not by a routing
556
785
  // row — a flow whose PR is open routes to `witness ship` forever, and only the child
@@ -558,17 +787,16 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
558
787
  // human, so under autonomy this fires only where a human merges.
559
788
  // Final review F10: only the CLI's own line counts, and only for a flow with a PR — agent
560
789
  // prose that mentions a merge must never hand a human `gh pr merge` for a flow without one.
790
+ // Row 214: the line is read wherever the CLI printed it. The ship skill runs `witness ship` in
791
+ // the agent's bash tool, so in production it is a tool's output, which drive hears and never
792
+ // prints — the session's printed lines alone met it only when an agent happened to quote it.
561
793
  const pr = action.target !== undefined ? findById(canonNow, action.target)?.meta.pr : undefined;
562
- const childCtx = {
563
- ...ctx,
564
- out: (l) => {
565
- const line = l.replace(STREAM_PREFIX, '');
566
- if (pr !== undefined && MERGE_LINE.exec(line)?.[1] === String(pr))
567
- lane.merged = line;
568
- ctx.out(l);
569
- },
570
- };
571
- lane.end = spawnSession(step, cfg, childCtx, n, { manual: flags.manual, signal: abort.signal });
794
+ const hear = (line) => { if (pr !== undefined && MERGE_LINE.exec(line)?.[1] === String(pr))
795
+ lane.merged = line; };
796
+ // Row 214: what the session journals for its flow. Target-less work has no stream of its own
797
+ // to watch (row 181 keys it on counts).
798
+ const progress = action.target !== undefined ? journalWatch(root, action.target) : undefined;
799
+ lane.end = spawnSession(step, cfg, ctx, n, { manual: flags.manual, signal: abort.signal, hear, root, next, progress });
572
800
  return lane;
573
801
  };
574
802
  // Every wait drive takes goes through here: printed, bounded and counted toward the total.
@@ -840,8 +1068,12 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
840
1068
  // because its scoped `next` prints the re-run (A1) — unless the re-run is a step of the
841
1069
  // design session, which is the chat's (row 194).
842
1070
  const rerun = action.target !== undefined ? routed.get(action.target) : undefined;
1071
+ // Row 214 (D13): such a session says it takes the re-run, not the decision line it replaced.
1072
+ // Only then: `routed` keeps a target's re-run for the whole run.
1073
+ let next = action.line;
843
1074
  if (step.kind === 'decision' && autonomous && rerun !== undefined) {
844
1075
  step = conversationStage({ line: rerun }) ? { kind: 'conversation', line: rerun } : { kind: 'spawn', home: root, target: action.target };
1076
+ next = rerun;
845
1077
  }
846
1078
  if (step.kind !== 'spawn') {
847
1079
  await standAside(step, action, key);
@@ -863,7 +1095,7 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
863
1095
  spawns += 1;
864
1096
  holdAwake();
865
1097
  pauseSince = undefined;
866
- lanes.set(key, launch(step, action, spawns));
1098
+ lanes.set(key, launch(step, action, spawns, next));
867
1099
  }
868
1100
  if (autonomous) {
869
1101
  publish();
package/dist/harness.js CHANGED
@@ -1,8 +1,11 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { existsSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { basename, join } from 'node:path';
3
5
  import { CLAUDE_THINKING_BUDGET, parsePin } from './pin.js';
4
6
  import { ok, refuse, v } from './refusal.js';
5
7
  import { pinIn } from './version.js';
8
+ import { claudeStream, piStream } from './worker-stream.js';
6
9
  export const HARNESSES = ['claude-code', 'pi'];
7
10
  export const DEFAULT_HARNESS = 'claude-code';
8
11
  // The six shipped stage skills, by directory name. `check`'s visibility probe asks
@@ -104,11 +107,17 @@ const REGISTRY = {
104
107
  // The REGISTRY self-reference resolves at CALL time (the const is initialized long
105
108
  // before any spawn), and it is what keeps the model flag rendered by the one
106
109
  // renderer instead of re-derived per entry.
110
+ //
111
+ // Row 214: text output is the result alone, at the end; stream-json writes every event as it
112
+ // happens (and print mode refuses it without --verbose). The session is saved in claude's own
113
+ // list, as any `claude -p` run's is: claude has no flag to keep it elsewhere.
107
114
  spawn: (prompt, model) => ({
108
115
  cmd: 'claude',
109
- args: ['-p', prompt, '--dangerously-skip-permissions', ...modelFlags(REGISTRY['claude-code'], model)],
116
+ args: ['-p', prompt, '--output-format', 'stream-json', '--verbose', '--dangerously-skip-permissions',
117
+ ...modelFlags(REGISTRY['claude-code'], model)],
110
118
  env: thinkingEnv(REGISTRY['claude-code'], model),
111
119
  }),
120
+ stream: (home) => claudeStream(home),
112
121
  },
113
122
  },
114
123
  pi: {
@@ -156,10 +165,30 @@ const REGISTRY = {
156
165
  worker: {
157
166
  // No bypass flag exists or is needed: pi's built-in tools are not approval-gated
158
167
  // (`pi --help` lists only --approve/--no-approve, which govern trusting
159
- // project-local files). --no-session keeps a headless worker's run out of the user's
160
- // session store; the worker otherwise keeps its skills and context files, which a
161
- // drive session runs on.
162
- spawn: (prompt, model) => ({ cmd: 'pi', args: ['-p', prompt, '--no-session', ...modelFlags(REGISTRY.pi, model)], env: {} }),
168
+ // project-local files). The worker keeps its skills and context files, which a drive
169
+ // session runs on.
170
+ //
171
+ // Row 214: `--mode json` writes every event as it happens, where text mode wrote the last
172
+ // answer once the session ended, and drive renders it. And the session is kept, no longer
173
+ // `--no-session`: a drive session's transcript is the one record of what it did. Kept in a
174
+ // folder of drive's own, `<agent dir>/sessions/witness-drive/<repo>-<sha1 of its root>`
175
+ // (P14), not the repo's folder in pi's store, so `pi -c` and `pi -r` in the repo stay the
176
+ // human's; and never in the repo, where a worktree's transcript would ride into ship's
177
+ // `git add -A` — `--session-dir` outranks a `sessionDir` setting, which may be relative to
178
+ // the working directory. No `--name` or `--session-id`: only newer pi builds have them, and
179
+ // an older one would refuse every spawn — the stream's own header names the session.
180
+ spawn: (prompt, model, transcripts) => ({
181
+ cmd: 'pi',
182
+ args: ['-p', prompt, '--mode', 'json', ...modelFlags(REGISTRY.pi, model),
183
+ ...(transcripts !== undefined ? ['--session-dir', transcripts] : [])],
184
+ env: {},
185
+ }),
186
+ stream: (home) => piStream(home),
187
+ // The agent dir is pi's own rule: PI_CODING_AGENT_DIR, else `.pi/agent` in the home — HOME,
188
+ // else USERPROFILE (resolveSkills' precedent), else the OS's answer. Each rung skips an empty
189
+ // value, as pi's own lookup does: a relative folder would be the session's working
190
+ // directory, the one place a transcript must not land (P17).
191
+ transcripts: (env, root) => join(env.PI_CODING_AGENT_DIR || join(env.HOME || env.USERPROFILE || homedir(), '.pi', 'agent'), 'sessions', 'witness-drive', `${basename(root).replace(/[^\w.-]/g, '-')}-${createHash('sha1').update(root).digest('hex').slice(0, 8)}`),
163
192
  },
164
193
  },
165
194
  };