@arcforge/types 2.0.162 → 2.0.164

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.
@@ -1,5 +1,6 @@
1
1
  import { resolveIsolation } from "./policy-resolve"
2
- import type { CapsulePolicy, PolicyBucket, PolicyRule } from "./policy"
2
+ import { isRulePair } from "./policy"
3
+ import type { CapsulePolicy, EffectiveRule, PolicyBucket, PolicyRule, ResolvedCapsulePolicy, ResolvedToolBag, ResolvedToolEntry, ToolBucket, ToolRule } from "./policy"
3
4
 
4
5
  /**
5
6
  * The key a blanket rule normalises to — see `PolicyBucket`.
@@ -13,7 +14,7 @@ import type { CapsulePolicy, PolicyBucket, PolicyRule } from "./policy"
13
14
  export const POLICY_WILDCARD = "*"
14
15
 
15
16
  /** A rule with no keys of its own — `true`, `false`, `"escalate"`, or a glob object. */
16
- function isBareRule(value: PolicyBucket | Partial<CapsulePolicy["process"]>): value is PolicyRule {
17
+ function isBareRule(value: PolicyBucket): value is PolicyRule {
17
18
  if (typeof value === "boolean" || value === "escalate") return true
18
19
  // The glob object form. Distinguished from a keyed bucket by its OWN keys:
19
20
  // `allow`/`deny`/`escalate` are the rule's vocabulary, and a bucket keyed
@@ -29,17 +30,37 @@ function bucket(value: PolicyBucket | undefined): Record<string, PolicyRule> {
29
30
  return isBareRule(value) ? { [POLICY_WILDCARD]: value } : value
30
31
  }
31
32
 
32
- export type NormalizedPolicy = Omit<AuthoredPolicy, "tools" | "network" | "process"> & {
33
- tools?: Record<string, PolicyRule>
34
- network?: Record<string, PolicyRule>
35
- process?: Partial<CapsulePolicy["process"]>
33
+ /** bucket(), for the one surface whose entries may be per-member bags. */
34
+ function toolBucket(value: ToolBucket | undefined): Record<string, ToolRule> {
35
+ if (value === undefined) return {}
36
+ return isBareRule(value) ? { [POLICY_WILDCARD]: value } : value
36
37
  }
37
38
 
38
- /** A policy as a human authored it — bare rules still un-expanded. */
39
- export type AuthoredPolicy = Omit<Partial<CapsulePolicy>, "tools" | "network" | "process"> & {
40
- tools?: PolicyBucket
41
- network?: PolicyBucket
42
- process?: Partial<CapsulePolicy["process"]> | PolicyRule
39
+ /**
40
+ * One entry in the `tools` map: a verdict for the whole name, or a bag of
41
+ * per-member verdicts one level deep (`fs: { read: true }`).
42
+ *
43
+ * Bags are an AGENT-side facility only — see mergeTools below.
44
+ */
45
+ export type ToolPolicyEntry = ResolvedToolEntry
46
+
47
+ export type NormalizedPolicy = Omit<AuthoredPolicy, "tools" | "shell"> & {
48
+ tools?: Record<string, ToolPolicyEntry>
49
+ shell?: NonNullable<ResolvedCapsulePolicy["shell"]>
50
+ }
51
+
52
+ /**
53
+ * A policy as a human authored it — bare rules still un-expanded.
54
+ *
55
+ * `net`, `env` and `limits` are already in their final shape: they are lists
56
+ * and scalars, not rule maps, so there is no bare form to expand. Only `tools`
57
+ * (a keyed bucket) and `shell` (a bare verdict standing for the whole surface)
58
+ * need normalising.
59
+ */
60
+ export type AuthoredPolicy = Omit<Partial<CapsulePolicy>, "tools" | "shell"> & {
61
+ tools?: ToolBucket
62
+ /** `shell: false` is the common statement and expands to a full deny. */
63
+ shell?: NonNullable<CapsulePolicy["shell"]> | boolean
43
64
  }
44
65
 
45
66
  /**
@@ -47,21 +68,52 @@ export type AuthoredPolicy = Omit<Partial<CapsulePolicy>, "tools" | "network" |
47
68
  *
48
69
  * `tools: "escalate"` and `tools: { "*": "escalate" }` are the same statement;
49
70
  * this makes them the same VALUE, so nothing downstream has to ask which was
50
- * written. `process` is a fixed pair rather than an open bucket, so a bare rule
51
- * there applies to both verbs instead of becoming a key no verb would match.
71
+ * written. `shell` takes a bare boolean for the same reason, expanded into the
72
+ * full block rather than becoming a key no verb would match.
52
73
  */
53
74
  export function keyed(policy: AuthoredPolicy): NormalizedPolicy {
54
- const { tools, network, process: proc, ...rest } = policy
75
+ const { tools, shell, ...rest } = policy
55
76
  return {
56
77
  ...rest,
57
- ...(tools !== undefined ? { tools: bucket(tools) } : {}),
58
- ...(network !== undefined ? { network: bucket(network) } : {}),
59
- ...(proc !== undefined
60
- ? { process: isBareRule(proc) ? { spawn: proc, run: proc } : proc }
78
+ ...(tools !== undefined ? { tools: toolBucket(tools) } : {}),
79
+ // `shell: false` — the whole surface off — is the statement most
80
+ // policies want, so it is authorable as a bare boolean and expanded
81
+ // here into the deny-everything form the enforcer reads.
82
+ ...(shell !== undefined
83
+ ? { shell: typeof shell === "boolean" ? shellFromBare(shell) : shell }
61
84
  : {}),
62
85
  }
63
86
  }
64
87
 
88
+ /**
89
+ * `shell: true` / `shell: false` as a full shell block.
90
+ *
91
+ * `false` is a total denial: no program, and explicitly no raw shell. `true`
92
+ * grants execution but STILL leaves `raw` off — turning on shell access should
93
+ * not silently also hand over `sh -c`, which is the one switch that makes every
94
+ * other rule in this surface unenforceable.
95
+ */
96
+ /**
97
+ * An already-resolved pair cannot itself be a ceiling operand.
98
+ *
99
+ * Intersection runs over AUTHORED policies, where every slot is a plain rule.
100
+ * A pair only ever appears in this function's OUTPUT, so encountering one on
101
+ * the way in means a resolved policy was fed back through the resolver — a
102
+ * wiring fault, and one that would silently drop a layer if it were coerced.
103
+ */
104
+ function asRule(rule: ToolPolicyEntry | undefined): PolicyRule | undefined {
105
+ if (isRulePair(rule)) throw new Error("POLICY_ALREADY_RESOLVED: cannot intersect a resolved rule pair")
106
+ // A bag reaching here is a caller error the same way a pair is: bags are
107
+ // handled by mergeTools before this point, so one arriving means the two
108
+ // branches disagree about what shape they are looking at.
109
+ if (isMemberBag(rule)) throw new Error("POLICY_BAG_NOT_A_RULE: a member bag has no single verdict")
110
+ return rule
111
+ }
112
+
113
+ function shellFromBare(allowed: boolean): NonNullable<CapsulePolicy["shell"]> {
114
+ return allowed ? { allow: ["*"], raw: false } : { allow: [], deny: ["*"], raw: false, spawn: false }
115
+ }
116
+
65
117
  /**
66
118
  * One capability's rule under both layers.
67
119
  *
@@ -69,23 +121,107 @@ export function keyed(policy: AuthoredPolicy): NormalizedPolicy {
69
121
  * pattern and cannot be widened at all. Otherwise the agent's rule stands and
70
122
  * the profile's is carried alongside for the mediator to evaluate against.
71
123
  */
72
- function pairRule(profile: PolicyRule | undefined, agent: PolicyRule | undefined): PolicyRule {
124
+ function pairRule(profile: PolicyRule | undefined, agent: PolicyRule | undefined): EffectiveRule {
73
125
  if (profile === false) return false
74
126
  if (profile === "escalate" && agent !== false) return "escalate"
75
127
  if (profile === undefined) return agent ?? true
76
128
  if (profile === true) return agent ?? true
77
- // Profile is glob-shaped: the agent narrows within it, and the pair is
78
- // evaluated per call. With no agent rule, the profile IS the rule.
79
- return agent ?? profile
129
+ // Profile is glob-shaped. With no agent rule the profile IS the rule.
130
+ if (agent === undefined) return profile
131
+ // A bare agent verdict cannot widen a glob ceiling, but it can narrow: a
132
+ // `false` is final, and an `escalate` is stricter than any allow the
133
+ // profile's globs could produce.
134
+ if (agent === false) return false
135
+ if (agent === "escalate") return "escalate"
136
+ // `agent === true` does NOT collapse to true — that would discard the
137
+ // ceiling entirely. The profile's globs still bind, so the profile stands
138
+ // alone as the rule.
139
+ if (agent === true) return profile
140
+ // Both glob-shaped: carry BOTH. Collapsing here is what let an agent's
141
+ // allowlist widen past its profile's — see PolicyRulePair.
142
+ return { profile, agent }
143
+ }
144
+
145
+ /**
146
+ * The `tools` ceiling merge — pairRules, plus the bag case.
147
+ *
148
+ * A PROFILE rule is always a bare verdict or a glob: per-member bags are an
149
+ * AGENT-side facility, deliberately. A profile ceiling is a blunt instrument
150
+ * — "this machine does not do filesystem writes" — and it holds however the
151
+ * agent's tool surface changes. Per-member precision belongs to the agent,
152
+ * which is the only layer that knows what it actually installed.
153
+ *
154
+ * So a bag is never intersected member-by-member. The profile's verdict for
155
+ * the whole name applies to everything under it: a profile `fs: false`
156
+ * denies the bag outright, no matter what the agent wrote inside it, and a
157
+ * profile that says nothing lets the bag stand as authored.
158
+ *
159
+ * That keeps the ceiling honest without inventing intersection semantics for
160
+ * a case nobody has asked for — and it means a bag can never be the thing
161
+ * that widens a permission.
162
+ */
163
+ function mergeTools(
164
+ profile: Record<string, ToolPolicyEntry> | undefined,
165
+ agent: Record<string, ToolPolicyEntry> | undefined,
166
+ ): Record<string, ToolPolicyEntry> {
167
+ const keys = new Set([...Object.keys(profile ?? {}), ...Object.keys(agent ?? {})])
168
+ const out: Record<string, ToolPolicyEntry> = {}
169
+ const blanket = profile?.[POLICY_WILDCARD]
170
+
171
+ for (const key of keys) {
172
+ const agentEntry = agent?.[key]
173
+ const profileEntry = profile?.[key] ?? blanket
174
+
175
+ if (isMemberBag(agentEntry)) {
176
+ // The ceiling still binds — it just binds to the whole bag.
177
+ // `false` and `"escalate"` are final either way; anything else
178
+ // leaves the agent's per-member rules exactly as written.
179
+ if (profileEntry === false) { out[key] = false; continue }
180
+ if (profileEntry === "escalate") { out[key] = "escalate"; continue }
181
+ out[key] = agentEntry
182
+ continue
183
+ }
184
+
185
+ // A profile bag is not a thing. Treated as "no opinion" rather than
186
+ // silently half-applied, so a mistyped ceiling cannot read as a
187
+ // narrower one than it is.
188
+ const ceiling = isMemberBag(profileEntry) ? undefined : profileEntry
189
+ out[key] = pairRule(asRule(ceiling), asRule(agentEntry as ToolPolicyEntry | undefined))
190
+ }
191
+
192
+ return out
193
+ }
194
+
195
+ /**
196
+ * A per-member bag rather than a verdict for the whole name.
197
+ *
198
+ * Both are objects, so the KEYS decide: a glob `PolicyRule` carries only
199
+ * `allow`/`deny`/`escalate`; anything else is a member name. An empty object
200
+ * is a rule — `{}` states nothing about any member.
201
+ *
202
+ * EXPORTED because the mediator asks the same question at call time. Two
203
+ * copies of this test would be two chances for a rule to normalise as one
204
+ * shape and evaluate as the other, which is a silent permission change.
205
+ */
206
+ export function isMemberBag(entry: ToolPolicyEntry | undefined): entry is ResolvedToolBag {
207
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return false
208
+ const keys = Object.keys(entry)
209
+ if (keys.length === 0) return false
210
+ // A carried PAIR is also an object, and its keys are `profile`/`agent` —
211
+ // neither a rule's vocabulary nor a member name. Excluded explicitly, or a
212
+ // ceiling-resolved rule would be walked as though it were a bag of two
213
+ // tools called "profile" and "agent".
214
+ if ("profile" in entry && "agent" in entry) return false
215
+ return !keys.some(key => key === "allow" || key === "deny" || key === "escalate")
80
216
  }
81
217
 
82
218
  /** pairRule across two keyed maps, over the union of their keys. */
83
219
  function pairRules(
84
- profile: Record<string, PolicyRule> | undefined,
85
- agent: Record<string, PolicyRule> | undefined,
86
- ): Record<string, PolicyRule> {
220
+ profile: Record<string, EffectiveRule> | undefined,
221
+ agent: Record<string, EffectiveRule> | undefined,
222
+ ): Record<string, EffectiveRule> {
87
223
  const keys = new Set([...Object.keys(profile ?? {}), ...Object.keys(agent ?? {})])
88
- const out: Record<string, PolicyRule> = {}
224
+ const out: Record<string, EffectiveRule> = {}
89
225
 
90
226
  // A profile WILDCARD applies to every key, not only to `*`.
91
227
  //
@@ -101,7 +237,7 @@ function pairRules(
101
237
  // the verdict can still name which layer decided.
102
238
  const blanket = profile?.[POLICY_WILDCARD]
103
239
 
104
- for (const key of keys) out[key] = pairRule(profile?.[key] ?? blanket, agent?.[key])
240
+ for (const key of keys) out[key] = pairRule(asRule(profile?.[key] ?? blanket), asRule(agent?.[key]))
105
241
  return out
106
242
  }
107
243
 
@@ -156,16 +292,113 @@ export function intersect(
156
292
  ...(profile.fs ? { fs: profile.fs } : {}),
157
293
  ...(profile.limits ? { limits: profile.limits } : {}),
158
294
 
159
- ...(profile.network || agent.network
160
- ? { network: pairRules(profile.network, agent.network) }
295
+ // ── net: the LIST intersection ─────────────────────────────────────
296
+ //
297
+ // Not pairRules: there are no per-key verdicts to rank. A ceiling over
298
+ // two allowlists is their INTERSECTION — a destination must be admitted
299
+ // by both layers — and the denylists UNION, because either layer
300
+ // refusing is a refusal. This is the one surface where merging is not
301
+ // only safe but required, precisely because there are no globs to
302
+ // widen: entries are literal hosts and the intersection of two literal
303
+ // sets cannot contain a member neither set had.
304
+ ...(profile.net || agent.net ? { net: mergeNet(profile.net, agent.net) } : {}),
305
+
306
+ // env: same shape, same reasoning. A host variable must be granted by
307
+ // both layers to cross into the box.
308
+ ...(profile.env || agent.env
309
+ ? { env: { allow: intersectLists(profile.env?.allow, agent.env?.allow) } }
161
310
  : {}),
311
+
162
312
  ...(profile.tools || agent.tools
163
- ? { tools: pairRules(profile.tools, agent.tools) }
313
+ ? { tools: mergeTools(profile.tools, agent.tools) }
164
314
  : {}),
165
315
 
166
- process: {
167
- spawn: pairRule(profile.process?.spawn, agent.process?.spawn),
168
- run: pairRule(profile.process?.run, agent.process?.run),
316
+ ...(profile.shell || agent.shell ? { shell: mergeShell(profile.shell, agent.shell) } : {}),
317
+ }
318
+ }
319
+
320
+
321
+ /**
322
+ * Two allowlists under a ceiling: what BOTH layers admit.
323
+ *
324
+ * `undefined` from a layer is "no opinion" and defers to the other — the same
325
+ * silence rule the verdict resolver uses. Two present lists intersect, so a
326
+ * profile can only ever shrink what an agent reaches.
327
+ */
328
+ function intersectLists(profile: string[] | undefined, agent: string[] | undefined): string[] {
329
+ if (profile === undefined) return agent ?? []
330
+ if (agent === undefined) return profile
331
+ const ceiling = new Set(profile)
332
+ return agent.filter(entry => ceiling.has(entry))
333
+ }
334
+
335
+ /** Either layer's denial stands. */
336
+ function unionLists(profile: string[] | undefined, agent: string[] | undefined): string[] {
337
+ return [...new Set([...(profile ?? []), ...(agent ?? [])])]
338
+ }
339
+
340
+ /**
341
+ * The `net` ceiling: allowlists intersect, denylists union.
342
+ *
343
+ * `dns` takes the STRICTER setting rather than the agent's, ranked
344
+ * off < allowlist < open — a profile that closed DNS cannot be reopened by an
345
+ * agent declaring `"open"`.
346
+ */
347
+ const DNS_RANK = { off: 0, allowlist: 1, open: 2 } as const
348
+
349
+ function mergeNet(
350
+ profile: CapsulePolicy["net"],
351
+ agent: CapsulePolicy["net"],
352
+ ): NonNullable<CapsulePolicy["net"]> {
353
+ const dns = ((): NonNullable<CapsulePolicy["net"]>["dns"] | undefined => {
354
+ if (profile?.dns === undefined) return agent?.dns
355
+ if (agent?.dns === undefined) return profile.dns
356
+ return DNS_RANK[agent.dns] < DNS_RANK[profile.dns] ? agent.dns : profile.dns
357
+ })()
358
+
359
+ return {
360
+ allow: intersectLists(profile?.allow, agent?.allow),
361
+ deny: unionLists(profile?.deny, agent?.deny),
362
+ ...(dns !== undefined ? { dns } : {}),
363
+ }
364
+ }
365
+
366
+ /**
367
+ * The `shell` ceiling.
368
+ *
369
+ * Programs intersect and denials union, like `net`. `raw` is an AND: a shell is
370
+ * available only if both layers permit it, so a profile turning it off holds
371
+ * against every agent. `args` pairs per program through the ordinary rule
372
+ * ceiling, since those ARE glob rules with verdicts.
373
+ */
374
+ function mergeShell(
375
+ profile: NormalizedPolicy["shell"],
376
+ agent: NormalizedPolicy["shell"],
377
+ ): NonNullable<ResolvedCapsulePolicy["shell"]> {
378
+ const spawnRule = (entry: NormalizedPolicy["shell"]) =>
379
+ (entry?.spawn !== null && typeof entry?.spawn === "object" && "rule" in entry.spawn
380
+ ? entry.spawn.rule
381
+ : entry?.spawn as EffectiveRule | undefined)
382
+ const spawnMax = (entry: NormalizedPolicy["shell"]) =>
383
+ (entry?.spawn !== null && typeof entry?.spawn === "object" && "max" in entry.spawn
384
+ ? entry.spawn.max
385
+ : undefined)
386
+
387
+ const maxes = [spawnMax(profile), spawnMax(agent)].filter((n): n is number => typeof n === "number")
388
+
389
+ return {
390
+ allow: intersectLists(profile?.allow, agent?.allow),
391
+ deny: unionLists(profile?.deny, agent?.deny),
392
+ ...(profile?.args || agent?.args
393
+ ? { args: pairRules(profile?.args, agent?.args) }
394
+ : {}),
395
+ // Both must permit it. Absent means "no opinion", which for the one
396
+ // switch that disarms every other rule defaults CLOSED.
397
+ raw: (profile?.raw ?? false) && (agent?.raw ?? false),
398
+ spawn: {
399
+ rule: pairRule(asRule(spawnRule(profile)), asRule(spawnRule(agent))),
400
+ // The tighter cap wins; no cap on either side means unlimited.
401
+ ...(maxes.length > 0 ? { max: Math.min(...maxes) } : {}),
169
402
  },
170
403
  }
171
404
  }
@@ -1,4 +1,5 @@
1
- import type { CapsulePolicy, PolicyRule, PolicyVerdictSource } from "./policy"
1
+ import { isRulePair } from "./policy"
2
+ import type { CapsulePolicy, EffectiveRule, PolicyRule, PolicyVerdictSource } from "./policy"
2
3
 
3
4
  /**
4
5
  * Resolving two policy layers into one verdict — the ceiling model.
@@ -93,12 +94,23 @@ export function policyGlobMatch(pattern: string, value: string): boolean {
93
94
  * authoring order, so a user cannot accidentally out-order their own denial.
94
95
  */
95
96
  export function evaluateRule(
96
- rule: PolicyRule | undefined,
97
+ rule: EffectiveRule | undefined,
97
98
  subject: string,
98
99
  layer: PolicyVerdictSource["layer"],
99
100
  ): ResolvedVerdict | undefined {
100
101
  if (rule === undefined) return undefined
101
102
 
103
+ // A carried pair is TWO layers that both declared a glob rule. Each is
104
+ // evaluated against the subject on its own and the stricter wins — the
105
+ // ceiling, applied at the only moment it can be: when there is a concrete
106
+ // subject to match. Merging them into one rule at the seam is what let an
107
+ // agent allowlist widen past its profile's; see PolicyRulePair.
108
+ //
109
+ // The `layer` argument is ignored for a pair, deliberately: the whole point
110
+ // is that the answer names which of the two decided, so a caller-supplied
111
+ // label would be a lie half the time.
112
+ if (isRulePair(rule)) return resolveVerdict(rule.profile, rule.agent, subject)
113
+
102
114
  if (rule === true) return { verdict: "allow", source: { layer, subject, rule } }
103
115
  if (rule === false) return { verdict: "deny", source: { layer, subject, rule } }
104
116
  if (rule === "escalate") return { verdict: "escalate", source: { layer, subject, rule } }
@@ -0,0 +1,189 @@
1
+ import { isRulePair } from "./policy"
2
+ import { evaluateRule, policyGlobMatch, type PolicyVerdict, type ResolvedVerdict } from "./policy-resolve"
3
+ import type { EffectiveRule, ResolvedCapsulePolicy } from "./policy"
4
+
5
+ /**
6
+ * Deciding whether a program may run.
7
+ *
8
+ * ── Why this is not a glob against the command string ───────────────────────
9
+ *
10
+ * The old `process.run` rule matched one pattern against the whole command
11
+ * line, which is not enforceable against anything that is trying. The same
12
+ * effect reaches the same binary as `git push --force`, `git push --force`
13
+ * (two spaces), `env git push --force`, `/usr/bin/git push --force`, or
14
+ * `sh -c "git push --force"` — and a string matcher catches the first spelling
15
+ * only. An allowlist four spellings defeat is a linter wearing a security
16
+ * label.
17
+ *
18
+ * So the decision is made on the PROGRAM, normalised to a bare binary name
19
+ * before matching, with argument patterns as an explicitly secondary layer.
20
+ * Lives in @arcforge/types because the mediator, the capsule and `axon policy`
21
+ * must all answer this identically.
22
+ */
23
+
24
+ /** The shells whose whole purpose is to run an arbitrary command string. */
25
+ const SHELLS = new Set([
26
+ "sh", "bash", "zsh", "dash", "ksh", "fish", "csh", "tcsh", "ash", "busybox",
27
+ ])
28
+
29
+ /**
30
+ * Argv-ish wrappers that run ANOTHER program, hiding it from a naive read of
31
+ * argv[0].
32
+ *
33
+ * `env FOO=1 git push` execs git; a check that only looked at `env` would admit
34
+ * it. Each entry names how many leading tokens to skip before the real program
35
+ * appears — `env` takes assignments, so its tail is scanned rather than counted.
36
+ */
37
+ const WRAPPERS = new Set(["env", "nice", "nohup", "stdbuf", "setsid", "time", "timeout", "xargs"])
38
+
39
+ /** A program name stripped of its path: `/usr/bin/git` → `git`. */
40
+ export function programName(program: string): string {
41
+ const base = program.split("/").pop() ?? program
42
+ return base
43
+ }
44
+
45
+ /**
46
+ * The program a command line actually executes, seeing through wrappers.
47
+ *
48
+ * Returns the resolved program plus whether a SHELL was reached — the caller
49
+ * needs both, because a shell is gated by `raw` rather than by `allow`.
50
+ */
51
+ export function resolveProgram(argv: string[]): { program: string; shell: boolean; via: string[] } {
52
+ const via: string[] = []
53
+ let index = 0
54
+
55
+ while (index < argv.length) {
56
+ const name = programName(argv[index]!)
57
+ if (!WRAPPERS.has(name)) break
58
+ via.push(name)
59
+ index++
60
+ // `env` may carry KEY=VALUE assignments before the program.
61
+ if (name === "env") {
62
+ while (index < argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[index]!)) index++
63
+ }
64
+ // `timeout`/`nice` take a leading numeric/flag argument.
65
+ if ((name === "timeout" || name === "nice") && index < argv.length && /^-?\d/.test(argv[index]!)) index++
66
+ }
67
+
68
+ const program = programName(argv[index] ?? "")
69
+ return { program, shell: SHELLS.has(program), via }
70
+ }
71
+
72
+ export type ShellDecision = {
73
+ verdict: PolicyVerdict
74
+ /** The program the decision was made about, after unwrapping. */
75
+ program: string
76
+ /** Why, for the audit record and the model-facing denial. */
77
+ reason: "raw-shell" | "denied" | "not-allowed" | "args" | "allowed" | "no-policy"
78
+ source?: ResolvedVerdict["source"]
79
+ }
80
+
81
+ /**
82
+ * Decide one execution against the resolved `shell` policy.
83
+ *
84
+ * Order is deliberate and each step is a different question:
85
+ * 1. Is this a shell, and is `raw` off? A shell defeats every rule below it,
86
+ * so it is answered first and separately.
87
+ * 2. Does `deny` name the program? Deny always beats allow.
88
+ * 3. Does `allow` admit it? An allowlist that names nothing matching is a
89
+ * denial — the same "declared, matched nothing" rule the glob resolver uses.
90
+ * 4. Do the argument patterns object? Advisory, and last.
91
+ */
92
+ export function decideShell(
93
+ shell: ResolvedCapsulePolicy["shell"],
94
+ argv: string[],
95
+ /**
96
+ * What an UNDECLARED `shell` surface means.
97
+ *
98
+ * The two callers sit on opposite sides of a trust boundary and need
99
+ * opposite answers, which is why this is a parameter rather than a constant:
100
+ *
101
+ * "deny" — the CAPSULE. It runs foreign, model-emitted code and must
102
+ * never grant capability by omission. A bare `Capsule()` with no
103
+ * policy can run nothing.
104
+ * "allow" — AXON. It is wiring a box for its own declared blueprint, and
105
+ * "I did not set a security policy" means a personal tool with
106
+ * the user's own privileges, not a brick.
107
+ *
108
+ * Getting this wrong in either direction is silent: one bricks every
109
+ * unconfigured capsule, the other hands an unconfigured sandbox a shell.
110
+ */
111
+ fallback: "allow" | "deny" = "deny",
112
+ ): ShellDecision {
113
+ // No shell block at all: the caller's own default posture decides.
114
+ if (!shell) return { verdict: fallback, program: programName(argv[0] ?? ""), reason: "no-policy" }
115
+
116
+ const { program, shell: isShell } = resolveProgram(argv)
117
+
118
+ // A shell turns one grant into arbitrary execution. Gated on its own switch
119
+ // so `allow: ["git"]` cannot be quietly widened by `sh` being on the box.
120
+ if (isShell && shell.raw !== true) {
121
+ return { verdict: "deny", program, reason: "raw-shell" }
122
+ }
123
+
124
+ if (shell.deny?.some(pattern => policyGlobMatch(pattern, program))) {
125
+ return { verdict: "deny", program, reason: "denied" }
126
+ }
127
+
128
+ if (shell.allow !== undefined) {
129
+ const admitted = shell.allow.some(pattern => policyGlobMatch(pattern, program))
130
+ if (!admitted) return { verdict: "deny", program, reason: "not-allowed" }
131
+ }
132
+
133
+ // Argument patterns — advisory, and only consulted once the program itself
134
+ // is admitted. A rule here can still escalate or deny.
135
+ //
136
+ // Evaluated as a FILTER over an already-admitted program, not as an
137
+ // allowlist. `evaluateRule` treats "declared, matched nothing" as a denial,
138
+ // which is right for a rule that decides whether a capability exists at all
139
+ // and wrong here: `args: { git: { deny: ["push --force*"] } }` states one
140
+ // thing about `git push --force` and nothing whatsoever about `git status`.
141
+ // Reading its silence as a denial would mean naming a single forbidden flag
142
+ // silently forbade every other use of the program.
143
+ const argRule: EffectiveRule | undefined = shell.args?.[program]
144
+ if (argRule !== undefined) {
145
+ // Match against the argv TAIL — everything after the program itself —
146
+ // so a pattern reads as the arguments a user would type, not as a
147
+ // command line whose leading path they have to predict.
148
+ const at = argv.findIndex(entry => programName(entry) === program)
149
+ const tail = argv.slice(at + 1).join(" ")
150
+ const resolved = evaluateRule(argRule, tail, "agent")
151
+ const matched = resolved?.source?.pattern !== undefined || typeof argRule !== "object" || isRulePair(argRule)
152
+ if (resolved && resolved.verdict !== "allow" && matched) {
153
+ return { verdict: resolved.verdict, program, reason: "args", ...(resolved.source ? { source: resolved.source } : {}) }
154
+ }
155
+ }
156
+
157
+ return { verdict: "allow", program, reason: "allowed" }
158
+ }
159
+
160
+ /**
161
+ * Split a command STRING into argv for the decision above.
162
+ *
163
+ * Deliberately simple: it honours quotes so `git commit -m "a b"` is three
164
+ * arguments, and nothing else. It is not a shell parser and must never become
165
+ * one — if a caller needs `$(...)`, pipes or globbing expanded, what they
166
+ * actually have is a shell invocation, which `raw` governs.
167
+ */
168
+ export function splitCommand(command: string): string[] {
169
+ const argv: string[] = []
170
+ let current = ""
171
+ let quote: '"' | "'" | null = null
172
+ let has = false
173
+
174
+ for (const char of command) {
175
+ if (quote) {
176
+ if (char === quote) quote = null
177
+ else current += char
178
+ continue
179
+ }
180
+ if (char === '"' || char === "'") { quote = char; has = true; continue }
181
+ if (/\s/.test(char)) {
182
+ if (current || has) { argv.push(current); current = ""; has = false }
183
+ continue
184
+ }
185
+ current += char
186
+ }
187
+ if (current || has) argv.push(current)
188
+ return argv
189
+ }