pi-daddy 0.15.0 → 0.16.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 (66) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +27 -12
  3. package/dist/cli.js +0 -0
  4. package/dist/executor.d.ts +38 -0
  5. package/dist/executor.d.ts.map +1 -0
  6. package/dist/executor.js +93 -0
  7. package/dist/executor.js.map +1 -0
  8. package/dist/herdr-cli.d.ts +78 -0
  9. package/dist/herdr-cli.d.ts.map +1 -0
  10. package/dist/herdr-cli.js +113 -0
  11. package/dist/herdr-cli.js.map +1 -0
  12. package/dist/herdr-name.d.ts +37 -0
  13. package/dist/herdr-name.d.ts.map +1 -0
  14. package/dist/herdr-name.js +59 -0
  15. package/dist/herdr-name.js.map +1 -0
  16. package/dist/herdr-poll.d.ts +104 -0
  17. package/dist/herdr-poll.d.ts.map +1 -0
  18. package/dist/herdr-poll.js +150 -0
  19. package/dist/herdr-poll.js.map +1 -0
  20. package/dist/herdr-stage.d.ts +40 -0
  21. package/dist/herdr-stage.d.ts.map +1 -0
  22. package/dist/herdr-stage.js +54 -0
  23. package/dist/herdr-stage.js.map +1 -0
  24. package/dist/ledger-report.d.ts +18 -0
  25. package/dist/ledger-report.d.ts.map +1 -1
  26. package/dist/ledger-report.js +10 -0
  27. package/dist/ledger-report.js.map +1 -1
  28. package/dist/ledger.d.ts +17 -0
  29. package/dist/ledger.d.ts.map +1 -1
  30. package/dist/ledger.js +1 -0
  31. package/dist/ledger.js.map +1 -1
  32. package/dist/pane-reaper.d.ts +66 -4
  33. package/dist/pane-reaper.d.ts.map +1 -1
  34. package/dist/pane-reaper.js +131 -9
  35. package/dist/pane-reaper.js.map +1 -1
  36. package/dist/progress.d.ts +96 -0
  37. package/dist/progress.d.ts.map +1 -0
  38. package/dist/progress.js +167 -0
  39. package/dist/progress.js.map +1 -0
  40. package/dist/run-child.d.ts +27 -0
  41. package/dist/run-child.d.ts.map +1 -1
  42. package/dist/run-child.js +84 -7
  43. package/dist/run-child.js.map +1 -1
  44. package/dist/run-herdr.d.ts +41 -28
  45. package/dist/run-herdr.d.ts.map +1 -1
  46. package/dist/run-herdr.js +150 -167
  47. package/dist/run-herdr.js.map +1 -1
  48. package/extensions/delegation.ts +94 -2
  49. package/extensions/grants-command.ts +26 -1
  50. package/extensions/grants.ts +85 -163
  51. package/extensions/run-delegation.ts +70 -8
  52. package/extensions/session-report.ts +231 -0
  53. package/extensions/session.ts +63 -11
  54. package/extensions/tripwire.ts +44 -0
  55. package/package.json +17 -1
  56. package/src/executor.ts +122 -0
  57. package/src/herdr-cli.ts +125 -0
  58. package/src/herdr-name.ts +61 -0
  59. package/src/herdr-poll.ts +185 -0
  60. package/src/herdr-stage.ts +55 -0
  61. package/src/ledger-report.ts +21 -0
  62. package/src/ledger.ts +18 -0
  63. package/src/pane-reaper.ts +147 -9
  64. package/src/progress.ts +206 -0
  65. package/src/run-child.ts +96 -7
  66. package/src/run-herdr.ts +170 -174
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import type { Capability } from "../src/resolve.ts";
16
+ import type { ExecutorChoice } from "../src/executor.ts";
16
17
  import type { Catalog } from "../src/catalog.ts";
17
18
  import type { SkillDefinition } from "../src/definitions.ts";
18
19
  import type { GatedPlan } from "./run-delegation.ts";
@@ -23,6 +24,13 @@ export interface GrantsCommandContext {
23
24
  cwd: string;
24
25
  governed: boolean;
25
26
  ownGrant: Capability[];
27
+ /**
28
+ * Which executor this session settled on, and why — ADR-0031.
29
+ *
30
+ * The whole `ExecutorChoice` rather than a rendered string, so this command cannot compose a different
31
+ * sentence from the one the session banner printed. Two spellings of one fact is R-28.
32
+ */
33
+ executor: ExecutorChoice;
26
34
  observed: boolean;
27
35
  depth: number;
28
36
  maxDepth: number;
@@ -71,7 +79,7 @@ handler: async (args: string, ctx: any) => {
71
79
  // Everything this command may see, named in one place. Previously these were whatever happened to be in
72
80
  // the enclosing closure — which is how a diagnostic came to disagree with the enforcer (R-28).
73
81
  const {
74
- cwd, governed, ownGrant, observed, depth, maxDepth, ledgerPath,
82
+ cwd, governed, ownGrant, executor, observed, depth, maxDepth, ledgerPath,
75
83
  catalog, definitions, sessionApprovals, inheritedApprovals, snapshotOf, previewDelegation,
76
84
  } = ctx.grants as GrantsCommandContext;
77
85
 
@@ -102,6 +110,17 @@ handler: async (args: string, ctx: any) => {
102
110
  ` integrity ${report.ok ? "OK" : `${report.corrupt.length} UNPARSEABLE LINE(S)`}`,
103
111
  ];
104
112
  for (const bad of report.corrupt.slice(0, 5)) lines.push(` line ${bad.line}: ${bad.text}`);
113
+ // ADR-0031, and R-51's lesson applied on the day the field was added rather than a release later: a field
114
+ // the writer sets and no diagnostic reads is one that needs `jq`, and `docs/SPEC.md` claims the executor is
115
+ // announced "per child in the ledger". `unknown` is shown only when present, because on a fresh ledger it
116
+ // is always zero and a permanent zero is noise; on an upgraded one it is the count of pre-0.16 lines, which
117
+ // is worth seeing.
118
+ lines.push(
119
+ ` executors ${report.executors.herdr} herdr pane(s) · ${report.executors.process} subprocess(es)` +
120
+ (report.executors.unknown > 0
121
+ ? ` · ${report.executors.unknown} not recorded (written before 0.16.0, which added the field)`
122
+ : ""),
123
+ );
105
124
  // R-51. ADR-0018 advertises that the ledger answers "did these four children run the same
106
125
  // instructions?" and "has this definition changed since?" — and nothing read `definitionDigest`, so
107
126
  // both needed hand-written jq and the second was not reproducible with `sha256sum` (the digest covers
@@ -300,6 +319,12 @@ handler: async (args: string, ctx: any) => {
300
319
  const lines = [
301
320
  governed ? "grants: ACTIVE" : "grants: inactive (set PI_GRANTS_GRANT to govern this session)",
302
321
  ` holding ${ownGrant.join(", ") || "(nothing)"}${observed ? " (observed)" : " (inherited, not yet observed)"}`,
322
+ // ADR-0031/0032. This screen named the grant, the depth, the ledger, the approvals and the catalog, and
323
+ // never said WHERE children run — so an operator on a machine where herdr hosts their whole workspace
324
+ // could not discover that their children were invisible subprocesses. That gap is what produced
325
+ // ADR-0031, and its probe is only defensible because this line exists. Placed next to `holding` so the
326
+ // two facts about what a spawn will be sit together.
327
+ ` executor ${executor.disclosure}`,
303
328
  ` depth ${depth} of max ${maxDepth}${maxDepth <= 0 ? " (spawning disabled)" : ""}`,
304
329
  ` ledger ${ledgerPath ?? "(not recording — set PI_GRANTS_LEDGER)"}`,
305
330
  ` approvals ${sessionApprovals.size} this session, ${valid.size} persisted` +
@@ -21,28 +21,22 @@
21
21
  * child derives its own grant from the tool array of its first provider request.
22
22
  */
23
23
 
24
- import { existsSync } from "node:fs";
25
24
  import { fileURLToPath } from "node:url";
26
25
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
27
26
  import { WILDCARD } from "../src/pi-tools.ts";
28
- import { AGENT_WILDCARD } from "../src/resolve.ts";
29
- import { legacyApprovalsPath, sharedApprovalsPath } from "../src/approval-store.ts";
30
27
  import { buildCatalog } from "../src/catalog.ts";
31
- import { loadDefinitions } from "../src/definitions.ts";
32
- import { appendRecord, buildRecord, verifyLedger } from "../src/ledger.ts";
28
+ import { appendRecord, buildRecord } from "../src/ledger.ts";
29
+ import { openPaneCount, reapOpenPanesAsync } from "../src/pane-reaper.ts";
33
30
  import {
34
31
  ENV_GRANT, deriveOwnGrant, observeToolNames } from "../src/propagation.ts";
35
32
  import { snapshotOf } from "./approvals.ts";
36
33
  import { registerDelegationTools } from "./delegation.ts";
37
34
  import { grantsCommand } from "./grants-command.ts";
38
35
  import { runInit } from "./init-command.ts";
39
- import type { Capability } from "../src/resolve.ts";
40
-
41
36
  import { planWithApprovals } from "./run-delegation.ts";
42
- import { createGrantsSession, loadProjectDefinitions, type GrantsSession } from "./session.ts";
43
- import { renderSpawnableSummary, summariseSpawnable } from "./spawn-summary.ts";
44
-
45
- const SPAWN_TOOLS = new Set(["Agent", "subagent", "spawn_agent"]);
37
+ import { createGrantsSession, loadProjectDefinitions, resolveExecutor, type GrantsSession } from "./session.ts";
38
+ import { reportSessionStart } from "./session-report.ts";
39
+ import { SPAWN_TOOLS, tripwireReason } from "./tripwire.ts";
46
40
 
47
41
  export default function (pi: ExtensionAPI) {
48
42
  // The path pi loads as the extension, so a child granted `tool:delegate` can be started with `-e <this>`.
@@ -70,6 +64,10 @@ export default function (pi: ExtensionAPI) {
70
64
  // When they do not, the session is governed by a different directory's decision than the one it is
71
65
  // working in, which is exactly the confusion a grant must never cause, so it is said out loud rather
72
66
  // than left to be inferred from a surprising refusal. Sync, so it is not the R-60 shape.
67
+ // Inside no try of its own, and that is deliberate: it is synchronous, so it cannot be the R-60 shape. A
68
+ // reviewer noted it sits before the try that contains `resolveExecutor` — which is the right order, because
69
+ // this warning is about WHICH directory's grant was read and must reach the operator even if everything
70
+ // after it fails.
73
71
  if (session.storeCwd !== ctx.cwd && process.env[ENV_GRANT] === undefined) {
74
72
  ctx.ui.notify(
75
73
  `grants: this session's stored grant was read for ${session.storeCwd}, but pi is working in ` +
@@ -97,163 +95,62 @@ export default function (pi: ExtensionAPI) {
97
95
  "error",
98
96
  );
99
97
  }
98
+ // ADR-0031: probe once, HERE, before anything reports — so the disclosure line can name the executor,
99
+ // and so a demanded-but-unreachable herdr is reported before the operator's first prompt rather than at
100
+ // their first delegation. Its own try, because a failure here must not cancel the controls after it
101
+ // (R-60), and `probeHerdr` is documented as never throwing precisely so this is belt-and-braces.
102
+ try {
103
+ await resolveExecutor(session);
104
+ } catch (error) {
105
+ // Says what is actually true of the state left behind, which depends on the variable: with
106
+ // `PI_GRANTS_HERDR=1` the session holds a REFUSAL and every delegation fails, so telling the operator
107
+ // "using the captured subprocess" would be the opposite of what happens. The old wording asserted the
108
+ // fallback unconditionally.
109
+ ctx.ui.notify(
110
+ `grants: could not settle which executor to use ` +
111
+ `(${error instanceof Error ? error.message : String(error)}) — ` +
112
+ (session.executor.refusal
113
+ ? `PI_GRANTS_HERDR=1 still demands herdr, so every delegation in this session will refuse. ` +
114
+ `Unset it to let this session probe, or set 0 to choose subprocesses.`
115
+ : `using the captured subprocess, which needs nothing installed. Set PI_GRANTS_HERDR=0 to make ` +
116
+ `that explicit, or 1 to demand herdr panes.`),
117
+ "warning",
118
+ );
119
+ }
100
120
  session.publishChildEnv();
101
121
  // The definitions now exist, so the `delegate` schema can finally name them (R-39). pi serialises a
102
122
  // tool's schema at REQUEST time, not at registration — measured — which is what makes this reach the
103
123
  // model at all.
104
124
  delegation.refreshSpawnable();
105
- // A malformed bound is now loud as well as safe. Silently disabling spawning would be just as
106
- // confusing as silently disabling the limit was dangerous — the operator set the variable, so
107
- // they need to know it did not take effect (G7 / A-S4).
108
- if (session.malformedBounds.length > 0) {
109
- ctx.ui.notify(
110
- `grants: ${session.malformedBounds.join(" and ")} could not be read as a non-negative integer — ` +
111
- `spawning is disabled for this session (failing closed)`,
112
- "warning",
113
- );
114
- }
115
- // ADR-0014: a pre-0.6 in-workspace approvals file is IGNORED, not migrated — importing it would
116
- // import exactly the entries whose trustworthiness the move exists to remove. Say so, because an
117
- // operator whose approvals silently stopped applying deserves to know why.
118
- // ADR-0020: the pre-0.11 single shared store is ignored, not migrated. Same reasoning shape as the
119
- // legacy file below — an operator whose approvals silently stopped applying must be told why — but a
120
- // different reason for not migrating: splitting it by `cwd` would be lossless, and it is still declined
121
- // because one-shot migration code in the layer with nine defects buys less than one re-approval costs.
122
- try {
123
- if (existsSync(sharedApprovalsPath())) {
124
- ctx.ui.notify(
125
- `grants: ignoring ${sharedApprovalsPath()} — approvals are now stored one file per governed ` +
126
- `directory (ADR-0020), because a single shared file could not hold two projects' approvals ` +
127
- `for a same-named definition. Re-approve when next asked. **Deleting the old file is ` +
128
- `recommended, not merely safe**: entries written by 0.10.x may contain the task text a model ` +
129
- `composed at approval time, which this version no longer stores anywhere (ADR-0021).`,
130
- "warning",
131
- );
132
- }
133
- } catch {
134
- /* never throw into the agent loop */
135
- }
136
- try {
137
- if (existsSync(legacyApprovalsPath(ctx.cwd))) {
138
- ctx.ui.notify(
139
- `grants: ignoring ${legacyApprovalsPath(ctx.cwd)} — approvals now live outside the workspace ` +
140
- `(it was writable by the very agents it gated). Re-approve when next asked; the old file is ` +
141
- `safe to delete.`,
142
- "warning",
143
- );
144
- }
145
- } catch {
146
- /* never throw into the agent loop */
147
- }
148
- // R-47. `gatedBlocked` filters `requested`, and for a definition spawn `requested` is that
149
- // definition's CEILING — which never contains `agent:<name>`, because the authorisation check
150
- // (ADR-0017) is a separate, ungated branch. So `PI_GRANTS_GATED=agent:deploy`, written by an operator
151
- // who read "it attenuates like any other capability" and meant "ask me before deploy runs", produces
152
- // no dialog and no warning. It DOES bite when a definition passes the id down in its own
153
- // `allowed-tools`, so the flag half-works — which is worse than not working, and is R-25's shape in
154
- // the namespace ADR-0017 just promoted out of exactly that state.
125
+ // Everything an operator is TOLD at session start now lives in `./session-report.ts`. Lifted because
126
+ // this file had reached 398 of the 400-line ceiling and ADR-0032 adds a control to it; the split is the
127
+ // same move `session.ts` and `grants-command.ts` were extracted under, and the guard is obeyed rather
128
+ // than raised.
155
129
  //
156
- // Warned rather than enforced: making it gate the spawn is a behaviour change and wants a decision.
157
- // Silence is the part that is indefensible either way.
158
- // `agent:*` grants no tools, but it authorises every definition in BOTH skill roots — including
159
- // `~/.pi/agent/skills/`, which other software installs into, so ADR-0017's "an operator-authored
160
- // file" is not true of everything it covers. Paired with a shell that is every body on disk running
161
- // with `bash`. `docs/SPEC.md` calls the combination poor and nothing detected it, which is R-47's
162
- // shape in a control shipped one day later.
163
- if (session.ownGrant.includes(AGENT_WILDCARD) && session.gated.length === 0 && session.ownGrant.includes("tool:bash")) {
164
- ctx.ui.notify(
165
- `grants: PI_GRANTS_GRANT pairs agent:* with tool:bash and gates nothing — every SKILL.md in ` +
166
- `this project AND in ~/.pi/agent/skills (which other tools install into) may run with a shell. ` +
167
- `Enumerate the agent: ids you mean, or leave PI_GRANTS_GATED at its default so bash is asked for.`,
168
- "warning",
169
- );
170
- }
171
- const inertGates = session.gated.filter((c) => c.startsWith("agent:"));
172
- if (inertGates.length > 0) {
130
+ // Its own try/catch, required by `test/session-start-guard.test.ts` and right on the merits: every
131
+ // control inside `reportSessionStart` already has one, but a throw from the reporter ITSELF would
132
+ // otherwise reach the blanket catch below and be reported as "session start did not complete" — which
133
+ // would be true and useless, because nothing about the grant or its enforcement depends on any of it.
134
+ // Naming that distinction is the difference between an operator checking their configuration and an
135
+ // operator distrusting their governance.
136
+ try {
137
+ await reportSessionStart(session, ctx);
138
+ } catch (error) {
173
139
  ctx.ui.notify(
174
- `grants: ${inertGates.join(", ")} in PI_GRANTS_GATED does NOT gate spawning that definition — ` +
175
- `the authorisation check for a definition is separate and ungated, so a human is never asked. ` +
176
- `It applies only where a definition passes the id down in its own allowed-tools. To control ` +
177
- `which definitions may run, withhold the agent: capability from PI_GRANTS_GRANT instead.`,
140
+ // Names the CHECKS as well as the display lines. The first version listed only "the grant, the
141
+ // executor and the spawnable definitions" — which understated it: a throw partway through the reporter
142
+ // also skips the legacy/shared approval-store notices and the **ledger-corruption check**, which is an
143
+ // error rather than an FYI. Telling an operator that three lines are missing, when a control also did
144
+ // not run, is the reassuring half of the truth.
145
+ `grants: the session-start report could not be produced ` +
146
+ `(${error instanceof Error ? error.message : String(error)}) — the grant, the executor and the ` +
147
+ `spawnable definitions were not printed, AND the checks that run alongside them did not complete: ` +
148
+ `ledger integrity was not verified and any ignored-approvals notices were not shown. Run /grants and ` +
149
+ `/grants ledger for all of it. Governance itself is unaffected: it is enforced by --tools when a ` +
150
+ `child is spawned.`,
178
151
  "warning",
179
152
  );
180
153
  }
181
- // R-34. `verifyLedger` existed and nothing ran it, so a torn line was detectable and undetected —
182
- // and a check an operator has to know to run is not a control, it is a feature. Setting
183
- // `PI_GRANTS_LEDGER` already means "I want an audit trail"; noticing that the trail is damaged is
184
- // part of keeping one.
185
- //
186
- // Corruption only, deliberately. The escalation count is a *query* — `/grants ledger` answers it —
187
- // and reporting historical attempts unprompted at every start is the fatigue shape R-25 names, which
188
- // ends with the operator ignoring the line that matters.
189
- //
190
- // Awaited rather than fired and forgotten: it is one read, on a path that already awaits two
191
- // directory scans, and awaiting is what guarantees the warning reaches a live `ctx.ui`.
192
- //
193
- // R-60. `verifyLedger` RETHROWS every read error that is not ENOENT — right for `/grants ledger`,
194
- // where an operator asked a direct question and deserves the failure — and this call is the only one
195
- // that makes it inside the blanket catch below. So an unreadable ledger threw here and cancelled every
196
- // remaining control **in silence**: no alarm, and not even the `holding [...]` line that is the one
197
- // sign governance is on. Confirmed by execution — `PI_GRANTS_LEDGER` naming a directory produced ZERO
198
- // notifications from a governed session. A trail that cannot be read at all is a worse failure than a
199
- // torn line, and it was the one case this control said nothing about.
200
- if (session.ledgerPath) {
201
- try {
202
- const report = await verifyLedger(session.ledgerPath);
203
- if (report.exists && !report.ok) {
204
- ctx.ui.notify(
205
- `grants: ledger ${session.ledgerPath} has ${report.corrupt.length} unparseable line(s) — ` +
206
- `first at line ${report.corrupt[0]?.line}. A torn line is indistinguishable from a spawn that ` +
207
- `never happened, so this audit trail is incomplete. Run /grants ledger for detail; the file is ` +
208
- `left alone because a corrupt line is evidence.`,
209
- "error",
210
- );
211
- }
212
- } catch (error) {
213
- ctx.ui.notify(
214
- `grants: ledger ${session.ledgerPath} could not be read ` +
215
- `(${(error as { code?: string }).code ?? String(error)}) — nothing can be verified about this ` +
216
- `audit trail, and the first spawn will refuse rather than proceed unrecorded. Check that ` +
217
- `PI_GRANTS_LEDGER names a writable FILE.`,
218
- "error",
219
- );
220
- }
221
- }
222
- if (session.governed) {
223
- ctx.ui.notify(
224
- `grants: depth ${session.depth}/${session.maxDepth}, holding [${session.ownGrant.join(", ") || "nothing"}]`,
225
- "info",
226
- );
227
- // B1 / P4. The grant alone never named the definitions, never said where they came from, and never
228
- // said which ones were being WITHHELD — so an operator who had just installed a package of
229
- // `SKILL.md` files could not tell governance-is-working from did-the-install-fail. Classified by the
230
- // real planner (see `./spawn-summary.ts`), never by a second reading of the rules.
231
- //
232
- // Its own try/catch, and not because `summariseSpawnable` throws today: this is the R-60 shape
233
- // exactly — one added `await` inside the blanket catch cancelling every control below it in
234
- // silence. There is nothing below it now; there will be.
235
- try {
236
- const line = renderSpawnableSummary(
237
- await summariseSpawnable(
238
- session.definitions,
239
- (name) => planWithApprovals(session, { task: "(preview)", agent: name }, {}, null),
240
- // The session facts that make every per-definition verdict identical. `mayDelegate` in
241
- // particular: without `tool:delegate` there is no delegate tool at all, and the line used to
242
- // report definitions as spawnable in the one session where nothing can ever be spawned.
243
- { mayDelegate: session.mayDelegate, depth: session.depth, maxDepth: session.maxDepth },
244
- ),
245
- session.definitions.size,
246
- );
247
- if (line) ctx.ui.notify(line, "info");
248
- } catch (error) {
249
- ctx.ui.notify(
250
- `grants: could not work out which definitions are spawnable ` +
251
- `(${error instanceof Error ? error.message : String(error)}) — run /grants for the per-definition ` +
252
- `verdict. Nothing about the grant or its enforcement depends on this line.`,
253
- "warning",
254
- );
255
- }
256
- }
257
154
  } catch (error) {
258
155
  // Rule 8 — fail closed, and be LOUD about it. Swallowing is still right: a startup fault must not
259
156
  // reach the agent loop. Swallowing SILENTLY is what let R-60 exist, and would let the next one exist
@@ -273,6 +170,33 @@ export default function (pi: ExtensionAPI) {
273
170
  return undefined;
274
171
  });
275
172
 
173
+ /**
174
+ * Reap the herdr panes this agent run opened — ADR-0032.
175
+ *
176
+ * **`agent_settled`, not `turn_end`, and that is the whole finding.** `turn_end` fires at the end of each
177
+ * provider round-trip, i.e. no later than the `finally` that used to close the pane — so building pane
178
+ * lifetime on it would have shipped a no-op that read like a feature. `agent_settled` is documented as firing
179
+ * once the run has fully settled with no retry, compaction or queued continuation: the moment the operator
180
+ * gets their prompt back. Independent corroboration that this is the right boundary: herdr's own pi
181
+ * integration drives its busy/idle display from `agent_start`/`agent_settled`.
182
+ *
183
+ * The sweep is ASYNC (`reapOpenPanesAsync`) rather than the `exit` handler's sync one, which is `execFileSync`
184
+ * with a six-second budget by necessity. Running that here would freeze pi for up to six seconds every time
185
+ * the operator gets their prompt back — a feature built to make work visible, stalling the thing it serves.
186
+ *
187
+ * `exit` remains the backstop. SIGKILL still orphans panes, exactly as R-62 records, and no signal handler is
188
+ * installed here for the reason R-62 gives: it would turn pi's "interrupt this turn" into "exit pi".
189
+ */
190
+ pi.on("agent_settled", async () => {
191
+ try {
192
+ if (session.executor.kind !== "herdr" || openPaneCount() === 0) return undefined;
193
+ await reapOpenPanesAsync();
194
+ } catch {
195
+ /* never throw into the agent loop; the exit handler is still the backstop */
196
+ }
197
+ return undefined;
198
+ });
199
+
276
200
  // Observe this session's real tool surface once, and tighten the grant to it. Authoritative because
277
201
  // it is exactly what pi sent the model.
278
202
  pi.on("before_provider_request", (event) => {
@@ -321,11 +245,7 @@ export default function (pi: ExtensionAPI) {
321
245
  pi.on("tool_call", async (event) => {
322
246
  if (!session.governed || !SPAWN_TOOLS.has(event.toolName)) return undefined;
323
247
 
324
- const reason =
325
- `grants: "${event.toolName}" spawns sub-agents outside this session's governance — refused. ` +
326
- `This session grants capabilities by spawning them itself (\`delegate\`), so a child created by ` +
327
- `another extension would hold whatever that extension decided, with no grant, no depth bound and ` +
328
- `no ledger entry. Use \`delegate\` instead. If you meant to run ungoverned, unset PI_GRANTS_GRANT.`;
248
+ const reason = tripwireReason(event.toolName);
329
249
 
330
250
  if (session.ledgerPath) {
331
251
  // Recorded like any other refusal: an audit that omits the spawns we turned away cannot answer
@@ -339,6 +259,7 @@ export default function (pi: ExtensionAPI) {
339
259
  agentType: event.toolName,
340
260
  // The wildcard is the honest record: an unknown spawner was going to hand this child whatever
341
261
  // IT decided, and we have no way to know what that would have been.
262
+ executor: session.executor.kind,
342
263
  requested: [WILDCARD],
343
264
  parentGrant: session.ownGrant,
344
265
  result: { effective: [], denied: [WILDCARD], clipped: [], gatedBlocked: [], universal: [], subsumedBy: [] },
@@ -371,6 +292,7 @@ export default function (pi: ExtensionAPI) {
371
292
  cwd: session.cwd,
372
293
  governed: session.governed,
373
294
  ownGrant: session.ownGrant,
295
+ executor: session.executor,
374
296
  observed: session.observed,
375
297
  depth: session.depth,
376
298
  maxDepth: session.maxDepth,
@@ -22,7 +22,8 @@ import type { Capability } from "../src/resolve.ts";
22
22
  import { ENV_CHILD_TIMEOUT, runChild, timeoutFromEnv } from "../src/run-child.ts";
23
23
  import { runHerdrPane } from "../src/run-herdr.ts";
24
24
  import { obtainApprovals, republishable, snapshotOf, type ApprovalOutcome, type ApprovalUIContext } from "./approvals.ts";
25
- import { ENV_HERDR_KEEP_PANE, ENV_HERDR_WORKSPACE, type GrantsSession } from "./session.ts";
25
+ import { resolveWorkspace } from "../src/herdr-cli.ts";
26
+ import { ENV_HERDR_KEEP_PANE, type GrantsSession } from "./session.ts";
26
27
 
27
28
  /** What one child was asked to do. The shape both tools accept, per child. */
28
29
  interface ChildSpec {
@@ -156,6 +157,22 @@ export async function runOneDelegation(
156
157
  budget: number | undefined,
157
158
  ctx: DelegationToolContext,
158
159
  signal: AbortSignal | undefined,
160
+ /**
161
+ * Progress for the parent's status block (ADR-0032). Optional, so nothing here depends on being watched.
162
+ *
163
+ * One sink for both executors: the herdr path additionally reports a pane id, and the process path never
164
+ * has one. Every field is display-only — the child's answer is still the returned outcome.
165
+ */
166
+ onProgress?: (update: {
167
+ /** Appended (process executor: a genuine byte stream). */
168
+ chunk?: string;
169
+ /** Replaces (herdr executor: a snapshot of a bounded terminal). The two are NOT interchangeable. */
170
+ snapshot?: string[];
171
+ paneId?: string;
172
+ /** The name herdr actually knows this child by — minted in `runHerdrPane`, so it cannot be derived. */
173
+ agentName?: string;
174
+ state?: "running" | "completed" | "failed";
175
+ }) => void,
159
176
  ): Promise<DelegationOutcome> {
160
177
  // pi resolves a BARE model id to an unauthenticated provider and the child dies at startup — the id
161
178
  // alone is not enough, it must be qualified with its provider (`Model<Api>` carries both).
@@ -163,9 +180,32 @@ export async function runOneDelegation(
163
180
  const request = { task: spec.task, agent: spec.agent, tools: spec.tools, model: spec.model ?? defaultModel };
164
181
  const extra = { fanoutBudget: budget, spawnId: ids.parentId, childSpawnId: ids.childId };
165
182
 
183
+ // ADR-0031: herdr was DEMANDED (`PI_GRANTS_HERDR=1`) and is not answering. Refused rather than relocated —
184
+ // the operator chose that over falling back, so the ledger can never name a child that ran somewhere nobody
185
+ // chose.
186
+ //
187
+ // **Decided BEFORE the gate, and the ordering is a fix.** This sat after `planWithApprovals`, which opens the
188
+ // approval dialog — so with herdr down a human was asked to approve `tool:bash`, answered *Always*, and was
189
+ // then refused anyway. Measured: the answer still reached `process.env.PI_GRANTS_APPROVED`, still wrote a
190
+ // **30-day project-wide** entry to the persisted store, and still produced a ledger line asserting a human
191
+ // approved `bash` for a child that never existed. A refused operation must not leave authority behind, and
192
+ // asking for permission that cannot be used is R-25's fatigue shape with nothing bought.
193
+ //
194
+ // `ctx: null` rather than skipping the plan entirely: the ledger still gets a full, honest record of what was
195
+ // requested and refused, and stored approvals still count toward it — nothing is *hidden*, only nobody is
196
+ // *asked*. It is the same argument `/grants` uses for its preview.
197
+ const refusal = session.executor.refusal;
166
198
  // Planning and the gate live in `planWithApprovals`, shared with the `/grants` preview so the two cannot
167
- // disagree (R-38). This call is the enforcing one: it passes `ctx`, so a human CAN be asked.
168
- let { plan, approval: approvalOutcome } = await planWithApprovals(session, request, extra, ctx, signal);
199
+ // disagree (R-38). This call is the enforcing one when a human may be asked: `ctx` is passed unless the
200
+ // executor has already made the outcome certain.
201
+ let { plan, approval: approvalOutcome } = await planWithApprovals(session, request, extra, refusal ? null : ctx, signal);
202
+
203
+ // Applied in front of the ledger write below, so the record describes a refusal rather than a spawn. Turning
204
+ // `plan.ok` off reuses the existing blocked-record path, so this adds a reason rather than a second refusal
205
+ // mechanism.
206
+ if (refusal) {
207
+ plan = { ...plan, ok: false, reason: `grants: ${refusal}` };
208
+ }
169
209
 
170
210
  // G6 / B-I3: no `&& plan.result` guard — `planDelegation` always carries one now.
171
211
  if (session.ledgerPath) {
@@ -179,6 +219,9 @@ export async function runOneDelegation(
179
219
  childId: ids.childId,
180
220
  depth: plan.childDepth,
181
221
  agentType: spec.agent ?? "delegate",
222
+ // ADR-0031: where this child actually ran. Read off the live session, which the probe has settled
223
+ // by now, so the record and the executor cannot disagree.
224
+ executor: session.executor.kind,
182
225
  requested: plan.requested,
183
226
  parentGrant: session.ownGrant,
184
227
  result: plan.result,
@@ -208,10 +251,14 @@ export async function runOneDelegation(
208
251
  // G8: bounded output, a wall-clock timeout with SIGTERM->SIGKILL escalation, and an abort observed
209
252
  // even if it happened before we got here. See src/run-child.ts for why each one exists.
210
253
  //
211
- // ADR-0016 point 6: two executors, one plan. `runChild` is the default because it needs nothing
212
- // installed; herdr gives the same governed argv a VISIBLE, attachable pane. Opt-in per session rather
213
- // than auto-detected — a governed run must not silently relocate because a binary is on PATH.
214
- const output = session.useHerdr
254
+ // ADR-0016 point 6: two executors, one plan. `runChild` needs nothing installed; herdr gives the same
255
+ // governed argv a VISIBLE, attachable pane.
256
+ //
257
+ // **Which one is chosen was reversed by ADR-0031**: the session probes for a reachable herdr server at
258
+ // startup rather than waiting to be told. Still never detected from a binary on `PATH` — only from a server
259
+ // that answered — and the choice is disclosed at session start, in `/grants`, and per child in the ledger.
260
+ // Read live off `session.executor`, because the probe finishes after this module is loaded.
261
+ const output = session.executor.kind === "herdr"
215
262
  ? await runHerdrPane({
216
263
  args: plan.args.slice(0, -1),
217
264
  // The task is delivered as a prompt, so it never reaches argv at all. `plan.args` still ends
@@ -223,10 +270,22 @@ export async function runOneDelegation(
223
270
  env: plan.env,
224
271
  cwd: ctx.cwd,
225
272
  name: `${spec.agent ?? "delegate"}-${ids.childId}`,
226
- workspace: process.env[ENV_HERDR_WORKSPACE],
273
+ // Was `process.env[ENV_HERDR_WORKSPACE]`, i.e. "omitted lets herdr choose" — which put children in a
274
+ // different workspace from the pi session that spawned them, so switching to one meant hopping
275
+ // workspaces rather than tabs. `resolveWorkspace` prefers the operator's explicit answer and otherwise
276
+ // inherits the parent's own `HERDR_WORKSPACE_ID` (measured; herdr sets it in every pane it creates).
277
+ workspace: resolveWorkspace(process.env),
227
278
  signal,
228
279
  timeoutMs: timeoutFromEnv(process.env[ENV_CHILD_TIMEOUT]),
229
280
  keepPane: process.env[ENV_HERDR_KEEP_PANE] === "1",
281
+ // ADR-0032. The pane id arrives first and is what a human switches to; the pane's tail follows as the
282
+ // child works. Both are display only.
283
+ //
284
+ // `snapshot`, not `chunk`: `agent read` returns a snapshot of a bounded terminal, and the sink must
285
+ // REPLACE what it holds. Treating it as a stream produced an 89,000× amplification and fabricated lines
286
+ // the child never printed — see `tailLines` in `src/herdr-poll.ts`.
287
+ onPane: onProgress ? (paneId, agentName) => onProgress({ paneId, agentName, state: "running" }) : undefined,
288
+ onSnapshot: onProgress ? (snapshot) => onProgress({ snapshot }) : undefined,
230
289
  })
231
290
  : await runChild({
232
291
  command: "pi",
@@ -238,6 +297,9 @@ export async function runOneDelegation(
238
297
  cwd: ctx.cwd,
239
298
  signal,
240
299
  timeoutMs: timeoutFromEnv(process.env[ENV_CHILD_TIMEOUT]),
300
+ // No pane on this path, so streaming is the ONLY observability a subprocess child can have — which is
301
+ // why ADR-0032 chose the streaming option over status lines alone.
302
+ onOutput: onProgress ? (chunk) => onProgress({ chunk }) : undefined,
241
303
  });
242
304
 
243
305
  // G8: a child that failed is reported as a failure. A non-zero exit, a timeout and a truncated flood