@popovych.co/witness 0.26.1 → 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 |
@@ -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
  };
@@ -17,6 +17,8 @@ export const monotonicTicker = {
17
17
  now: () => performance.now(),
18
18
  after: (ms, fn) => { const t = setTimeout(fn, ms); return () => clearTimeout(t); },
19
19
  };
20
+ // Row 214: `tick` hears every check with the awake time, so what drive does once a second for a
21
+ // running session (its quiet line, its journal watch) runs on this one clock, in awake time.
20
22
  export function sessionClock(limitMs, ticker, on) {
21
23
  const t0 = ticker.now();
22
24
  let last = t0; // when the pending check was armed
@@ -39,10 +41,13 @@ export function sessionClock(limitMs, ticker, on) {
39
41
  wait = Math.min(SESSION_TICK_MS, limitMs - awake);
40
42
  cancel = ticker.after(wait, check);
41
43
  };
44
+ // The next check is armed before `tick` runs: a tick that threw would otherwise leave the
45
+ // session with no limit at all, and one that stopped the clock cancels the check it armed.
42
46
  const check = () => {
43
47
  const awake = account(ticker.now());
44
48
  if (awake < limitMs) {
45
49
  arm(awake);
50
+ on.tick?.(awake);
46
51
  return;
47
52
  }
48
53
  expired = true;
package/dist/toon.js CHANGED
@@ -1,6 +1,12 @@
1
1
  // A shell word is quoted only when it needs it, so the common line stays the one a human
2
2
  // types — a path in drive's watch line, a command in a `--cmd` grant (row 205).
3
3
  export const shellArg = (p) => /^[\w@%+=:,./-]+$/.test(p) ? p : `'${p.replaceAll("'", "'\\''")}'`;
4
+ // Row 214. The same rule for a PowerShell word — drive's Windows watch line. Bare only when no
5
+ // character in it means anything to PowerShell: a bare `,` builds an array, a leading `@` splats
6
+ // and a leading `-` binds as a parameter, so none of them is bare here as in a POSIX word. Else
7
+ // single-quoted, where nothing expands and the one special character is a single quote — any of
8
+ // the five PowerShell reads as one (' ‘ ’ ‚ ‛) — written twice.
9
+ export const psArg = (p) => /^[\w%+=:./\\][\w%+=:./\\-]*$/.test(p) ? p : `'${p.replace(/['‘’‚‛]/g, (q) => q + q)}'`;
4
10
  // Security review. A command a human is asked to trust is repo-authored text: a carriage return
5
11
  // or an escape sequence could paint a different command over the real one, a bidi override
6
12
  // reorder it (Trojan Source), an invisible filler hide a second command beside it. A denylist of
@@ -8,8 +14,19 @@ export const shellArg = (p) => /^[\w@%+=:,./-]+$/.test(p) ? p : `'${p.replaceAll
8
14
  // is, anything else is spelled out, and a command carrying any of it is never granted.
9
15
  const UNSHOWABLE = /[^\x20-\x7e]/u;
10
16
  export const hasControl = (s) => UNSHOWABLE.test(s);
11
- export const visible = (s) => s.replace(new RegExp(UNSHOWABLE.source, 'gu'), (c) => c === '\n' ? '\\n' : c === '\r' ? '\\r' : c === '\t' ? '\\t'
12
- : c.codePointAt(0) < 0x100 ? `\\x${c.codePointAt(0).toString(16).padStart(2, '0')}` : `\\u{${c.codePointAt(0).toString(16)}}`);
17
+ // One character spelled out: the one spelling `visible` and `logSafe` share.
18
+ const spell = (c) => c === '\n' ? '\\n' : c === '\r' ? '\\r' : c === '\t' ? '\\t'
19
+ : c.codePointAt(0) < 0x100 ? `\\x${c.codePointAt(0).toString(16).padStart(2, '0')}` : `\\u{${c.codePointAt(0).toString(16)}}`;
20
+ export const visible = (s) => s.replace(new RegExp(UNSHOWABLE.source, 'gu'), spell);
21
+ // Row 214. What a session drive runs wrote, on the human's terminal and in .witness/drive.log: the
22
+ // same paint-over and reorder attacks, from text an agent controls (a command, a path, its prose).
23
+ // Nobody grants a log line, so the rule is narrower than `visible`'s — control and format
24
+ // characters (ESC, CR, TAB, bidi overrides, zero-width fillers) and the line and paragraph
25
+ // separators U+2028/U+2029, which editors and some terminals render as a line break, are spelled
26
+ // out, and printable text in any script stays as written: `visible` would mangle drive's own `·`
27
+ // and `→`, and every sentence an agent writes in another language.
28
+ const UNLOGGABLE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
29
+ export const logSafe = (s) => s.replace(UNLOGGABLE, spell);
13
30
  function esc(value) {
14
31
  const s = String(value ?? '');
15
32
  return /[,"\n]|^\s|\s$/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
package/dist/usage.js CHANGED
@@ -115,12 +115,15 @@ export function limitIn(text, now) {
115
115
  return found.find((l) => l.kind === 'usage') ?? found[0];
116
116
  }
117
117
  // A session's end reads as a limit only from its last three lines. A usage shape counts at
118
- // any exit code (claude may exit 0 on one); a transient shape only on a non-zero exit.
118
+ // any exit code (claude may exit 0 on one). A transient shape counts on a session that failed:
119
+ // its stream ended in an error, which pi's JSON mode reports at exit 0 (row 214), or it exited
120
+ // non-zero by itself. A session drive timed out ended on drive's signal, not on the 529 its
121
+ // harness retried a while before and that still sits in its tail.
119
122
  export function sessionLimit(end, now) {
120
123
  const limit = limitIn(end.tail.slice(-3).join('\n'), now);
121
124
  if (!limit)
122
125
  return undefined;
123
- if (limit.kind === 'transient' && end.code === 0)
126
+ if (limit.kind === 'transient' && end.failed !== true && (end.code === 0 || end.outcome === 'timeout'))
124
127
  return undefined;
125
128
  return limit;
126
129
  }
package/dist/verbs/log.js CHANGED
@@ -10,7 +10,8 @@ import { short } from '../sha.js';
10
10
  import { stepProgress, stepsLine } from '../steps.js';
11
11
  import { kv, rows } from '../toon.js';
12
12
  import { decidedBy } from '../autonomy.js';
13
- function detail(e) {
13
+ // Row 214: drive's `journal:` lines print an act as `witness log` does.
14
+ export function entryDetail(e) {
14
15
  switch (e.t) {
15
16
  case 'recap': {
16
17
  const size = (k) => (Array.isArray(e[k]) ? e[k].length : 0);
@@ -129,7 +130,7 @@ export async function run(ctx, argv) {
129
130
  const root = rootRes.value;
130
131
  if (values.all) {
131
132
  const merged = mergedRows(root);
132
- rows('all', ['n', 'stream', 't', 'detail'], merged.map((r, i) => ({ n: i + 1, stream: r.stream, t: r.entry.t, detail: detail(r.entry) })))
133
+ rows('all', ['n', 'stream', 't', 'detail'], merged.map((r, i) => ({ n: i + 1, stream: r.stream, t: r.entry.t, detail: entryDetail(r.entry) })))
133
134
  .forEach(ctx.out);
134
135
  return EXIT.OK;
135
136
  }
@@ -140,7 +141,7 @@ export async function run(ctx, argv) {
140
141
  const chain = lineageChain(root, id);
141
142
  ctx.out(`lineage: ${chain.join(' → ')}`);
142
143
  const merged = chain.flatMap((sid) => readStream(root, sid).map((entry) => ({ stream: sid, entry })));
143
- rows('lineage', ['n', 'stream', 't', 'detail'], merged.map((r, i) => ({ n: i + 1, stream: r.stream, t: r.entry.t, detail: detail(r.entry) })))
144
+ rows('lineage', ['n', 'stream', 't', 'detail'], merged.map((r, i) => ({ n: i + 1, stream: r.stream, t: r.entry.t, detail: entryDetail(r.entry) })))
144
145
  .forEach(ctx.out);
145
146
  return EXIT.OK;
146
147
  }
@@ -149,7 +150,7 @@ export async function run(ctx, argv) {
149
150
  return EXIT.REFUSED;
150
151
  }
151
152
  const entries = readStream(root, id);
152
- rows('entries', ['n', 't', 'detail'], entries.map((e, i) => ({ n: i + 1, t: e.t, detail: detail(e) })))
153
+ rows('entries', ['n', 't', 'detail'], entries.map((e, i) => ({ n: i + 1, t: e.t, detail: entryDetail(e) })))
153
154
  .forEach(ctx.out);
154
155
  // Row 191 §4.3. A plan's stream ends with where the plan stands; an effort has no steps.
155
156
  const plan = findById(loadCanon(root), id);
@@ -0,0 +1,447 @@
1
+ import { logSafe } from './toon.js';
2
+ // One action line is one terminal line: a heredoc or a 40 KB `Write` must not flood the log.
3
+ export const ACTION_MAX = 160;
4
+ // A record that is no event — a warning a harness printed, half a record — is shown as written,
5
+ // up to this many code points: one that runs to megabytes is still one line.
6
+ export const PASSTHROUGH_MAX = 400;
7
+ // The verbs a human reads at a glance, by lower-cased tool name — claude's `Read` and pi's `read`
8
+ // are one action. `path` marks an argument shown relative to the session's home. A Map, so a tool
9
+ // named `constructor` or `__proto__` is any other tool, never one of Object's own keys.
10
+ const ACTIONS = new Map([
11
+ ['bash', { verb: '$', keys: ['command'] }],
12
+ ['powershell', { verb: '$', keys: ['command'] }],
13
+ ['read', { verb: 'read', keys: ['path', 'file_path'], path: true }],
14
+ ['edit', { verb: 'edit', keys: ['path', 'file_path'], path: true }],
15
+ ['multiedit', { verb: 'edit', keys: ['path', 'file_path'], path: true }],
16
+ ['notebookedit', { verb: 'edit', keys: ['notebook_path'], path: true }],
17
+ ['write', { verb: 'write', keys: ['path', 'file_path'], path: true }],
18
+ ['grep', { verb: 'grep', keys: ['pattern'] }],
19
+ ['find', { verb: 'find', keys: ['pattern'] }],
20
+ ['glob', { verb: 'find', keys: ['pattern'] }],
21
+ ['ls', { verb: 'ls', keys: ['path'], path: true }],
22
+ ]);
23
+ const obj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v) ? v : undefined;
24
+ const str = (v) => typeof v === 'string' ? v : undefined;
25
+ // A count or a status as written; anything else is no value. `String()` of an object a record
26
+ // carries could throw (`{"toString": 1}`), so it is never called on one.
27
+ const scalar = (v) => typeof v === 'string' || typeof v === 'number' ? String(v) : undefined;
28
+ const lines = (text) => text.split('\n').map((l) => l.replace(/\r$/, '')).filter((l) => l.trim() !== '');
29
+ // Each index of a command line that sits outside quotes, `$(…)` and `${…}`. Unbalanced text never
30
+ // returns to the top, so a stray quote keeps the rest of the line whole.
31
+ function* topLevel(s) {
32
+ const open = []; // the closer each open context waits for
33
+ for (let i = 0; i < s.length; i++) {
34
+ const c = s[i];
35
+ const closer = open.at(-1);
36
+ if (closer === "'") {
37
+ if (c === "'")
38
+ open.pop();
39
+ continue;
40
+ }
41
+ if (c === '\\') {
42
+ i += 1;
43
+ continue;
44
+ }
45
+ if (c === '$' && (s[i + 1] === '(' || s[i + 1] === '{')) {
46
+ open.push(s[i + 1] === '(' ? ')' : '}');
47
+ i += 1;
48
+ continue;
49
+ }
50
+ if (closer === '"') {
51
+ if (c === '"')
52
+ open.pop();
53
+ continue;
54
+ }
55
+ if (c === "'" || c === '"') {
56
+ open.push(c);
57
+ continue;
58
+ }
59
+ if (closer === ')' && c === '(') {
60
+ open.push(')');
61
+ continue;
62
+ }
63
+ if (closer !== undefined) {
64
+ if (c === closer)
65
+ open.pop();
66
+ continue;
67
+ }
68
+ yield i;
69
+ }
70
+ }
71
+ // The leading segment of a command line and what follows its separator: an `&&`, `;` or newline
72
+ // at the top level.
73
+ function leading(s) {
74
+ for (const i of topLevel(s)) {
75
+ if (s[i] === '\n' || s[i] === ';')
76
+ return { head: s.slice(0, i), rest: s.slice(i + 1) };
77
+ if (s[i] === '&' && s[i + 1] === '&')
78
+ return { head: s.slice(0, i), rest: s.slice(i + 2) };
79
+ }
80
+ return { head: s, rest: '' };
81
+ }
82
+ function words(s) {
83
+ const out = [];
84
+ let start = 0;
85
+ for (const i of topLevel(s)) {
86
+ if (/\s/.test(s[i])) {
87
+ if (i > start)
88
+ out.push(s.slice(start, i));
89
+ start = i + 1;
90
+ }
91
+ }
92
+ if (s.length > start)
93
+ out.push(s.slice(start));
94
+ return out;
95
+ }
96
+ // What a command line sets up before the command it runs: `cd <dir>`, `[export ]NAME=<value>`,
97
+ // `set -<flags>[ <words>]` — and nothing, the empty segment an `&&` at a line's end leaves.
98
+ const ASSIGNMENT = /^[A-Za-z_]\w*=/;
99
+ function preamble(segment) {
100
+ const w = words(segment);
101
+ if (w.length === 0)
102
+ return true;
103
+ if (w[0] === 'cd')
104
+ return w.length === 2;
105
+ if (w[0] === 'set')
106
+ return w.length >= 2 && /^[-+][A-Za-z]+$/.test(w[1]);
107
+ if (w[0] === 'export')
108
+ return w.length === 2 && ASSIGNMENT.test(w[1]);
109
+ return w.length === 1 && ASSIGNMENT.test(w[0]);
110
+ }
111
+ const WITNESS_VAR = /"\$\{WITNESS\}"|"\$WITNESS"|\$\{WITNESS\}|\$WITNESS(?!\w)/g;
112
+ // P15: nine in ten of a real implement session's shell calls start `cd <worktree> && WITNESS=…;`,
113
+ // and cut at ACTION_MAX most witness calls lost their verb. The command a call runs is what is
114
+ // left once its leading setup is gone, with the stage skills' `$WITNESS` read as the `witness` it
115
+ // is. A line that is nothing but setup stays as written.
116
+ export function shellCommand(command) {
117
+ let rest = command;
118
+ for (;;) {
119
+ const { head, rest: after } = leading(rest);
120
+ if (!preamble(head))
121
+ break;
122
+ rest = after;
123
+ if (rest.trim() === '')
124
+ return command;
125
+ }
126
+ return rest.trimStart().replace(WITNESS_VAR, 'witness');
127
+ }
128
+ // A path under the session's home, from it. Compared on `/`, and without case under a drive
129
+ // letter, as Windows compares: `C:\R\src\a.rs` is `src/a.rs` in the home `c:/r`.
130
+ function relative(p, home) {
131
+ const h = home.replaceAll('\\', '/').replace(/\/+$/, '');
132
+ const q = p.replaceAll('\\', '/');
133
+ if (h === '')
134
+ return p;
135
+ const fold = /^[A-Za-z]:/.test(h) ? (x) => x.toLowerCase() : (x) => x;
136
+ if (fold(q) === fold(h))
137
+ return '.';
138
+ return q[h.length] === '/' && fold(q.slice(0, h.length)) === fold(h) ? q.slice(h.length + 1) : p;
139
+ }
140
+ // `$ cargo test discovery`, `read src/a.rs`: what a tool call does, in one line. Any other tool is
141
+ // its name and its first string argument (`Task review the diff`). In this order: a shell
142
+ // command loses its setup (shellCommand), only its first line is kept, a path is made relative to
143
+ // the home, the line is spelled out (logSafe), and then cut — so ACTION_MAX bounds what the
144
+ // terminal shows. An action line says what was attempted: a call a guard refused reads the same.
145
+ export function actionLine(tool, args, home) {
146
+ const a = obj(args) ?? {};
147
+ const known = ACTIONS.get(tool.toLowerCase());
148
+ const raw = known !== undefined ? known.keys.map((k) => str(a[k])).find((v) => v !== undefined) : Object.values(a).map(str).find((v) => v !== undefined);
149
+ const arg = raw !== undefined && known?.verb === '$' ? shellCommand(raw) : raw;
150
+ const [first = '', ...rest] = (arg ?? '').split('\n');
151
+ const more = rest.some((l) => l.trim() !== '') ? ' …' : '';
152
+ const head = known?.verb ?? tool;
153
+ const said = first.replace(/\r$/, '');
154
+ const shown = known?.path ? relative(said, home) : said;
155
+ const line = logSafe(shown === '' ? head : `${head} ${shown}${more}`);
156
+ const chars = [...line];
157
+ return chars.length <= ACTION_MAX ? line : `${chars.slice(0, ACTION_MAX - 1).join('')}…`;
158
+ }
159
+ // A record shown as written, spelled out, and cut past PASSTHROUGH_MAX code points with how long
160
+ // it was. Drive shows a record this way too when a renderer it holds fails, and every stderr line.
161
+ export function passthrough(record) {
162
+ const safe = logSafe(record);
163
+ let n = 0;
164
+ let end = 0;
165
+ for (const c of safe) {
166
+ if (n < PASSTHROUGH_MAX)
167
+ end += c.length;
168
+ n += 1;
169
+ }
170
+ return n <= PASSTHROUGH_MAX ? safe : `${safe.slice(0, end)} … (${n} characters)`;
171
+ }
172
+ function parse(record) {
173
+ if (!record.startsWith('{'))
174
+ return undefined;
175
+ try {
176
+ return obj(JSON.parse(record));
177
+ }
178
+ catch {
179
+ return undefined;
180
+ }
181
+ }
182
+ const show = (text) => ({ kind: 'show', text: logSafe(text) });
183
+ const shown = (text) => lines(text).map(show);
184
+ // Heard lines are spelled out too: the merge sniff keeps one, and drive prints what it kept.
185
+ // `strip` takes off what the harness put before each line (claude's Read numbers its lines).
186
+ const heard = (text, strip) => lines(strip === undefined ? text : text.split('\n').map((l) => l.replace(strip, '')).join('\n'))
187
+ .map((l) => ({ kind: 'heard', text: logSafe(l) }));
188
+ // A tool result's text, whichever shape carries it: a string, or `{type: 'text'}` blocks.
189
+ const textOf = (content) => typeof content === 'string' ? content
190
+ : Array.isArray(content) ? content.map(obj).filter((c) => c?.type === 'text').map((c) => str(c?.text) ?? '').join('\n') : '';
191
+ const oldest = (open) => open.values().next().value;
192
+ // The oldest open call that is not in the background, else the oldest one that is: a server an
193
+ // agent left running is not what a call it is waiting on now waits for.
194
+ const oldestForeground = (open, background) => {
195
+ for (const [id, action] of open)
196
+ if (!background.has(id))
197
+ return action;
198
+ return oldest(open);
199
+ };
200
+ // A tool's result is heard and never shown, error or not: both harnesses mark every non-zero exit
201
+ // as a tool error (pi throws "Command exited with code N", claude answers `Exit code 1`), so a
202
+ // `failed` line would fire on every red test run and every grep that found nothing. The action
203
+ // line says what ran, and `journal:` what landed.
204
+ //
205
+ // pi (`pi -p --mode json`): a `session` header, then `tool_execution_start` / `_end` around each
206
+ // call, `message_start` / `message_end` around each message, token deltas, `turn_start` /
207
+ // `turn_end`, `agent_end` carrying the whole conversation, and `auto_retry_start` /
208
+ // `compaction_start`. pi writes an answer's `message_start` only once the provider's stream has
209
+ // begun, so the model is awaited from its turn's start until that answer ends.
210
+ export function piStream(home) {
211
+ const open = new Map(); // toolCallId → action line, oldest first
212
+ let named; // the session id last emitted
213
+ let turn = false; // the model is awaited: a turn started, its answer has not ended
214
+ let stop; // the last assistant message's stopReason
215
+ return {
216
+ line(record) {
217
+ const e = parse(record);
218
+ if (e === undefined)
219
+ return [{ kind: 'show', text: passthrough(record) }];
220
+ switch (e.type) {
221
+ case 'session': {
222
+ const id = str(e.id);
223
+ if (id === undefined || id === named)
224
+ return [];
225
+ named = id;
226
+ return [{ kind: 'session', id }];
227
+ }
228
+ case 'tool_execution_start': {
229
+ const action = actionLine(str(e.toolName) ?? 'tool', e.args, home);
230
+ const id = scalar(e.toolCallId);
231
+ if (id !== undefined)
232
+ open.set(id, action);
233
+ return [{ kind: 'show', text: action }];
234
+ }
235
+ case 'tool_execution_end': {
236
+ const id = scalar(e.toolCallId);
237
+ if (id !== undefined)
238
+ open.delete(id);
239
+ return heard(textOf(obj(e.result)?.content));
240
+ }
241
+ case 'turn_start':
242
+ turn = true;
243
+ return [];
244
+ case 'message_start':
245
+ if (obj(e.message)?.role === 'assistant')
246
+ turn = true;
247
+ return [];
248
+ case 'message_end': {
249
+ const m = obj(e.message);
250
+ if (m?.role !== 'assistant')
251
+ return [];
252
+ turn = false;
253
+ // A later answer that succeeded clears an earlier error: a retry that worked is no failure.
254
+ stop = str(m.stopReason);
255
+ const said = shown(textOf(m.content));
256
+ // What text mode prints on stderr for the same turn, and its exit 1.
257
+ if (stop === 'error' || stop === 'aborted')
258
+ said.push(...shown(str(m.errorMessage) || `Request ${stop}`));
259
+ return said;
260
+ }
261
+ case 'auto_retry_start':
262
+ return [show(`retrying · attempt ${scalar(e.attempt) ?? '?'}/${scalar(e.maxAttempts) ?? '?'} · ${lines(str(e.errorMessage) ?? '')[0] ?? ''}`)];
263
+ case 'compaction_start':
264
+ return [show('compacting context')];
265
+ default:
266
+ return [];
267
+ }
268
+ },
269
+ inFlight: () => oldest(open) ?? (turn ? 'the model' : undefined),
270
+ failed: () => stop === 'error' || stop === 'aborted',
271
+ };
272
+ }
273
+ // claude Read's line numbers, ` 1\t` (P12).
274
+ const READ_NUMBER = /^\s*\d+\t/;
275
+ // The statuses a `task_updated` patch ends a task with.
276
+ const TASK_ENDED = new Set(['completed', 'failed', 'killed']);
277
+ // claude (`claude -p --output-format stream-json --verbose`): `system:init` naming the session,
278
+ // one `assistant` record per content block (thinking, text, tool_use), a `user` record carrying
279
+ // each tool_result, hooks and `rate_limit_event`, `system:api_retry` / `compact_boundary`, and a
280
+ // `result` whose `is_error` is the failure.
281
+ //
282
+ // P12: a command that outruns the Bash limit runs on in the background. Its `task_started` comes
283
+ // before its tool_result, which only says it went to the background; a first `result` follows and
284
+ // the process keeps running; `task_notification` says the command ended, a second `init` names the
285
+ // same session, the agent reads the output file, and a second `result` closes. So a backgrounded
286
+ // call stays open past its tool_result until its task notifies (or a `task_updated` ends it), and
287
+ // there may be several results. P17: claude registers a task for a foreground call too — a
288
+ // subagent, a Bash that has run a while — so only a task marked `is_backgrounded` keeps a call
289
+ // open; claude 2.1.312 moves a Bash that outruns its limit to the background with a
290
+ // `task_updated` whose patch says so (its SDK schema: "A later move to the background arrives as
291
+ // task_updated patch.is_backgrounded"), not with a second `task_started`.
292
+ export function claudeStream(home) {
293
+ const open = new Map(); // tool_use id → action line, oldest first
294
+ const calls = new Map(); // every tool_use id → its action line
295
+ const background = new Set(); // tool_use ids a task runs past their tool_result
296
+ const tasks = new Map(); // a running task's id → its tool_use id
297
+ const reads = new Set(); // tool_use ids of Read calls, whose result is numbered
298
+ let named; // the session id last emitted
299
+ // The model is awaited from `init` or a tool_result until a record carrying a tool_use, or a
300
+ // result: its thinking and its text are the model still at work.
301
+ let awaiting = false;
302
+ let said; // the last text shown: a result often repeats it
303
+ let failed = false;
304
+ const close = (id) => {
305
+ if (id === undefined)
306
+ return;
307
+ background.delete(id);
308
+ open.delete(id);
309
+ };
310
+ // A call its task runs in the background: open until the task ends, even when the move to the
311
+ // background is told after the call's tool_result closed it.
312
+ const toBackground = (id) => {
313
+ if (id === undefined)
314
+ return;
315
+ background.add(id);
316
+ const action = calls.get(id);
317
+ if (!open.has(id) && action !== undefined)
318
+ open.set(id, action);
319
+ };
320
+ return {
321
+ line(record) {
322
+ const e = parse(record);
323
+ if (e === undefined)
324
+ return [{ kind: 'show', text: passthrough(record) }];
325
+ switch (e.type) {
326
+ case 'system':
327
+ switch (e.subtype) {
328
+ case 'init': {
329
+ awaiting = true;
330
+ const id = str(e.session_id);
331
+ if (id === undefined || id === named)
332
+ return [];
333
+ named = id;
334
+ return [{ kind: 'session', id }];
335
+ }
336
+ case 'api_retry': {
337
+ const why = [scalar(e.error_status), scalar(e.error)].filter((x) => x !== undefined).join(' ');
338
+ return [show(`retrying · attempt ${scalar(e.attempt) ?? '?'}/${scalar(e.max_retries) ?? '?'} · ${why}`)];
339
+ }
340
+ case 'compact_boundary':
341
+ return [show('compacting context')];
342
+ case 'task_started': {
343
+ const id = str(e.tool_use_id);
344
+ if (id === undefined)
345
+ return [];
346
+ const task = str(e.task_id);
347
+ if (task !== undefined)
348
+ tasks.set(task, id);
349
+ if (e.is_backgrounded === true)
350
+ toBackground(id);
351
+ return [];
352
+ }
353
+ case 'task_notification': {
354
+ const task = str(e.task_id);
355
+ close(str(e.tool_use_id) ?? (task !== undefined ? tasks.get(task) : undefined));
356
+ if (task !== undefined)
357
+ tasks.delete(task);
358
+ return [];
359
+ }
360
+ case 'task_updated': {
361
+ const task = str(e.task_id);
362
+ const patch = obj(e.patch);
363
+ if (task === undefined || patch === undefined)
364
+ return [];
365
+ if (patch.is_backgrounded === true)
366
+ toBackground(tasks.get(task));
367
+ const status = str(patch.status);
368
+ if (status !== undefined && TASK_ENDED.has(status)) {
369
+ close(tasks.get(task));
370
+ tasks.delete(task);
371
+ }
372
+ return [];
373
+ }
374
+ default:
375
+ return [];
376
+ }
377
+ case 'assistant': {
378
+ const content = obj(e.message)?.content;
379
+ if (!Array.isArray(content))
380
+ return [];
381
+ const out = [];
382
+ for (const b of content) {
383
+ const block = obj(b);
384
+ if (block?.type === 'tool_use') {
385
+ awaiting = false;
386
+ const tool = str(block.name) ?? 'tool';
387
+ const action = actionLine(tool, block.input, home);
388
+ const id = str(block.id);
389
+ if (id !== undefined) {
390
+ open.set(id, action);
391
+ calls.set(id, action);
392
+ if (tool.toLowerCase() === 'read')
393
+ reads.add(id);
394
+ }
395
+ out.push({ kind: 'show', text: action });
396
+ }
397
+ else if (block?.type === 'text') {
398
+ said = str(block.text) ?? '';
399
+ out.push(...shown(said));
400
+ }
401
+ }
402
+ return out;
403
+ }
404
+ case 'user': {
405
+ const content = obj(e.message)?.content;
406
+ // A string is a prompt, never a tool's result.
407
+ if (!Array.isArray(content))
408
+ return [];
409
+ const out = [];
410
+ for (const b of content) {
411
+ const block = obj(b);
412
+ if (block?.type !== 'tool_result')
413
+ continue;
414
+ awaiting = true;
415
+ const id = str(block.tool_use_id);
416
+ if (id !== undefined && !background.has(id))
417
+ open.delete(id);
418
+ const numbered = id !== undefined && reads.delete(id);
419
+ out.push(...heard(textOf(block.content), numbered ? READ_NUMBER : undefined));
420
+ }
421
+ return out;
422
+ }
423
+ case 'result': {
424
+ awaiting = false;
425
+ failed = e.is_error === true;
426
+ // Its text when it says something not just shown; P8's error subtypes carry no text,
427
+ // only `errors[]`, and an error with neither is named by its subtype.
428
+ const text = str(e.result);
429
+ if (text !== undefined) {
430
+ if (text.trim() === said?.trim())
431
+ return [];
432
+ said = text;
433
+ return shown(text);
434
+ }
435
+ if (!failed)
436
+ return [];
437
+ const errors = Array.isArray(e.errors) ? e.errors.map(str).filter((x) => x !== undefined) : [];
438
+ return errors.length > 0 ? errors.flatMap(shown) : shown(str(e.subtype) ?? '');
439
+ }
440
+ default:
441
+ return [];
442
+ }
443
+ },
444
+ inFlight: () => oldestForeground(open, background) ?? (awaiting ? 'the model' : undefined),
445
+ failed: () => failed,
446
+ };
447
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popovych.co/witness",
3
- "version": "0.26.1",
3
+ "version": "0.26.2",
4
4
  "description": "Evidence-gated spec-driven development pipeline for AI coding agents: brainstorm to PR in six stages, where specs are state, plans are motion, and no transition passes without evidence. Drives from Claude Code or Pi.",
5
5
  "keywords": [
6
6
  "spec-driven-development",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "witness",
3
3
  "description": "Spec-driven development with evidence gates: brainstorm → PR through six stages and five gates. Skills author, the pinned witness CLI writes state and witnesses evidence; gates stop where judgment is owed.",
4
- "version": "0.26.1",
4
+ "version": "0.26.2",
5
5
  "author": {
6
6
  "name": "Kostiantyn Popovych"
7
7
  },
@@ -12,7 +12,7 @@ Any other words in `$ARGUMENTS` are the human's ask: run `$WITNESS ask "<those w
12
12
  Resolve the CLI once:
13
13
 
14
14
  ```bash
15
- WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1}"
15
+ WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2}"
16
16
  ```
17
17
 
18
18
  If the repo has no `witness.config.yaml`, run `$WITNESS init` first (one bootstrap commit), then proceed. If init or any verb refuses on a dirty tree, the human commits or cleans it — **never `git commit` yourself, anywhere, at any stage**: the CLI makes its own state commits, and the ship phase makes the sole code commit.
@@ -3,4 +3,4 @@
3
3
  # context). Silent everywhere that isn't a witness repo; failures swallowed:
4
4
  # session start must never hang or die on this.
5
5
  [ -f witness.config.yaml ] || exit 0
6
- ${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1} 2>/dev/null || true
6
+ ${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2} 2>/dev/null || true
@@ -16,7 +16,7 @@ recap, keeps a local draft, writes no document. See NOTICE.md. -->
16
16
  Resolve the CLI once per session:
17
17
 
18
18
  ```bash
19
- WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1}"
19
+ WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2}"
20
20
  ```
21
21
 
22
22
  - **Render the CLI's decision output verbatim and in full — every line, unmodified.** Never print a command set you remember; never recompose, reformat, summarise or reorder what the CLI emitted. Which decisions are live, how they rank, and what each costs are the CLI's answers, and they change with the round, the bound, the repair grant and the content sha — a remembered set is wrong in more states than it is right.
@@ -10,7 +10,7 @@ description: Slice a witness effort's confirmed recap into vertical spec slices,
10
10
  Resolve the CLI once per session:
11
11
 
12
12
  ```bash
13
- WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1}"
13
+ WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2}"
14
14
  ```
15
15
 
16
16
  - **Render the CLI's decision output verbatim and in full — every line, unmodified.** Never print a command set you remember; never recompose, reformat, summarise or reorder what the CLI emitted. Which decisions are live, how they rank, and what each costs are the CLI's answers, and they change with the round, the bound, the repair grant and the content sha — a remembered set is wrong in more states than it is right.
@@ -16,7 +16,7 @@ No text copied verbatim; the design-critic lens is new material. -->
16
16
  Resolve the CLI once per session:
17
17
 
18
18
  ```bash
19
- WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1}"
19
+ WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2}"
20
20
  ```
21
21
 
22
22
  - **Render the CLI's decision output verbatim and in full — every line, unmodified.** Never print a command set you remember; never recompose, reformat, summarise or reorder what the CLI emitted. Which decisions are live, how they rank, and what each costs are the CLI's answers, and they change with the round, the bound, the repair grant and the content sha — a remembered set is wrong in more states than it is right.
@@ -15,7 +15,7 @@ tests carry the parent spec's tag in their NAME. See NOTICE.md. -->
15
15
  Resolve the CLI once per session:
16
16
 
17
17
  ```bash
18
- WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1}"
18
+ WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2}"
19
19
  ```
20
20
 
21
21
  - **Render the CLI's decision output verbatim and in full — every line, unmodified.** Never print a command set you remember; never recompose, reformat, summarise or reorder what the CLI emitted. Which decisions are live, how they rank, and what each costs are the CLI's answers, and they change with the round, the bound, the repair grant and the content sha — a remembered set is wrong in more states than it is right.
@@ -15,7 +15,7 @@ parent's criteria. See NOTICE.md. -->
15
15
  Resolve the CLI once per session:
16
16
 
17
17
  ```bash
18
- WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1}"
18
+ WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2}"
19
19
  ```
20
20
 
21
21
  - **Render the CLI's decision output verbatim and in full — every line, unmodified.** Never print a command set you remember; never recompose, reformat, summarise or reorder what the CLI emitted. Which decisions are live, how they rank, and what each costs are the CLI's answers, and they change with the round, the bound, the repair grant and the content sha — a remembered set is wrong in more states than it is right.
@@ -15,7 +15,7 @@ model can. See NOTICE.md. -->
15
15
  Resolve the CLI once per session:
16
16
 
17
17
  ```bash
18
- WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.1}"
18
+ WITNESS="${WITNESS_BIN:-npx -y @popovych.co/witness@0.26.2}"
19
19
  ```
20
20
 
21
21
  - **Render the CLI's decision output verbatim and in full — every line, unmodified.** Never print a command set you remember; never recompose, reformat, summarise or reorder what the CLI emitted. Which decisions are live, how they rank, and what each costs are the CLI's answers, and they change with the round, the bound, the repair grant and the content sha — a remembered set is wrong in more states than it is right.