@popovych.co/witness 0.28.0 → 0.28.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
@@ -251,7 +251,10 @@ parked.
251
251
  After each witness upgrade, run `witness migrate --dry-run` to see what the new version adds or
252
252
  changes, then `witness migrate`: it brings `witness.config.yaml` to the current schema, keeps
253
253
  every value you chose and every comment you wrote, names each change, and commits the file. A
254
- value still at an old default moves to the new one, and the output says so. Until you migrate,
254
+ value still at an old default moves to the new one, and the output says so. It also stamps
255
+ `specs/principles.md` approved when it is still the empty template an older `witness init` wrote
256
+ as a draft — a principles file you changed is approved only by the decompose gate of the effort
257
+ that amended it. Until you migrate,
255
258
  an older file keeps working: witness reads it as `migrate` would, changes nothing in it, and warns
256
259
  (`witness check` shows `older-schema`). A file from a newer witness refuses: upgrade witness.
257
260
 
@@ -286,7 +289,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
286
289
  | `read <id> [--design] [--outline] [--lines <a>-<b>] [--decisions]` | print a spec/plan/design from the primary root — the read route, since a worktree carries no canon copy; `--outline` names each anchor's line range for fat artifacts, and for a look its controls and hidden states; `--decisions` prints the decisions a spec carries with its effort's constraints and non-goals, or an effort's whole recap |
287
290
  | `check` | schema, graph, invariants, needs, trailer audit, probes |
288
291
  | `index` | id · summary · status · depends across the canon, then each spec's plans |
289
- | `satisfy <id> --need <id\|n\|text>` | journal a manual need as met — the spec is never rewritten |
292
+ | `satisfy <id> --need <id\|n\|text>` | journal a manual need as met — the spec is never rewritten; refused inside a session, since the human marks a need met |
290
293
  | `trust [<id>] [--cmd '<exact command>']… [--yes]` | list every command a target's flow runs (the runner, `ship.test`, `ship.lint`, its spec's `cmd:` criteria, its `cmd:` needs) with its source; `--cmd` grants exactly the named command, `--yes` grants all only at a terminal; no session grants trust · with no id, everything the repo runs |
291
294
  | `retry <target>` | ask drive to try a set-aside target again, after a fix that leaves no record of its own (code, a tool, an account); refused inside a session |
292
295
  | `wait [--since <token>]` | under autonomy, block until something new needs you, drive stops with work left, a merge lands on GitHub, or a newer chat takes over — the `/witness` chat runs it; journals nothing |
@@ -302,7 +305,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
302
305
  | `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:` |
303
306
  | `turn -- <command> [args…]` | run one command in the repo's test turn — it waits while another worktree's test run holds it, unless `drive.parallelSuites: true` — and on Windows inside a job object, so whatever it starts ends with it; exits with the command's code · the implement and ship skills run every test a session runs itself through it |
304
307
  | `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 |
305
- | `adopt <path>` | absolve a finished hand-edit into the journal |
308
+ | `adopt <path>` | absolve a finished hand-edit into the journal — content only: a hand edit that moves `status`, `drift`, `pr` or `design` is refused, since only witness writes a doc's position |
306
309
  | `abandon <plan-id \| effort-slug…>` | wind a plan/effort down; reverts only specs that effort itself wrote — several efforts go as one act, so a split or an amendment they share goes back together |
307
310
  | `dispatch-report <plan-id> --steps-assigned <n> --steps-completed <n>` | journal a session slice's telemetry |
308
311
  | `rename <old> <new>` | id rename across canon, refs, journal |
package/dist/adopt.js CHANGED
@@ -3,22 +3,36 @@ import { join } from 'node:path';
3
3
  import { splitDoc } from './fm.js';
4
4
  import { TRAILER, git, tryGit } from './gitio.js';
5
5
  import { readStream } from './journal.js';
6
- import { canonicalSha } from './sha.js';
6
+ import { canonicalSha, VOLATILE_FIELDS } from './sha.js';
7
+ export const positionOf = (meta) => Object.fromEntries(VOLATILE_FIELDS.map((f) => [f, meta[f]]));
7
8
  const hasTrailer = (root, sha) => git(root, 'show', '-s', '--format=%B', sha).split('\n').some((l) => l.trim() === TRAILER);
8
9
  const commitsTouching = (root, rel) => git(root, 'log', '--format=%H', '--', rel).split('\n').filter(Boolean);
10
+ // Row 220. The same walk through a move: each commit with the path the file had in it, so a
11
+ // doc moved by hand (`git mv`, D167) is measured against the state it was witnessed in before.
12
+ function commitsFollowing(root, rel) {
13
+ return git(root, 'log', '--follow', '--format=%x00%H', '--name-only', '--', rel).split('\0').flatMap((chunk) => {
14
+ const [sha, ...paths] = chunk.split('\n').filter(Boolean);
15
+ return sha === undefined ? [] : [{ sha, path: paths[0] ?? rel }];
16
+ });
17
+ }
9
18
  // `absolved`: commits an `adopt` entry took in (`adoptedCommits`), which count as witnessed too —
10
- // a hand commit that `adopt` absolved is the doc's witnessed state from then on.
11
- export function lastWitnessed(root, rel, absolved = new Set()) {
12
- for (const sha of commitsTouching(root, rel)) {
19
+ // a hand commit that `adopt` absolved is the doc's witnessed state from then on. `follow` walks
20
+ // the file's history through a move (row 220's position baseline).
21
+ export function lastWitnessed(root, rel, absolved = new Set(), opts = {}) {
22
+ const walk = opts.follow === true ? commitsFollowing(root, rel) : commitsTouching(root, rel).map((sha) => ({ sha, path: rel }));
23
+ for (const { sha, path } of walk) {
13
24
  if (!hasTrailer(root, sha) && !absolved.has(sha))
14
25
  continue;
15
- const raw = tryGit(root, 'show', `${sha}:${rel}`);
26
+ const raw = tryGit(root, 'show', `${sha}:${path}`);
16
27
  if (!raw.ok)
17
28
  continue;
18
29
  const doc = splitDoc(raw.out);
19
30
  if (!doc.ok)
20
31
  continue;
21
- return { sha: canonicalSha(doc.value.meta, doc.value.body), criteria: doc.value.meta.criteria ?? null, id: String(doc.value.meta.id) };
32
+ return {
33
+ sha: canonicalSha(doc.value.meta, doc.value.body), criteria: doc.value.meta.criteria ?? null, id: String(doc.value.meta.id),
34
+ commit: sha, position: positionOf(doc.value.meta),
35
+ };
22
36
  }
23
37
  return undefined;
24
38
  }
@@ -42,3 +56,75 @@ export function adoptedCommits(root) {
42
56
  }
43
57
  return out;
44
58
  }
59
+ // Final review F1. An adopt absolves its commits for the doc it adopted — the stream it is
60
+ // journaled on — never for every doc those commits touched: one hand commit that forged one doc's
61
+ // position and edited another's body was laundered by adopting the innocent one.
62
+ export function adoptedCommitsFor(root, id) {
63
+ const out = new Set();
64
+ for (const entry of readStream(root, id)) {
65
+ if (entry.t !== 'adopt' || !Array.isArray(entry.commits))
66
+ continue;
67
+ for (const sha of entry.commits)
68
+ out.add(sha);
69
+ }
70
+ return out;
71
+ }
72
+ // For the trailer audit: each absolved commit and the doc ids it was absolved for (the stream,
73
+ // and the entry's artifact, which a later rename may leave apart).
74
+ export function absolutions(root) {
75
+ const out = new Map();
76
+ const dir = join(root, '.witness', 'journal');
77
+ if (!existsSync(dir))
78
+ return out;
79
+ for (const file of readdirSync(dir)) {
80
+ if (!file.endsWith('.jsonl'))
81
+ continue;
82
+ const stream = file.slice(0, -'.jsonl'.length);
83
+ for (const entry of readStream(root, stream)) {
84
+ if (entry.t !== 'adopt' || !Array.isArray(entry.commits))
85
+ continue;
86
+ for (const sha of entry.commits) {
87
+ const ids = out.get(sha) ?? new Set();
88
+ ids.add(stream);
89
+ if (typeof entry.artifact === 'string')
90
+ ids.add(entry.artifact);
91
+ out.set(sha, ids);
92
+ }
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ // Security review. The state paths a commit changed that no adopt absolved it for: a spec or
98
+ // plan whose id (as it stood there, or in the parent for a deletion) is not among `ids`, and
99
+ // every other audited path — a journal line or a design file is never a hand edit adopt takes in.
100
+ // Empty means the commit is absolved whole.
101
+ export function unabsolvedPaths(root, sha, ids, dirs) {
102
+ const under = (p, ds) => ds.some((d) => p.startsWith(`${d}/`));
103
+ // NUL-separated status/path pairs: never quoted, whatever bytes a path carries. Anything that
104
+ // does not parse is reported, never skipped. Against the first parent, so a merge's own changes
105
+ // are read (diff-tree on a merge alone prints nothing); a root commit against the empty tree.
106
+ const [, parent] = git(root, 'rev-list', '--parents', '-n', '1', sha).split(' ');
107
+ const fields = (parent !== undefined
108
+ ? git(root, 'diff-tree', '-z', '--no-renames', '--name-status', '-r', parent, sha)
109
+ : git(root, 'diff-tree', '-z', '--no-commit-id', '--no-renames', '--name-status', '-r', '--root', sha))
110
+ .split('\0').filter((x) => x !== '');
111
+ const out = [];
112
+ for (let i = 0; i < fields.length; i += 2) {
113
+ const status = fields[i];
114
+ const p = fields[i + 1];
115
+ if (p === undefined || !/^[ACDMTUX]$/.test(status)) {
116
+ out.push(`(unparsed: ${status})`);
117
+ continue;
118
+ }
119
+ if (under(p, dirs.docs) && p.endsWith('.md')) {
120
+ const raw = tryGit(root, 'show', `${status === 'D' ? `${sha}^` : sha}:${p}`);
121
+ const doc = raw.ok ? splitDoc(raw.out) : undefined;
122
+ const id = doc?.ok && typeof doc.value.meta.id === 'string' ? doc.value.meta.id : undefined;
123
+ if (id === undefined || !ids.has(id))
124
+ out.push(p);
125
+ }
126
+ else if (under(p, [...dirs.docs, ...dirs.other]))
127
+ out.push(p);
128
+ }
129
+ return out;
130
+ }
package/dist/allowlist.js CHANGED
@@ -54,9 +54,13 @@ export function untrustedCmdsFor(root, doc) {
54
54
  // drive's report, the chat — renders it here: escaped, beside its source, and with the grant
55
55
  // that names it only when the verb would take it (printable ASCII, `witness trust`).
56
56
  export const shownCmd = (c) => `${visible(c.cmd)} (${visible(c.source)})`;
57
+ export const UNGRANTABLE = 'never granted here — rewrite it in printable ASCII where it is written';
57
58
  export const grantOf = (target, c) => hasControl(c.cmd)
58
- ? 'never granted here — rewrite it in printable ASCII where it is written'
59
+ ? UNGRANTABLE
59
60
  : `witness trust ${target} --cmd ${shellArg(c.cmd)}`;
61
+ // Row 205. The commands a grant leaves blocked for that reason, counted: the trust verb's summary
62
+ // and `decide --approve --trust-cmds` say it in these words.
63
+ export const unsafeLeft = (n) => `${n} carry characters outside printable ASCII — never granted here · rewrite where it is written`;
60
64
  // The filtered runner template, `ship.test`, `ship.lint`, each when set. Full-suite mode's
61
65
  // runner IS `ship.test`, and a command listed twice is listed once, under its first source.
62
66
  export function configCommands(cfg) {
@@ -131,6 +135,11 @@ export async function ensureTrusted(root, ctx, cmd) {
131
135
  const commands = load(root);
132
136
  if (commands.includes(cmd))
133
137
  return 'trusted';
138
+ // Row 237. The prompt is where a human reads the command, so a command they cannot read whole —
139
+ // one holding any character outside printable ASCII — is never offered, and so never granted
140
+ // here. Automation and the human's own list, above, still answer first.
141
+ if (hasControl(cmd))
142
+ return 'blocked';
134
143
  if (!ctx.isTTY)
135
144
  return 'blocked';
136
145
  const answer = await ctx.ask(`witness wants to run: ${cmd}\ntrust this command? saves to .witness/allow.json (gitignored) [y/N]`);
package/dist/arbiter.js CHANGED
@@ -9,7 +9,7 @@ import { SESSION_DEFAULT, stageModel, unansweredPin } from './model.js';
9
9
  import { PLACEHOLDER } from './recommend.js';
10
10
  import { ok, refuse, v } from './refusal.js';
11
11
  import { invokeReviewerAsync, parseVerdictText, promptsSha, resolvePrompt } from './reviewer.js';
12
- import { effortOf, effortSpecs } from './reviewed.js';
12
+ import { effortCanon, effortOf } from './reviewed.js';
13
13
  import { anchorRecurrence, gateRuns, roundBudget } from './rounds.js';
14
14
  import { findById } from './scan.js';
15
15
  import { canonicalJson } from './sha.js';
@@ -170,8 +170,10 @@ export function decisionEvidence(root, canon, stop) {
170
170
  scope.push(`### The plan: ${target}\n\n${serializeDoc({ meta: plan.meta, body: plan.body })}`);
171
171
  }
172
172
  else {
173
- for (const s of effortSpecs(root, canon, target)) {
174
- scope.push(`### The spec: ${String(s.meta.id)}\n\n${serializeDoc({ meta: s.meta, body: s.body })}`);
173
+ // Row 221. What the decompose gate judged: the effort's specs and the principles it wrote.
174
+ for (const s of effortCanon(root, canon, target)) {
175
+ const kind = s.meta.type === 'principles' ? 'The principles (standing rules, not a slice)' : 'The spec';
176
+ scope.push(`### ${kind}: ${String(s.meta.id)}\n\n${serializeDoc({ meta: s.meta, body: s.body })}`);
175
177
  }
176
178
  }
177
179
  sections.push({ title: 'Scope', body: scope.join('\n\n') });
@@ -1,4 +1,4 @@
1
- import { lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
1
+ import { lstatSync, mkdirSync, readFileSync, utimesSync, 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';
@@ -39,12 +39,25 @@ export const DRIVE_LOCK = '.witness/drive.lock';
39
39
  export const DRIVE_LOG = '.witness/drive.log';
40
40
  // How a background drive learns its own log path, set by `detachDrive` on its child alone.
41
41
  export const DRIVE_LOG_ENV = 'WITNESS_DRIVE_LOG';
42
+ // Row 224 (#69). The drive lock is a lease. A pid alone outlives its drive: a drive stopped
43
+ // hard (`taskkill /F`, `kill -9`, a reboot) never runs its `finally`, and once that pid is
44
+ // reused the lock read as a running drive and its printed stop aimed at an unrelated tree. The
45
+ // running drive renews the lock's mtime every DRIVE_RENEW_MS; a lock not renewed for
46
+ // DRIVE_LEASE_MS is no drive, whatever its pid. A drive whose host slept renews within a
47
+ // renewal of waking, so a new drive takes over a live pid's expired lease only after
48
+ // DRIVE_TAKEOVER_GRACE_MS without a renewal — never one that wakes in time.
49
+ export const DRIVE_LEASE_MS = 120_000;
50
+ export const DRIVE_RENEW_MS = 10_000;
51
+ export const DRIVE_TAKEOVER_GRACE_MS = 25_000;
42
52
  function readHolder(root) {
43
53
  const p = join(root, DRIVE_LOCK);
44
54
  let text;
55
+ let renewed;
45
56
  try {
46
- if (lstatSync(p).isSymbolicLink())
57
+ const st = lstatSync(p);
58
+ if (st.isSymbolicLink())
47
59
  return 'unreadable';
60
+ renewed = st.mtimeMs;
48
61
  text = readFileSync(p, 'utf8');
49
62
  }
50
63
  catch (e) {
@@ -57,25 +70,70 @@ function readHolder(root) {
57
70
  // The lock says only WHETHER a background log exists; its path is always derived. What
58
71
  // the file says is never printed: `watch:` is a line the engine acts on, and a path read
59
72
  // from a file could carry a newline and a forged `launch:` or `run:` line.
60
- return { pid: h.pid, ...(h.log !== undefined ? { log: join(root, DRIVE_LOG) } : {}) };
73
+ return { pid: h.pid, renewed, leased: h.lease === 1, ...(h.log !== undefined ? { log: join(root, DRIVE_LOG) } : {}) };
61
74
  }
62
75
  catch {
63
76
  return 'unreadable';
64
77
  }
65
78
  }
66
- // A live holder only: a dead one (a drive killed with SIGKILL) reads as none.
67
- export function driveHolder(root) {
79
+ const leaseLive = (h, now) => !h.leased || now - h.renewed < DRIVE_LEASE_MS;
80
+ // A live holder only: a dead one (a drive killed with SIGKILL) reads as none, and so does a
81
+ // live pid whose lease expired (row 224).
82
+ export function driveHolder(root, now = Date.now()) {
68
83
  const h = readHolder(root);
69
- return typeof h === 'object' && isAlive(h.pid) ? h : undefined;
84
+ if (typeof h !== 'object' || !isAlive(h.pid) || !leaseLive(h, now))
85
+ return undefined;
86
+ return { pid: h.pid, ...(h.log !== undefined ? { log: h.log } : {}) };
70
87
  }
71
- export function acquireDriveLock(root, info, pid = process.pid) {
88
+ // Row 224. The running drive's renewal: the lock's mtime set to now when the lock is this
89
+ // pid's. A link at the lock path is never followed (utimes would touch what it points at).
90
+ // `false` says the lease is no longer this drive's — taken over, or removed — and the drive
91
+ // that held it stops. A renewal that fails while the lock still names this pid (a scanner
92
+ // holding the file, EBUSY) is retried on the next tick, never read as lost: a lease left
93
+ // unrenewed that long expires, and the next renewal then finds the successor's lock.
94
+ export function renewDriveLock(root, pid = process.pid) {
95
+ const h = readHolder(root);
96
+ if (typeof h !== 'object' || h.pid !== pid)
97
+ return false;
98
+ const p = join(root, DRIVE_LOCK);
99
+ try {
100
+ if (lstatSync(p).isSymbolicLink())
101
+ return false;
102
+ }
103
+ catch {
104
+ return false;
105
+ }
106
+ try {
107
+ const now = new Date();
108
+ utimesSync(p, now, now);
109
+ }
110
+ catch { /* still this drive's lock: retried on the next tick */ }
111
+ return true;
112
+ }
113
+ // Row 224. The lock holder's renewal, from the moment it holds the lock to its release, so a
114
+ // drive waiting on a session, a usage pause or a human's answer alike keeps its lease. The
115
+ // timer never keeps the process alive. `onLost` runs once, when the lease is no longer this
116
+ // pid's, and the renewal stops.
117
+ export function holdLease(root, onLost, everyMs = DRIVE_RENEW_MS, pid = process.pid) {
118
+ const timer = setInterval(() => {
119
+ if (renewDriveLock(root, pid))
120
+ return;
121
+ clearInterval(timer);
122
+ onLost();
123
+ }, everyMs);
124
+ timer.unref();
125
+ return () => clearInterval(timer);
126
+ }
127
+ export function acquireDriveLock(root, info, pid = process.pid, graceMs = DRIVE_TAKEOVER_GRACE_MS) {
72
128
  const p = join(root, DRIVE_LOCK);
73
129
  mkdirSync(join(root, '.witness'), { recursive: true });
74
130
  const release = () => releaseIfMine(p, pid);
75
- const t0 = Date.now();
131
+ let t0 = Date.now();
132
+ // Row 224. When this drive first saw a live pid's lease expired, and how renewed it was then.
133
+ let expired;
76
134
  for (;;) {
77
135
  try {
78
- writeFileSync(p, JSON.stringify({ pid, ...(info.log !== undefined ? { log: info.log } : {}) }), { flag: 'wx' });
136
+ writeFileSync(p, JSON.stringify({ pid, ...(info.log !== undefined ? { log: info.log } : {}), lease: 1 }), { flag: 'wx' });
79
137
  return ok(release);
80
138
  }
81
139
  catch (e) {
@@ -86,22 +144,47 @@ export function acquireDriveLock(root, info, pid = process.pid) {
86
144
  const h = readHolder(root);
87
145
  if (typeof h === 'object' && h.pid === pid)
88
146
  return ok(release);
89
- if (typeof h === 'object' && isAlive(h.pid)) {
90
- return refuse([v(DRIVE_LOCK, 'drive-running', `pid ${h.pid}`, `one drive per repo — ${watchLine(h)}`)]);
147
+ const alive = typeof h === 'object' && isAlive(h.pid);
148
+ if (typeof h === 'object' && alive) {
149
+ const running = refuse([v(DRIVE_LOCK, 'drive-running', `pid ${h.pid}`, `one drive per repo — ${watchLine(h)}`)]);
150
+ if (leaseLive(h, Date.now()))
151
+ return running;
152
+ // Expired, but the pid lives: a reused pid, a frozen drive — or a drive whose host just
153
+ // woke, which renews within DRIVE_RENEW_MS. Watched for the grace; a renewal refuses.
154
+ if (expired === undefined || expired.pid !== h.pid)
155
+ expired = { pid: h.pid, renewed: h.renewed, since: Date.now() };
156
+ else if (h.renewed !== expired.renewed)
157
+ return running;
158
+ if (Date.now() - expired.since < graceMs) {
159
+ pause(Math.min(250, graceMs));
160
+ continue;
161
+ }
162
+ t0 = Math.max(t0, expired.since + graceMs);
91
163
  }
92
164
  if (Date.now() - t0 > 5_000) {
93
165
  return refuse([v(DRIVE_LOCK, 'drive-running', 'the lock changed hands while it was being taken', 'run this again')]);
94
166
  }
95
167
  // `wx` creates the file empty before the pid lands: an unreadable lock gets the repo
96
168
  // lock's grace before it counts as a dead drive's. A dead one is taken atomically
97
- // (F15), so of several drives started at once exactly one gets in.
169
+ // (F15), so of several drives started at once exactly one gets in; an expired lease is
170
+ // taken only while it stays as the grace saw it (same pid, not renewed).
98
171
  if (h === 'unreadable') {
99
172
  pause(50);
100
173
  if (Date.now() - t0 < 1_000)
101
174
  continue;
102
175
  }
103
176
  try {
104
- const took = takeStale(p, (text) => typeof h === 'object' ? pidOf(text) === h.pid : pidOf(text) === undefined);
177
+ const stale = (text) => {
178
+ if (typeof h !== 'object')
179
+ return pidOf(text) === undefined;
180
+ if (pidOf(text) !== h.pid)
181
+ return false;
182
+ if (!alive)
183
+ return true;
184
+ const now = readHolder(root);
185
+ return typeof now === 'object' && now.pid === h.pid && now.renewed === h.renewed;
186
+ };
187
+ const took = takeStale(p, stale);
105
188
  if (took === 'busy')
106
189
  pause(50);
107
190
  }
package/dist/drive.js CHANGED
@@ -649,6 +649,14 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
649
649
  abort.abort();
650
650
  };
651
651
  const aborted = new Promise((done) => abort.signal.addEventListener('abort', () => done(), { once: true }));
652
+ // Row 224. The lease lost — another drive holds the lock now: this run ends as a signal ends
653
+ // it, every session stopped, so two drives never work the repo at once.
654
+ const outside = () => { if (signalled === undefined)
655
+ onSignal('SIGTERM'); };
656
+ if (flags.signal?.aborted)
657
+ outside();
658
+ else
659
+ flags.signal?.addEventListener('abort', outside, { once: true });
652
660
  // Final review F2. A lane holds its whole flow: a spec and the plans written for it. The
653
661
  // plan queue's lane is keyed by the spec, and its session writes the plan and keeps working
654
662
  // on it (witness-plan gates it in the same session), so the new plan's id must not read as
@@ -1159,10 +1167,28 @@ export async function driveLoop(root, cfg, ctx, flags, clock = realClock) {
1159
1167
  releaseAwake();
1160
1168
  }
1161
1169
  }
1170
+ // Row 223 (#68). What `--detach` starts. With no WITNESS_BIN, this CLI's own bin.js under this
1171
+ // node. On posix a WITNESS_BIN runs through `/bin/sh -c 'exec <bin> "$@"'`, so the printed pid
1172
+ // is the CLI's own and no shell sits between it and a `kill`. Windows has no /bin/sh: the bin
1173
+ // is split as a command line (a quoted first word may carry spaces — an install under Program
1174
+ // Files) and its first word resolved like every other spawn, an npm `.cmd` shim through
1175
+ // System32's cmd.exe (row 201). A bin nothing answers to is refused here, not at the spawn.
1176
+ export function detachArgv(bin, args, env, platform = process.platform) {
1177
+ if (bin === undefined) {
1178
+ return ok({ file: process.execPath, args: [join(dirname(fileURLToPath(import.meta.url)), 'bin.js'), 'drive', ...args], env, windowsVerbatimArguments: false });
1179
+ }
1180
+ if (platform !== 'win32') {
1181
+ return ok({ file: '/bin/sh', args: ['-c', `exec ${bin} "$@"`, 'witness', 'drive', ...args], env, windowsVerbatimArguments: false });
1182
+ }
1183
+ const [first, ...rest] = splitArgv(bin);
1184
+ if (first === undefined) {
1185
+ return refuse([v('WITNESS_BIN', 'bin-empty', JSON.stringify(bin), 'the command that runs witness, e.g. node C:\\path\\to\\bin.js — or unset it')]);
1186
+ }
1187
+ return resolveSpawn(first, [...rest, 'drive', ...args], env, 'win32');
1188
+ }
1162
1189
  // Row 180. `--detach`: this CLI again, as `witness drive <args>`, in the background at the
1163
- // root, appending to `.witness/drive.log`. With WITNESS_BIN set it runs through
1164
- // `exec <bin> "$@"`, so the printed pid is the CLI's own and no shell sits between it and a
1165
- // `kill`. The child takes the drive lock itself and records its log there.
1190
+ // root, appending to `.witness/drive.log` — started as `detachArgv` says (row 223). The child
1191
+ // takes the drive lock itself and records its log there.
1166
1192
  export function detachDrive(root, ctx, args) {
1167
1193
  const log = join(root, DRIVE_LOG);
1168
1194
  mkdirSync(dirname(log), { recursive: true });
@@ -1180,14 +1206,17 @@ export function detachDrive(root, ctx, args) {
1180
1206
  closeSync(fd);
1181
1207
  return refuse([v(DRIVE_LOG, 'drive-log-unsafe', 'not a regular file', 'a regular file at .witness/drive.log — remove whatever is there and run this again')]);
1182
1208
  }
1209
+ const how = detachArgv(ctx.env.WITNESS_BIN, args, ctx.env);
1210
+ if (!how.ok) {
1211
+ closeSync(fd);
1212
+ return how;
1213
+ }
1214
+ const { file, args: argv, env, windowsVerbatimArguments } = how.value;
1183
1215
  writeSync(fd, `--- witness drive ${new Date().toISOString()} ---\n`);
1184
- const [file, argv] = ctx.env.WITNESS_BIN !== undefined
1185
- ? ['/bin/sh', ['-c', `exec ${ctx.env.WITNESS_BIN} "$@"`, 'witness', 'drive', ...args]]
1186
- : [process.execPath, [join(dirname(fileURLToPath(import.meta.url)), 'bin.js'), 'drive', ...args]];
1187
1216
  try {
1188
1217
  const child = spawn(file, argv, {
1189
- cwd: root, detached: true, stdio: ['ignore', fd, fd],
1190
- env: { ...ctx.env, [DRIVE_LOG_ENV]: log, [NO_CONSOLE_ENV]: '1' },
1218
+ cwd: root, detached: true, stdio: ['ignore', fd, fd], windowsVerbatimArguments,
1219
+ env: { ...env, [DRIVE_LOG_ENV]: log, [NO_CONSOLE_ENV]: '1' },
1191
1220
  });
1192
1221
  if (child.pid === undefined)
1193
1222
  return refuse([v('--detach', 'spawn-failed', file, 'a runnable witness CLI')]);
@@ -3,12 +3,20 @@ import { serializeDoc } from '../fm.js';
3
3
  import { canonicalJson } from '../sha.js';
4
4
  import { contextDigest } from '../delta.js';
5
5
  import { snapshotFiles } from '../snapshot.js';
6
- import { latestRecap, streamExists } from '../journal.js';
6
+ import { effortAbandoned, latestRecap, readStream, streamExists } from '../journal.js';
7
7
  import { findCycle, findById } from '../scan.js';
8
- import { effortReviewedSha, effortSpecs, effortWrites } from '../reviewed.js';
8
+ import { effortCanon, effortReviewedSha, effortWrites } from '../reviewed.js';
9
9
  import { validateDoc } from '../schemas.js';
10
10
  import { registerGate } from '../gate.js';
11
11
  import { basisMoved, planBasis, specBasis } from '../basis.js';
12
+ // Row 221 (final review). The critic's lenses are written for slices; principles are not one.
13
+ const PRINCIPLES_LENSES = [
14
+ 'This effort also amends the repo\'s principles. Principles are standing rules, not a slice:',
15
+ 'work only coverage quality (does a rule really advance each goal it covers), non-goal violations,',
16
+ 'decision fidelity, contradictions (within the principles and against every spec) and duplicated facts',
17
+ 'over them. Never judge them for slice shape, summary, criteria, ui flag or depends — they carry none.',
18
+ 'A goal the principles cover is covered.',
19
+ ].join(' ');
12
20
  function stampsFor(docs) {
13
21
  return docs
14
22
  .filter((d) => String(d.meta.status) === 'draft')
@@ -25,10 +33,17 @@ registerGate({
25
33
  const recap = latestRecap(root, effort);
26
34
  if (!recap)
27
35
  return refuse([v('effort', 'unknown-effort', effort, 'a stream whose first entry is a recap')]);
36
+ // Row 221 (final review). An abandoned effort's gate judges nothing: its specs went back, and
37
+ // the principles it may have left are not its gate's to approve.
38
+ if (effortAbandoned(readStream(root, effort))) {
39
+ return refuse([v('effort', 'effort-abandoned', effort, 'a live effort — an abandoned effort approves nothing; amend through a new feature or fix effort')]);
40
+ }
28
41
  const writes = effortWrites(root, effort);
29
- const docs = effortSpecs(root, canon, effort);
42
+ // Row 221. Principles are canon like a spec: the effort that changes them has them reviewed
43
+ // here, and an approve stamps them with its specs.
44
+ const docs = effortCanon(root, canon, effort);
30
45
  if (docs.length === 0) {
31
- return refuse([v('effort', 'nothing-to-gate', effort, `written specs — run: witness write <id> --effort ${effort} --meta m.json --body b.md`)]);
46
+ return refuse([v('effort', 'nothing-to-gate', effort, `written specs or principles — run: witness write <id> --effort ${effort} --meta m.json --body b.md`)]);
32
47
  }
33
48
  const checks = [];
34
49
  const schemaProblems = docs.flatMap((d) => validateDoc(d.meta, d.body).map((x) => `${String(d.meta.id)} ${x.field}:${x.rule}`));
@@ -41,7 +56,8 @@ registerGate({
41
56
  for (const d of docs) {
42
57
  const covers = writes.get(String(d.meta.id))?.covers ?? [];
43
58
  covers.forEach((g) => covered.add(g));
44
- if (covers.length === 0)
59
+ // Row 221. Principles count toward the goals they cover; only a spec must cover one.
60
+ if (covers.length === 0 && d.meta.type === 'spec')
45
61
  orphans.push(String(d.meta.id));
46
62
  }
47
63
  const missing = goals.filter((g) => !covered.has(g));
@@ -85,7 +101,9 @@ registerGate({
85
101
  '### Confirmed scope recap (latest)', canonicalJson(recap),
86
102
  '### Goal coverage (journaled)', coverageTable,
87
103
  ...(decisionTable !== undefined ? ['### Decision coverage (journaled)', decisionTable] : []),
88
- ...docs.flatMap((d) => [`### Spec: ${String(d.meta.id)}`, serializeDoc({ meta: d.meta, body: d.body })]),
104
+ // Row 221. Only when the effort wrote principles, so every other effort's prompt is today's.
105
+ ...(docs.some((d) => d.meta.type === 'principles') ? ['### Principles in this effort', PRINCIPLES_LENSES] : []),
106
+ ...docs.flatMap((d) => [`### ${d.meta.type === 'principles' ? 'Principles' : 'Spec'}: ${String(d.meta.id)}`, serializeDoc({ meta: d.meta, body: d.body })]),
89
107
  ].join('\n\n');
90
108
  const { sha } = effortReviewedSha(root, canon, effort);
91
109
  const tree = snapshotFiles(root, docs.map((d) => ({ name: `${String(d.meta.id)}.md`, content: serializeDoc({ meta: d.meta, body: d.body }) })));
@@ -109,6 +127,6 @@ registerGate({
109
127
  return streamExists(root, effort) ? effort : undefined;
110
128
  },
111
129
  approveStamps(root, canon, effort) {
112
- return stampsFor(effortSpecs(root, canon, effort));
130
+ return stampsFor(effortCanon(root, canon, effort));
113
131
  },
114
132
  });
package/dist/needs.js CHANGED
@@ -1,5 +1,6 @@
1
- import { ensureTrusted } from './allowlist.js';
1
+ import { ensureTrusted, UNGRANTABLE } from './allowlist.js';
2
2
  import { execSync } from './spawn.js';
3
+ import { hasControl } from './toon.js';
3
4
  // Row 179. What a journaled satisfaction names a need by: its id, else its manual text.
4
5
  export function needKey(n) {
5
6
  return n.id ?? n.manual;
@@ -26,9 +27,12 @@ export async function evaluateNeeds(root, ctx, needs, doc) {
26
27
  else if (typeof n.cmd === 'string') {
27
28
  const trust = await ensureTrusted(root, ctx, n.cmd);
28
29
  if (trust !== 'trusted') {
30
+ // Row 237. No grant exists for a command outside printable ASCII, so its remedy says so
31
+ // rather than send the human to `witness next` for one.
32
+ const blocked = hasControl(n.cmd) ? UNGRANTABLE : 'untrusted on this machine — witness next names the grant to make';
29
33
  out.push({
30
34
  label: n.cmd, kind: 'cmd', status: trust,
31
- detail: trust === 'blocked' ? 'untrusted on this machine — witness next names the grant to make' : 'trust declined',
35
+ detail: trust === 'blocked' ? blocked : 'trust declined',
32
36
  });
33
37
  continue;
34
38
  }
@@ -0,0 +1,18 @@
1
+ import { tryGit } from './gitio.js';
2
+ // Row 221. The template `witness init` writes, born approved. An older init wrote it draft.
3
+ export const PRINCIPLES_BODY = `# Principles
4
+
5
+ Repo-wide rules and trade-offs. Amend via \`witness write\`; chores may name
6
+ this doc as their plan's parent.
7
+ `;
8
+ // Row 221. The principles an older init left: the template, still draft, its body untouched and
9
+ // its file clean — what `witness migrate` stamps approved. A changed body is content someone
10
+ // wrote, which only a gate approves. One predicate for migrate, `next` and `write`'s refusal.
11
+ export function templateDraft(root, doc) {
12
+ if (doc === undefined || doc.meta.type !== 'principles' || String(doc.meta.status) !== 'draft')
13
+ return false;
14
+ const norm = (t) => t.replace(/\r\n?/g, '\n').trim();
15
+ if (norm(doc.body) !== norm(PRINCIPLES_BODY))
16
+ return false;
17
+ return tryGit(root, 'status', '--porcelain', '--', doc.rel).out.trim() === '';
18
+ }
package/dist/recommend.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { anchorRecurrence, boundReached, ladderSpent, lastGateRun, notePrefill, pendingDecision, repairsOnRegate, repairGranted, roundBudget, roundsSinceApprove, } from './rounds.js';
2
+ import { hasControl, visible } from './toon.js';
2
3
  // Commands are emitted raw (D120): `esc` would quote the `--note "…"` argument and the
3
4
  // line would paste into a shell as an empty note.
4
5
  export function renderDecision(d) {
@@ -42,13 +43,18 @@ const opt = (command, depth, rest = {}) => ({ command, depth, runnable: !PLACEHO
42
43
  // checks-failed · non-blocking-only · reserved-stop-clean · manual-stop
43
44
  // D154. Trust must never be the toll for approval. Where a plain `--approve` is offered
44
45
  // and the artifact carries untrusted `cmd:` criteria, the block renders BOTH forms — plain
45
- // first, so approving without granting stays the easy path — and names the commands
46
- // verbatim, because a grant the human cannot read is not one they made. Applied once, over
47
- // the finished option list, rather than at each of the five rules that offer an approve.
46
+ // first, so approving without granting stays the easy path — and names the commands, because
47
+ // a grant the human cannot read is not one they made. Applied once, over the finished option
48
+ // list, rather than at each of the five rules that offer an approve.
49
+ // Row 205. The twin grants what `witness trust` would and nothing else: a command holding a
50
+ // character outside printable ASCII is never granted. So the plain approve names every untrusted
51
+ // command, each spelled out (`visible`), since all of them stay blocked; the twin is offered only
52
+ // while one is grantable, and prices only those.
48
53
  function withTrustVariants(d, untrusted) {
49
54
  if (untrusted.length === 0)
50
55
  return d;
51
- const listed = untrusted.join(' · ');
56
+ const listed = untrusted.map(visible).join(' · ');
57
+ const grantable = untrusted.filter((c) => !hasControl(c));
52
58
  const options = [];
53
59
  for (const o of d.options) {
54
60
  options.push(o);
@@ -61,11 +67,13 @@ function withTrustVariants(d, untrusted) {
61
67
  tradeoff: [o.tradeoff, `the listed commands stay blocked at headless gates: ${listed}`]
62
68
  .filter(Boolean).join(' · '),
63
69
  };
70
+ if (grantable.length === 0)
71
+ continue;
64
72
  // The twin is the same stamp plus a grant, so it carries the stamp's depth: next to a
65
73
  // deferral approve (checks-failed) it is a deferral too, never a root fix.
66
74
  options.push(opt(`${o.command} --trust-cmds`, o.depth, {
67
75
  when: 'you have read these commands and accept them running unattended at every later gate',
68
- tradeoff: `grants them repo-wide in .witness/allow.json (machine-local): ${listed}`,
76
+ tradeoff: `grants them repo-wide in .witness/allow.json (machine-local): ${grantable.join(' · ')}`,
69
77
  note: 'a bare affirmation never grants trust — this form must be named (D143)',
70
78
  }));
71
79
  }