@popovych.co/witness 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -2
- package/dist/awake.js +16 -0
- package/dist/caps.js +74 -0
- package/dist/cli.js +1 -1
- package/dist/config.js +86 -10
- package/dist/drive-presence.js +104 -0
- package/dist/drive-report.js +104 -0
- package/dist/drive.js +510 -113
- package/dist/evidence.js +42 -9
- package/dist/gitio.js +9 -0
- package/dist/harness.js +11 -4
- package/dist/lock.js +167 -16
- package/dist/notify.js +31 -0
- package/dist/opener.js +1 -1
- package/dist/reviewer.js +53 -4
- package/dist/runner-lock.js +129 -0
- package/dist/runner.js +4 -0
- package/dist/settle.js +9 -3
- package/dist/txn.js +17 -2
- package/dist/usage.js +145 -0
- package/dist/verbs/decide.js +11 -3
- package/dist/verbs/drive.js +84 -14
- package/dist/verbs/evidence.js +29 -47
- package/dist/verbs/init.js +3 -0
- package/dist/verbs/next.js +70 -10
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/commands/witness.md +4 -1
- package/plugin/hooks/session-dashboard.sh +1 -1
- package/plugin/skills/witness-brainstorm/SKILL.md +1 -1
- package/plugin/skills/witness-decompose/SKILL.md +1 -1
- package/plugin/skills/witness-design/SKILL.md +1 -1
- package/plugin/skills/witness-implement/SKILL.md +1 -1
- package/plugin/skills/witness-plan/SKILL.md +1 -1
- package/plugin/skills/witness-ship/SKILL.md +1 -1
package/README.md
CHANGED
|
@@ -149,6 +149,12 @@ either.
|
|
|
149
149
|
| `harness: claude-code \| pi` | **the judge** — which harness runs this repo's gate reviewers, is measured by `calibrate`, and is probed by `check`. Judgment resolves `harness:` → `PI_CODING_AGENT` → `CLAUDECODE` → `claude-code`; session lines (`next`'s handoff, `dispatch`'s relay, `init --agent auto`) resolve detection first, because those name the CLI you are about to type at. Committed, so it binds every teammate's gates; `witness init --agent` writes it once and never re-points it. Undeclared repos are judged by whichever agent's session is open — `witness check` and `witness status` say so |
|
|
150
150
|
| `gates.reviewerTimeoutMs` | milliseconds per reviewer invocation (default 600000) |
|
|
151
151
|
| `drive.sessionTimeoutMs` | milliseconds a `drive`-spawned session may run before SIGTERM (default 3600000) |
|
|
152
|
+
| `drive.parallel` | sessions `witness drive` runs at once under autonomy, one per target (default 2) |
|
|
153
|
+
| `drive.parallelSuites` | `true` lets test runs in two worktrees overlap (default false: they take turns, because suites that boot servers or browsers collide) |
|
|
154
|
+
| `drive.caps.rounds` | gate rounds one target may run across budget resets (default 16) — the run parks a target that reaches it |
|
|
155
|
+
| `drive.caps.upstream` | upstream resets one target may take (default 6) — the run parks a target that reaches it |
|
|
156
|
+
| `drive.caps.spawns` | sessions one target may take in one drive run (default 24) — the run parks a target that reaches it |
|
|
157
|
+
| `drive.caps.wallClockMs` | milliseconds of session time one target may take in one drive run (default 57600000 · 16 h) — the run parks a target that reaches it |
|
|
152
158
|
| `autonomy: on \| off` | whether the CLI settles its own stops — through its recommendation or the arbiter it launches — and merges its own PRs once CI is green (default off). A committed repo fact: it counts only once HEAD says it, and the merge also needs the ship branch on origin to say it. `--manual` on a gate run keeps that run's stop for a human, and three stops always reach one: the look of a new screen, an unmet plan need and a trust grant |
|
|
153
159
|
| `ship.merge: merge \| squash \| rebase` | how `witness ship` merges its own PR under `autonomy: on` (default merge) — only once the ship gate is approved and CI is green, and never when the approval lapsed or GitHub refuses |
|
|
154
160
|
| `ship.ciSettleMs` | milliseconds a green check set must hold still before `witness ship` merges under autonomy (default 60000, at most 1800000) — gh's watch ends the moment nothing is pending, so a check that registers late would otherwise be missed. Green means at least one check passed and none failed, was cancelled or is pending |
|
|
@@ -165,6 +171,7 @@ are declared in machine config, not env:
|
|
|
165
171
|
reviewerExtensions:
|
|
166
172
|
- /Users/you/.pi/agent/npm/node_modules/pi-claude-oauth-adapter
|
|
167
173
|
opener: xdg-open # optional; nonstandard desktops only
|
|
174
|
+
notify: /usr/local/bin/ping-me # optional; the run summary is its one argument · default: the platform notifier
|
|
168
175
|
```
|
|
169
176
|
|
|
170
177
|
Repo facts live in `witness.config.yaml` (committed); machine facts live in
|
|
@@ -189,7 +196,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
|
|
|
189
196
|
| `design <spec-id> --file <html>\|--open\|--reconfirm` | register/show a `ui` spec's approved look |
|
|
190
197
|
| `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 |
|
|
191
198
|
| `next` | the one next action across every effort |
|
|
192
|
-
| `drive [--flow <plan-id>] [--max-spawns <n>]` |
|
|
199
|
+
| `drive [--flow <plan-id>] [--max-spawns <n>] [--manual] [--detach] [--ask "<text>"]` | 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`; `--ask` queues an ask first; `--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 |
|
|
193
200
|
| `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 |
|
|
194
201
|
| `test-evidence` / `verify-red` | journal red/green criteria evidence from a worktree |
|
|
195
202
|
| `adopt <path>` | absolve a finished hand-edit into the journal |
|
|
@@ -234,7 +241,8 @@ depends on none of them (DESIGN.md row 79):
|
|
|
234
241
|
|
|
235
242
|
- **Keep the host awake.** A suspend longer than an hour mid-run expires the prompt
|
|
236
243
|
cache; on wake the full agent context is re-written at cache-write price. On macOS:
|
|
237
|
-
`caffeinate -
|
|
244
|
+
`witness drive` holds `caffeinate -ims` for its own lifetime (a closed lid on battery
|
|
245
|
+
still sleeps); for a chat session, `caffeinate -dims`, or plug in and disable sleep.
|
|
238
246
|
- **`CLAUDE_CODE_AUTO_COMPACT_WINDOW`** (set at CLI launch) lowers the harness's
|
|
239
247
|
auto-compaction threshold as belt-and-suspenders under the dispatch budget. It is
|
|
240
248
|
documented for main sessions only — whether subagents honor it is unverified.
|
package/dist/awake.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
export function keepAwake(env, platform, pid) {
|
|
3
|
+
// Test seam, on WITNESS_DRIVE_AGENT_BIN's precedent: never documented.
|
|
4
|
+
const bin = env.WITNESS_KEEP_AWAKE_BIN ?? (platform === 'darwin' ? 'caffeinate' : undefined);
|
|
5
|
+
if (bin === undefined)
|
|
6
|
+
return { stop: () => { } };
|
|
7
|
+
const args = ['-ims', '-w', String(pid)];
|
|
8
|
+
const child = spawn(bin, args, { stdio: 'ignore' });
|
|
9
|
+
child.on('error', () => { }); // a missing binary costs the guard, never the run
|
|
10
|
+
child.unref();
|
|
11
|
+
return {
|
|
12
|
+
command: [bin, ...args].join(' '),
|
|
13
|
+
stop: () => { if (child.exitCode === null && child.signalCode === null)
|
|
14
|
+
child.kill('SIGTERM'); },
|
|
15
|
+
};
|
|
16
|
+
}
|
package/dist/caps.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { EXIT } from './cli.js';
|
|
2
|
+
import { fellBack, gateRuns, lastGateRun } from './rounds.js';
|
|
3
|
+
import { duration } from './usage.js';
|
|
4
|
+
import { gateSettled } from './verbs/next.js';
|
|
5
|
+
const isCapPark = (e) => {
|
|
6
|
+
if (e.t !== 'human-decision')
|
|
7
|
+
return false;
|
|
8
|
+
const d = e;
|
|
9
|
+
return d.selected === 'policy' && typeof d.rule === 'string' && d.rule.startsWith('cap-');
|
|
10
|
+
};
|
|
11
|
+
// The gates still open on a target — run, and neither settled nor approved — most recent
|
|
12
|
+
// last. A cap parks only on one of these (F7): a flow whose gates converged is moving, and a
|
|
13
|
+
// stop journaled on a settled gate would hide it behind a reopen that refuses.
|
|
14
|
+
function openGates(entries) {
|
|
15
|
+
const order = entries.filter((e) => e.t === 'gate-run').map((e) => String(e.gate));
|
|
16
|
+
return [...new Set(order.reverse())].reverse().filter((g) => !gateSettled(entries, g));
|
|
17
|
+
}
|
|
18
|
+
// First hit wins, in this order: rounds · upstream · spawns · wall clock.
|
|
19
|
+
export function capHit(entries, use, caps) {
|
|
20
|
+
let lastPark = -1;
|
|
21
|
+
entries.forEach((e, i) => { if (isCapPark(e))
|
|
22
|
+
lastPark = i; });
|
|
23
|
+
const since = entries.slice(lastPark + 1);
|
|
24
|
+
// Every budget reset is ignored: this counts the rounds a gate ran, not its window. The
|
|
25
|
+
// exemptions are `roundsSinceApprove`'s — a malformed or fallen-back round spends nothing.
|
|
26
|
+
const gates = [...new Set(since.filter((e) => e.t === 'gate-run').map((e) => String(e.gate)))];
|
|
27
|
+
for (const gate of gates) {
|
|
28
|
+
const n = gateRuns(since, gate).filter((r) => r.outcome !== 'malformed' && !fellBack(r)).length;
|
|
29
|
+
// a gate that converged at the cap is not capped
|
|
30
|
+
if (n >= caps.rounds && !gateSettled(entries, gate)) {
|
|
31
|
+
return { cap: 'rounds', gate, note: `drive cap: ${gate} ran ${n} rounds across budget resets · drive.caps.rounds ${caps.rounds}` };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const upstream = since.filter((e) => e.t === 'human-decision' &&
|
|
35
|
+
e.decision === 'revise-upstream').length;
|
|
36
|
+
if (upstream >= caps.upstream && openGates(entries).length > 0) {
|
|
37
|
+
return { cap: 'upstream', note: `drive cap: ${upstream} upstream resets · drive.caps.upstream ${caps.upstream}` };
|
|
38
|
+
}
|
|
39
|
+
if (use.spawns >= caps.spawns) {
|
|
40
|
+
return { cap: 'spawns', note: `drive cap: ${use.spawns} session(s) this run · drive.caps.spawns ${caps.spawns}` };
|
|
41
|
+
}
|
|
42
|
+
if (use.ms >= caps.wallClockMs) {
|
|
43
|
+
return {
|
|
44
|
+
cap: 'wall-clock',
|
|
45
|
+
note: `drive cap: ${duration(use.ms)} of sessions this run · drive.caps.wallClockMs ${duration(caps.wallClockMs)}`,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
// The park goes through A1's one door with `selected: 'policy'` and the cap as its rule.
|
|
51
|
+
// `park` anchors it on the gate's last run even after the author moved the tree. A target
|
|
52
|
+
// with no open gate has nothing to park on; a refusal from the door is named, not guessed.
|
|
53
|
+
export async function parkAtCap(ctx, root, target, hit) {
|
|
54
|
+
const { readStream } = await import('./journal.js');
|
|
55
|
+
const entries = readStream(root, target);
|
|
56
|
+
if (!entries.some((e) => e.t === 'gate-run'))
|
|
57
|
+
return { parked: false, why: 'no gate run to park it on' };
|
|
58
|
+
const open = openGates(entries);
|
|
59
|
+
const gate = hit.gate !== undefined && open.includes(hit.gate) ? hit.gate : open.at(-1);
|
|
60
|
+
const last = gate !== undefined ? lastGateRun(entries, gate) : undefined;
|
|
61
|
+
if (gate === undefined || last === undefined)
|
|
62
|
+
return { parked: false, why: 'no open gate to park it on' };
|
|
63
|
+
// Loaded on A1's precedent for settle.ts: decide.ts reaches the gate registry.
|
|
64
|
+
const { applyDecision } = await import('./verbs/decide.js');
|
|
65
|
+
const errs = [];
|
|
66
|
+
const code = await applyDecision({ ...ctx, cwd: root, err: (l) => { errs.push(l); ctx.err(l); } }, {
|
|
67
|
+
gate, target, decision: 'stop', note: hit.note, selected: 'policy', rule: `cap-${hit.cap}`, park: true, runId: last.run_id,
|
|
68
|
+
});
|
|
69
|
+
if (code === EXIT.OK)
|
|
70
|
+
return { parked: true };
|
|
71
|
+
// the refusal's rows are indented under its header; the rule is each row's second field
|
|
72
|
+
const rule = errs.map((l) => /^\s+[^,]+,([a-z-]+),/.exec(l)?.[1]).find((r) => r !== undefined);
|
|
73
|
+
return { parked: false, why: `the policy could not park it (${rule ?? `exit ${code}`})` };
|
|
74
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -61,7 +61,7 @@ const VERB_USAGE = {
|
|
|
61
61
|
floor: 'witness floor --show | --set <triple> --note <why>',
|
|
62
62
|
design: 'witness design <spec-id> --file <html> | --reconfirm | --open',
|
|
63
63
|
diff: 'witness diff <spec-id>',
|
|
64
|
-
drive: 'witness drive [--flow <plan-id>] [--max-spawns <n>] —
|
|
64
|
+
drive: 'witness drive [--flow <plan-id>] [--max-spawns <n>] [--manual] [--detach] [--ask "<text>"] — runs every session itself · under autonomy it needs no terminal and reports when nothing else can move',
|
|
65
65
|
'dispatch-report': 'witness dispatch-report <plan-id> --steps-assigned <n> --steps-completed <n> [--tokens <n>] [--tool-uses <n>] [--duration-ms <n>]',
|
|
66
66
|
gate: 'witness gate <decompose|plan|implement|ship|design> <target> [--fresh] [--manual]',
|
|
67
67
|
index: 'witness index',
|
package/dist/config.js
CHANGED
|
@@ -104,20 +104,87 @@ export function resolveImplement(raw) {
|
|
|
104
104
|
// once, a starved one kills a working e2e run and hands the human a false `spawn-timeout`
|
|
105
105
|
// to debug. The ceiling exists to break a hung child, not to pace a healthy one.
|
|
106
106
|
export const DEFAULT_SESSION_TIMEOUT_MS = 3_600_000;
|
|
107
|
+
// Rows 181 and 183. Drive runs up to `parallel` sessions at once, one per target (design
|
|
108
|
+
// §11 call 5). The caps park a target that will not converge; their defaults are fewhats's
|
|
109
|
+
// 2026-10-19 calibration (B5): rounds = the largest normal merged plan's 13 implement rounds
|
|
110
|
+
// plus one budget window · upstream = where the human abandoned thread-mirror-plan-1 ·
|
|
111
|
+
// spawns = half again over the busiest normal merged plan's 16 sessions · wall clock = 16 h,
|
|
112
|
+
// over the slowest normal merged plan's ~14 h in worktree sessions.
|
|
113
|
+
export const DEFAULT_PARALLEL = 2;
|
|
114
|
+
export const DEFAULT_CAPS = { rounds: 16, upstream: 6, spawns: 24, wallClockMs: 57_600_000 };
|
|
115
|
+
const DRIVE_WANTS = {
|
|
116
|
+
sessionTimeoutMs: 'an integer >= 1 — milliseconds each spawned session may take before SIGTERM',
|
|
117
|
+
parallel: 'an integer >= 1 — sessions drive runs at once · one per target',
|
|
118
|
+
};
|
|
119
|
+
const CAP_WANTS = {
|
|
120
|
+
rounds: 'an integer >= 1 — gate rounds one target may run across budget resets before drive parks it',
|
|
121
|
+
upstream: 'an integer >= 1 — upstream resets one target may take before drive parks it',
|
|
122
|
+
spawns: 'an integer >= 1 — sessions one target may take in one drive run',
|
|
123
|
+
wallClockMs: 'an integer >= 1 — milliseconds of session time one target may take in one drive run',
|
|
124
|
+
};
|
|
125
|
+
const DRIVE_KEYS = ['sessionTimeoutMs', 'parallel', 'parallelSuites', 'caps'];
|
|
126
|
+
const isCount = (val) => typeof val === 'number' && Number.isInteger(val) && val >= 1;
|
|
127
|
+
const isMap = (val) => typeof val === 'object' && val !== null && !Array.isArray(val);
|
|
128
|
+
// Strict: no consumer sets `drive:` today, so a typo'd key refusing costs nobody, while a
|
|
129
|
+
// typo'd cap silently defaulting would let a flow run past the bound its author meant.
|
|
107
130
|
export function resolveDrive(raw) {
|
|
108
131
|
const conf = raw.drive;
|
|
132
|
+
const defaults = {
|
|
133
|
+
sessionTimeoutMs: DEFAULT_SESSION_TIMEOUT_MS, parallel: DEFAULT_PARALLEL, parallelSuites: false, caps: { ...DEFAULT_CAPS },
|
|
134
|
+
};
|
|
109
135
|
if (conf === undefined)
|
|
110
|
-
return ok(
|
|
111
|
-
if (
|
|
136
|
+
return ok(defaults);
|
|
137
|
+
if (!isMap(conf))
|
|
112
138
|
return refuse([v('drive', 'invalid', String(conf), 'a map of drive settings')]);
|
|
139
|
+
const violations = [];
|
|
140
|
+
for (const key of Object.keys(conf)) {
|
|
141
|
+
if (!DRIVE_KEYS.includes(key)) {
|
|
142
|
+
violations.push(v(`drive.${key}`, 'unknown-drive-key', key, `a drive setting (${DRIVE_KEYS.join(' | ')})`));
|
|
143
|
+
}
|
|
113
144
|
}
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
145
|
+
const out = defaults;
|
|
146
|
+
for (const key of ['sessionTimeoutMs', 'parallel']) {
|
|
147
|
+
const val = conf[key];
|
|
148
|
+
if (val === undefined)
|
|
149
|
+
continue;
|
|
150
|
+
if (!isCount(val))
|
|
151
|
+
violations.push(v(`drive.${key}`, 'invalid', String(val), DRIVE_WANTS[key]));
|
|
152
|
+
else
|
|
153
|
+
out[key] = val;
|
|
154
|
+
}
|
|
155
|
+
if (conf.parallelSuites !== undefined) {
|
|
156
|
+
if (typeof conf.parallelSuites !== 'boolean') {
|
|
157
|
+
violations.push(v('drive.parallelSuites', 'invalid', String(conf.parallelSuites), 'true | false — whether test runs in two worktrees may overlap'));
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
out.parallelSuites = conf.parallelSuites;
|
|
161
|
+
}
|
|
119
162
|
}
|
|
120
|
-
|
|
163
|
+
const caps = conf.caps;
|
|
164
|
+
if (caps !== undefined) {
|
|
165
|
+
if (!isMap(caps)) {
|
|
166
|
+
violations.push(v('drive.caps', 'invalid', String(caps), 'a map of cap settings'));
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
for (const key of Object.keys(caps)) {
|
|
170
|
+
if (!(key in CAP_WANTS)) {
|
|
171
|
+
violations.push(v(`drive.caps.${key}`, 'unknown-drive-key', key, `a cap (${Object.keys(CAP_WANTS).join(' | ')})`));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
for (const key of Object.keys(CAP_WANTS)) {
|
|
175
|
+
const val = caps[key];
|
|
176
|
+
if (val === undefined)
|
|
177
|
+
continue;
|
|
178
|
+
if (!isCount(val))
|
|
179
|
+
violations.push(v(`drive.caps.${key}`, 'invalid', String(val), CAP_WANTS[key]));
|
|
180
|
+
else
|
|
181
|
+
out.caps[key] = val;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (violations.length)
|
|
186
|
+
return refuse(violations);
|
|
187
|
+
return ok(out);
|
|
121
188
|
}
|
|
122
189
|
export const DEFAULT_REVIEWER_TIMEOUT_MS = 600_000;
|
|
123
190
|
// gates.* is otherwise read loosely at its consumers (stagePin); the timeout is
|
|
@@ -188,7 +255,7 @@ export function autonomyAt(root, rev) {
|
|
|
188
255
|
}
|
|
189
256
|
}
|
|
190
257
|
const committedAutonomy = (root) => autonomyAt(root, 'HEAD');
|
|
191
|
-
const LOCAL_KEYS = ['reviewerExtensions', 'opener'];
|
|
258
|
+
const LOCAL_KEYS = ['reviewerExtensions', 'opener', 'notify'];
|
|
192
259
|
export const localConfigPath = (root) => join(root, '.witness', 'config.local.yaml');
|
|
193
260
|
export function loadLocalConfig(root) {
|
|
194
261
|
const p = localConfigPath(root);
|
|
@@ -230,9 +297,18 @@ export function loadLocalConfig(root) {
|
|
|
230
297
|
opener = obj.opener;
|
|
231
298
|
}
|
|
232
299
|
}
|
|
300
|
+
let notify;
|
|
301
|
+
if (obj.notify !== undefined) {
|
|
302
|
+
if (typeof obj.notify !== 'string' || obj.notify === '') {
|
|
303
|
+
violations.push(v('notify', 'invalid', String(obj.notify), 'a command name or path — it receives the run summary as its one argument'));
|
|
304
|
+
}
|
|
305
|
+
else {
|
|
306
|
+
notify = obj.notify;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
233
309
|
if (violations.length)
|
|
234
310
|
return refuse(violations);
|
|
235
|
-
return ok({ reviewerExtensions, ...(opener !== undefined ? { opener } : {}) });
|
|
311
|
+
return ok({ reviewerExtensions, ...(opener !== undefined ? { opener } : {}), ...(notify !== undefined ? { notify } : {}) });
|
|
236
312
|
}
|
|
237
313
|
// Lenient path resolution for callers without a loaded Config (canon scan, git
|
|
238
314
|
// state scoping): a missing or broken config falls back to the defaults — the
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { isAlive, pause, pidOf, releaseIfMine, takeStale } from './lock.js';
|
|
4
|
+
import { ok, refuse, v } from './refusal.js';
|
|
5
|
+
// Row 180. What a process knows about the drive it runs under. Drive marks every child
|
|
6
|
+
// session with WITNESS_DRIVE=<target>: the marker is the recursion guard (a marked session's
|
|
7
|
+
// `witness drive` refuses) and the child's scope (its `next` answers for that target alone).
|
|
8
|
+
export const DRIVE_ENV = 'WITNESS_DRIVE';
|
|
9
|
+
export const TARGETLESS = '-'; // the marker's value for work with no target
|
|
10
|
+
// Final review F14: when drive will kill this session (epoch ms). A reviewer inside it never
|
|
11
|
+
// waits past that — a wait drive kills mid-way leaves an orphaned gate and a stuck target.
|
|
12
|
+
export const DRIVE_DEADLINE_ENV = 'WITNESS_DRIVE_DEADLINE';
|
|
13
|
+
// unset → undefined · '-' → { target: undefined } · else → { target: <value> }
|
|
14
|
+
export function driveChild(env) {
|
|
15
|
+
const marker = env[DRIVE_ENV];
|
|
16
|
+
if (marker === undefined || marker === '')
|
|
17
|
+
return undefined;
|
|
18
|
+
return { target: marker === TARGETLESS ? undefined : marker };
|
|
19
|
+
}
|
|
20
|
+
// Row 180. One drive per repo: `.witness/drive.lock` names the live drive's pid and, for a
|
|
21
|
+
// background drive, its log — so a second drive, or `next` under autonomy, can say where to
|
|
22
|
+
// watch the one that runs and how to stop it.
|
|
23
|
+
export const DRIVE_LOCK = '.witness/drive.lock';
|
|
24
|
+
export const DRIVE_LOG = '.witness/drive.log';
|
|
25
|
+
// How a background drive learns its own log path, set by `detachDrive` on its child alone.
|
|
26
|
+
export const DRIVE_LOG_ENV = 'WITNESS_DRIVE_LOG';
|
|
27
|
+
function readHolder(root) {
|
|
28
|
+
const p = join(root, DRIVE_LOCK);
|
|
29
|
+
let text;
|
|
30
|
+
try {
|
|
31
|
+
if (lstatSync(p).isSymbolicLink())
|
|
32
|
+
return 'unreadable';
|
|
33
|
+
text = readFileSync(p, 'utf8');
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
return e.code === 'ENOENT' ? 'absent' : 'unreadable';
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const h = JSON.parse(text);
|
|
40
|
+
if (typeof h.pid !== 'number' || !Number.isInteger(h.pid) || h.pid < 1)
|
|
41
|
+
return 'unreadable';
|
|
42
|
+
// The lock says only WHETHER a background log exists; its path is always derived. What
|
|
43
|
+
// the file says is never printed: `watch:` is a line the engine acts on, and a path read
|
|
44
|
+
// from a file could carry a newline and a forged `launch:` or `run:` line.
|
|
45
|
+
return { pid: h.pid, ...(h.log !== undefined ? { log: join(root, DRIVE_LOG) } : {}) };
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return 'unreadable';
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// A live holder only: a dead one (a drive killed with SIGKILL) reads as none.
|
|
52
|
+
export function driveHolder(root) {
|
|
53
|
+
const h = readHolder(root);
|
|
54
|
+
return typeof h === 'object' && isAlive(h.pid) ? h : undefined;
|
|
55
|
+
}
|
|
56
|
+
export function acquireDriveLock(root, info, pid = process.pid) {
|
|
57
|
+
const p = join(root, DRIVE_LOCK);
|
|
58
|
+
mkdirSync(join(root, '.witness'), { recursive: true });
|
|
59
|
+
const release = () => releaseIfMine(p, pid);
|
|
60
|
+
const t0 = Date.now();
|
|
61
|
+
for (;;) {
|
|
62
|
+
try {
|
|
63
|
+
writeFileSync(p, JSON.stringify({ pid, ...(info.log !== undefined ? { log: info.log } : {}) }), { flag: 'wx' });
|
|
64
|
+
return ok(release);
|
|
65
|
+
}
|
|
66
|
+
catch (e) {
|
|
67
|
+
if (e.code !== 'EEXIST') {
|
|
68
|
+
return refuse([v(DRIVE_LOCK, 'drive-lock-unwritable', e.code ?? String(e), 'a writable .witness directory')]);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const h = readHolder(root);
|
|
72
|
+
if (typeof h === 'object' && h.pid === pid)
|
|
73
|
+
return ok(release);
|
|
74
|
+
if (typeof h === 'object' && isAlive(h.pid)) {
|
|
75
|
+
return refuse([v(DRIVE_LOCK, 'drive-running', `pid ${h.pid}`, `one drive per repo — ${watchLine(h)}`)]);
|
|
76
|
+
}
|
|
77
|
+
if (Date.now() - t0 > 5_000) {
|
|
78
|
+
return refuse([v(DRIVE_LOCK, 'drive-running', 'the lock changed hands while it was being taken', 'run this again')]);
|
|
79
|
+
}
|
|
80
|
+
// `wx` creates the file empty before the pid lands: an unreadable lock gets the repo
|
|
81
|
+
// lock's grace before it counts as a dead drive's. A dead one is taken atomically
|
|
82
|
+
// (F15), so of several drives started at once exactly one gets in.
|
|
83
|
+
if (h === 'unreadable') {
|
|
84
|
+
pause(50);
|
|
85
|
+
if (Date.now() - t0 < 1_000)
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
const took = takeStale(p, (text) => typeof h === 'object' ? pidOf(text) === h.pid : pidOf(text) === undefined);
|
|
90
|
+
if (took === 'busy')
|
|
91
|
+
pause(50);
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
return refuse([v(DRIVE_LOCK, 'drive-lock-unwritable', e.code ?? String(e), 'a writable .witness directory')]);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
// A path is quoted only when it needs it, so the common line stays the one a human types.
|
|
99
|
+
const shellArg = (p) => /^[\w@%+=:,./-]+$/.test(p) ? p : `'${p.replaceAll("'", "'\\''")}'`;
|
|
100
|
+
export function watchLine(h) {
|
|
101
|
+
return h.log !== undefined
|
|
102
|
+
? `tail -f ${shellArg(h.log)} · stop it: kill ${h.pid}`
|
|
103
|
+
: `the terminal running witness drive · pid ${h.pid}`;
|
|
104
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
|
+
import { handoffLine, resolveDriver } from './harness.js';
|
|
4
|
+
import { readStream } from './journal.js';
|
|
5
|
+
import { unmetNeeds } from './needs.js';
|
|
6
|
+
import { findById, loadCanon } from './scan.js';
|
|
7
|
+
import { pendingTxn } from './txn.js';
|
|
8
|
+
import { owedDecisions, parkedGates } from './verbs/next.js';
|
|
9
|
+
import { recoverChoice } from './verbs/recover.js';
|
|
10
|
+
const journalDir = (root) => join(root, '.witness', 'journal');
|
|
11
|
+
const streams = (root) => existsSync(journalDir(root))
|
|
12
|
+
? readdirSync(journalDir(root)).filter((f) => f.endsWith('.jsonl')).map((f) => f.slice(0, -'.jsonl'.length)).sort()
|
|
13
|
+
: [];
|
|
14
|
+
export function runStart(root) {
|
|
15
|
+
return { lines: new Map(streams(root).map((s) => [s, readStream(root, s).length])) };
|
|
16
|
+
}
|
|
17
|
+
export function entriesSince(root, start) {
|
|
18
|
+
return streams(root).flatMap((stream) => readStream(root, stream).slice(start.lines.get(stream) ?? 0).map((entry) => ({ stream, entry })));
|
|
19
|
+
}
|
|
20
|
+
const prOf = (line) => /PR #(\d+)/.exec(line)?.[1];
|
|
21
|
+
// Every `run:` and `then:` line is raw: a command is never kv-escaped (D120).
|
|
22
|
+
export function driveReport(root, ctx, cfg, start, aside, run) {
|
|
23
|
+
const canon = loadCanon(root);
|
|
24
|
+
const since = entriesSince(root, start);
|
|
25
|
+
const merged = since.filter(({ entry }) => entry.t === 'status' && entry.cause === 'merge')
|
|
26
|
+
.map(({ entry }) => `merged: ${String(entry.artifact)} · PR #${String(entry.pr)}`);
|
|
27
|
+
// The waits, each target once, in the order a human answers them.
|
|
28
|
+
const waits = [];
|
|
29
|
+
const named = new Set();
|
|
30
|
+
const wait = (target, rows) => { named.add(target); waits.push(...rows); };
|
|
31
|
+
// A crash no session could recover blocks every write: it is named first (F4).
|
|
32
|
+
const txn = pendingTxn(root);
|
|
33
|
+
if (txn !== undefined) {
|
|
34
|
+
wait('-txn', [`wait: pending transaction · ${txn.op}`, ` run: ${recoverChoice(root, txn).options[0].command}`]);
|
|
35
|
+
}
|
|
36
|
+
for (const a of aside.filter((x) => x.kind === 'kept' && (x.stop === 'design-look' || x.stop === 'trust-grant'))) {
|
|
37
|
+
if (named.has(a.target))
|
|
38
|
+
continue;
|
|
39
|
+
wait(a.target, a.stop === 'design-look'
|
|
40
|
+
? [`wait: design look · ${a.target}`, ` run: witness design ${a.target} --open`, ` then: witness decide design ${a.target} --show`]
|
|
41
|
+
: [`wait: trust grant · ${a.target} · in a terminal · answer each prompt`, ` run: witness gate ${a.gate ?? '<gate>'} ${a.target}`]);
|
|
42
|
+
}
|
|
43
|
+
for (const u of unmetNeeds(canon)) {
|
|
44
|
+
const held = u.type === 'spec' && u.holds.length > 0;
|
|
45
|
+
wait(u.doc, [
|
|
46
|
+
held ? `wait: held criterion · ${u.doc} · ${u.text} holds ${u.holds.join(' · ')}` : `wait: unmet need · ${u.doc} · ${u.text}`,
|
|
47
|
+
` run: ${u.satisfy}`,
|
|
48
|
+
]);
|
|
49
|
+
}
|
|
50
|
+
for (const o of owedDecisions(root, canon)) {
|
|
51
|
+
if (named.has(o.target))
|
|
52
|
+
continue;
|
|
53
|
+
wait(o.target, [`wait: decision · ${o.gate} ${o.target}`, ` run: witness decide ${o.gate} ${o.target} --show`]);
|
|
54
|
+
}
|
|
55
|
+
const driver = resolveDriver(ctx.env, cfg.raw);
|
|
56
|
+
for (const a of aside.filter((x) => x.kind === 'conversation' || x.kind === 'merge')) {
|
|
57
|
+
if (named.has(a.target))
|
|
58
|
+
continue;
|
|
59
|
+
if (a.kind === 'conversation') {
|
|
60
|
+
const who = a.target === '-' ? 'brainstorm' : a.target;
|
|
61
|
+
wait(a.target, [`wait: conversation · ${who}`,
|
|
62
|
+
...(driver.ok ? [` run: ${handoffLine(driver.value.harness, root, undefined)}`] : [])]);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
const pr = prOf(a.line) ?? (findById(canon, a.target)?.meta.pr !== undefined ? String(findById(canon, a.target).meta.pr) : undefined);
|
|
66
|
+
wait(a.target, [`wait: merge · ${a.target}${pr ? ` · PR #${pr}` : ''}`, ...(pr ? [` run: gh pr merge ${pr}`] : [])]);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const parked = parkedGates(root, canon).flatMap((p) => {
|
|
70
|
+
const stopped = readStream(root, p.target)
|
|
71
|
+
.filter((e) => e.t === 'human-decision' && e.gate === p.gate)
|
|
72
|
+
.map((e) => e).filter((d) => d.decision === 'stop').at(-1);
|
|
73
|
+
const why = stopped?.selected === 'policy' && stopped.note ? stopped.note : `parked at ${p.anchor}`;
|
|
74
|
+
return [`parked: ${p.target} · ${p.gate} round ${p.round} — ${why}`, ` run: ${p.reopen}`];
|
|
75
|
+
});
|
|
76
|
+
// A capped target the policy could not park carries no gate (drive.ts): it is stuck too.
|
|
77
|
+
const stuck = aside.filter((a) => a.kind === 'stuck' || (a.kind === 'capped' && a.gate === undefined))
|
|
78
|
+
.map((a) => `stuck: ${a.target} — ${a.why}`);
|
|
79
|
+
const obligations = since.filter(({ entry }) => entry.t === 'deferral').map(({ entry }) => {
|
|
80
|
+
const d = entry;
|
|
81
|
+
return `obligation: ${d.id} · ${d.artifact} · ${d.anchor} — ${d.kind}`;
|
|
82
|
+
});
|
|
83
|
+
const counts = { policy: 0, arbiter: 0, affirmation: 0, named: 0 };
|
|
84
|
+
for (const { entry } of since) {
|
|
85
|
+
if (entry.t !== 'human-decision')
|
|
86
|
+
continue;
|
|
87
|
+
const d = entry;
|
|
88
|
+
if (d.caused_by !== undefined)
|
|
89
|
+
continue; // a reopen record, not a decision
|
|
90
|
+
counts[d.selected ?? 'named'] += 1;
|
|
91
|
+
}
|
|
92
|
+
const m = merged.length;
|
|
93
|
+
const w = named.size;
|
|
94
|
+
const p = parkedGates(root, canon).length;
|
|
95
|
+
const s = stuck.length;
|
|
96
|
+
const tally = `${m} merged · ${w} wait on you · ${p} parked · ${s} stuck`;
|
|
97
|
+
const lines = [
|
|
98
|
+
`drive: ${run.stopped !== undefined ? 'stopped' : 'done'} — ${tally}`,
|
|
99
|
+
...merged, ...waits, ...parked, ...stuck, ...obligations,
|
|
100
|
+
`decisions: policy ${counts.policy} · arbiter ${counts.arbiter} · affirmation ${counts.affirmation} · named ${counts.named}`,
|
|
101
|
+
...(w > 0 ? ['help: answer the waits above · then /witness or witness drive picks up where this run stopped'] : []),
|
|
102
|
+
];
|
|
103
|
+
return { lines, summary: `witness drive — ${basename(root)} · ${tally}`, merged: m, waiting: w, parked: p, stuck: s };
|
|
104
|
+
}
|