pi-daddy 0.18.0 → 0.19.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 (130) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +46 -2
  3. package/contracts/ledger/v2/README.md +59 -0
  4. package/contracts/ledger/v2/fixtures/capability-decision.json +95 -0
  5. package/contracts/ledger/v2/fixtures/check-receipt.json +40 -0
  6. package/contracts/ledger/v2/fixtures/child-lifecycle.json +42 -0
  7. package/contracts/ledger/v2/fixtures/workspace-lease.json +41 -0
  8. package/contracts/ledger/v2/ledger-event.schema.json +633 -0
  9. package/dist/approval-prompt.d.ts +2 -1
  10. package/dist/approval-prompt.d.ts.map +1 -1
  11. package/dist/approval-prompt.js +9 -0
  12. package/dist/approval-prompt.js.map +1 -1
  13. package/dist/approval.d.ts +4 -2
  14. package/dist/approval.d.ts.map +1 -1
  15. package/dist/approval.js +4 -0
  16. package/dist/approval.js.map +1 -1
  17. package/dist/capabilities.d.ts +105 -0
  18. package/dist/capabilities.d.ts.map +1 -1
  19. package/dist/capabilities.js +161 -3
  20. package/dist/capabilities.js.map +1 -1
  21. package/dist/catalog.d.ts +15 -1
  22. package/dist/catalog.d.ts.map +1 -1
  23. package/dist/catalog.js +54 -3
  24. package/dist/catalog.js.map +1 -1
  25. package/dist/check-runner.d.ts.map +1 -1
  26. package/dist/check-runner.js +5 -7
  27. package/dist/check-runner.js.map +1 -1
  28. package/dist/cli.d.ts.map +1 -1
  29. package/dist/cli.js +21 -1
  30. package/dist/cli.js.map +1 -1
  31. package/dist/definitions.d.ts.map +1 -1
  32. package/dist/definitions.js +7 -1
  33. package/dist/definitions.js.map +1 -1
  34. package/dist/delegate.d.ts.map +1 -1
  35. package/dist/delegate.js +32 -4
  36. package/dist/delegate.js.map +1 -1
  37. package/dist/delegation-approval.d.ts.map +1 -1
  38. package/dist/delegation-approval.js +37 -12
  39. package/dist/delegation-approval.js.map +1 -1
  40. package/dist/executor.d.ts +2 -1
  41. package/dist/executor.d.ts.map +1 -1
  42. package/dist/executor.js +1 -0
  43. package/dist/executor.js.map +1 -1
  44. package/dist/grant-env.d.ts +2 -0
  45. package/dist/grant-env.d.ts.map +1 -1
  46. package/dist/grant-env.js +26 -3
  47. package/dist/grant-env.js.map +1 -1
  48. package/dist/index.d.ts +1 -1
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +1 -1
  51. package/dist/index.js.map +1 -1
  52. package/dist/init.d.ts +13 -1
  53. package/dist/init.d.ts.map +1 -1
  54. package/dist/init.js +35 -2
  55. package/dist/init.js.map +1 -1
  56. package/dist/lease-helper.d.ts +58 -0
  57. package/dist/lease-helper.d.ts.map +1 -0
  58. package/dist/lease-helper.js +94 -0
  59. package/dist/lease-helper.js.map +1 -0
  60. package/dist/lease-record.d.ts +15 -3
  61. package/dist/lease-record.d.ts.map +1 -1
  62. package/dist/lease-record.js.map +1 -1
  63. package/dist/ledger-events.d.ts +35 -14
  64. package/dist/ledger-events.d.ts.map +1 -1
  65. package/dist/ledger-events.js +41 -0
  66. package/dist/ledger-events.js.map +1 -1
  67. package/dist/ledger.d.ts +10 -5
  68. package/dist/ledger.d.ts.map +1 -1
  69. package/dist/ledger.js +13 -3
  70. package/dist/ledger.js.map +1 -1
  71. package/dist/propagation.d.ts +16 -0
  72. package/dist/propagation.d.ts.map +1 -1
  73. package/dist/propagation.js +22 -2
  74. package/dist/propagation.js.map +1 -1
  75. package/dist/refusals.d.ts +1 -1
  76. package/dist/refusals.d.ts.map +1 -1
  77. package/dist/refusals.js +2 -0
  78. package/dist/refusals.js.map +1 -1
  79. package/dist/resolve.d.ts +10 -0
  80. package/dist/resolve.d.ts.map +1 -1
  81. package/dist/resolve.js +33 -3
  82. package/dist/resolve.js.map +1 -1
  83. package/dist/routing-authority.d.ts +71 -0
  84. package/dist/routing-authority.d.ts.map +1 -0
  85. package/dist/routing-authority.js +100 -0
  86. package/dist/routing-authority.js.map +1 -0
  87. package/dist/skill-packages.d.ts +11 -5
  88. package/dist/skill-packages.d.ts.map +1 -1
  89. package/dist/skill-packages.js +20 -11
  90. package/dist/skill-packages.js.map +1 -1
  91. package/dist/workspace-lease.d.ts +15 -3
  92. package/dist/workspace-lease.d.ts.map +1 -1
  93. package/dist/workspace-lease.js +81 -24
  94. package/dist/workspace-lease.js.map +1 -1
  95. package/dist/workspace.d.ts +25 -0
  96. package/dist/workspace.d.ts.map +1 -1
  97. package/dist/workspace.js +142 -5
  98. package/dist/workspace.js.map +1 -1
  99. package/extensions/delegation.ts +7 -1
  100. package/extensions/grants-command.ts +11 -1
  101. package/extensions/grants.ts +6 -1
  102. package/extensions/init-command.ts +33 -2
  103. package/extensions/session-report.ts +13 -20
  104. package/extensions/session.ts +9 -1
  105. package/extensions/workspace-runtime.ts +34 -4
  106. package/package.json +8 -3
  107. package/src/approval-prompt.ts +2 -1
  108. package/src/approval.ts +4 -2
  109. package/src/capabilities.ts +173 -4
  110. package/src/catalog.ts +62 -4
  111. package/src/check-runner.ts +8 -8
  112. package/src/cli.ts +24 -1
  113. package/src/definitions.ts +7 -1
  114. package/src/delegate.ts +42 -4
  115. package/src/delegation-approval.ts +37 -12
  116. package/src/executor.ts +2 -1
  117. package/src/grant-env.ts +39 -7
  118. package/src/index.ts +1 -0
  119. package/src/init.ts +40 -2
  120. package/src/lease-helper.ts +97 -0
  121. package/src/lease-record.ts +15 -3
  122. package/src/ledger-events.ts +66 -22
  123. package/src/ledger.ts +30 -6
  124. package/src/propagation.ts +23 -2
  125. package/src/refusals.ts +2 -0
  126. package/src/resolve.ts +35 -3
  127. package/src/routing-authority.ts +121 -0
  128. package/src/skill-packages.ts +20 -13
  129. package/src/workspace-lease.ts +84 -24
  130. package/src/workspace.ts +179 -6
@@ -30,7 +30,8 @@ import { homedir } from "node:os";
30
30
  import { join, resolve, sep } from "node:path";
31
31
  import { ceilingForDefinition, parseSkillDefinition, type SkillDefinition } from "./definitions.ts";
32
32
  import { WILDCARD } from "./pi-tools.ts";
33
- import { AGENT_WILDCARD, type Capability } from "./resolve.ts";
33
+ import { AGENT_WILDCARD, WORKSPACE_WILDCARD, type Capability } from "./resolve.ts";
34
+ import { isSafeCapability } from "./capabilities.ts";
34
35
 
35
36
  export interface DiscoveredSkill {
36
37
  definition: SkillDefinition;
@@ -107,21 +108,27 @@ export function isSafeName(name: string): boolean {
107
108
  * grants), which is right for the enforcement path — the catalog refuses what it does not know — and is
108
109
  * exactly why the check has to be here, at the boundary that *generates* rather than the one that enforces.
109
110
  *
110
- * The grammar is the one `docs/SPEC.md` documents: `tool:<name>`, `skill:<name>`, `agent:<name>`, and
111
- * `ext:<pkg>/<tool>` where `<pkg>` may be npm-scoped. No wildcards — those are refused separately and
112
- * loudly, because "you tried to grant yourself everything" is a different fact from "that is not a name".
111
+ * The grammar is the one `docs/SPEC.md` documents: `tool:<name>`, `skill:<name>`, `agent:<name>`,
112
+ * `workspace:<id>`, and `ext:<pkg>/<tool>` where `<pkg>` may be npm-scoped. No wildcards — those are refused
113
+ * separately and loudly, because "you tried to grant yourself everything" is a different fact from "that is
114
+ * not a name".
115
+ *
116
+ * `workspace:` was absent until 2026-08-21, so the boundary that GENERATES grants could not emit the one
117
+ * capability ADR-0035's breaking change made mandatory: a package needing to route was reported as declaring
118
+ * something that "is not a name". A namespace has to be added here as well as to the enforcing path, and
119
+ * that is the whole lesson of the review this came out of.
113
120
  */
114
- export function isSafeCapability(id: Capability): boolean {
115
- const segment = "[A-Za-z0-9][A-Za-z0-9._-]*";
116
- return (
117
- new RegExp(`^(tool|skill|agent):${segment}$`).test(id) ||
118
- new RegExp(`^ext:(@${segment}/)?${segment}/${segment}$`).test(id)
119
- );
120
- }
121
+ // Imported as well as re-exported: a bare `export … from` does not bind the name in this module's scope, and
122
+ // `refusalFor` below calls it. Re-exported because this has been the import site since 0.13.0.
123
+ export { isSafeCapability };
121
124
 
122
- /** The two ids that confer root authority. A package declaring one is claiming it, not describing a need. */
125
+ /**
126
+ * The ids that confer authority over a whole namespace. A package declaring one is claiming it, not
127
+ * describing a need — so it is reported as a *wildcard claim* rather than as a malformed name, which is a
128
+ * different sentence to show an operator. `workspace:*` belongs here for the same reason `agent:*` does.
129
+ */
123
130
  function wildcardsIn(capabilities: Capability[]): Capability[] {
124
- return capabilities.filter((c) => c === WILDCARD || c === AGENT_WILDCARD);
131
+ return capabilities.filter((c) => c === WILDCARD || c === AGENT_WILDCARD || c === WORKSPACE_WILDCARD);
125
132
  }
126
133
 
127
134
  /**
@@ -14,6 +14,7 @@ import { homedir } from "node:os";
14
14
  import { join } from "node:path";
15
15
  import { GovernanceRefusal, refusal } from "./refusals.ts";
16
16
  import type { ValidatedWorkspace, WorkspaceAccess } from "./workspace.ts";
17
+ import { assertCloseBounds, HELPER_SOURCE, LEASE_READY, unrefStream } from "./lease-helper.ts";
17
18
 
18
19
  export const ENV_WORKSPACE_LEASE_DIR = "PI_GRANTS_WORKSPACE_LEASE_DIR";
19
20
 
@@ -22,28 +23,17 @@ export function defaultWorkspaceLeaseDir(env: NodeJS.ProcessEnv = process.env):
22
23
  return env[ENV_WORKSPACE_LEASE_DIR] ?? join(agentDir, "pi-daddy", "workspace-leases");
23
24
  }
24
25
 
25
- const LEASE_READY = "PI_DADDY_LEASE_READY";
26
- // The lock holder also owns crash cleanup for the governed child. If the parent dies, stdin closes;
27
- // the helper signals the attached process, or closes the herdr tab, before releasing flock. A raw
28
- // descendant deliberately detached by bash remains ADR-0012's OS-containment boundary, not a lease
29
- // guarantee. The process branch SIGTERMs, escalates to SIGKILL at +500ms, and releases at +750ms
30
- // WITHOUT confirming death (R-101). The herdr branch retries `tab close` a BOUNDED number of times
31
- // and then releases anyway, leaving a marker file: an unreleasable lock strands a worktree forever
32
- // with no in-product recovery, which is strictly worse than a recorded failure to close (R-102).
33
- const HELPER_SOURCE = `
34
- import { execFile } from "node:child_process";
35
- import { writeFileSync } from "node:fs";
36
- let clean=false, target=null, buffered="";
37
- process.stdout.write(${JSON.stringify(`${LEASE_READY}:`)}+process.pid+"\\n");
38
- process.stdin.setEncoding("utf8");
39
- process.stdin.on("data",chunk=>{buffered+=chunk;for(;;){const i=buffered.indexOf("\\n");if(i<0)break;const line=buffered.slice(0,i);buffered=buffered.slice(i+1);try{const value=JSON.parse(line);if(value.release)clean=true;else if(value.process_pid)target={process_pid:value.process_pid};else if(value.herdr_tab)target={herdr_tab:value.herdr_tab};}catch{}}});
40
- process.stdin.on("end",()=>{if(clean||!target)return process.exit(0);if(target.process_pid){try{process.kill(target.process_pid,"SIGTERM")}catch{return process.exit(0)}setTimeout(()=>{try{process.kill(target.process_pid,"SIGKILL")}catch{}},500);return setTimeout(()=>process.exit(0),750);}let left=Number(process.env.PI_DADDY_LEASE_CLOSE_ATTEMPTS||10);const giveUp=()=>{try{if(process.env.PI_DADDY_LEASE_MARKER)writeFileSync(process.env.PI_DADDY_LEASE_MARKER,JSON.stringify({reason:"herdr-close-failed",herdr_tab:target.herdr_tab})+"\\n")}catch{}process.exit(0)};const close=()=>execFile("herdr",["tab","close",target.herdr_tab],error=>{if(!error)return process.exit(0);if(--left<=0)return giveUp();setTimeout(close,1000)});close();});
41
- process.stdin.resume();`;
42
26
 
43
27
  /**
44
- * The ledger outcome for a release. ONE definition, exported, because two call sites had their own copies
45
- * and the check runner's copy asserted `released` unconditionally — reproducing in the evidence path the
46
- * exact defect this union was added to expose (R-100/R-103).
28
+ * The ledger outcome for a release. Exported because call sites had their own copies and the check runner's
29
+ * asserted `released` unconditionally — reproducing in the evidence path the exact defect this union was
30
+ * added to expose (R-100/R-103).
31
+ *
32
+ * **It is NOT the only definition, and saying so here was wrong.** `extensions/workspace-runtime.ts` keeps a
33
+ * private copy with no `not-held` arm, and it is the one the whole delegation path uses — so releasing a
34
+ * *read* lease on a delegated child is still recorded `released`, a handover the kernel never performed.
35
+ * Measured; open as R-141; the sentence claiming a single definition survived two review passes because
36
+ * `test/workspace.test.ts` pins the `not-held` arm on THIS function, which no delegation path calls.
47
37
  */
48
38
  export function leaseReleaseLedgerOutcome(
49
39
  outcome: LeaseReleaseOutcome | "retained",
@@ -78,9 +68,17 @@ export async function acquireWorkspaceLease(input: {
78
68
  signal?: AbortSignal;
79
69
  flockCommand?: string;
80
70
  acquisitionTimeoutMs?: number;
71
+ /**
72
+ * Bound on how long ONE `herdr tab close` attempt may take before it counts as failed (R-146). A hung
73
+ * herdr is not a failed herdr: without this the attempt never returns and the retry bound below is
74
+ * unreachable.
75
+ */
76
+ herdrCloseTimeoutMs?: number;
81
77
  /** Bound on the helper's `herdr tab close` retries before it releases the lock anyway (R-102). */
82
78
  herdrCloseAttempts?: number;
83
79
  }): Promise<WorkspaceLease> {
80
+ // Before the read-lease return, so both paths are validated (R-152).
81
+ assertCloseBounds(input);
84
82
  if (input.access === "read") {
85
83
  return {
86
84
  workspace: input.workspace,
@@ -89,7 +87,9 @@ export async function acquireWorkspaceLease(input: {
89
87
  recovered: false,
90
88
  attachProcess: () => {},
91
89
  attachHerdrTab: () => {},
92
- markRetained: async () => {},
90
+ // A read lease took no kernel lock, so there is nothing to keep: `not-held` is the same answer
91
+ // `release()` gives, and it is the truth rather than a retention that never happened (R-152).
92
+ markRetained: async () => "not-held" as const,
93
93
  readCloseFailure: async () => null,
94
94
  lost: new Promise(() => {}),
95
95
  // No kernel lock was ever taken, so there is no handover to claim (R-105, release side).
@@ -108,7 +108,12 @@ export async function acquireWorkspaceLease(input: {
108
108
  process.execPath, "--input-type=module", "-e", HELPER_SOURCE,
109
109
  ], {
110
110
  stdio: ["pipe", "pipe", "pipe"],
111
- env: { ...process.env, PI_DADDY_LEASE_MARKER: paths.marker, PI_DADDY_LEASE_CLOSE_ATTEMPTS: String(input.herdrCloseAttempts ?? 10) },
111
+ env: {
112
+ ...process.env,
113
+ PI_DADDY_LEASE_MARKER: paths.marker,
114
+ PI_DADDY_LEASE_CLOSE_ATTEMPTS: String(input.herdrCloseAttempts ?? 10),
115
+ PI_DADDY_LEASE_CLOSE_TIMEOUT_MS: String(input.herdrCloseTimeoutMs ?? 15_000),
116
+ },
112
117
  // Own process group, for two reasons. It lets teardown kill `flock` AND the helper holding the lock
113
118
  // file descriptor as one unit even before the helper has reported its pid (R-99), and it stops a
114
119
  // stray group signal — a terminal Ctrl-C, a closed window — from releasing a live writer's lock as
@@ -240,12 +245,67 @@ export async function acquireWorkspaceLease(input: {
240
245
  async markRetained(reason = "retained") {
241
246
  // Deliberately does NOT touch the kernel lock or the helper: the pane may still be live. It only
242
247
  // stops the record from looking like a crash.
248
+ //
249
+ // **Both guards below exist because the CALLER ledgers whatever this returns (R-152).**
250
+ //
251
+ // Already settled: `release()` checked `settled` and this did not, so a completed handover could be
252
+ // rewritten into `retained:…` and the memoized answer flipped with it — the mirror of the defect R-146
253
+ // fixed, reachable by the `try { … } finally { await lease.release() }` shape this API invites.
254
+ if (settled) return settled;
255
+ // Already dead: the helper is gone and the kernel lock with it, so the fact is `lost`. Recording a
256
+ // retention here tells an operator a pane may still be live and tells the next owner nothing crashed —
257
+ // precisely the two facts R-103's outcome union was added to keep apart.
258
+ if (holder.exitCode !== null || holder.signalCode !== null) return (settled = "lost");
243
259
  const current = await readMetadata(paths.metadata);
260
+ let recorded = false;
244
261
  if (current !== "malformed" && current?.token === token) {
245
- await atomicMetadata(paths.metadata, {
262
+ recorded = await atomicMetadata(paths.metadata, {
246
263
  ...metadata, state: "released", released_at: new Date().toISOString(), release_reason: `retained:${reason}`,
247
- }).catch(() => undefined);
264
+ }).then(() => true, () => false);
248
265
  }
266
+ /**
267
+ * **It must, however, let THIS process exit (R-146).** Leaving the helper alone is the decision;
268
+ * leaving the parent's three pipes and the child handle referenced was an accident, and it meant a
269
+ * retained lease wedged its own process forever — measured `exit=124` against `exit=0` for the same
270
+ * sequence ending in `release()`.
271
+ *
272
+ * **Which hosts it actually wedged, corrected after review.** `process.exit()` runs `exit` handlers and
273
+ * ignores pending handles, so this only bites a host that lets the loop drain: pi's **print** mode sets
274
+ * `process.exitCode` and returns (`dist/main.js`), and a library consumer — an ADR-0034 external
275
+ * controller calling this package directly — does the same. pi's interactive and rpc modes call
276
+ * `process.exit()` explicitly (`dist/modes/interactive/interactive-mode.js:3148`), so there the process
277
+ * still leaves and `pane-reaper`'s `process.once("exit")` sweep still runs. An earlier version of this
278
+ * comment claimed the sweep was lost generally and cited `src/cli.ts`, which has one subcommand
279
+ * (`init`) and can neither hold a lease nor open a pane.
280
+ *
281
+ * Unref rather than close, because the lock must outlive this call: when the parent does exit, the
282
+ * helper sees EOF and runs the path it was written for — bounded `herdr tab close` attempts, a marker
283
+ * file, then release anyway (R-102: an unreleasable lock strands a worktree with no in-product
284
+ * recovery, which is strictly worse than a recorded failure to close). Narrowed to this path on
285
+ * purpose: at spawn it would remove the accidental guarantee that a process cannot exit while a lease
286
+ * is still ACTIVE, which is a different decision and not this fix.
287
+ */
288
+ /**
289
+ * **Terminal (R-146).** `releasing` stops a late `holder.close` being reported as a lost lease, and
290
+ * `settled` stops a later `release()` running the clean handshake — which it did: measured, it returned
291
+ * `released`, overwrote `retained:herdr-close-failed` with `completed`, and sent `{release:true}` so the
292
+ * helper exited `clean` and never attempted the close. The pane retention exists to protect was
293
+ * abandoned silently, and the ledger asserted a clean handover for a lease kept *because* a pane would
294
+ * not close. No in-tree caller does this — but `WorkspaceLease` is a public export and
295
+ * `try { … } finally { await lease.release() }` is the obvious shape for the external controllers this
296
+ * whole fix is for.
297
+ */
298
+ releasing = true;
299
+ // **Settle only if the record was actually written.** An unwritable lease directory used to leave the
300
+ // record `state: "active"` while the ledger said `retained`, so the next owner reported a phantom
301
+ // `recovered: true` — and making retention terminal removed the later `release()` that would still have
302
+ // written the handover. Unsettled, that repair is available again; the residue is stated in R-152
303
+ // rather than implied, because nothing here can write a record to a directory that refuses writes.
304
+ if (recorded) settled = "retained";
305
+ holder.unref();
306
+ unrefStream(holder.stdout);
307
+ unrefStream(holder.stderr);
308
+ return "retained";
249
309
  },
250
310
  async readCloseFailure() {
251
311
  try {
package/src/workspace.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { execFile } from "node:child_process";
3
3
  import { once } from "node:events";
4
- import { mkdir, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
4
+ import { mkdir, open, readFile, realpath, rename, stat, writeFile } from "node:fs/promises";
5
+ import type { FileHandle } from "node:fs/promises";
6
+ import { constants } from "node:fs";
5
7
  import { homedir } from "node:os";
6
8
  import { isAbsolute, join } from "node:path";
7
9
  import { promisify } from "node:util";
8
10
  import { GovernanceRefusal, refusal } from "./refusals.ts";
11
+ import { isSafeWorkspaceId, workspaceCapability } from "./capabilities.ts";
9
12
 
10
13
  const execFileAsync = promisify(execFile);
11
14
  export const ENV_WORKSPACE_REGISTRY = "PI_GRANTS_WORKSPACE_REGISTRY";
@@ -16,6 +19,17 @@ export type WorkspaceAccess = "read" | "write";
16
19
  export interface WorkspaceRegistryFile {
17
20
  version: 1;
18
21
  workspaces: Record<string, { path: string }>;
22
+ /**
23
+ * Where this was loaded from, carried so a refusal can NAME it.
24
+ *
25
+ * `docs/SPEC.md` claimed an unregistered id is refused "with `WORKSPACE_NOT_REGISTERED`, which names the
26
+ * file", and `catalog.ts` justified exempting the whole namespace from the unknown check on the strength of
27
+ * that — *"a second, weaker check here can only turn that precise refusal into a misleading one"*. The
28
+ * refusal named no file: the registry object had no idea where it came from. Carried on the object rather
29
+ * than passed per call so a caller cannot forget it. Optional because a hand-built literal (tests,
30
+ * `workspaceEntries` fixtures) has no source.
31
+ */
32
+ source?: string;
19
33
  }
20
34
 
21
35
  export interface ValidatedWorkspace {
@@ -25,14 +39,129 @@ export interface ValidatedWorkspace {
25
39
  gitCommonDir: string;
26
40
  }
27
41
 
42
+ /**
43
+ * How long a registry read may take before it is a refusal rather than a wait.
44
+ *
45
+ * **R-79's defect class, and this reader reintroduced it.** That entry records a probe that hung forever on
46
+ * a FIFO with "no timeout anywhere in the path". This function used a bare `readFile`, which was survivable
47
+ * while it ran only at spawn time — and stopped being survivable when 0.19.0 began reading the registry from
48
+ * `buildCatalog` and `registeredWorkspaceIds`, both awaited inside `session_start`. Measured on `52135ca`:
49
+ * `PI_GRANTS_WORKSPACE_REGISTRY` pointing at a FIFO blocked session start indefinitely, so the session never
50
+ * reached the `holding [...]` line, the executor probe, or any control after it — and `delegate` awaits the
51
+ * same promise, so delegation hung too. A blocking special file, an unresponsive network mount or a hostile
52
+ * `mkfifo` all reach it.
53
+ *
54
+ * Two seconds because this is an operator-authored local JSON file: any legitimate one is a single-digit
55
+ * millisecond read (measured: 8ms), so the bound is three orders of magnitude of headroom and still bounded.
56
+ */
57
+ const REGISTRY_READ_TIMEOUT_MS = 2_000;
58
+
59
+ /** A registry is an operator-authored JSON file; anything approaching this is not one. */
60
+ const REGISTRY_MAX_BYTES = 1 << 20;
61
+
28
62
  export async function loadWorkspaceRegistry(path: string): Promise<WorkspaceRegistryFile> {
63
+ // **One handle, opened non-blocking, and every check made against THAT handle.** Three defects made this
64
+ // the shape rather than `stat`-then-`readFile`:
65
+ //
66
+ // - `AbortSignal.timeout` cannot rescue a FIFO: a signal is observed between chunks, while a FIFO blocks
67
+ // inside `open(2)` before any read begins. `O_NONBLOCK` makes the open itself return instead (measured:
68
+ // 1ms), which is what actually bounds this path. R-79's defect class, and R-136's.
69
+ // - `stat` by name followed by `readFile` by name is a TOCTOU: swapping a regular file for a FIFO between
70
+ // the two hung the loader indefinitely, and the attacker is any process at the same uid — precisely the
71
+ // actor the mode check below cannot exclude. Measured, 5 of 6 iterations completing in ~1ms and the
72
+ // sixth never returning. `fstat` on a held descriptor has no name to re-resolve.
73
+ // - a second reader (the ADR-0035 registry pin, since reverted to its own PR) reimplemented the guards and
74
+ // got them wrong. One reader is why that cannot happen again.
75
+ let handle: FileHandle;
76
+ try {
77
+ handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
78
+ } catch (error) {
79
+ throw new GovernanceRefusal(refusal(
80
+ "WORKSPACE_NOT_REGISTERED",
81
+ `workspace registry ${path} could not be opened (${String(error)})`,
82
+ { registry_path: path },
83
+ ));
84
+ }
85
+ let raw: string;
86
+ try {
87
+ const info = await handle.stat();
88
+ if (!info.isFile()) {
89
+ throw new GovernanceRefusal(refusal(
90
+ "WORKSPACE_NOT_REGISTERED",
91
+ `workspace registry ${path} is not a regular file — refusing to read it. A FIFO, device or socket ` +
92
+ `at ${ENV_WORKSPACE_REGISTRY} would block session start rather than fail, because opening one ` +
93
+ `waits for a writer that may never come.`,
94
+ { registry_path: path },
95
+ ));
96
+ }
97
+ if (info.size > REGISTRY_MAX_BYTES) {
98
+ throw new GovernanceRefusal(refusal(
99
+ "WORKSPACE_NOT_REGISTERED",
100
+ `workspace registry ${path} is ${info.size} bytes, over the ${REGISTRY_MAX_BYTES} limit — refusing ` +
101
+ `rather than reading it into memory at session start.`,
102
+ { registry_path: path },
103
+ ));
104
+ }
105
+ // **Ownership and mode are NOT checked here, and that is a scope decision (R-137, ADR-0036).** A
106
+ // previous revision refused a registry not owned by this user or writable by others. Those guards are
107
+ // about *tamper resistance*, which is a different question from the one ADR-0035 raised, and they went in
108
+ // mid-review without an ADR — where they promptly acquired a false claim ("nobody ELSE may rewrite it":
109
+ // it inspects the file and never its parent directory, and `rename(2)` needs only directory write) and a
110
+ // false-positive refusal of `0664`, which `umask 002` produces for every file an operator creates.
111
+ //
112
+ // What IS checked above is what ADR-0035 made this reader's problem: it began reading the registry at
113
+ // SESSION START, so the read must be bounded and must not block. Integrity is R-137, open and measured.
114
+ // The deadline is checked BETWEEN chunks, which is all `AbortSignal.timeout` ever did on the previous
115
+ // implementation — review measured 74 of 200 one-MiB reads completing in full with `signal.aborted`
116
+ // already true, because a signal is never observed *inside* a libuv read request. An explicit check makes
117
+ // the bound as real as it can be in-process, and its limit is the same one honestly stated below: a
118
+ // stalled `open` or a single wedged read cannot be interrupted from here.
119
+ const deadline = Date.now() + REGISTRY_READ_TIMEOUT_MS;
120
+ const buffer = Buffer.allocUnsafe(REGISTRY_MAX_BYTES + 1);
121
+ let filled = 0;
122
+ while (filled < buffer.length) {
123
+ if (Date.now() > deadline) {
124
+ throw new GovernanceRefusal(refusal(
125
+ "WORKSPACE_NOT_REGISTERED",
126
+ `workspace registry ${path} did not finish reading within ${REGISTRY_READ_TIMEOUT_MS}ms — ` +
127
+ `refusing rather than waiting, because session start awaits this read.`,
128
+ { registry_path: path },
129
+ ));
130
+ }
131
+ const { bytesRead } = await handle.read(buffer, filled, buffer.length - filled, filled);
132
+ if (bytesRead === 0) break;
133
+ filled += bytesRead;
134
+ }
135
+ if (filled > REGISTRY_MAX_BYTES) {
136
+ throw new GovernanceRefusal(refusal(
137
+ "WORKSPACE_NOT_REGISTERED",
138
+ `workspace registry ${path} exceeded the ${REGISTRY_MAX_BYTES} limit while being read — it grew ` +
139
+ `after its size was checked. Refusing rather than allocating it.`,
140
+ { registry_path: path },
141
+ ));
142
+ }
143
+ raw = buffer.subarray(0, filled).toString("utf8");
144
+ } catch (error) {
145
+ if (error instanceof GovernanceRefusal) throw error;
146
+ const timedOut = error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
147
+ throw new GovernanceRefusal(refusal(
148
+ "WORKSPACE_NOT_REGISTERED",
149
+ timedOut
150
+ ? `workspace registry ${path} did not return within ${REGISTRY_READ_TIMEOUT_MS}ms — refusing rather ` +
151
+ `than waiting, because session start awaits this read.`
152
+ : `workspace registry ${path} could not be read (${String(error)})`,
153
+ { registry_path: path },
154
+ ));
155
+ } finally {
156
+ await handle.close().catch(() => {});
157
+ }
29
158
  let parsed: unknown;
30
159
  try {
31
- parsed = JSON.parse(await readFile(path, "utf8"));
160
+ parsed = JSON.parse(raw);
32
161
  } catch (error) {
33
162
  throw new GovernanceRefusal(refusal(
34
163
  "WORKSPACE_NOT_REGISTERED",
35
- `workspace registry ${path} could not be read (${String(error)})`,
164
+ `workspace registry ${path} is not valid JSON (${String(error)})`,
36
165
  { registry_path: path },
37
166
  ));
38
167
  }
@@ -52,17 +181,61 @@ export async function loadWorkspaceRegistry(path: string): Promise<WorkspaceRegi
52
181
  { registry_path: path, workspace_id: id },
53
182
  ));
54
183
  }
184
+ // ADR-0035 made a registry id the tail of a CAPABILITY id (`workspace:<id>`), so this file is an input
185
+ // to the grant grammar and has to obey it — the STRICT one. This shipped with the loose
186
+ // `isWellFormedCapability` blocklist, and review measured what that let through: an id of `*` minted
187
+ // `WORKSPACE_WILDCARD` (an operator naming one worktree held routing over all of them), an id with a
188
+ // space became two capabilities because `ceilingForDefinition` splits on `[\s,]+`, and quote/`$()` ids
189
+ // reached a generated file whose own instructions say to paste them into `PI_GRANTS_GRANT`. See
190
+ // `isSafeCapability`, which is now the one grammar for both channels into that file.
191
+ if (!isSafeWorkspaceId(id)) {
192
+ throw new GovernanceRefusal(refusal(
193
+ "GRANT_ID_MALFORMED",
194
+ `workspace registry id ${JSON.stringify(id)} cannot be used: since ADR-0035 an id becomes the ` +
195
+ `capability ${JSON.stringify(workspaceCapability(id))}, and an id must match ` +
196
+ `[A-Za-z0-9][A-Za-z0-9._/-]* — slashes and dots are fine (a worktree named after its branch ` +
197
+ `works), but not spaces, quotes, commas, wildcards, shell metacharacters or non-ASCII, each of ` +
198
+ `which either splits into several capabilities or reaches a file you are told to source. ` +
199
+ `Rename it in ${path}.`,
200
+ { registry_path: path, workspace_id: id },
201
+ ));
202
+ }
203
+ }
204
+ return { version: 1, workspaces: structuredClone(file.workspaces), source: path };
205
+ }
206
+
207
+ /**
208
+ * The registered workspace ids, for `planInit` to scaffold and `/grants` to list. `[]` when there is no registry or it is broken.
209
+ *
210
+ * Fails SOFT, and only because nothing here is an authority: this decides which ids appear as COMMENTS in a
211
+ * generated file. `loadWorkspaceRegistry` throws a GovernanceRefusal naming the file, and that refusal is
212
+ * the operator's signal at the point of use, where routing genuinely depends on it. Swallowing it there
213
+ * would be unsafe; swallowing it here costs a suggestion. Same argument as `buildCatalog`'s.
214
+ *
215
+ * Lives here rather than in `init.ts` because it reads the filesystem, and `planInit` — the centrepiece of
216
+ * that module — documents itself as "Pure: no filesystem". It is a registry concern; this is where the
217
+ * registry lives. Moved when `init.ts` crossed the 400-line ceiling, which this project splits for rather
218
+ * than raising (`delegate.ts` at 413, `grants.ts` at 398).
219
+ */
220
+ export async function registeredWorkspaceIds(registryPath = process.env[ENV_WORKSPACE_REGISTRY]): Promise<string[]> {
221
+ if (!registryPath) return [];
222
+ try {
223
+ return Object.keys((await loadWorkspaceRegistry(registryPath)).workspaces).sort();
224
+ } catch {
225
+ return [];
55
226
  }
56
- return { version: 1, workspaces: structuredClone(file.workspaces) };
57
227
  }
58
228
 
59
229
  export async function resolveWorkspace(registry: WorkspaceRegistryFile, workspaceId: string): Promise<ValidatedWorkspace> {
60
230
  const registered = Object.hasOwn(registry.workspaces, workspaceId) ? registry.workspaces[workspaceId] : undefined;
231
+ const known = Object.keys(registry.workspaces).sort();
61
232
  if (!registered) {
62
233
  throw new GovernanceRefusal(refusal(
63
234
  "WORKSPACE_NOT_REGISTERED",
64
- `workspace ${JSON.stringify(workspaceId)} is not present in the operator-owned registry`,
65
- { workspace_id: workspaceId },
235
+ `workspace ${JSON.stringify(workspaceId)} is not present in the operator-owned registry` +
236
+ (registry.source ? ` ${registry.source}` : "") +
237
+ (known.length > 0 ? ` — it lists: ${known.join(", ")}` : " — it lists nothing"),
238
+ { workspace_id: workspaceId, ...(registry.source ? { registry_path: registry.source } : {}) },
66
239
  ));
67
240
  }
68
241
  return validateRegisteredWorkspace({ workspaceId, registeredRoot: registered.path });