@popovych.co/witness 0.28.0 → 0.28.1

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/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
  });
@@ -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/reviewed.js CHANGED
@@ -93,6 +93,35 @@ export function effortSpecs(root, canon, effort) {
93
93
  }
94
94
  return docs.sort((a, b) => String(a.meta.id).localeCompare(String(b.meta.id)));
95
95
  }
96
+ // Row 221. Principles are canon like a spec: the effort that changes them has them reviewed.
97
+ // What an effort's decompose gate resolves, reviews and stamps — its written specs, and the
98
+ // principles while its write is their current content. Every effort amends the one shared doc,
99
+ // so a later effort's amendment is that effort's to have reviewed, and an earlier writer is not
100
+ // reopened by it. `effortSpecs` stays for the callers that need specs only.
101
+ export function effortCanon(root, canon, effort) {
102
+ const docs = [];
103
+ for (const [id, w] of effortWrites(root, effort)) {
104
+ const doc = findById(canon, id);
105
+ if (!doc)
106
+ continue;
107
+ if (doc.meta.type === 'spec' || (doc.meta.type === 'principles' && w.sha === canonicalSha(doc.meta, doc.body)))
108
+ docs.push(doc);
109
+ }
110
+ return docs.sort((a, b) => String(a.meta.id).localeCompare(String(b.meta.id)));
111
+ }
112
+ // Row 221. The effort that owns the principles as they stand: the live one whose latest write
113
+ // of them is the current content — its decompose gate approves them; by slug when several. None
114
+ // when no live effort wrote this content (a hand edit adopted, an older init's template, or an
115
+ // effort since abandoned, whose gate approves nothing): then a feature or fix effort amends them.
116
+ export function principlesOwner(root, canon) {
117
+ const doc = findById(canon, 'principles');
118
+ if (!doc)
119
+ return undefined;
120
+ const current = canonicalSha(doc.meta, doc.body);
121
+ return effortStreams(root)
122
+ .filter((e) => effortWrites(root, e).get('principles')?.sha === current && !effortAbandoned(readStream(root, e)))
123
+ .sort((a, b) => a.localeCompare(b))[0];
124
+ }
96
125
  export function effortOf(root, artifactId) {
97
126
  const hits = [];
98
127
  for (const effort of effortStreams(root)) {
@@ -112,7 +141,7 @@ function sha256(parts) {
112
141
  }
113
142
  export function effortReviewedSha(root, canon, effort) {
114
143
  const recap = latestRecap(root, effort);
115
- const docs = effortSpecs(root, canon, effort);
144
+ const docs = effortCanon(root, canon, effort); // row 221: principles an effort wrote are judged content too
116
145
  const writes = effortWrites(root, effort);
117
146
  // Row 198 (Builder's call 7). The decision mapping is judged content, so a carries-only
118
147
  // rewrite moves the identity rather than resuming into row 112's `cached` replay — a spec
@@ -1,5 +1,5 @@
1
1
  import { join } from 'node:path';
2
- import { adoptedCommits, lastWitnessed, untrailedCommitsFor } from '../adopt.js';
2
+ import { adoptedCommitsFor, lastWitnessed, positionOf, untrailedCommitsFor } from '../adopt.js';
3
3
  import { EXIT } from '../cli.js';
4
4
  import { canonPaths } from '../config.js';
5
5
  import { runCriteria } from '../criteria.js';
@@ -12,7 +12,7 @@ import { renderRefusal, v } from '../refusal.js';
12
12
  import { idRetired, pathRetired } from '../departure.js';
13
13
  import { findById, findCycle, loadCanon } from '../scan.js';
14
14
  import { validateDoc } from '../schemas.js';
15
- import { canonicalSha, short } from '../sha.js';
15
+ import { canonicalJson, canonicalSha, short, VOLATILE_FIELDS } from '../sha.js';
16
16
  import { kv } from '../toon.js';
17
17
  import { crashPoint, guardTxn, withTxn } from '../txn.js';
18
18
  export async function run(ctx, argv) {
@@ -59,6 +59,7 @@ export async function run(ctx, argv) {
59
59
  const cycle = findCycle(canon);
60
60
  if (cycle)
61
61
  violations.push(v('depends', 'cycle', cycle.join(' -> '), 'an acyclic graph'));
62
+ violations.push(...positionMoves(root, rel, id, meta));
62
63
  if (violations.length) {
63
64
  renderRefusal(violations).forEach(ctx.err);
64
65
  ctx.err(`help: fix the file and re-run, or revert instead: git checkout HEAD -- ${rel}`);
@@ -68,7 +69,8 @@ export async function run(ctx, argv) {
68
69
  const currentSha = canonicalSha(meta, body);
69
70
  const changed = witnessed?.sha !== currentSha;
70
71
  const criteriaChanged = JSON.stringify(meta.criteria ?? null) !== JSON.stringify(witnessed?.criteria ?? null);
71
- const commits = untrailedCommitsFor(root, rel).filter((sha) => !adoptedCommits(root).has(sha));
72
+ const absolved = adoptedCommitsFor(root, id); // final review F1: absolved for this doc, not any
73
+ const commits = untrailedCommitsFor(root, rel).filter((sha) => !absolved.has(sha));
72
74
  const dirty = dirtyStatePaths(root).includes(rel);
73
75
  if (!changed && !dirty && commits.length === 0) {
74
76
  ctx.out(kv('adopt', `${id}: nothing to adopt — content matches the last witnessed state`));
@@ -127,3 +129,18 @@ export async function run(ctx, argv) {
127
129
  ctx.out('help: history: witness log ' + id);
128
130
  return reverify && !reverify.ok ? EXIT.FINDINGS : EXIT.OK;
129
131
  }
132
+ // Row 220 (#65). Position — status, drift, pr, design — is written by the CLI's own transitions
133
+ // alone, and the content sha leaves it out, so a hand edit of position alone read as unchanged
134
+ // and adopt absolved it. Measured against the doc's last witnessed state (a trailered commit, or
135
+ // one an earlier adopt absolved), followed through a hand move, when that state is this id's; a doc adopt
136
+ // has never seen is born draft, with no stamps. Every moved field is named in the one refusal.
137
+ function positionMoves(root, rel, id, meta) {
138
+ const base = lastWitnessed(root, rel, adoptedCommitsFor(root, id), { follow: true });
139
+ const seen = base !== undefined && base.id === id ? base : undefined;
140
+ const was = seen?.position ?? positionOf({ status: 'draft' });
141
+ const now = positionOf(meta);
142
+ const shown = (x) => (x === undefined ? '(none)' : typeof x === 'string' ? x : canonicalJson(x));
143
+ return VOLATILE_FIELDS.filter((f) => canonicalJson(was[f]) !== canonicalJson(now[f])).map((f) => v(f, 'position-moved', `${shown(was[f])} → ${shown(now[f])}`, seen !== undefined
144
+ ? `position is written by the CLI — set ${f} back to ${shown(was[f])}, or revert the file: git checkout ${short(seen.commit)} -- ${rel}`
145
+ : `position is written by the CLI — a doc adopt has never seen is born ${f === 'status' ? 'status: draft' : `draft, with no ${f}`}`));
146
+ }