pi-daddy 0.13.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 (105) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/LICENSE +21 -0
  3. package/README.md +584 -0
  4. package/dist/approval-prompt.d.ts +116 -0
  5. package/dist/approval-prompt.d.ts.map +1 -0
  6. package/dist/approval-prompt.js +124 -0
  7. package/dist/approval-prompt.js.map +1 -0
  8. package/dist/approval-store.d.ts +149 -0
  9. package/dist/approval-store.d.ts.map +1 -0
  10. package/dist/approval-store.js +311 -0
  11. package/dist/approval-store.js.map +1 -0
  12. package/dist/approval.d.ts +221 -0
  13. package/dist/approval.d.ts.map +1 -0
  14. package/dist/approval.js +244 -0
  15. package/dist/approval.js.map +1 -0
  16. package/dist/capabilities.d.ts +31 -0
  17. package/dist/capabilities.d.ts.map +1 -0
  18. package/dist/capabilities.js +45 -0
  19. package/dist/capabilities.js.map +1 -0
  20. package/dist/catalog.d.ts +81 -0
  21. package/dist/catalog.d.ts.map +1 -0
  22. package/dist/catalog.js +164 -0
  23. package/dist/catalog.js.map +1 -0
  24. package/dist/definitions.d.ts +101 -0
  25. package/dist/definitions.d.ts.map +1 -0
  26. package/dist/definitions.js +182 -0
  27. package/dist/definitions.js.map +1 -0
  28. package/dist/delegate.d.ts +133 -0
  29. package/dist/delegate.d.ts.map +1 -0
  30. package/dist/delegate.js +261 -0
  31. package/dist/delegate.js.map +1 -0
  32. package/dist/fanout.d.ts +62 -0
  33. package/dist/fanout.d.ts.map +1 -0
  34. package/dist/fanout.js +84 -0
  35. package/dist/fanout.js.map +1 -0
  36. package/dist/file-lock.d.ts +54 -0
  37. package/dist/file-lock.d.ts.map +1 -0
  38. package/dist/file-lock.js +142 -0
  39. package/dist/file-lock.js.map +1 -0
  40. package/dist/index.d.ts +7 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +7 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/ledger-report.d.ts +106 -0
  45. package/dist/ledger-report.d.ts.map +1 -0
  46. package/dist/ledger-report.js +157 -0
  47. package/dist/ledger-report.js.map +1 -0
  48. package/dist/ledger.d.ts +139 -0
  49. package/dist/ledger.d.ts.map +1 -0
  50. package/dist/ledger.js +94 -0
  51. package/dist/ledger.js.map +1 -0
  52. package/dist/pane-reaper.d.ts +49 -0
  53. package/dist/pane-reaper.d.ts.map +1 -0
  54. package/dist/pane-reaper.js +120 -0
  55. package/dist/pane-reaper.js.map +1 -0
  56. package/dist/pi-tools.d.ts +20 -0
  57. package/dist/pi-tools.d.ts.map +1 -0
  58. package/dist/pi-tools.js +21 -0
  59. package/dist/pi-tools.js.map +1 -0
  60. package/dist/propagation.d.ts +185 -0
  61. package/dist/propagation.d.ts.map +1 -0
  62. package/dist/propagation.js +255 -0
  63. package/dist/propagation.js.map +1 -0
  64. package/dist/resolve.d.ts +110 -0
  65. package/dist/resolve.d.ts.map +1 -0
  66. package/dist/resolve.js +181 -0
  67. package/dist/resolve.js.map +1 -0
  68. package/dist/run-child.d.ts +50 -0
  69. package/dist/run-child.d.ts.map +1 -0
  70. package/dist/run-child.js +109 -0
  71. package/dist/run-child.js.map +1 -0
  72. package/dist/run-herdr.d.ts +91 -0
  73. package/dist/run-herdr.d.ts.map +1 -0
  74. package/dist/run-herdr.js +306 -0
  75. package/dist/run-herdr.js.map +1 -0
  76. package/dist/spawn.d.ts +60 -0
  77. package/dist/spawn.d.ts.map +1 -0
  78. package/dist/spawn.js +116 -0
  79. package/dist/spawn.js.map +1 -0
  80. package/extensions/approvals.ts +285 -0
  81. package/extensions/delegation.ts +237 -0
  82. package/extensions/grants-command.ts +310 -0
  83. package/extensions/grants.ts +346 -0
  84. package/extensions/run-delegation.ts +270 -0
  85. package/extensions/session.ts +234 -0
  86. package/package.json +122 -0
  87. package/src/approval-prompt.ts +222 -0
  88. package/src/approval-store.ts +383 -0
  89. package/src/approval.ts +364 -0
  90. package/src/capabilities.ts +51 -0
  91. package/src/catalog.ts +186 -0
  92. package/src/definitions.ts +233 -0
  93. package/src/delegate.ts +383 -0
  94. package/src/fanout.ts +96 -0
  95. package/src/file-lock.ts +142 -0
  96. package/src/index.ts +59 -0
  97. package/src/ledger-report.ts +227 -0
  98. package/src/ledger.ts +214 -0
  99. package/src/pane-reaper.ts +132 -0
  100. package/src/pi-tools.ts +25 -0
  101. package/src/propagation.ts +308 -0
  102. package/src/resolve.ts +235 -0
  103. package/src/run-child.ts +149 -0
  104. package/src/run-herdr.ts +357 -0
  105. package/src/spawn.ts +156 -0
@@ -0,0 +1,308 @@
1
+ /**
2
+ * Race-free grant propagation.
3
+ *
4
+ * The first implementation wrote each child's computed grant into `process.env` inside the `tool_call`
5
+ * handler. The environment is process-global, so two concurrent spawns could read each other's values —
6
+ * a real hole in a security control.
7
+ *
8
+ * The fix removes the need for a per-child channel entirely, rather than trying to build one:
9
+ *
10
+ * 1. Everything pushed to children is a property of the PARENT, not of the individual spawn — the
11
+ * parent's own grant, the child depth (parent depth + 1), and the configured bounds. Those are
12
+ * identical for every sibling, so concurrent spawns cannot disagree and there is nothing to race.
13
+ * `ENV_APPROVED` (approvals a human granted at or above this level) is safe on the same global
14
+ * channel for the same reason: it is intersected with the parent's own grant before being written,
15
+ * which is itself a parent-level fact, so it too is identical for every sibling.
16
+ * 2. Each child derives ITS OWN grant on arrival: `inheritedParentGrant ∩ ownObservedTools`, where the
17
+ * observed set comes from the `tools` array of its first provider request — authoritative, because
18
+ * it is literally what pi sent the model.
19
+ *
20
+ * The environment is therefore written ONCE per session, before any spawn can occur (the first provider
21
+ * request precedes any tool call), and never mutated per spawn.
22
+ *
23
+ * The invariant still holds transitively: own = observed ∩ inheritedParent ⊆ inheritedParent, so no
24
+ * descendant can exceed the root. It is also defence in depth — even if a spawn slipped past the
25
+ * interceptor and pi handed the child more than the parent held, the intersection clamps it back.
26
+ */
27
+
28
+ import type { Capability } from "./resolve.ts";
29
+ import { WILDCARD } from "./pi-tools.ts";
30
+ import { inheritApprovals, type InheritableApproval } from "./approval.ts";
31
+
32
+ export const ENV_GRANT = "PI_GRANTS_GRANT";
33
+ /**
34
+ * Total descendants this session may create in its whole subtree (`src/fanout.ts`).
35
+ *
36
+ * In `GRANT_ENV_KEYS` and therefore stripped from a child's environment and re-supplied only by the spawn
37
+ * plan — like depth, and for the same reason: it is capability state that must ATTENUATE downward, not an
38
+ * operator preference that should inherit. `PI_GRANTS_CHILD_TIMEOUT` is deliberately the other kind.
39
+ */
40
+ export const ENV_FANOUT = "PI_GRANTS_FANOUT";
41
+ /**
42
+ * This session's ledger id, so a child's records name their real parent (review finding F8).
43
+ *
44
+ * Without it every level restarts at `d0` and the ledger cannot be joined into a tree across processes.
45
+ */
46
+ export const ENV_PARENT_ID = "PI_GRANTS_PARENT_ID";
47
+ export const ENV_DEPTH = "PI_GRANTS_DEPTH";
48
+ export const ENV_MAX_DEPTH = "PI_GRANTS_MAX_DEPTH";
49
+ export const ENV_GATED = "PI_GRANTS_GATED";
50
+ export const ENV_LEDGER = "PI_GRANTS_LEDGER";
51
+ export const ENV_APPROVED = "PI_GRANTS_APPROVED";
52
+
53
+ /**
54
+ * Every variable this package uses to push governance state at a child.
55
+ *
56
+ * Named as a set so `mergeChildEnv` can guarantee that none of them survives from the parent's own
57
+ * environment into a child's — a governance variable a child inherits by accident is one nobody decided
58
+ * to give it.
59
+ */
60
+ export const GRANT_ENV_KEYS = [
61
+ ENV_GRANT,
62
+ ENV_DEPTH,
63
+ ENV_MAX_DEPTH,
64
+ ENV_GATED,
65
+ ENV_LEDGER,
66
+ ENV_APPROVED,
67
+ ENV_FANOUT,
68
+ ENV_PARENT_ID,
69
+ ] as const;
70
+
71
+ export const parseList = (raw: string | undefined): Capability[] =>
72
+ (raw ?? "").split(",").map((s) => s.trim()).filter((s) => s.length > 0);
73
+
74
+ /** Does a bare pi tool name correspond to this capability? `read` matches `tool:read` and `ext:pkg/read`. */
75
+ function matchesToolName(capability: Capability, toolName: string): boolean {
76
+ if (capability === `tool:${toolName}`) return true;
77
+ return capability.startsWith("ext:") && capability.slice(capability.lastIndexOf("/") + 1) === toolName;
78
+ }
79
+
80
+ /**
81
+ * Is this capability something an observed tool array can speak about at all? (R-36, ADR-0017 step 1.)
82
+ *
83
+ * `tool:` and `ext:` name tools, so a tool array that omits one is evidence the session does not have it.
84
+ * `skill:` and `agent:` name a loadable instruction file and a spawnable definition — neither is ever a
85
+ * tool, so an observation says **nothing** about them and must not be read as evidence of absence.
86
+ */
87
+ const isToolCapability = (capability: Capability): boolean =>
88
+ capability.startsWith("tool:") || capability.startsWith("ext:");
89
+
90
+ /**
91
+ * Derive this session's own grant from what it inherited and what pi actually gave it.
92
+ *
93
+ * `observedTools` is the bare tool-name list from the session's own provider payload, or null when it
94
+ * has not been observed yet — in which case the inherited grant is used unchanged (it is already an
95
+ * upper bound, so this is safe, just less tight).
96
+ *
97
+ * A wildcard holder stays a wildcard holder: an enumerated observation must not silently downgrade an
98
+ * explicitly unlimited grant, or a root session would lose the authority it was configured with.
99
+ *
100
+ * **R-36 / ADR-0017 step 1: only tool-shaped capabilities are filtered.** The observation is a list of
101
+ * TOOLS, so it is evidence about `tool:` and `ext:` and about nothing else. Until this was fixed, a child
102
+ * inheriting `tool:read, skill:review` held only `tool:read` from its first provider request onward — it
103
+ * still *had* the skill (it arrives as `--skill`), but could not re-grant it and `/grants` stopped listing
104
+ * it. Silently, and in the narrowing direction, which is why it survived: nothing fails when a grant
105
+ * quietly shrinks. It also made ADR-0017's `agent:` prerequisite unsatisfiable below the root.
106
+ */
107
+ export function deriveOwnGrant(
108
+ inheritedParentGrant: Capability[],
109
+ observedTools: string[] | null,
110
+ ): Capability[] {
111
+ if (observedTools === null) return [...inheritedParentGrant];
112
+ // Capabilities an observation cannot speak about ride through both branches untouched.
113
+ const nonTool = inheritedParentGrant.filter((c) => !isToolCapability(c) && c !== WILDCARD);
114
+ if (inheritedParentGrant.includes(WILDCARD)) {
115
+ // Keep the wildcard, and additionally enumerate what was observed so descendants can be checked
116
+ // against concrete names too.
117
+ const enumerated = observedTools.map((t) => `tool:${t}`);
118
+ return [...new Set([WILDCARD, ...enumerated, ...nonTool])].sort();
119
+ }
120
+ return [
121
+ ...inheritedParentGrant.filter(
122
+ (c) => isToolCapability(c) && observedTools.some((t) => matchesToolName(c, t)),
123
+ ),
124
+ ...nonTool,
125
+ ].sort();
126
+ }
127
+
128
+ /**
129
+ * Parse a bound from the environment, distinguishing **absent** from **malformed**.
130
+ *
131
+ * G7 / A-S4 + B-I4. `Number.parseInt` is the wrong tool for reading configuration: it accepts a numeric
132
+ * prefix (`parseInt("2abc")` is `2`), returns `NaN` for anything else, and `NaN` silently passes every
133
+ * comparison as false — so a malformed `PI_GRANTS_MAX_DEPTH` did not tighten the limit, it removed it.
134
+ *
135
+ * The three-way return is the point. `undefined` means "not configured, use the documented default";
136
+ * `null` means "configured wrongly", which callers must treat as a failure rather than a default,
137
+ * because a value someone tried to set and mistyped is not the same as one they never set.
138
+ */
139
+ export function parseBound(raw: string | undefined): number | null | undefined {
140
+ if (raw === undefined) return undefined;
141
+ const trimmed = raw.trim();
142
+ // Exact non-negative decimal integers only: no signs, no fractions, no 0x, no numeric prefixes.
143
+ if (!/^\d+$/.test(trimmed)) return null;
144
+ const value = Number(trimmed);
145
+ return Number.isSafeInteger(value) ? value : null;
146
+ }
147
+
148
+ export interface DepthConfig {
149
+ depth: number;
150
+ maxDepth: number;
151
+ /** Names of the variables that were set but unreadable, for an operator-facing warning. */
152
+ malformed: string[];
153
+ }
154
+
155
+ /**
156
+ * Resolve this session's depth bounds, failing closed on anything malformed.
157
+ *
158
+ * **Malformed input disables spawning entirely (`maxDepth: 0`)** rather than falling back to a default,
159
+ * and that applies to a bad `PI_GRANTS_DEPTH` just as much as a bad `PI_GRANTS_MAX_DEPTH`. The old
160
+ * `|| 0` guard on depth failed open in a subtler way than the missing guard on maxDepth: a session that
161
+ * could not read its own depth was treated as a **root**, which is the most permissive answer available
162
+ * and precisely the value an attacker would choose. If we do not know how deep we are, we must not spawn.
163
+ */
164
+ export function depthConfig(depthRaw: string | undefined, maxDepthRaw: string | undefined): DepthConfig {
165
+ const depth = parseBound(depthRaw);
166
+ const maxDepth = parseBound(maxDepthRaw);
167
+ const malformed: string[] = [];
168
+ if (depth === null) malformed.push(ENV_DEPTH);
169
+ if (maxDepth === null) malformed.push(ENV_MAX_DEPTH);
170
+
171
+ if (malformed.length > 0) return { depth: depth ?? 0, maxDepth: 0, malformed };
172
+ return { depth: depth ?? 0, maxDepth: maxDepth ?? DEFAULT_MAX_DEPTH, malformed };
173
+ }
174
+
175
+ /** The documented default child-depth bound when `PI_GRANTS_MAX_DEPTH` is not set. */
176
+ export const DEFAULT_MAX_DEPTH = 2;
177
+
178
+ /**
179
+ * Gated by default in a governed session (ADR-0012).
180
+ *
181
+ * `bash` is not one capability among others; it is an execution primitive. A child holding it can run
182
+ * `env -u PI_GRANTS_GRANT pi …` and obtain a completely **ungoverned** descendant — measured, not
183
+ * theorised (`docs/probes/g5-bash-escape`). Handing that down silently is the thing worth changing.
184
+ *
185
+ * Subsumption-aware gating (also ADR-0012) means this single entry covers `write`, `edit`, `read`,
186
+ * `grep`, `find` and `ls` as well, since `bash` confers all of them.
187
+ */
188
+ export const DEFAULT_GATED: Capability[] = ["tool:bash"];
189
+
190
+ /**
191
+ * Read the gate list, distinguishing **absent** from **explicitly empty**.
192
+ *
193
+ * `parseList` alone cannot: it maps both `undefined` and `""` to `[]`. That distinction is the operator's
194
+ * only way to turn the default off — without it, someone who wants no gates would have to stop governing
195
+ * altogether, which is strictly worse than the thing they were trying to avoid.
196
+ */
197
+ export function gatedFromEnv(raw: string | undefined): Capability[] {
198
+ if (raw === undefined) return [...DEFAULT_GATED];
199
+ return parseList(raw);
200
+ }
201
+
202
+ export interface ChildEnvInput {
203
+ /** This session's own grant — becomes the child's inherited parent grant. */
204
+ ownGrant: Capability[];
205
+ /** This session's depth; children are one deeper. */
206
+ depth: number;
207
+ maxDepth: number;
208
+ gated: Capability[];
209
+ /**
210
+ * Gated capabilities a human approved at or above this level.
211
+ *
212
+ * Safe to push on the GLOBAL channel because it is intersected with THIS session's own grant, which is
213
+ * a parent-level fact — identical for every sibling, so there is nothing to race on. Each child then
214
+ * re-intersects with its own grant on arrival, exactly as it does for the grant itself.
215
+ */
216
+ /**
217
+ * Approvals eligible to cross the boundary (ADR-0014): capability, subject and scope. `once` is
218
+ * dropped by `inheritApprovals`, and the subject is preserved so it cannot satisfy another one.
219
+ */
220
+ approved?: InheritableApproval[];
221
+ ledgerPath?: string;
222
+ /**
223
+ * Whether THIS session is governed — i.e. `PI_GRANTS_GRANT` was set for it.
224
+ *
225
+ * G7 / B-I8. Governance is opt-in: with the variable unset the README promises "nothing is blocked".
226
+ * That was true of the session itself and false of its children, because this function still exported
227
+ * a grant, a depth and a bound, so an ungoverned parent silently started governing its descendants —
228
+ * and the grant it exported was its own observed tool surface, which is a real restriction arrived at
229
+ * by accident. An ungoverned session must be transparent, not a source of policy.
230
+ *
231
+ * Defaults to `true` so that every existing caller keeps publishing; only the extension, which alone
232
+ * knows whether the variable was set, passes `false`.
233
+ */
234
+ governed?: boolean;
235
+ }
236
+
237
+ /**
238
+ * The environment a child should inherit. Constant across all of this session's children by
239
+ * construction, which is what makes concurrent spawning safe.
240
+ *
241
+ * **The wildcard is never inherited.** A root may HOLD `tool:*` — that is authority to grant anything —
242
+ * but handing it down would let every descendant reacquire the full catalog, which makes attenuation
243
+ * meaningless below the root. Children therefore inherit the ENUMERATED grant only.
244
+ *
245
+ * Consequence, deliberate: a wildcard root that has not yet observed its own tools hands children an
246
+ * empty grant, so they can spawn nothing. That fails closed. It is also unreachable in normal flow,
247
+ * because a session's first provider request always precedes its first tool call.
248
+ */
249
+ export function childEnv(input: ChildEnvInput): Record<string, string> {
250
+ if (input.governed === false) return {};
251
+ const inheritable = input.ownGrant.filter((c) => c !== WILDCARD);
252
+ const env: Record<string, string> = {
253
+ [ENV_GRANT]: inheritable.join(","),
254
+ [ENV_DEPTH]: String(input.depth + 1),
255
+ [ENV_MAX_DEPTH]: String(input.maxDepth),
256
+ };
257
+ if (input.gated.length > 0) env[ENV_GATED] = input.gated.join(",");
258
+ // ALWAYS written, empty string included. This is the one value that changes during a session (a human
259
+ // approves something, or the session's own grant narrows on observation), and the interceptor path
260
+ // publishes it by ASSIGNING into the process-global `process.env`. Omitting it when empty would leave
261
+ // whatever was there before — the parent's own, unclamped `PI_GRANTS_APPROVED` — visible to every child.
262
+ // `parseList("")` is `[]`, so an empty value reads back exactly as an absent one.
263
+ env[ENV_APPROVED] = inheritApprovals(input.approved ?? [], inheritable).join(",");
264
+ if (input.ledgerPath) env[ENV_LEDGER] = input.ledgerPath;
265
+ return env;
266
+ }
267
+
268
+ /**
269
+ * The environment for a child this process spawns itself: the parent's environment with every governance
270
+ * variable stripped, then the per-child plan applied.
271
+ *
272
+ * Spreading `{ ...process.env, ...plan.env }` is not enough. `plan.env` omits keys that do not apply to
273
+ * this child (an empty approval set, no gated list), and an omitted key does not overwrite — so the
274
+ * parent's own value survives into the child. Stripping first makes the plan the ONLY source of every
275
+ * governance variable, which is what `delegate.ts`'s "nothing is written to the shared `process.env`"
276
+ * claim actually requires. Consumers re-clamp anyway; this is the defence in depth behind that.
277
+ */
278
+ export function mergeChildEnv(
279
+ parentEnv: NodeJS.ProcessEnv,
280
+ planEnv: Record<string, string>,
281
+ ): NodeJS.ProcessEnv {
282
+ const merged: NodeJS.ProcessEnv = { ...parentEnv };
283
+ for (const key of GRANT_ENV_KEYS) delete merged[key];
284
+ return { ...merged, ...planEnv };
285
+ }
286
+
287
+ /** Extract bare tool names from a provider payload's tool array, tolerating provider shape differences. */
288
+ export function observeToolNames(payload: unknown): string[] | null {
289
+ if (!payload || typeof payload !== "object") return null;
290
+ const record = payload as Record<string, unknown>;
291
+ for (const key of ["tools", "functions"]) {
292
+ const candidate = record[key];
293
+ if (!Array.isArray(candidate)) continue;
294
+ const names = candidate
295
+ .map((entry) => {
296
+ if (!entry || typeof entry !== "object") return undefined;
297
+ const e = entry as Record<string, unknown>;
298
+ // Anthropic/OpenAI tool objects, and OpenAI's nested `function.name` form.
299
+ const nested = e.function as Record<string, unknown> | undefined;
300
+ const name = e.name ?? nested?.name;
301
+ return typeof name === "string" ? name : undefined;
302
+ })
303
+ .filter((n): n is string => Boolean(n));
304
+ // An empty tools array is a real observation (the session has no tools), not a failure to observe.
305
+ return names;
306
+ }
307
+ return null;
308
+ }
package/src/resolve.ts ADDED
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Grant resolution — the entire security surface of capability governance, as a pure function.
3
+ *
4
+ * The invariant (ADR-0008): a capability set may only ever SHRINK as it passes down a delegation
5
+ * tree. Escalation is impossible by construction rather than by policy, because a parent can never
6
+ * confer what it does not itself hold.
7
+ *
8
+ * effective = ( requested ∩ parentGrant ∩ ceiling ) \ (gated \ approved)
9
+ *
10
+ * Being pure — no I/O, no model, no network — this is exhaustively testable, which matters because it
11
+ * is the only place an escalation could be introduced.
12
+ */
13
+
14
+ /** `tool:read` · `ext:pi-web-access/web_search` · `skill:review` · `agent:researcher` */
15
+ export type Capability = string;
16
+
17
+ /**
18
+ * Capabilities that transitively confer everything else. Granting one is equivalent to granting the
19
+ * whole catalog, so they can never be a *narrowing* grant.
20
+ *
21
+ * `ext:pi-fabric/fabric_exec` is here on measured evidence, not suspicion: a child granted
22
+ * `tools: []` (nothing at all) plus `recursive: true` still reached `pi.write` and `pi.bash` and
23
+ * spawned a grandchild that wrote to disk. See docs/probes/pi-fabric-eval (probes 2, 4, 7, 8).
24
+ */
25
+ export const UNIVERSAL_CAPABILITIES: readonly Capability[] = [
26
+ "ext:pi-fabric/fabric_exec",
27
+ "tool:fabric_exec",
28
+ ];
29
+
30
+ /**
31
+ * Capabilities that functionally contain others.
32
+ *
33
+ * `bash` can run `grep`, `find`, `ls`, `cat`, and `sed` — so a session holding it can already do
34
+ * everything the file and search tools do, whatever the tool list says. Modelling this explicitly serves
35
+ * two purposes:
36
+ *
37
+ * 1. It removes false escalation reports. pi's *default* surface is only `read`, `bash`, `edit`, `write`
38
+ * (measured, not assumed), so an agent type declaring `tools: read, grep, find, ls` would otherwise
39
+ * look like an escalation from any normal parent — despite being strictly weaker.
40
+ * 2. It makes the uncomfortable truth visible rather than implied: **a grant containing `bash` is not a
41
+ * narrow grant.** `subsumedBy` in the result says so, so a reviewer can see what the grant really means.
42
+ */
43
+ export const SUBSUMPTION: Readonly<Record<Capability, readonly Capability[]>> = {
44
+ "tool:bash": [
45
+ "tool:grep",
46
+ "tool:find",
47
+ "tool:ls",
48
+ "tool:read",
49
+ "tool:write",
50
+ "tool:edit",
51
+ "tool:edit-diff",
52
+ ],
53
+ };
54
+
55
+ /** Expand a grant to everything it functionally confers. */
56
+ export function expandSubsumed(grant: Capability[]): Capability[] {
57
+ const expanded = new Set(grant);
58
+ for (const held of grant) {
59
+ for (const implied of SUBSUMPTION[held] ?? []) expanded.add(implied);
60
+ }
61
+ return [...expanded].sort();
62
+ }
63
+
64
+ import { WILDCARD } from "./pi-tools.ts";
65
+
66
+ /**
67
+ * "Any definition" — ADR-0023, and one of two wildcards this module understands.
68
+ *
69
+ * Declared here rather than beside `WILDCARD` because `pi-tools.ts` imports `Capability` from this module.
70
+ * That import is `import type`, so it is erased and the runtime dependency runs one way only — which is
71
+ * what makes importing `WILDCARD` back safe.
72
+ *
73
+ * Deliberately weaker than `tool:*`: it confers **no tool authority**, so `agent:*,tool:read` may spawn
74
+ * every definition on disk and hand each of them nothing but `read`. It exists because the alternative was
75
+ * `tool:*` — authority to grant every tool — which made the safe configuration the laborious one.
76
+ */
77
+ export const AGENT_WILDCARD: Capability = "agent:*";
78
+
79
+ export interface ResolveInput {
80
+ /** What the delegating agent asked to give the child. */
81
+ requested: Capability[];
82
+ /** What the delegating agent itself holds. The root's grant is configured, never defaulted to all. */
83
+ parentGrant: Capability[];
84
+ /** Declarative maximum for the child's agent type (its frontmatter). Omit for no ceiling. */
85
+ ceiling?: Capability[];
86
+ /** Destructive capabilities that may never enter a grant without explicit human approval. */
87
+ gated?: Capability[];
88
+ /** Gated capabilities a human has approved for this specific spawn. */
89
+ approved?: Capability[];
90
+ /**
91
+ * Honour functional subsumption when deciding what the parent covers (default true).
92
+ * Set false for a strict name-equality check.
93
+ */
94
+ subsumption?: boolean;
95
+ }
96
+
97
+ export interface ResolveResult {
98
+ /** The capability set the child may hold. */
99
+ effective: Capability[];
100
+ /** Requested but NOT held by the parent — the escalation-attempt signal. Log every one. */
101
+ denied: Capability[];
102
+ /** Held by the parent but outside the child type's declared ceiling. */
103
+ clipped: Capability[];
104
+ /** Allowed by the tree but gated and unapproved. */
105
+ gatedBlocked: Capability[];
106
+ /** Universal capabilities that survived resolution — see `assertNarrowing`. */
107
+ universal: Capability[];
108
+ /**
109
+ * Capabilities the parent covers only through subsumption, not by holding them directly — e.g. `grep`
110
+ * covered because the parent holds `bash`. Non-empty means the grant is broader than its list suggests.
111
+ */
112
+ subsumedBy: Capability[];
113
+ }
114
+
115
+ const unique = (xs: Capability[]): Capability[] => [...new Set(xs)].sort();
116
+
117
+ /**
118
+ * Resolve a child's grant. Total and side-effect free; every rejected capability is reported rather
119
+ * than silently dropped, because a grant nobody can audit proves nothing.
120
+ */
121
+ export function resolve(input: ResolveInput): ResolveResult {
122
+ const requested = unique(input.requested);
123
+ const held = new Set(input.parentGrant);
124
+ const parent =
125
+ input.subsumption === false ? held : new Set(expandSubsumed(input.parentGrant));
126
+ /**
127
+ * `agent:*` covers any `agent:<name>` — ADR-0023, and the ONLY wildcard rule in this function.
128
+ *
129
+ * `resolve` is otherwise exact-match plus subsumption, deliberately: `tool:*` works not because anything
130
+ * here understands it, but because `deriveOwnGrant` *enumerates* a session's observed tool names beside
131
+ * it. Definitions are not tools, so nothing enumerates them — which is why `maySpawnDefinition` had to
132
+ * special-case the wildcard, and why this needs stating rather than falling out.
133
+ *
134
+ * Scoped to one namespace on purpose. There is no generalised `<ns>:*` rule, so a namespace added later
135
+ * does not silently acquire a wildcard; adding one is a deliberate edit and another decision.
136
+ */
137
+ const anyDefinition = held.has(AGENT_WILDCARD);
138
+ /**
139
+ * `tool:*` satisfies **any** capability, including `skill:` and `agent:` ids.
140
+ *
141
+ * Missing until 0.11.2, and the omission broke the one rule this package must never break by accident:
142
+ * *governance is opt-in*. An ungoverned session holds `[tool:*, …observed tools]` and nothing else, so
143
+ * spawning a definition whose `allowed-tools` names `agent:worker` or `skill:review` — the composition
144
+ * ADR-0017 created and ADR-0023's own example uses — was refused with **"capability escalation
145
+ * blocked"**, and recorded as an escalation attempt, in a session that had opted out.
146
+ *
147
+ * `maySpawnDefinition` had always honoured `tool:*` for definition ids and `docs/SPEC.md` had always
148
+ * claimed it "satisfies any capability". This function disagreed with both, which is R-28's shape: two
149
+ * spellings of one rule, and the enforcing one was wrong.
150
+ */
151
+ const anyCapability = held.has(WILDCARD);
152
+ const covered = (c: Capability): boolean =>
153
+ parent.has(c) || anyCapability || (anyDefinition && c.startsWith("agent:"));
154
+ const ceiling = input.ceiling === undefined ? null : new Set(input.ceiling);
155
+ const gated = new Set(input.gated ?? []);
156
+ const approved = new Set(input.approved ?? []);
157
+
158
+ // Order is irrelevant to the outcome (set intersection is commutative), so each rejection reason is
159
+ // reported independently rather than being masked by whichever filter happened to run first.
160
+ const denied = requested.filter((c) => !covered(c));
161
+ const clipped = requested.filter((c) => covered(c) && ceiling !== null && !ceiling.has(c));
162
+ /**
163
+ * Is this capability gated, directly or by subsuming something gated?
164
+ *
165
+ * ADR-0012. Exact-name gating was defeatable by handing down a broader capability: the package's own
166
+ * `SUBSUMPTION` table says `bash` confers `write`, so gating `write` produced **no prompt** when `bash`
167
+ * was granted instead. The gate read as satisfied because the string never appeared.
168
+ *
169
+ * The direction is load-bearing and easy to invert. A capability is gated when it **subsumes**
170
+ * something gated — never when it **is subsumed by** something gated. Gating `bash` must not quietly
171
+ * gate a plain `write` grant, which would make gating a broad capability restrict the narrow ones and
172
+ * invert least privilege.
173
+ */
174
+ const isGated = (c: Capability): boolean => {
175
+ if (gated.has(c)) return true;
176
+ if (input.subsumption === false) return false;
177
+ return (SUBSUMPTION[c] ?? []).some((implied) => gated.has(implied));
178
+ };
179
+
180
+ const gatedBlocked = requested.filter(
181
+ (c) => covered(c) && (ceiling === null || ceiling.has(c)) && isGated(c) && !approved.has(c),
182
+ );
183
+
184
+ const rejected = new Set([...denied, ...clipped, ...gatedBlocked]);
185
+ const effective = requested.filter((c) => !rejected.has(c));
186
+
187
+ return {
188
+ effective,
189
+ denied,
190
+ clipped,
191
+ gatedBlocked,
192
+ universal: effective.filter((c) => UNIVERSAL_CAPABILITIES.includes(c)),
193
+ // F9: capabilities covered by a WILDCARD are not "subsumed" — this field means "the grant is broader
194
+ // than its list suggests", which is the `bash`-covers-`grep` warning. A wildcard holder already knows
195
+ // its grant is broad; listing every id under it would bury the signal the field exists to carry.
196
+ subsumedBy: effective.filter((c) => !held.has(c) && !anyCapability && !(anyDefinition && c.startsWith("agent:"))),
197
+ };
198
+ }
199
+
200
+ /**
201
+ * Fail closed on a grant that cannot actually narrow anything.
202
+ *
203
+ * A universal capability in an "attenuated" grant is not a narrow grant with one extra item — it is
204
+ * full authority wearing a narrow grant's clothing. Callers must opt in explicitly rather than
205
+ * discover this at runtime.
206
+ */
207
+ export function assertNarrowing(result: ResolveResult, allowUniversal = false): void {
208
+ if (!allowUniversal && result.universal.length > 0) {
209
+ throw new Error(
210
+ `refusing to issue a grant containing universal capabilities: ${result.universal.join(", ")}. ` +
211
+ `These transitively confer the whole catalog, so the grant would not narrow anything. ` +
212
+ `Pass allowUniversal to override deliberately.`,
213
+ );
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Project an effective grant onto pi's `--tools` allowlist.
219
+ *
220
+ * pi core is the enforcement point — verified: `--tools` and `--no-tools` both hard-block extension
221
+ * tools, and an explicitly `-e`-loaded extension cannot re-add its tool past them
222
+ * (docs/probes/pi-fabric-eval probes 9–11). That is why enforcement needs no in-descendant runtime.
223
+ *
224
+ * Returns `null` when the grant contains no callable tools, meaning the caller should pass
225
+ * `--no-tools` rather than an empty `--tools` (an empty list is not a valid allowlist).
226
+ */
227
+ export function toPiToolsAllowlist(effective: Capability[]): string[] | null {
228
+ const names = effective
229
+ .filter((c) => c.startsWith("tool:") || c.startsWith("ext:"))
230
+ // `tool:read` -> `read`; `ext:pkg/web_search` -> `web_search` (pi matches on bare tool name)
231
+ .map((c) => (c.startsWith("tool:") ? c.slice(5) : c.slice(c.lastIndexOf("/") + 1)))
232
+ .filter((n) => n.length > 0);
233
+ const deduped = [...new Set(names)].sort();
234
+ return deduped.length > 0 ? deduped : null;
235
+ }