@popovych.co/witness 0.28.3 → 0.30.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.
Files changed (87) hide show
  1. package/README.md +15 -3
  2. package/dist/act.d.ts +2 -1
  3. package/dist/act.js +9 -0
  4. package/dist/arbiter.d.ts +1 -0
  5. package/dist/arbiter.js +20 -3
  6. package/dist/autonomy.js +8 -0
  7. package/dist/busy.d.ts +38 -0
  8. package/dist/busy.js +274 -0
  9. package/dist/caps.d.ts +3 -2
  10. package/dist/caps.js +24 -3
  11. package/dist/carry.d.ts +74 -0
  12. package/dist/carry.js +687 -0
  13. package/dist/clash.d.ts +23 -0
  14. package/dist/clash.js +225 -0
  15. package/dist/cli.js +1 -1
  16. package/dist/content-sha.d.ts +3 -0
  17. package/dist/content-sha.js +44 -0
  18. package/dist/decide-view.d.ts +15 -0
  19. package/dist/decide-view.js +67 -24
  20. package/dist/drift.js +5 -3
  21. package/dist/drive-presence.d.ts +3 -0
  22. package/dist/drive-presence.js +18 -6
  23. package/dist/drive.d.ts +23 -5
  24. package/dist/drive.js +353 -95
  25. package/dist/evidence.d.ts +2 -0
  26. package/dist/evidence.js +327 -29
  27. package/dist/gate.d.ts +2 -0
  28. package/dist/gate.js +262 -43
  29. package/dist/gates/decompose.js +3 -2
  30. package/dist/gates/design.js +3 -5
  31. package/dist/gates/implement.js +15 -11
  32. package/dist/gates/plan.js +3 -4
  33. package/dist/gates/ship.js +14 -12
  34. package/dist/gitio.d.ts +6 -0
  35. package/dist/gitio.js +32 -2
  36. package/dist/harness.d.ts +1 -0
  37. package/dist/harness.js +3 -1
  38. package/dist/journal.d.ts +10 -1
  39. package/dist/live.d.ts +6 -1
  40. package/dist/live.js +15 -3
  41. package/dist/needs-you.d.ts +18 -2
  42. package/dist/needs-you.js +55 -17
  43. package/dist/progress.js +5 -0
  44. package/dist/recommend.d.ts +3 -0
  45. package/dist/recommend.js +148 -23
  46. package/dist/reviewed.d.ts +4 -0
  47. package/dist/reviewed.js +9 -0
  48. package/dist/reviewer.d.ts +3 -3
  49. package/dist/reviewer.js +117 -55
  50. package/dist/rounds.d.ts +47 -4
  51. package/dist/rounds.js +448 -61
  52. package/dist/session-end.d.ts +14 -0
  53. package/dist/session-end.js +89 -0
  54. package/dist/settle.d.ts +26 -2
  55. package/dist/settle.js +140 -15
  56. package/dist/ship-outcome.d.ts +24 -0
  57. package/dist/ship-outcome.js +76 -0
  58. package/dist/ship.d.ts +25 -2
  59. package/dist/ship.js +716 -127
  60. package/dist/slice.js +4 -2
  61. package/dist/stamp.d.ts +6 -0
  62. package/dist/stamp.js +28 -7
  63. package/dist/steps.d.ts +1 -0
  64. package/dist/steps.js +31 -7
  65. package/dist/verbs/check.js +57 -6
  66. package/dist/verbs/dashboard.js +24 -17
  67. package/dist/verbs/decide.d.ts +12 -0
  68. package/dist/verbs/decide.js +158 -82
  69. package/dist/verbs/evidence.js +52 -4
  70. package/dist/verbs/gate.js +5 -2
  71. package/dist/verbs/log.js +25 -9
  72. package/dist/verbs/next.d.ts +30 -4
  73. package/dist/verbs/next.js +628 -131
  74. package/dist/verbs/turn.js +13 -0
  75. package/dist/verbs/wait.js +30 -5
  76. package/dist/worker-stream.d.ts +7 -0
  77. package/dist/worker-stream.js +150 -5
  78. package/package.json +1 -1
  79. package/plugin/.claude-plugin/plugin.json +1 -1
  80. package/plugin/commands/witness.md +21 -3
  81. package/plugin/hooks/session-dashboard.sh +1 -1
  82. package/plugin/skills/witness-brainstorm/SKILL.md +2 -2
  83. package/plugin/skills/witness-decompose/SKILL.md +3 -3
  84. package/plugin/skills/witness-design/SKILL.md +3 -3
  85. package/plugin/skills/witness-implement/SKILL.md +7 -7
  86. package/plugin/skills/witness-plan/SKILL.md +4 -4
  87. package/plugin/skills/witness-ship/SKILL.md +40 -22
package/README.md CHANGED
@@ -244,7 +244,19 @@ own and every `witness turn`, which is how a session runs its tests — because
244
244
  servers or browsers collide. On Windows each session, test run and gate reviewer runs in a job
245
245
  object, so whatever it starts — detached, or orphaned by an installer that exited — ends with it;
246
246
  elsewhere a session's process group does. A target that reaches any `drive.caps.*` bound is
247
- parked.
247
+ parked. Below the round bound a parked gate goes back to work with your own
248
+ `witness decide <gate> <target> --revise --note "<why>"` — it lifts the park without running the
249
+ gate, and `next` routes the owed work, steps first; `witness status` and `decide --show` print it on a
250
+ `revise:` row, beside a `fresh:` row (a re-review of the work as it stands) when no work is owed. It
251
+ also restarts drive's caps for that target.
252
+
253
+ A ship that ends on a hold only you can clear is a stop of yours, remembered in the journal, so it
254
+ survives a drive restart: `waiting: merge` (no CI checks, or none passed) with the merge command
255
+ pinned to the approved commit (`gh pr merge N --<ship.merge> --match-head-commit <sha>`), or
256
+ `waiting: fix` (the PR aims at another branch, was closed, holds commits the worktree lacks, or a
257
+ login was refused) with no merge command at all. Each has a `recheck:` row, `witness ship <plan>`,
258
+ for when you have acted. A hold that clears by itself — CI still running, GitHub not answering — is
259
+ drive's to check again, within its caps.
248
260
 
249
261
  ### Upgrading
250
262
 
@@ -294,7 +306,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
294
306
  | `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 |
295
307
  | `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 |
296
308
  | `log <id>` | render a journal stream |
297
- | `gate <decompose\|plan\|implement\|ship\|design> <id>` | run the reviewer gate; journals the round, stamps on pass |
309
+ | `gate <decompose\|plan\|implement\|ship\|design> <id> [--fresh] [--manual] [--unchanged]` | run the reviewer gate; journals the round, stamps on pass · `--unchanged` hands a revise back when the author judges it needs no change: where the gate would answer changed-nothing it journals the hand-back and the revise is decided again, and anywhere else it runs as the plain gate and says why nothing was handed back |
298
310
  | `decide <gate> <id> --approve\|--revise [--pin <policy>]` | record the human decision on a stopped gate; `--pin` adds a standing content policy |
299
311
  | `design <spec-id> --file <html>\|--open\|--reconfirm\|--preview <html>` | register/show a `ui` spec's approved look; `--preview` opens a page and records nothing |
300
312
  | `review design <spec-id> [--file <html>]` | the design gate's reviewers on a look — the registered one, or a page not yet registered — asking the gate's full-review question; journals nothing, decides nothing, and replays the gate's answer when the gate already judged the same bytes in full |
@@ -302,7 +314,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
302
314
  | `next` | the one next action across every effort |
303
315
  | `drive [--flow <plan-id>] [--max-spawns <n>] [--manual] [--detach]` | runs every session itself · under autonomy it needs no terminal and reports when nothing else can move. Up to `drive.parallel` targets at once, one session per target; usage limits are waited out; a target past a cap is parked. `--detach` (autonomy only) runs it in the background into `.witness/drive.log` — each session's start, every command and file its agent touches, every act it journals for its flow, a `still running` line after 5 quiet minutes, and how it ended; drive's pi sessions are kept in pi's session store under `witness-drive/`; `--manual` runs serially and asks you at every stop. One drive per repo. A session drive spawned is refused — agents are what drive spawns, never what spawns drive |
304
316
  | `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 |
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:` |
317
+ | `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), and after it while a criteria step is open (an amendment's step routes first); left off for a fix round, once every step is closed. A green that closes a step prints `context:`, `steps:` and `slice:` |
306
318
  | `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 |
307
319
  | `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 |
308
320
  | `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 |
package/dist/act.d.ts CHANGED
@@ -12,5 +12,6 @@ export interface Act {
12
12
  }
13
13
  export declare function actOn(platform: Platform, argv: readonly string[]): Act;
14
14
  export declare function cliAct(...argv: string[]): Act;
15
- export declare function runRow(act: Act, label?: 'run' | 'then', indent?: string): string;
15
+ export declare function runRow(act: Act, label?: 'run' | 'then' | 'revise' | 'fresh' | 'recheck', indent?: string): string;
16
16
  export declare function exitsLine(acts: readonly Act[], platform?: Platform): string;
17
+ export declare function reopenRows(reopen: readonly Act[]): string[];
package/dist/act.js CHANGED
@@ -59,3 +59,12 @@ export function exitsLine(acts, platform = process.platform) {
59
59
  return shared ? words(a.argv, platform).slice(3).join(' ') : a.line;
60
60
  }).join(' | ');
61
61
  }
62
+ // Row 241 (R11). A parked gate's reopen as rows: below the bound a `revise:` row, and a `fresh:` row
63
+ // beside it when no work is owed; at the bound the endgame menu, a set of choices, as `exits:`.
64
+ export function reopenRows(reopen) {
65
+ const labelOf = (a) => a.argv[0] === 'decide' && a.argv.includes('--revise') && !a.argv.includes('--upstream') && !a.argv.includes('--repair') ? 'revise'
66
+ : a.argv[0] === 'gate' && a.argv.includes('--fresh') ? 'fresh' : undefined;
67
+ if (reopen.length > 0 && reopen.every((a) => labelOf(a) !== undefined))
68
+ return reopen.map((a) => runRow(a, labelOf(a)));
69
+ return reopen.length === 1 ? [runRow(reopen[0])] : [` exits: ${exitsLine(reopen)}`];
70
+ }
package/dist/arbiter.d.ts CHANGED
@@ -28,6 +28,7 @@ export declare function arbitrate(ctx: Ctx, root: string, cfg: Config, req: Arbi
28
28
  export declare function menuFor(block: Decision, run: GateRunEntry): Array<Option & {
29
29
  act: Act;
30
30
  }>;
31
+ export declare const HANDED_BACK_FACT = "the author handed this revise back with the content unchanged";
31
32
  export declare function decisionEvidence(root: string, canon: Canon, stop: {
32
33
  gate: string;
33
34
  target: string;
package/dist/arbiter.js CHANGED
@@ -9,7 +9,7 @@ import { SESSION_DEFAULT, stageModel, unansweredPin } from './model.js';
9
9
  import { ok, refuse, v } from './refusal.js';
10
10
  import { invokeReviewerAsync, parseVerdictText, promptsSha, resolvePrompt } from './reviewer.js';
11
11
  import { effortCanon, effortOf } from './reviewed.js';
12
- import { anchorRecurrence, gateRuns, roundBudget } from './rounds.js';
12
+ import { REVISE_HUMAN, anchorRecurrence, gateRuns, roundBudget } from './rounds.js';
13
13
  import { findById } from './scan.js';
14
14
  import { canonicalJson } from './sha.js';
15
15
  // How a later mode adds its own prompt without a second invoker.
@@ -98,19 +98,31 @@ export async function arbitrate(ctx, root, cfg, req) {
98
98
  // Row 239. Read off each option's act, never its printed line: an option the CLI built from no
99
99
  // act is not offered, a word is a flag only where the act holds it as one, and the one input the
100
100
  // arbiter may fill is the `<why>` slot (settle fills it through argv).
101
+ // Row 244 (design §4.2.6, §4.2.7; P38). The arbiter never revises a gate a revise already stands on:
102
+ // in the states where a plain revise is the human's alone (`REVISE_HUMAN`) every plain revise goes,
103
+ // the noted one included, while the send-upstream stays. A handed-back revise (`revise-returned`) is
104
+ // the one such state a settle brings to the arbiter, and there it matters twice over: hand-backs spend
105
+ // no rounds, so the bound would never stop a revise → hand-back loop.
101
106
  export function menuFor(block, run) {
102
107
  const failed = run.checks.filter((c) => !c.ok);
103
108
  const approveBarred = run.gate === 'design' || (failed.length > 0 && !failed.every((c) => c.name === 'amendment-ack'));
109
+ const reviseBarred = block.state !== undefined && REVISE_HUMAN.has(block.state);
110
+ const plainRevise = (argv) => argv.includes('--revise') && !argv.includes('--upstream') && !argv.includes('--repair');
104
111
  return block.options.filter((o) => o.act?.argv[0] === 'decide' &&
105
112
  !o.act.argv.includes('--trust-cmds') &&
106
113
  o.act.inputs.every((i) => i.name === 'why') &&
107
- !(approveBarred && o.act.argv.includes('--approve')));
114
+ !(approveBarred && o.act.argv.includes('--approve')) &&
115
+ !(reviseBarred && plainRevise(o.act.argv)));
108
116
  }
117
+ // Row 244 (design §4.2.6). A hand-back as the arbiter hears it: a journal fact in this fixed sentence,
118
+ // never a word the author wrote (anti-goal 1) — the entry carries none, and no field of it is read.
119
+ export const HANDED_BACK_FACT = 'the author handed this revise back with the content unchanged';
109
120
  const anchorText = (a) => (typeof a === 'string' ? a : `omission:${a.scope}`);
110
121
  const HISTORY_RUNS = 10;
111
122
  // The evidence the arbiter reads, composed by the CLI from the journal and canon. It never
112
123
  // carries a session transcript: none exists to carry, and the author's narration is
113
- // exactly what the arbiter must not hear (anti-goal 1).
124
+ // exactly what the arbiter must not hear (anti-goal 1). A hand-back reaches it as a fact the CLI
125
+ // states (`HANDED_BACK_FACT`), never as the author's account of why.
114
126
  export function decisionEvidence(root, canon, stop) {
115
127
  const { gate, target, entries, run, block } = stop;
116
128
  const findings = (run.verdicts ?? []).flatMap((rv) => rv.findings.map((f) => ({ reviewer: rv.reviewer, f })));
@@ -145,6 +157,11 @@ export function decisionEvidence(root, canon, stop) {
145
157
  for (const e of entries.slice(at + 1)) {
146
158
  if (e.t === 'gate-run' && e.gate === gate)
147
159
  break;
160
+ // Row 244 (design §4.2.6). The hand-back in its place among the gate's decisions, after the revise it answers.
161
+ if (e.t === 'revise-returned' && e.gate === gate) {
162
+ history.push(` - handed back · ${HANDED_BACK_FACT}`);
163
+ continue;
164
+ }
148
165
  if (e.t !== 'human-decision' || e.gate !== gate)
149
166
  continue;
150
167
  const d = e;
package/dist/autonomy.js CHANGED
@@ -80,6 +80,13 @@ export function policyFor(facts) {
80
80
  if (failed.some((c) => (c.untrusted?.length ?? 0) > 0) && !boundReached(entries, gate)) {
81
81
  return { kind: 'take', act: cliAct('gate', gate, target) };
82
82
  }
83
+ // Row 244 (design §4.2.6; the user's decision 2). A revise its author handed back unchanged is decided
84
+ // again, by the arbiter: neither the author nor a reviewer found a fix, so no rule has the right
85
+ // answer. It comes after the arms that belong elsewhere — the human's trust grant, the free re-runs
86
+ // (stale or malformed, fallen back, trust granted since) and the human's design look — and stays out
87
+ // of TAKEN, whose revise the author would only hand back again.
88
+ if (block.rule === 'revise-returned')
89
+ return { kind: 'arbiter' };
83
90
  if (block.rule === 'checks-failed') {
84
91
  // amendment-ack is the one check an approve clears, so approving is a judgment about the
85
92
  // amendment against the ask — the arbiter's, never the rule's (§11 call 10).
@@ -88,6 +95,7 @@ export function policyFor(facts) {
88
95
  if (TAKEN.has(block.rule) || block.rule.startsWith('anchor-recurrence-'))
89
96
  return first();
90
97
  // bound · bound-stale · ladder-spent · pin-contradiction · reserved-stop-clean · manual-stop
98
+ // (revise-returned has its own arm above)
91
99
  return { kind: 'arbiter' };
92
100
  }
93
101
  // Row 173. Who made a disposition, in one spelling for every surface that says so
package/dist/busy.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { Ctx } from './cli.js';
2
+ import type { Config } from './config.js';
3
+ import { type Violation } from './refusal.js';
4
+ export type BusyKind = 'settle' | 'ship';
5
+ export interface BusyLock {
6
+ pid: number;
7
+ since: number;
8
+ until: number;
9
+ }
10
+ export declare const BUSY_DIR = ".witness/live/busy";
11
+ export declare const BUSY_MAX_MS = 86400000;
12
+ export declare const busyIo: {
13
+ create(p: string, text: string): void;
14
+ unlink(p: string): void;
15
+ };
16
+ export type TakeBusy = {
17
+ taken: true;
18
+ release: () => void;
19
+ } | {
20
+ taken: false;
21
+ holder: BusyLock;
22
+ } | {
23
+ taken: false;
24
+ refused: Violation[];
25
+ };
26
+ export declare function takeBusy(root: string, kind: BusyKind, target: string, until: number, opts?: {
27
+ now?: number;
28
+ pid?: number;
29
+ }): TakeBusy;
30
+ export declare function busyHolder(root: string, kind: BusyKind, target: string, opts?: {
31
+ now?: number;
32
+ pid?: number;
33
+ }): BusyLock | undefined;
34
+ export declare function sweepDeadBusy(root: string, opts?: {
35
+ pid?: number;
36
+ }): number;
37
+ export declare function settleUntil(cfg: Config, env: Ctx['env'], now: number): number;
38
+ export declare function shipUntil(cfg: Config, env: Ctx['env'], now: number): number;
package/dist/busy.js ADDED
@@ -0,0 +1,274 @@
1
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, unlinkSync, writeSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DRIVE_DEADLINE_ENV } from './drive-presence.js';
4
+ import { isId } from './dsl.js';
5
+ import { LOCK_WAIT_MS, isAlive, pause, takeStale } from './lock.js';
6
+ import { v } from './refusal.js';
7
+ import { ensureExcluded } from './worktree.js';
8
+ export const BUSY_DIR = '.witness/live/busy';
9
+ // A lock whose `until` lies more than this after its `since` is stale, whatever it claims.
10
+ export const BUSY_MAX_MS = 86_400_000;
11
+ // An empty or unparseable file is a write in progress for this long (`lock.ts`'s grace).
12
+ const UNREADABLE_GRACE_MS = 1_000;
13
+ // Windows: a scanner or the indexer can hold a fresh file for a moment (EPERM, EBUSY, EACCES).
14
+ const CREATE_RETRY_MS = 1_000;
15
+ const RETRY_PAUSE_MS = 50;
16
+ const TRANSIENT = new Set(['EPERM', 'EBUSY', 'EACCES']);
17
+ // A `since` this far ahead of now is a tampered lock or a clock set wrong, never a live holder.
18
+ const SINCE_SLACK_MS = 60_000;
19
+ // The one seam for file errors, so a test can stand in for a Windows scanner.
20
+ export const busyIo = {
21
+ create(p, text) {
22
+ const fd = openSync(p, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o644);
23
+ try {
24
+ writeSync(fd, text);
25
+ }
26
+ finally {
27
+ closeSync(fd);
28
+ }
29
+ },
30
+ unlink(p) {
31
+ unlinkSync(p);
32
+ },
33
+ };
34
+ const unwritable = (why) => v(BUSY_DIR, 'lock-unwritable', why, 'a writable .witness/live/busy folder, not a link — witness writes its busy locks there');
35
+ // The folder, or why it cannot be used. A link anywhere on the way is refused, never followed.
36
+ function busyDir(root, create) {
37
+ const live = join(root, '.witness', 'live');
38
+ const dir = join(root, BUSY_DIR);
39
+ for (const p of [live, dir]) {
40
+ try {
41
+ if (!lstatSync(p).isDirectory())
42
+ return { refused: unwritable(`${p === live ? '.witness/live' : BUSY_DIR} is not a folder`) };
43
+ }
44
+ catch (e) {
45
+ if (e.code !== 'ENOENT')
46
+ return { refused: unwritable(e.code ?? String(e)) };
47
+ if (!create)
48
+ return undefined;
49
+ try {
50
+ mkdirSync(p, { recursive: true });
51
+ }
52
+ catch (err) {
53
+ return { refused: unwritable(err.code ?? String(err)) };
54
+ }
55
+ }
56
+ }
57
+ return dir;
58
+ }
59
+ const lockName = (kind, target) => `${target}.${kind}.json`;
60
+ function parseLock(text) {
61
+ let raw;
62
+ try {
63
+ raw = JSON.parse(text);
64
+ }
65
+ catch {
66
+ return 'unreadable';
67
+ }
68
+ const r = raw;
69
+ const num = (x) => typeof x === 'number' && Number.isFinite(x) && x >= 0;
70
+ if (!(Number.isInteger(r?.pid) && r.pid > 0 && num(r.since) && num(r.until)))
71
+ return 'malformed';
72
+ return { pid: r.pid, since: r.since, until: r.until };
73
+ }
74
+ function readLock(p) {
75
+ try {
76
+ if (lstatSync(p).isSymbolicLink())
77
+ return 'link';
78
+ const text = readFileSync(p, 'utf8');
79
+ const parsed = parseLock(text);
80
+ return typeof parsed === 'string' ? parsed : { lock: parsed };
81
+ }
82
+ catch (e) {
83
+ return e.code === 'ENOENT' ? 'absent' : 'unreadable';
84
+ }
85
+ }
86
+ // Live: its pid is alive, its `until` has not passed, and it claims no more than the cap.
87
+ const live = (l, now) => l.until >= l.since && l.until - l.since <= BUSY_MAX_MS && l.since <= now + SINCE_SLACK_MS && now <= l.until && isAlive(l.pid);
88
+ const olderThanGrace = (p, now) => {
89
+ try {
90
+ return now - lstatSync(p).mtimeMs >= UNREADABLE_GRACE_MS;
91
+ }
92
+ catch {
93
+ return true;
94
+ }
95
+ };
96
+ // Stale to `pid`: not live, or its own (no lock nests: a lock naming the reader is never busy to it).
97
+ function stale(p, text, pid, now) {
98
+ if (text === undefined) {
99
+ try {
100
+ if (lstatSync(p).isSymbolicLink())
101
+ return true;
102
+ }
103
+ catch {
104
+ return true;
105
+ }
106
+ return olderThanGrace(p, now);
107
+ }
108
+ const parsed = parseLock(text);
109
+ if (parsed === 'unreadable')
110
+ return olderThanGrace(p, now);
111
+ if (parsed === 'malformed')
112
+ return true;
113
+ return parsed.pid === pid || !live(parsed, now);
114
+ }
115
+ // Takes `kind`'s lock on `target` until `until`, or names the live holder. Never waits on a
116
+ // holder: the only pauses are for a write in progress and a scanner holding a fresh file.
117
+ export function takeBusy(root, kind, target, until, opts = {}) {
118
+ if (!isId(target))
119
+ return { taken: false, refused: [v('target', 'unknown-id', target, 'an artifact id — lowercase letters, digits and dashes')] };
120
+ const pid = opts.pid ?? process.pid;
121
+ const now = () => opts.now ?? Date.now();
122
+ // Spec c2: a repo whose ignore rules predate this folder must never show it. Best effort.
123
+ try {
124
+ ensureExcluded(root);
125
+ }
126
+ catch { /* not a git checkout we can write to */ }
127
+ const dir = busyDir(root, true);
128
+ if (dir === undefined)
129
+ return { taken: false, refused: [unwritable('the folder could not be made')] };
130
+ if (typeof dir !== 'string')
131
+ return { taken: false, refused: [dir.refused] };
132
+ const p = join(dir, lockName(kind, target));
133
+ const since = now();
134
+ const text = JSON.stringify({ pid, since, until });
135
+ const t0 = Date.now();
136
+ for (;;) {
137
+ try {
138
+ busyIo.create(p, text);
139
+ return { taken: true, release: () => releaseIf(p, text) };
140
+ }
141
+ catch (e) {
142
+ const code = e.code;
143
+ if (code !== 'EEXIST') {
144
+ if (code !== undefined && TRANSIENT.has(code) && Date.now() - t0 < CREATE_RETRY_MS) {
145
+ pause(RETRY_PAUSE_MS);
146
+ continue;
147
+ }
148
+ return { taken: false, refused: [unwritable(code ?? String(e))] };
149
+ }
150
+ }
151
+ const held = readLock(p);
152
+ if (typeof held === 'object' && held.lock.pid !== pid && live(held.lock, now()))
153
+ return { taken: false, holder: held.lock };
154
+ let took;
155
+ try {
156
+ took = takeStale(p, (t) => stale(p, t, pid, now()));
157
+ }
158
+ catch (e) {
159
+ return { taken: false, refused: [unwritable(`the stale lock could not be removed (${e.code ?? String(e)})`)] };
160
+ }
161
+ if (took === 'taken')
162
+ continue;
163
+ // a write in progress, or another stealer at work: re-read shortly, within the same budget
164
+ if (Date.now() - t0 >= CREATE_RETRY_MS + UNREADABLE_GRACE_MS) {
165
+ const again = readLock(p);
166
+ if (typeof again === 'object')
167
+ return { taken: false, holder: again.lock };
168
+ return { taken: false, refused: [unwritable('the lock is being written by another process')] };
169
+ }
170
+ pause(RETRY_PAUSE_MS);
171
+ }
172
+ }
173
+ // A lock is released by its taker only, and only while it still holds what the taker wrote.
174
+ // Windows: a scanner holding the file a moment fails the unlink (EBUSY, EPERM); it is retried within
175
+ // a second, as a create is, so a released lock does not read live to others until its `until`.
176
+ function releaseIf(p, text) {
177
+ const t0 = Date.now();
178
+ for (;;) {
179
+ try {
180
+ if (lstatSync(p).isSymbolicLink())
181
+ return;
182
+ if (readFileSync(p, 'utf8') !== text)
183
+ return;
184
+ busyIo.unlink(p);
185
+ return;
186
+ }
187
+ catch (e) {
188
+ const code = e.code;
189
+ // gone already; an unlink that keeps failing is left to the dead-pid rule
190
+ if (code === undefined || !TRANSIENT.has(code) || Date.now() - t0 >= CREATE_RETRY_MS)
191
+ return;
192
+ pause(RETRY_PAUSE_MS);
193
+ }
194
+ }
195
+ }
196
+ // The live holder of `kind`'s lock on `target`, when it is a process other than `opts.pid`.
197
+ export function busyHolder(root, kind, target, opts = {}) {
198
+ if (!isId(target))
199
+ return undefined;
200
+ const dir = busyDir(root, false);
201
+ if (typeof dir !== 'string')
202
+ return undefined;
203
+ const held = readLock(join(dir, lockName(kind, target)));
204
+ if (typeof held !== 'object')
205
+ return undefined;
206
+ const pid = opts.pid ?? process.pid;
207
+ return held.lock.pid !== pid && live(held.lock, opts.now ?? Date.now()) ? held.lock : undefined;
208
+ }
209
+ // Drive's cleanup (`releaseDeadTurn`'s pattern, row 218): the locks of dead pids, and the
210
+ // caller's own leftovers, before Windows can hand a dead pid to another process. The count.
211
+ export function sweepDeadBusy(root, opts = {}) {
212
+ const dir = busyDir(root, false);
213
+ if (typeof dir !== 'string')
214
+ return 0;
215
+ const pid = opts.pid ?? process.pid;
216
+ let n = 0;
217
+ let names;
218
+ try {
219
+ names = readdirSync(dir);
220
+ }
221
+ catch {
222
+ return 0;
223
+ }
224
+ for (const name of names) {
225
+ if (!/\.(settle|ship)\.json$/.test(name))
226
+ continue;
227
+ const p = join(dir, name);
228
+ // Asked again under the steal guard, so a live lock written meanwhile is never removed. A
229
+ // write in progress (an empty file) is not dropped: its taker is mid-create.
230
+ const droppable = (t) => {
231
+ if (t === undefined) {
232
+ try {
233
+ return lstatSync(p).isSymbolicLink();
234
+ }
235
+ catch {
236
+ return false;
237
+ }
238
+ }
239
+ const l = parseLock(t);
240
+ return l === 'malformed' || (typeof l === 'object' && (l.pid === pid || !isAlive(l.pid) || !live(l, Date.now())));
241
+ };
242
+ const text = readLock(p) === 'link' ? undefined : (() => { try {
243
+ return readFileSync(p, 'utf8');
244
+ }
245
+ catch {
246
+ return '';
247
+ } })();
248
+ if (!droppable(text))
249
+ continue;
250
+ try {
251
+ if (takeStale(p, droppable) === 'taken')
252
+ n++;
253
+ }
254
+ catch { /* left to the next sweep */ }
255
+ }
256
+ return n;
257
+ }
258
+ // The bound a taker writes: the estimate, or inside a drive session the session's deadline when
259
+ // later — a reviewer there may wait out a usage limit until then (reviewer.ts) — and never more
260
+ // than the cap after now. The cap goes last (pass 6, P20), so no bound is stale at birth.
261
+ function bound(estimateMs, env, now) {
262
+ const deadline = Number(env[DRIVE_DEADLINE_ENV]) || 0;
263
+ return Math.min(Math.max(now + estimateMs, deadline), now + BUSY_MAX_MS);
264
+ }
265
+ // A self-repair reroll is a second arbitration, each of up to three timed attempts, then the
266
+ // door's lock wait — twice when `parkRefused` follows — and two minutes of slack.
267
+ const settleEstimate = (cfg) => 2 * 3 * cfg.gates.reviewerTimeoutMs + 2 * LOCK_WAIT_MS + 120_000;
268
+ export function settleUntil(cfg, env, now) {
269
+ return bound(settleEstimate(cfg), env, now);
270
+ }
271
+ // The ship gate's battery, the CI watch, both settles, and ten minutes for git and gh.
272
+ export function shipUntil(cfg, env, now) {
273
+ return bound(3 * cfg.gates.reviewerTimeoutMs + cfg.ship.ciSettleMs + 1_800_000 + 2 * settleEstimate(cfg) + 600_000, env, now);
274
+ }
package/dist/caps.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Ctx } from './cli.js';
2
- import type { DriveCaps } from './config.js';
2
+ import type { Config, DriveCaps } from './config.js';
3
3
  import type { Entry } from './journal.js';
4
4
  export type CapName = 'rounds' | 'upstream' | 'spawns' | 'wall-clock';
5
5
  export interface TargetUse {
@@ -12,9 +12,10 @@ export interface CapHit {
12
12
  note: string;
13
13
  }
14
14
  export declare function capHit(entries: Entry[], use: TargetUse, caps: DriveCaps): CapHit | undefined;
15
- export declare function parkAtCap(ctx: Ctx, root: string, target: string, hit: CapHit): Promise<{
15
+ export declare function parkAtCap(ctx: Ctx, root: string, target: string, hit: CapHit, cfg: Config): Promise<{
16
16
  parked: true;
17
17
  } | {
18
18
  parked: false;
19
19
  why: string;
20
+ busy?: true;
20
21
  }>;
package/dist/caps.js CHANGED
@@ -1,5 +1,6 @@
1
+ import { settleUntil, takeBusy } from './busy.js';
1
2
  import { EXIT } from './cli.js';
2
- import { fellBack, gateRuns, lastGateRun } from './rounds.js';
3
+ import { fellBack, gateRuns, lastGateRun, settledToken, unparkAt } from './rounds.js';
3
4
  import { duration } from './usage.js';
4
5
  import { gateSettled } from './verbs/next.js';
5
6
  const isCapPark = (e) => {
@@ -17,8 +18,9 @@ function openGates(entries) {
17
18
  }
18
19
  // First hit wins, in this order: rounds · upstream · spawns · wall clock.
19
20
  export function capHit(entries, use, caps) {
21
+ // Row 241 (R11): a human un-park restarts the window, as a cap park does.
20
22
  let lastPark = -1;
21
- entries.forEach((e, i) => { if (isCapPark(e))
23
+ entries.forEach((e, i) => { if (isCapPark(e) || unparkAt(entries, i))
22
24
  lastPark = i; });
23
25
  const since = entries.slice(lastPark + 1);
24
26
  // Every budget reset is ignored: this counts the rounds a gate ran, not its window. The
@@ -50,7 +52,23 @@ export function capHit(entries, use, caps) {
50
52
  // The park goes through A1's one door with `selected: 'policy'` and the cap as its rule.
51
53
  // `park` anchors it on the gate's last run even after the author moved the tree. A target
52
54
  // 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) {
55
+ export async function parkAtCap(ctx, root, target, hit, cfg) {
56
+ // Row 240 (design §4.1.2): under the stop's settle lock, taken before the stream is read. Held
57
+ // by another live process, nothing parks and drive tries the target again next round.
58
+ const lock = takeBusy(root, 'settle', target, settleUntil(cfg, ctx.env, Date.now()));
59
+ if (!lock.taken) {
60
+ if ('holder' in lock)
61
+ return { parked: false, busy: true, why: 'busy' };
62
+ return { parked: false, why: `the policy could not park it (${lock.refused[0]?.rule ?? 'lock-unwritable'})` };
63
+ }
64
+ try {
65
+ return await parkUnderLock(ctx, root, target, hit);
66
+ }
67
+ finally {
68
+ lock.release();
69
+ }
70
+ }
71
+ async function parkUnderLock(ctx, root, target, hit) {
54
72
  const { readStream } = await import('./journal.js');
55
73
  const entries = readStream(root, target);
56
74
  if (!entries.some((e) => e.t === 'gate-run'))
@@ -63,8 +81,11 @@ export async function parkAtCap(ctx, root, target, hit) {
63
81
  // Loaded on A1's precedent for settle.ts: decide.ts reaches the gate registry.
64
82
  const { applyDecision } = await import('./verbs/decide.js');
65
83
  const errs = [];
84
+ // Row 240 (R3): the token of this read, so a park read before another decision on the gate —
85
+ // a human's revise-upstream, a settler's — refuses `settled-since` instead of parking on top (P7).
66
86
  const code = await applyDecision({ ...ctx, cwd: root, err: (l) => { errs.push(l); ctx.err(l); } }, {
67
87
  gate, target, decision: 'stop', note: hit.note, selected: 'policy', rule: `cap-${hit.cap}`, park: true, runId: last.run_id,
88
+ token: settledToken(entries, gate, last.run_id),
68
89
  });
69
90
  if (code === EXIT.OK)
70
91
  return { parked: true };
@@ -0,0 +1,74 @@
1
+ import { type Result, type Violation } from './refusal.js';
2
+ import { type Platform } from './toon.js';
3
+ export declare const CARRY_ACTION = "witness-carry";
4
+ export declare function carryGit(wt: string, ...args: string[]): {
5
+ code: number | null;
6
+ stdout: string;
7
+ stderr: string;
8
+ };
9
+ export declare function carryRef(planId: string): string;
10
+ export declare function keptPrefix(planId: string): string;
11
+ export type OpInProgress = 'rebase-merge' | 'rebase-apply' | 'MERGE_HEAD' | 'CHERRY_PICK_HEAD' | 'REVERT_HEAD';
12
+ export declare function operationInProgress(wt: string): OpInProgress | undefined;
13
+ export interface UnmergedPath {
14
+ path: string;
15
+ stages: Partial<Record<1 | 2 | 3, string>>;
16
+ }
17
+ export declare function unmergedPaths(wt: string): UnmergedPath[];
18
+ export interface KeptRef {
19
+ ref: string;
20
+ sha: string;
21
+ files: string[];
22
+ }
23
+ export declare function keptRefs(wt: string, planId: string): KeptRef[];
24
+ export declare function keepCarry(wt: string, planId: string, carry: string, files: string[]): Result<string>;
25
+ export declare function carryPending(planId: string, got: string): Violation;
26
+ export declare function seeWork(ref: string): string;
27
+ export declare function carryGone(planId: string, wt: string): Violation;
28
+ export declare function offBranchPending(planId: string, head: string): Violation;
29
+ export declare function sessionUnmerged(planId: string, files: readonly UnmergedPath[]): Violation[];
30
+ export declare function restorePending(planId: string, got: string): Violation;
31
+ export declare function touchedRebasePending(planId: string, why: string): Violation;
32
+ export declare function heldLock(wt: string, out: string, locks?: readonly string[]): string | undefined;
33
+ export declare function lockedRow(planId: string, lock: string, carried: boolean, unfinished?: boolean): Violation;
34
+ export declare function headReflog(wt: string): string[];
35
+ export type RebaseOwner = 'witness' | 'session' | 'silent';
36
+ export declare function rebaseOwnerSince(wt: string, op: OpInProgress | undefined, out: string, before: readonly string[]): RebaseOwner;
37
+ export declare function witnessOwnRebase(wt: string, carry: string): RebaseOwner;
38
+ export type StopReading = {
39
+ fresh: true;
40
+ unmerged: UnmergedPath[];
41
+ } | {
42
+ fresh: false;
43
+ why: string;
44
+ };
45
+ export declare function freshStop(wt: string): StopReading;
46
+ export declare function keepStopped(wt: string, planId: string, files: readonly string[]): Result<string>;
47
+ export declare function gitAtLeast(versionLine: string, major: number, minor: number): boolean;
48
+ export declare function blobAt(wt: string, rev: string, path: string): string | undefined;
49
+ export declare function workAlreadyBack(wt: string, carry: string): {
50
+ back: boolean;
51
+ lock?: string;
52
+ };
53
+ export declare function operationRefusal(wt: string, planId: string, op: OpInProgress, silent?: boolean): Violation;
54
+ export declare function captureCarry(wt: string, planId: string): Result<string | undefined>;
55
+ export declare function cleanTree(wt: string, planId: string): Result<void>;
56
+ export type Reapplied = {
57
+ kind: 'clean';
58
+ kept?: string;
59
+ } | {
60
+ kind: 'clash';
61
+ kept: string;
62
+ files: UnmergedPath[];
63
+ } | {
64
+ kind: 'refused';
65
+ out: string;
66
+ } | {
67
+ kind: 'locked';
68
+ lock: string;
69
+ };
70
+ export declare function reapply(wt: string, planId: string, carry: string): Reapplied;
71
+ export declare function dropCarry(wt: string, planId: string, carry: string): Reapplied;
72
+ export declare function baseInTheWay(wt: string, planId: string, base: string): Result<void>;
73
+ export declare function untrackedInTheWay(wt: string, paths: readonly string[]): string[] | undefined;
74
+ export declare function remedyLine(argv: readonly string[], platform?: Platform): string;