aegiscode 7.0.6 → 7.0.8

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.
@@ -0,0 +1,287 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * child.js — the Claude child's argv, DERIVED (AEGISONE, decision D8 rule 4).
10
+ *
11
+ * AEGISONE spawns `claude` for the Claude-Pro/BYOK path. That process runs its
12
+ * own permission system, and its prompts land on *its* stdin — which neither a
13
+ * GUI approval card nor the CLI's prompt loop can answer. The repo already ran
14
+ * this invocation for real (`benchmarks/frozen-run-final-noaider.json`):
15
+ *
16
+ * -p --output-format stream-json --dangerously-skip-permissions
17
+ * (ANTHROPIC_BASE_URL=api.deepseek.com/anthropic)
18
+ *
19
+ * Two bugs that shape every choice below:
20
+ *
21
+ * 1. **A hand-typed argv is a second decision.** If the spawn site writes its
22
+ * own flags, the child's policy and ours drift the moment either changes —
23
+ * and the child's is the one nobody can answer. So the argv is built here,
24
+ * from the posture record `one/src/permissions.js` already resolved, and
25
+ * the exact array is asserted by test (argv EQUALITY, not "a flag was
26
+ * passed"), for both child kinds.
27
+ * 2. **`-p` with an unanswered prompt is a HANG, not a refusal.** For a
28
+ * headless child the bypass is the derived skip; without it the child asks
29
+ * a question nobody can answer. The negative control for that lives with
30
+ * the runner (the "no one to answer it" path), and this module's half of it
31
+ * is that the headless argv carries NO permission flag when the posture
32
+ * says no skip — so the run fails fast instead of parking.
33
+ *
34
+ * ## Rule 4, in full
35
+ *
36
+ * headless `--dangerously-skip-permissions` iff our posture says skip;
37
+ * otherwise nothing at all (never a "harmless" default).
38
+ * interactive `--allow-dangerously-skip-permissions` instead — the same
39
+ * capability offered as an option rather than made the default,
40
+ * which is the narrowest thing that works and the variant
41
+ * Claude's own help describes as "without it being enabled by
42
+ * default".
43
+ * both `--allowedTools` / `--disallowedTools` from the SAME rule set
44
+ * (`allow` → allowed, `deny` → disallowed), so the child's policy
45
+ * tracks ours; `--permission-mode` only when it was explicitly
46
+ * given, validated against the CLI's own list, and ALWAYS
47
+ * recorded — recorded, never inferred.
48
+ *
49
+ * No `process.*` anywhere, module scope or not: the argv is a pure function of
50
+ * its descriptor, which is what makes the equality assertions above possible.
51
+ */
52
+
53
+ /** Rule 4's own flag spellings (verified against claude 2.1.228's --help). */
54
+ const FLAGS = Object.freeze({
55
+ headlessSkip: '--dangerously-skip-permissions',
56
+ interactiveSkip: '--allow-dangerously-skip-permissions',
57
+ permissionMode: '--permission-mode',
58
+ allowedTools: '--allowedTools',
59
+ disallowedTools: '--disallowedTools',
60
+ print: '-p',
61
+ outputFormat: '--output-format',
62
+ model: '--model',
63
+ // Conversation continuity for the Pro child (see `sessionId` below). Both
64
+ // spellings are the CLI's own (claude 2.1.228 --help): `--session-id <uuid>`
65
+ // names the session a NEW conversation runs in, `--resume <id>` reattaches to
66
+ // an existing one, which is what carries the prior turns' context across
67
+ // separate child processes.
68
+ sessionId: '--session-id',
69
+ resume: '--resume',
70
+ // The extra working directories the child may touch (claude 2.1.228 --help:
71
+ // "Additional directories to allow tool …"). See addDirArgs() — the spelling
72
+ // here is deliberately the EQUALS form and that is not cosmetic.
73
+ addDir: '--add-dir',
74
+ });
75
+
76
+ /**
77
+ * `--add-dir` is the child's own sandbox boundary: by default a headless child
78
+ * resolves every relative path and every tool's root against the directory it
79
+ * was spawned in, so a turn started in `repo/cli/` cannot read, run or even
80
+ * SEE `repo/test/` — the exact "outside the sandboxed directory" wall a real
81
+ * session reported from this product.
82
+ *
83
+ * ── why the EQUALS form, and why one flag per directory ─────────────────────
84
+ *
85
+ * `--add-dir` is VARIADIC: the child keeps consuming the words after it as
86
+ * directories. So the obvious `['--add-dir', dir, prompt]` is not merely
87
+ * fragile, it is broken — and this was measured against the installed binary
88
+ * (2.1.228), not reasoned about:
89
+ *
90
+ * claude -p --add-dir /tmp "do the thing" → Error: Input must be provided
91
+ * either through stdin or as a
92
+ * prompt argument when using --print
93
+ * claude -p --add-dir=/tmp "do the thing" → runs
94
+ *
95
+ * The prompt is the LAST item of the argv (rule 4 keeps it there, because the
96
+ * child reads it as the initial message). A space-form `--add-dir` immediately
97
+ * before it therefore swallows the user's prompt into the directory list, and
98
+ * the turn dies as an empty-input error before the model is ever reached.
99
+ * Attaching the value to the flag with `=` terminates the variadic run, so the
100
+ * prompt survives, and one flag per directory keeps a directory whose name
101
+ * begins with `-` from being re-read as another option. Empty and duplicate
102
+ * entries are dropped here rather than passed on: the list reaches the child's
103
+ * sandbox, so what it contains is a decision, not a formality.
104
+ */
105
+ function addDirArgs(dirs) {
106
+ const out = [];
107
+ for (const dir of unique(dirs)) out.push(`${FLAGS.addDir}=${dir}`);
108
+ return out;
109
+ }
110
+
111
+ /**
112
+ * A UUID, as `--session-id` requires. The CLI rejects anything else, and it
113
+ * rejects it AFTER the spawn — an argv that cannot work must not be built, so
114
+ * this returns null and the caller throws rather than typing a value the child
115
+ * will refuse while the turn looks as if it started.
116
+ */
117
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
118
+
119
+ const DEFAULT_OUTPUT_FORMAT = 'stream-json';
120
+
121
+ /** Dedupe while keeping the user's own rule order (rules are read top-down). */
122
+ function unique(list) {
123
+ const seen = new Set();
124
+ const out = [];
125
+ for (const item of Array.isArray(list) ? list : []) {
126
+ const v = String(item).trim();
127
+ if (!v || seen.has(v)) continue;
128
+ seen.add(v);
129
+ out.push(v);
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /**
135
+ * Build the Claude child's argv from the resolved posture.
136
+ *
137
+ * @param {object} [descriptor]
138
+ * @param {object} [descriptor.posture] a record from resolvePosture()
139
+ * @param {string} [descriptor.prompt] initial prompt (both kinds accept one)
140
+ * @param {string} [descriptor.model] explicit model id, if any
141
+ * @param {string} [descriptor.outputFormat] headless only; defaults to stream-json
142
+ * @param {string} [descriptor.permissionMode] explicit passthrough, one of
143
+ * PERMISSION_MODES (else throw)
144
+ * @param {string} [descriptor.resumeSessionId] reattach to an existing child
145
+ * session → `--resume <uuid>`
146
+ * @param {string} [descriptor.sessionId] name a NEW child session, so a
147
+ * LATER turn can `--resume` it
148
+ * @param {string[]} [descriptor.addDir] extra directories the child may
149
+ * work in → `--add-dir=<dir>` each
150
+ * @param {string[]} [descriptor.extra] extra argv items, appended last
151
+ * @returns {{argv: string[], record: object}} both frozen
152
+ * @throws when `permissionMode` is set to something Claude does not accept —
153
+ * a mode we cannot name is a mode we must not silently drop, because
154
+ * the run log would then record "no passthrough" for a run that asked
155
+ * for one.
156
+ * @throws when a session id is given that is not a UUID. Same reason, harder:
157
+ * `claude` refuses a malformed `--session-id` itself, after the spawn,
158
+ * so passing one through would turn a continuity bug into an opaque
159
+ * failed turn.
160
+ */
161
+ function claudeArgv(descriptor = {}) {
162
+ const posture = descriptor.posture;
163
+ if (!posture || typeof posture !== 'object') {
164
+ throw new Error('claudeArgv requires a resolved posture record (one/src/permissions.js resolvePosture)');
165
+ }
166
+ const kind = posture.childKind;
167
+ const headless = kind !== 'interactive';
168
+
169
+ // Imported lazily to keep this module free of a load-time dependency on the
170
+ // evaluator, and to keep the enum's single definition in one place.
171
+ const { PERMISSION_MODES } = require('./permissions.js');
172
+
173
+ const modeGiven = descriptor.permissionMode !== undefined && descriptor.permissionMode !== null;
174
+ const mode = modeGiven ? String(descriptor.permissionMode) : null;
175
+ if (modeGiven && !PERMISSION_MODES.includes(mode)) {
176
+ throw new Error(
177
+ `--permission-mode ${JSON.stringify(mode)} is not one of ${PERMISSION_MODES.join('|')} — ` +
178
+ 'refusing to pass (or to silently drop) a mode the child does not accept.'
179
+ );
180
+ }
181
+
182
+ const rules = posture.rules || {};
183
+ const allowedTools = unique(rules.allow);
184
+ const disallowedTools = unique(rules.deny);
185
+ // Ask rules have no `--allowedTools`/`--disallowedTools` spelling: they are
186
+ // recorded rather than approximated, because approximating "ask" as "deny"
187
+ // would be a refusal the user never asked for.
188
+ const unmappedAsk = unique(rules.ask);
189
+
190
+ // ── conversation continuity ───────────────────────────────────────────────
191
+ //
192
+ // The Pro child runs its own agent loop, so the engine does not replay the
193
+ // transcript into it (engine.js's `pro` branch). Continuity therefore has to
194
+ // come from the CLI's own session store, or every turn is a new conversation
195
+ // with no memory of the last one — which is exactly what it was.
196
+ //
197
+ // `resumeSessionId` wins over `sessionId`: a reattach to a session we already
198
+ // had is the same conversation, and naming a NEW id while resuming would
199
+ // start a second thread beside the live one. Both are validated as UUIDs
200
+ // before they reach argv, because the CLI's own rejection lands after the
201
+ // spawn.
202
+ const wantedResumeId = descriptor.resumeSessionId ? String(descriptor.resumeSessionId).trim() : '';
203
+ const wantedNewId = descriptor.sessionId ? String(descriptor.sessionId).trim() : '';
204
+ const resumeId = wantedResumeId || null;
205
+ const newId = !resumeId && wantedNewId ? wantedNewId : null;
206
+ for (const [label, value] of [['resumeSessionId', resumeId], ['sessionId', newId]]) {
207
+ if (value && !UUID_RE.test(value)) {
208
+ throw new Error(
209
+ `${label} ${JSON.stringify(value)} is not a UUID — refusing to pass it to ` +
210
+ '--resume/--session-id, which the child rejects after the spawn (turning a ' +
211
+ 'continuity bug into an opaque failed turn).'
212
+ );
213
+ }
214
+ }
215
+
216
+ const argv = [];
217
+ if (headless) {
218
+ argv.push(FLAGS.print, FLAGS.outputFormat, String(descriptor.outputFormat || DEFAULT_OUTPUT_FORMAT));
219
+ }
220
+ if (descriptor.model) argv.push(FLAGS.model, String(descriptor.model));
221
+ // The widened sandbox, before the permission flags: what the child may reach
222
+ // is decided here, and the prompt stays last (see addDirArgs).
223
+ const addDir = addDirArgs(descriptor.addDir);
224
+ argv.push(...addDir);
225
+ if (allowedTools.length) argv.push(FLAGS.allowedTools, allowedTools.join(','));
226
+ if (disallowedTools.length) argv.push(FLAGS.disallowedTools, disallowedTools.join(','));
227
+ if (modeGiven) argv.push(FLAGS.permissionMode, mode);
228
+ if (posture.child && posture.child.flag) argv.push(posture.child.flag);
229
+ // Before `extra` (the transport's own flags) and before the prompt, which
230
+ // must stay last so the child reads it as the initial message.
231
+ if (resumeId) argv.push(FLAGS.resume, resumeId);
232
+ else if (newId) argv.push(FLAGS.sessionId, newId);
233
+ if (Array.isArray(descriptor.extra)) argv.push(...descriptor.extra.map(String));
234
+ if (descriptor.prompt !== undefined && descriptor.prompt !== null) argv.push(String(descriptor.prompt));
235
+
236
+ const record = Object.freeze({
237
+ kind,
238
+ // "always recorded" (rule 4): the mode is in the record whether or not it
239
+ // was passed, and `passThrough` says which of the two happened.
240
+ permissionMode: mode,
241
+ permissionModePassed: modeGiven,
242
+ skip: Boolean(posture.child && posture.child.skip),
243
+ skipFlag: (posture.child && posture.child.flag) || null,
244
+ allowedTools: Object.freeze(allowedTools),
245
+ disallowedTools: Object.freeze(disallowedTools),
246
+ unmappedAsk: Object.freeze(unmappedAsk),
247
+ // Recorded, not inferred, exactly like the argv: an install that WIDENED its
248
+ // sandbox for the child is the one thing a later reader of the run log must
249
+ // not have to reconstruct from the argv's shape.
250
+ addDir: Object.freeze(addDir.map((a) => a.slice(FLAGS.addDir.length + 1))),
251
+ // Continuity, recorded the same way the mode is: which of the two happened
252
+ // (reattached vs. named a new session) is part of what this turn asked for,
253
+ // and a caller reading only the argv would have to infer it from position.
254
+ resumeSessionId: resumeId,
255
+ sessionId: newId,
256
+ argv: Object.freeze(argv.slice()),
257
+ });
258
+
259
+ return { argv: record.argv, record };
260
+ }
261
+
262
+ /** The run-log line for a child argv (rule 4: recorded, never inferred). */
263
+ function childRecordLine(record) {
264
+ if (!record || typeof record !== 'object') return null;
265
+ const mode = record.permissionModePassed
266
+ ? `${FLAGS.permissionMode}=${record.permissionMode}`
267
+ : 'no --permission-mode (none was set)';
268
+ return (
269
+ `aegis: claude child [${record.kind}] ${record.skipFlag || 'no permission flag'} · ${mode} · ` +
270
+ `allowedTools=[${record.allowedTools.join(', ')}] disallowedTools=[${record.disallowedTools.join(', ')}]` +
271
+ (record.unmappedAsk.length ? ` (ask rules recorded, unmapped: ${record.unmappedAsk.join(', ')})` : '') +
272
+ // The widened sandbox, named for the same reason the mode is: "the child
273
+ // could only see its own directory" is otherwise indistinguishable, in a
274
+ // transcript, from "the model chose not to look".
275
+ (record.addDir && record.addDir.length ? ` · addDir=[${record.addDir.join(', ')}]` : '') +
276
+ // The continuity half, named rather than left to be read off the argv:
277
+ // "resumed" and "new id" are the two things a turn can mean here, and a
278
+ // turn that silently did neither is the bug this line makes visible.
279
+ (record.resumeSessionId
280
+ ? ` · resumed session ${record.resumeSessionId}`
281
+ : record.sessionId
282
+ ? ` · new session ${record.sessionId}`
283
+ : ' · no session id (each turn is a new conversation)')
284
+ );
285
+ }
286
+
287
+ module.exports = { FLAGS, DEFAULT_OUTPUT_FORMAT, claudeArgv, addDirArgs, childRecordLine };
@@ -0,0 +1,371 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * permissions.js — ONE permission posture (AEGISONE, decision D8).
10
+ *
11
+ * Four permission surfaces used to live in this tree and none of them
12
+ * negotiated (see the plan's D8 table): the CLI's rule file + `evalPermission`,
13
+ * the desktop's `confirmModeEnabled()` gate, the avatar's level gate, and — out
14
+ * of process — the Claude Code child, which runs its own permission system
15
+ * whose prompts land on *its* stdin where neither a GUI card nor the CLI's
16
+ * prompt loop can answer them. In `-p` mode an unanswered prompt is not a
17
+ * refusal, it is a hang.
18
+ *
19
+ * This module is the product's half of the fix: it resolves the posture ONCE,
20
+ * from the facts a caller already has, into a FROZEN decision record that
21
+ * everything downstream reads instead of re-deciding for itself.
22
+ *
23
+ * ## What it is not
24
+ *
25
+ * * It is not a second rule engine. Rule matching is `evalPermission()`,
26
+ * imported from `cli/src/permissions.js` (D8 rule 1: "evalPermission()
27
+ * stays the only rule engine"). `loadEvaluator()` below resolves that
28
+ * module in both layouts — a checkout and the published bundle — and a
29
+ * missing evaluator is a thrown error, never a local re-implementation:
30
+ * a rules engine that can silently become a *different* rules engine is the
31
+ * drift this phase exists to remove.
32
+ * * It is not a switch that reaches the two floors of D8 rule 2. The ÆGIS
33
+ * covenant's `preActionAssert` and the avatar's `LEVEL_INDEPENDENT_
34
+ * APPROVALS` (`write`/`shell`/`network`/`offDevice`, always `'ask'`) are not
35
+ * represented here as skippable at all — `FROZEN_CLASSES` is exported so a
36
+ * test can assert it is the SAME set the avatar freezes, and `gateFor()`
37
+ * only ever downgrades an `'ask'` verdict, never an explicit `'deny'`.
38
+ * * It reads no `process.*` at module scope, and nothing at all in its
39
+ * functions: `env`, `interactive`, `skip` and `rules` all arrive as
40
+ * arguments. That is the standing seam rule for `one/`, and it is why the
41
+ * rule-5 case below can be asserted rather than hoped for.
42
+ *
43
+ * ## The record
44
+ *
45
+ * `resolvePosture({ rules, skip, interactive, childKind, env, flag })` returns
46
+ * an object that is frozen at every level. Frozen matters: the record is
47
+ * produced once per invocation and consumed by (a) this product's gate report,
48
+ * (b) the Claude child's argv builder, and (c) the run log. A record a later
49
+ * stage can mutate is a second decision, which is the bug D8 names.
50
+ *
51
+ * ## Rule 3's report
52
+ *
53
+ * `skipReport(record)` is the one stderr line rule 3 demands — "a flag whose
54
+ * blast radius is invisible is how a footgun ships" — and it names both what
55
+ * was skipped and, in as many words, what was not.
56
+ */
57
+
58
+ const path = require('node:path');
59
+
60
+ /** The two children D8 rule 4 distinguishes. */
61
+ const CHILD_KINDS = Object.freeze({ HEADLESS: 'headless', INTERACTIVE: 'interactive' });
62
+
63
+ /**
64
+ * What `--dangerously-skip-permissions` skips in THIS product: the configurable
65
+ * confirmation gates, i.e. the desktop card / CLI ask for the mutating tools.
66
+ * The classes are named the way the gate and the tool registry name them, so
67
+ * the report line says exactly which calls stop asking.
68
+ */
69
+ const CONFIGURABLE_CLASSES = Object.freeze(['exec', 'writeFile', 'editFile']);
70
+
71
+ /** The product flag's spelling (D8 rule 3), named once for both the bin and tests. */
72
+ const SKIP_FLAG = '--dangerously-skip-permissions';
73
+
74
+ /**
75
+ * The four classes no setting, flag or env var may auto-approve (D8 rule 2).
76
+ * The values are the avatar's, and `test/permissions.test.mjs` asserts this set
77
+ * is identical to `LEVEL_INDEPENDENT_APPROVALS`'s keys — so a phase that adds a
78
+ * fifth frozen class cannot land here silently.
79
+ */
80
+ const FROZEN_CLASSES = Object.freeze(['write', 'shell', 'network', 'offDevice']);
81
+
82
+ /** D8 rule 4's explicit passthrough values — recorded, never inferred. */
83
+ const PERMISSION_MODES = Object.freeze([
84
+ 'acceptEdits',
85
+ 'auto',
86
+ 'bypassPermissions',
87
+ 'manual',
88
+ 'dontAsk',
89
+ 'plan',
90
+ ]);
91
+
92
+ let cachedEvaluator = null;
93
+ let cachedConfig = null;
94
+
95
+ /**
96
+ * The ONE rule engine, resolved in both layouts:
97
+ *
98
+ * 1. `one/src/…` in a checkout → `../../cli/src/permissions.js`
99
+ * 2. `one/vendor/cli/src/…` in the published product → `../vendor/cli/src/…`
100
+ *
101
+ * @returns {{evalPermission: Function, resolveSkip: Function, SKIP: object}}
102
+ */
103
+ function loadEvaluator(injected) {
104
+ if (injected) return injected;
105
+ if (cachedEvaluator) return cachedEvaluator;
106
+ const candidates = [
107
+ path.join(__dirname, '..', '..', 'cli', 'src', 'permissions.js'),
108
+ path.join(__dirname, '..', 'vendor', 'cli', 'src', 'permissions.js'),
109
+ ];
110
+ for (const candidate of candidates) {
111
+ try {
112
+ const mod = require(candidate);
113
+ if (mod && typeof mod.evalPermission === 'function' && typeof mod.resolveSkip === 'function') {
114
+ cachedEvaluator = mod;
115
+ return mod;
116
+ }
117
+ } catch {
118
+ /* try the next layout */
119
+ }
120
+ }
121
+ throw new Error(
122
+ 'aegis: the one rule evaluator (cli/src/permissions.js) is missing from this install — ' +
123
+ 'refusing to resolve a permission posture from a second, unshared rule engine.'
124
+ );
125
+ }
126
+
127
+ /**
128
+ * The faces' OWN posture module, resolved in both layouts, exactly as the
129
+ * evaluator above is:
130
+ *
131
+ * 1. `one/src/…` in a checkout → `../../cli/src/config.js`
132
+ * 2. `one/vendor/cli/src/…` in the published product → `../vendor/cli/src/…`
133
+ *
134
+ * This is deliberately the CLI's module and not a new reader. `confirmPosture()`
135
+ * in there is the ONE read of the shared `confirmMode` key both faces write —
136
+ * the desktop's *Confirm before running tools* switch and the shell's
137
+ * `/automode` (alias `/yolo`) — and reading the store here a second way would
138
+ * be the split brain ON8 removed. NotFound is `null`, never a throw: a store
139
+ * that cannot be read must leave the gate UP, not blow up a launch.
140
+ *
141
+ * @returns {object|null}
142
+ */
143
+ function loadConfigStore(injected) {
144
+ if (injected) return injected;
145
+ if (cachedConfig) return cachedConfig;
146
+ const candidates = [
147
+ path.join(__dirname, '..', '..', 'cli', 'src', 'config.js'),
148
+ path.join(__dirname, '..', 'vendor', 'cli', 'src', 'config.js'),
149
+ ];
150
+ for (const candidate of candidates) {
151
+ try {
152
+ const mod = require(candidate);
153
+ if (mod && typeof mod.confirmPosture === 'function') {
154
+ cachedConfig = mod;
155
+ return mod;
156
+ }
157
+ } catch {
158
+ /* try the next layout */
159
+ }
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /**
165
+ * What the SHARED stores say — the same two facts `one/bin/aegis.js` used to
166
+ * pass as `undefined`.
167
+ *
168
+ * `confirmationsOn` is `confirmPosture().enabled`, i.e. the store's own answer
169
+ * with its polarity already resolved (true = the gate is UP, the user is asked
170
+ * before mutating tools). `rules` is the CLI's rule set verbatim, which is what
171
+ * rule 4's `--allowedTools`/`--disallowedTools` were always meant to be built
172
+ * from — the seam shipped with `rules: d.rules`, and nothing ever set `d.rules`
173
+ * in production, so the child was handed our rules by nobody.
174
+ *
175
+ * An unreadable store answers `undefined` for both, never a guess: "no stored
176
+ * posture" must mean "exactly as before", not "confirmations off".
177
+ *
178
+ * @returns {{confirmationsOn: boolean|undefined, rules: object|undefined, source: string}}
179
+ */
180
+ function storedPermissionFacts(opts = {}) {
181
+ const config = loadConfigStore(opts.config);
182
+ if (!config) return { confirmationsOn: undefined, rules: undefined, source: 'unavailable' };
183
+ try {
184
+ const gate = config.confirmPosture();
185
+ let rules;
186
+ try {
187
+ rules = config.loadPermissions();
188
+ } catch {
189
+ rules = undefined;
190
+ }
191
+ return {
192
+ confirmationsOn: gate && typeof gate.enabled === 'boolean' ? gate.enabled : undefined,
193
+ rules,
194
+ source: (gate && gate.source) || 'unavailable',
195
+ };
196
+ } catch {
197
+ return { confirmationsOn: undefined, rules: undefined, source: 'unavailable' };
198
+ }
199
+ }
200
+
201
+ /** The CLI's rule shape, verbatim (D8 rule 1: not a new schema). */
202
+ function normalizeRules(rules) {
203
+ const r = rules && typeof rules === 'object' ? rules : {};
204
+ const list = (v) => (Array.isArray(v) ? v.map(String) : []);
205
+ return Object.freeze({
206
+ defaultMode: r.defaultMode === 'allow' || r.defaultMode === 'deny' ? r.defaultMode : 'ask',
207
+ allow: Object.freeze(list(r.allow)),
208
+ deny: Object.freeze(list(r.deny)),
209
+ ask: Object.freeze(list(r.ask)),
210
+ // Only an explicitly written `defaultMode: 'ask'` prompts on the residual;
211
+ // the file-free default must not (cli/src/permissions.js's scope note).
212
+ explicitAsk: r.explicitAsk === true || r.defaultMode === 'ask',
213
+ });
214
+ }
215
+
216
+ /**
217
+ * Resolve the posture ONCE.
218
+ *
219
+ * @param {object} [input]
220
+ * @param {object} [input.rules] the shared rule set (CLI shape)
221
+ * @param {boolean} [input.flag] `--dangerously-skip-permissions` was passed
222
+ * @param {object} [input.env] environment (read, never mutated)
223
+ * @param {boolean} [input.interactive] both stdio ends are a terminal
224
+ * @param {string} [input.childKind] 'headless' | 'interactive'
225
+ * @param {boolean} [input.gate] the STORE's confirmation posture:
226
+ * `false` means the user already turned
227
+ * the gates off (`/automode`, or the
228
+ * desktop switch). Resolved by the caller
229
+ * (`storedPermissionFacts()`), never read
230
+ * from `process.*` here — the standing
231
+ * seam rule for `one/`.
232
+ * @param {object} [opts]
233
+ * @param {object} [opts.evaluator] injectable, for tests only
234
+ * @returns frozen decision record
235
+ */
236
+ function resolvePosture(input = {}, opts = {}) {
237
+ const evaluator = loadEvaluator(opts.evaluator);
238
+ const rules = normalizeRules(input.rules);
239
+ const interactive = input.interactive === true;
240
+ const childKind = input.childKind === CHILD_KINDS.INTERACTIVE ? CHILD_KINDS.INTERACTIVE : CHILD_KINDS.HEADLESS;
241
+ const skip = evaluator.resolveSkip({ flag: input.flag === true, env: input.env, interactive });
242
+ // ── the second, already-resolved answer ──────────────────────────────────
243
+ //
244
+ // `--dangerously-skip-permissions` is not the only way this product can be
245
+ // running with the gates down. Since ON8 there is a stored posture, written
246
+ // by `/automode` (alias `/yolo`), by `/confirm`, by `/multiyolo` and by the
247
+ // desktop's switch, that the faces read on every tool round. This resolver
248
+ // read the flag and the environment and nothing else, so a session whose user
249
+ // had already said "stop asking" handed the Claude child NO permission flag:
250
+ // headless, the child then asked a question nobody could answer — the hang
251
+ // rule 4 exists to prevent — while the terminal face beside it ran ungated.
252
+ // Two faces, one posture, one of them still asking is precisely the drift D8
253
+ // names, so the stored answer is folded in HERE, at the one place that
254
+ // produces the record, and never re-derived downstream.
255
+ //
256
+ // It cannot reach either floor. `skip` only ever downgrades an `'ask'`
257
+ // verdict in `gateFor()`, an explicit `deny` still wins, and the covenant's
258
+ // `preActionAssert` plus the avatar's `LEVEL_INDEPENDENT_APPROVALS`
259
+ // (`write`/`shell`/`network`/`offDevice`) are the same frozen four as before:
260
+ // the store is the *configurable* half of rule 2 by definition — it is what
261
+ // the confirmation gate itself reads — so honoring it here widens nothing.
262
+ const storedOff = input.gate === false;
263
+ const effectiveSkip = skip.skip || storedOff;
264
+ const skipSource = skip.skip ? skip.source : storedOff ? 'posture' : skip.source;
265
+
266
+ const isInteractiveChild = childKind === CHILD_KINDS.INTERACTIVE;
267
+ return Object.freeze({
268
+ version: 1,
269
+ rules,
270
+ interactive,
271
+ childKind,
272
+ // Rule 5 already applied: `skip` is the product's answer, not the raw env.
273
+ skip: effectiveSkip,
274
+ skipSource,
275
+ // Which of the two produced it. The run-log line and the rule-3 report are
276
+ // silent for a stored posture on purpose: the report exists because "a flag
277
+ // whose blast radius is invisible is how a footgun ships", and a flag typed
278
+ // for one run is that. A posture is a setting the user can see in both
279
+ // faces' own UI and turn back, and printing a skip banner on every launch
280
+ // of a deliberately-ungated install is noise that teaches scrolling — but
281
+ // the child's argv is still recorded by `childRecordLine`, so the decision
282
+ // remains accountable.
283
+ skipFromFlag: skip.skip,
284
+ envVarSet: skip.envSet,
285
+ // The store's answer, recorded rather than inferred (three states: true,
286
+ // false, and `null` for "there was no stored posture to read").
287
+ storedGate: input.gate === undefined || input.gate === null ? null : Boolean(input.gate),
288
+ warned: skip.warned,
289
+ warning: skip.warning || null,
290
+ // What a skip covers, and what it cannot touch. Both are frozen lists so a
291
+ // caller cannot widen either one in place.
292
+ skipped: Object.freeze(effectiveSkip ? CONFIGURABLE_CLASSES : []),
293
+ frozen: FROZEN_CLASSES,
294
+ // The child's variant, derived here so no spawn site re-derives it (rule 4).
295
+ child: Object.freeze({
296
+ kind: childKind,
297
+ skip: effectiveSkip,
298
+ flag: !effectiveSkip
299
+ ? null
300
+ : isInteractiveChild
301
+ ? '--allow-dangerously-skip-permissions'
302
+ : '--dangerously-skip-permissions',
303
+ why: !effectiveSkip
304
+ ? 'no skip was asked for, so no permission flag is passed to the child'
305
+ : isInteractiveChild
306
+ ? 'the interactive variant offers the bypass as an option (the child still asks; a human is there)'
307
+ : 'the headless variant takes the bypass as a default, because no one can answer the child\'s prompt',
308
+ }),
309
+ });
310
+ }
311
+
312
+ /**
313
+ * The verdict for one tool call, from the ONE evaluator.
314
+ *
315
+ * Precedence, and each step is load-bearing:
316
+ *
317
+ * 1. `'deny'` stays `'deny'` — an explicit deny rule is a rule, not a
318
+ * confirmation gate, so a skip must not be able to turn it into an allow.
319
+ * 2. `'allow'` stays `'allow'`.
320
+ * 3. `'ask'` becomes `'allow'` only when the posture says skip. That is
321
+ * exactly "this product's confirmation gates", the configurable half.
322
+ *
323
+ * The frozen four never reach a different answer through this function: their
324
+ * floors are the covenant assert and the avatar caps, which read neither this
325
+ * record nor the store.
326
+ */
327
+ function gateFor(posture, tool, args, opts = {}) {
328
+ const evaluator = loadEvaluator(opts.evaluator);
329
+ const rules = posture && posture.rules ? posture.rules : normalizeRules({});
330
+ const verdict = evaluator.evalPermission(tool, args, rules);
331
+ if (verdict === 'deny') return 'deny';
332
+ if (verdict === 'allow') return 'allow';
333
+ return posture && posture.skip ? 'allow' : 'ask';
334
+ }
335
+
336
+ /** The one-line "what was skipped" report (D8 rule 3). */
337
+ function skipReport(posture) {
338
+ if (!posture || !posture.skip) return null;
339
+ const childClause = posture.child.flag
340
+ ? `; the ${posture.child.kind} Claude child is passed ${posture.child.flag}`
341
+ : '';
342
+ // Named by its actual source, never as a flag the user did not type: a stored
343
+ // posture (`/automode`, the desktop switch) is reported for what it is, since
344
+ // printing `--dangerously-skip-permissions` for a setting would be the same
345
+ // kind of small lie as eating the flag.
346
+ const what =
347
+ posture.skipSource === 'posture'
348
+ ? 'automode (the stored confirmation posture both faces share)'
349
+ : '--dangerously-skip-permissions';
350
+ return (
351
+ `aegis: ${what} (via ${posture.skipSource}) — skipping the configurable ` +
352
+ `confirmation gates (${CONFIGURABLE_CLASSES.join(', ')})${childClause}. NOT skipped, and not ` +
353
+ `reachable by any setting, flag or env var: the ÆGIS covenant pre-action assert and the ` +
354
+ `${FROZEN_CLASSES.join('|')} approvals (always 'ask'), plus any explicit deny rule.`
355
+ );
356
+ }
357
+
358
+ module.exports = {
359
+ CHILD_KINDS,
360
+ CONFIGURABLE_CLASSES,
361
+ FROZEN_CLASSES,
362
+ PERMISSION_MODES,
363
+ SKIP_FLAG,
364
+ loadEvaluator,
365
+ loadConfigStore,
366
+ storedPermissionFacts,
367
+ normalizeRules,
368
+ resolvePosture,
369
+ gateFor,
370
+ skipReport,
371
+ };