aegis-desktop 1.0.30 → 1.0.32

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 (73) hide show
  1. package/LICENSING.md +186 -0
  2. package/bin/aegis.js +1 -1
  3. package/lib/local/claude-pro.js +1 -1
  4. package/lib/local/engine.js +1 -1
  5. package/lib/local/integrity.js +42 -2
  6. package/lib/local/perm-rules.js +206 -0
  7. package/lib/local/perm-store.js +298 -0
  8. package/lib/local/perm-write.js +199 -0
  9. package/lib/local/pro-sessions.js +3 -0
  10. package/lib/local/sandbox-appcontainer.js +242 -0
  11. package/lib/local/sandbox-bwrap.js +316 -0
  12. package/lib/local/sandbox-seatbelt.js +380 -0
  13. package/lib/local/sandbox.js +493 -0
  14. package/lib/local/shell.js +155 -20
  15. package/lib/local/tools.js +29 -4
  16. package/lib/settings.js +1 -1
  17. package/lib/sync/memory-store.js +3 -0
  18. package/main.js +774 -37
  19. package/package.json +20 -7
  20. package/preload.js +2 -2
  21. package/renderer/app.js +5 -1
  22. package/renderer/index.html +221 -5
  23. package/renderer/provider-mark.js +1 -1
  24. package/renderer/provider-toolbar.js +1 -1
  25. package/renderer/providers.js +1 -1
  26. package/renderer/style.css +223 -6
  27. package/renderer/usage.js +1 -1
  28. package/vendor/brain-catalog.js +1 -1
  29. package/vendor/byok-catalog.js +1 -1
  30. package/vendor/credits.js +45 -0
  31. package/vendor/faces/cli/package.json +3 -2
  32. package/vendor/faces/cli/src/app.js +1 -1
  33. package/vendor/faces/cli/src/chatflow.js +1 -1
  34. package/vendor/faces/cli/src/commands.js +3 -1
  35. package/vendor/faces/cli/src/config.js +1 -1
  36. package/vendor/faces/cli/src/engine.js +1 -1
  37. package/vendor/faces/cli/src/history.js +1 -1
  38. package/vendor/faces/cli/src/models.js +1 -1
  39. package/vendor/faces/cli/src/overlays.js +1 -1
  40. package/vendor/faces/cli/src/panels.js +1 -1
  41. package/vendor/faces/cli/vendor/client/brain-catalog.js +1 -1
  42. package/vendor/faces/cli/vendor/client/byok-catalog.js +1 -1
  43. package/vendor/faces/cli/vendor/client/credits.js +45 -0
  44. package/vendor/faces/cli/vendor/client/foreign-sessions.js +3 -0
  45. package/vendor/faces/cli/vendor/client/naming.js +1 -1
  46. package/vendor/faces/cli/vendor/client/prefs.js +1 -1
  47. package/vendor/faces/cli/vendor/client/session-search.js +3 -0
  48. package/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +1 -1
  49. package/vendor/faces/cli/vendor/desktop/lib/local/engine.js +1 -1
  50. package/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +1 -1
  51. package/vendor/faces/cli/vendor/desktop/lib/local/perm-rules.js +3 -0
  52. package/vendor/faces/cli/vendor/desktop/lib/local/perm-store.js +3 -0
  53. package/vendor/faces/cli/vendor/desktop/lib/local/perm-write.js +3 -0
  54. package/vendor/faces/cli/vendor/desktop/lib/local/pro-sessions.js +3 -0
  55. package/vendor/faces/cli/vendor/desktop/lib/local/sandbox-appcontainer.js +3 -0
  56. package/vendor/faces/cli/vendor/desktop/lib/local/sandbox-bwrap.js +3 -0
  57. package/vendor/faces/cli/vendor/desktop/lib/local/sandbox-seatbelt.js +3 -0
  58. package/vendor/faces/cli/vendor/desktop/lib/local/sandbox.js +3 -0
  59. package/vendor/faces/cli/vendor/desktop/lib/local/shell.js +1 -1
  60. package/vendor/faces/cli/vendor/desktop/lib/local/tools.js +1 -1
  61. package/vendor/faces/cli/vendor/desktop/lib/settings.js +1 -1
  62. package/vendor/faces/cli/vendor/desktop/main.js +4 -2
  63. package/vendor/faces/cli/vendor/desktop/renderer/usage.js +1 -1
  64. package/vendor/faces/cli/vendor/mcp/admission.js +3 -0
  65. package/vendor/faces/cli/vendor/mcp/server.js +1 -1
  66. package/vendor/faces/cli/vendor/one/src/child.js +1 -1
  67. package/vendor/faces/cli/vendor/one/src/permissions.js +1 -1
  68. package/vendor/foreign-sessions.js +3 -0
  69. package/vendor/naming.js +1 -1
  70. package/vendor/prefs.js +1 -1
  71. package/vendor/sandbox/provenance.json +20 -0
  72. package/vendor/sandbox/x64-linux/bwrap +0 -0
  73. package/vendor/session-search.js +3 -0
@@ -0,0 +1,206 @@
1
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
3
+ // SPDX-License-Identifier: AGPL-3.0-or-later
4
+ //
5
+ // ── Stored \/permissions rules, applied to the desktop's approval gate ──────
6
+ //
7
+ // §2 of ~/plan/agent-safety-plan.md. The desktop gate has exactly one setting
8
+ // today (`confirmMode`, one global on/off) plus a per-card yes/no. The CLI has
9
+ // a full tier engine: `defaultMode`, and `allow`/`deny`/`ask` pattern rules in
10
+ // `~/.aegiscode/permissions.json`, matched by `cli/src/permissions.js`. Both
11
+ // faces already share the *store* (`config.js`'s `confirmPosture`), so a user
12
+ // who writes `Bash(git status)` in the CLI expects the desktop to honour it.
13
+ // Before this module the desktop read none of it.
14
+ //
15
+ // ## Why this does NOT call evalPermission
16
+ //
17
+ // `evalPermission` answers `'allow'` for anything no rule matched — because in
18
+ // the CLI the residual allow means "the loop may run it, the interactive gate
19
+ // is elsewhere". The desktop's gate is the opposite shape: it prompts on every
20
+ // MUTATING_TOOLS call while `confirmMode` is on, so an `'allow'` residual piped
21
+ // into the short-circuit chain would silently answer "already approved" for
22
+ // every tool on the machine and remove the gate entirely. That is the failure
23
+ // this module exists to avoid, not to cause.
24
+ //
25
+ // So the only two verdicts taken from the store are the ones the user
26
+ // *explicitly wrote*:
27
+ //
28
+ // deny — a matching `deny` rule. A security floor: refused outright, and
29
+ // the refusal reuses the engine's own `denialText` so the model gets
30
+ // the same anti-retry wording a clicked "Deny" produces.
31
+ // allow — a matching `allow` rule. Skips the card, exactly like an "Allow for
32
+ // this session" decision that the user made in advance.
33
+ // null — no explicit rule. Keep the existing behaviour byte for byte: raise
34
+ // the card. This is the common case and it must stay the common case.
35
+ //
36
+ // ## Two ordering facts inherited from the CLI engine
37
+ //
38
+ // `matchRule` canonicalises tool names (`exec`≡`Bash`, `readFile`≡`Read`), so a
39
+ // rule written against either face's spelling governs both. And an allow rule
40
+ // is matched against `subjectFor(...)` — the command for a shell tool, the path
41
+ // for a file tool — which is why a bare `exec(*)` rule is a footgun worth
42
+ // knowing about: it also suppresses the multi-`cd` rail, since that rail is
43
+ // consulted only after allow rules. This module neither writes nor widens
44
+ // rules; it only reads them.
45
+ //
46
+ // ## The seam
47
+ //
48
+ // Rules are read through `one/src/permissions.js`'s `storedPermissionFacts()`,
49
+ // which resolves `cli/src/config.js` in all three install layouts and returns
50
+ // the CLI's rule shape verbatim. That is deliberate: reading
51
+ // `~/.aegiscode/permissions.json` here with a local `JSON.parse` would be a
52
+ // second rule reader, which is the drift D8 rule 1 forbids. A missing module is
53
+ // reported, never worked around — a gate that cannot see the rules must behave
54
+ // like a gate with no rules (cards for everything), not like a gate with all
55
+ // rules allowed.
56
+
57
+ 'use strict';
58
+
59
+ const path = require('path');
60
+
61
+ // ── Where the shared modules live ─────────────────────────────────────────
62
+
63
+ /**
64
+ * The install layouts, same candidates `claude-pro.js`'s `loadSeam` uses, plus
65
+ * the one the packaged desktop actually has:
66
+ *
67
+ * checkout desktop/lib/local → <repo>/one/src
68
+ * packaged desktop desktop/lib/local → desktop/vendor/one/src
69
+ * mirrored CLI cli/vendor/desktop/lib/local → cli/vendor/one/src
70
+ * packaged desktop, second form — the terminal face is staged under
71
+ * `vendor/faces/`, so `one/src/permissions.js` lands at
72
+ * `vendor/faces/cli/vendor/one/src`. Found by running the obf tree: without
73
+ * this candidate the seam answered `one/src/permissions.js not found` in
74
+ * exactly the build that ships, and the feature would have been dead on
75
+ * arrival while every checkout test stayed green.
76
+ */
77
+ function candidates(dir) {
78
+ const here = dir || __dirname;
79
+ return [
80
+ path.join(here, '..', '..', '..', 'one', 'src'),
81
+ path.join(here, '..', '..', 'vendor', 'one', 'src'),
82
+ path.join(here, '..', '..', '..', '..', 'one', 'src'),
83
+ path.join(here, '..', '..', 'vendor', 'faces', 'cli', 'vendor', 'one', 'src'),
84
+ ];
85
+ }
86
+
87
+ let cachedShared = null;
88
+
89
+ /**
90
+ * `{ permissions }` — `one/src/permissions.js`, which in turn resolves the one
91
+ * rule evaluator (`cli/src/permissions.js`). Returns null rather than throwing:
92
+ * the caller degrades to "no rules", which is safe, and says so once.
93
+ */
94
+ function loadShared(dir) {
95
+ if (cachedShared !== null && dir === undefined) return cachedShared;
96
+ for (const base of candidates(dir)) {
97
+ try {
98
+ const mod = require(path.join(base, 'permissions.js'));
99
+ if (
100
+ mod &&
101
+ typeof mod.storedPermissionFacts === 'function' &&
102
+ typeof mod.loadEvaluator === 'function'
103
+ ) {
104
+ const found = { permissions: mod };
105
+ if (dir === undefined) cachedShared = found;
106
+ return found;
107
+ }
108
+ } catch {
109
+ /* try the next layout */
110
+ }
111
+ }
112
+ return null;
113
+ }
114
+
115
+ // ── The decision ──────────────────────────────────────────────────────────
116
+
117
+ /**
118
+ * Do the stored rules have an explicit opinion about this call?
119
+ *
120
+ * @param {string} name tool name as the engine spells it (`exec`, `writeFile`)
121
+ * @param {object} args the normalised args (`normalizeToolArgs` already ran)
122
+ * @param {object} [opts]
123
+ * @param {object} [opts.facts] injected `storedPermissionFacts()` result, for
124
+ * tests — never read from disk in that case
125
+ * @param {string} [opts.dir] override the module-layout search root
126
+ * @returns {{verdict: 'allow'|'deny'|null, source: string, rule?: string, error?: string}}
127
+ * `verdict: null` means "no explicit rule" — the caller MUST keep whatever it
128
+ * was going to do, i.e. raise the card.
129
+ */
130
+ function rulesVerdict(name, args, opts = {}) {
131
+ const shared = loadShared(opts.dir);
132
+ if (!shared) {
133
+ return { verdict: null, source: 'unavailable', error: 'one/src/permissions.js not found' };
134
+ }
135
+ const { permissions } = shared;
136
+
137
+ let facts = opts.facts;
138
+ if (!facts) {
139
+ try {
140
+ facts = permissions.storedPermissionFacts();
141
+ } catch (e) {
142
+ return { verdict: null, source: 'unavailable', error: (e && e.message) || String(e) };
143
+ }
144
+ }
145
+ const rules = facts && facts.rules;
146
+ // No store, or a store with no readable rule file: no explicit opinion. The
147
+ // card stands. Never infer "the user allowed everything" from absence.
148
+ if (!rules || typeof rules !== 'object') return { verdict: null, source: (facts && facts.source) || 'none' };
149
+
150
+ let evaluator;
151
+ try {
152
+ evaluator = permissions.loadEvaluator();
153
+ } catch (e) {
154
+ return { verdict: null, source: 'unavailable', error: (e && e.message) || String(e) };
155
+ }
156
+ const { matchRule, subjectFor } = evaluator;
157
+ if (typeof matchRule !== 'function' || typeof subjectFor !== 'function') {
158
+ return { verdict: null, source: 'unavailable', error: 'rule evaluator is incomplete' };
159
+ }
160
+
161
+ const subject = subjectFor(name, args || {});
162
+ // deny first: a deny rule is a floor and outranks any allow rule, the same
163
+ // precedence evalPermission applies.
164
+ for (const key of ['deny', 'allow']) {
165
+ const list = Array.isArray(rules[key]) ? rules[key] : [];
166
+ for (const rule of list) {
167
+ let hit = false;
168
+ try {
169
+ hit = matchRule(rule, name, subject);
170
+ } catch {
171
+ hit = false; // a malformed rule matches nothing; it never widens access
172
+ }
173
+ if (hit) return { verdict: key === 'deny' ? 'deny' : 'allow', source: facts.source || 'store', rule };
174
+ }
175
+ }
176
+ return { verdict: null, source: facts.source || 'store' };
177
+ }
178
+
179
+ // ── The subject, from the same evaluator ──────────────────────────────────
180
+
181
+ /**
182
+ * The subject a rule matches against, from the SHARED evaluator.
183
+ *
184
+ * Exported so the engine's session tier can key its grants on the same value
185
+ * the durable tier uses (`perm-write.js` composes rules from it), instead of
186
+ * inventing a second derivation. Answers '' when the evaluator cannot be
187
+ * loaded — the engine reads that as "scoped, but to nothing", which is the safe
188
+ * direction: a grant can only ever cover less than the whole tool.
189
+ *
190
+ * Deliberately silent on failure. A gate that cannot see the evaluator must
191
+ * still gate, and `rulesVerdict` already reports the same unavailability on the
192
+ * path a user can act on.
193
+ */
194
+ function subjectFor(name, args) {
195
+ try {
196
+ const shared = loadShared();
197
+ if (!shared) return '';
198
+ const evaluator = shared.permissions.loadEvaluator();
199
+ if (!evaluator || typeof evaluator.subjectFor !== 'function') return '';
200
+ return evaluator.subjectFor(name, args || {});
201
+ } catch {
202
+ return '';
203
+ }
204
+ }
205
+
206
+ module.exports = { rulesVerdict, loadShared, candidates, subjectFor };
@@ -0,0 +1,298 @@
1
+ // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
2
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
3
+ // SPDX-License-Identifier: AGPL-3.0-or-later
4
+ //
5
+ // ── The permission rules a user can SEE and EDIT ──────────────────────────
6
+ //
7
+ // §2 taught the desktop gate to *read* `~/.aegiscode/permissions.json`; §3 gave
8
+ // the approval card a fourth answer that *writes* one exact rule. Both left the
9
+ // same hole: once a rule was stored, nothing in the window could show it, and
10
+ // the only way to take it back was to hand-edit JSON. A permission you cannot
11
+ // revoke from the app is a permission you have lost track of — and the whole
12
+ // point of the tier work is that the user, not the agent, holds the list.
13
+ //
14
+ // ## What this module is, and is not
15
+ //
16
+ // It is a THIN VIEW over `cli/src/config.js`'s rule store — the same
17
+ // `loadPermissions` / `addPermissionRule` / `removePermissionRule` /
18
+ // `savePermissions` pair `/permissions` uses, resolved through the same
19
+ // `loadShared` seam as `perm-rules.js` and `perm-write.js`. It never writes
20
+ // JSON itself, so there is one schema and one file format (D8 rule 1).
21
+ //
22
+ // It is NOT the decision path. `engine.js` consults `perm-rules.js`
23
+ // (`rulesVerdict`) at the gate; this module is only what the Settings card
24
+ // lists and mutates. Keeping them apart matters: a bug in the editor must not
25
+ // be able to change what the gate decides without also changing the file, and
26
+ // the gate re-reads the file on every call rather than trusting a cached view.
27
+ //
28
+ // ## Why every mutation is validated against the real matcher
29
+ //
30
+ // A rule the grammar cannot parse matches NOTHING (`matchRule` returns false on
31
+ // a failed `RULE_RE`). Storing one would be worse than storing nothing: the
32
+ // card would list a permission that has no effect, so a user would believe
33
+ // `exec(rm -rf *)` was denied while the gate still raised a card, or believe an
34
+ // allow was in force while the agent kept asking. So `addRule` composes the
35
+ // rule, then asks the REAL `matchRule` whether it matches its own subject —
36
+ // a rule that cannot match itself is refused with the reason. That check can
37
+ // only be trusted because it is the same function the gate uses.
38
+ //
39
+ // ## `*` is legitimate HERE and refused in §3, deliberately
40
+ //
41
+ // `perm-write.js` refuses to persist a subject containing `*` because the user
42
+ // clicked approve on ONE command, and a `*` inside it would silently widen what
43
+ // they approved. This module is the opposite situation: the user is typing the
44
+ // pattern and means it. `exec(npm run *)` is the entire reason tiers exist. So
45
+ // the wildcard is allowed here and the *typo* cases are what get caught — an
46
+ // unparseable rule, or one whose tool name the engine never calls.
47
+
48
+ 'use strict';
49
+
50
+ const { loadShared } = require('./perm-rules.js');
51
+
52
+ /** The three lists, in the order the card renders them. `deny` first: it is
53
+ * the floor, and a user looking for "what can never run" should not have to
54
+ * scroll past the allows to find it. */
55
+ const LISTS = Object.freeze(['deny', 'allow', 'ask']);
56
+
57
+ /**
58
+ * Resolve the CLI rule store, or explain why not.
59
+ *
60
+ * @param {object} [opts]
61
+ * @param {object} [opts.config] injected config module (tests) — when present
62
+ * the real file is never read or written
63
+ * @param {string} [opts.dir] module-layout override (tests)
64
+ * @returns {{ok: boolean, config?: object, reason?: string}}
65
+ */
66
+ function resolveStore(opts = {}) {
67
+ if (opts.config) {
68
+ // An injected store is validated like any other. Short-circuiting on it
69
+ // would mean the real install (the only caller that injects nothing) is the
70
+ // one path the checks never cover — and a store missing `savePermissions`
71
+ // would then answer `ok: true` and fail at the WRITE, after the UI had
72
+ // already told the user the rule was stored.
73
+ const missing = ['loadPermissions', 'savePermissions', 'addPermissionRule', 'removePermissionRule']
74
+ .find((fn) => typeof opts.config[fn] !== 'function');
75
+ if (missing) return { ok: false, reason: `the permissions store has no ${missing}()` };
76
+ return { ok: true, config: opts.config };
77
+ }
78
+ const shared = loadShared(opts.dir);
79
+ if (!shared) return { ok: false, reason: 'one/src/permissions.js not found' };
80
+ let config;
81
+ try {
82
+ config = shared.permissions.loadConfigStore();
83
+ } catch (e) {
84
+ return { ok: false, reason: (e && e.message) || String(e) };
85
+ }
86
+ if (!config) return { ok: false, reason: 'the permissions store is unavailable' };
87
+ for (const fn of ['loadPermissions', 'savePermissions', 'addPermissionRule', 'removePermissionRule']) {
88
+ if (typeof config[fn] !== 'function') {
89
+ return { ok: false, reason: `the permissions store has no ${fn}()` };
90
+ }
91
+ }
92
+ return { ok: true, config };
93
+ }
94
+
95
+ /**
96
+ * The rule set as the card consumes it.
97
+ *
98
+ * `explicitAsk` is stripped: it is DERIVED from `defaultMode` at read time
99
+ * (`cli/src/config.js` loadPermissions), and sending it to the renderer invites
100
+ * a round-trip that writes it back — the disagreeing-file bug `saveRuleMode`
101
+ * documents. The editor only ever sends a list + a pattern back.
102
+ *
103
+ * @returns {{ok: boolean, rules?: {defaultMode: string, deny: string[], allow: string[], ask: string[]}, source?: string, reason?: string}}
104
+ */
105
+ function listRules(opts = {}) {
106
+ const store = resolveStore(opts);
107
+ if (!store.ok) return { ok: false, reason: store.reason };
108
+ let raw;
109
+ try {
110
+ raw = store.config.loadPermissions();
111
+ } catch (e) {
112
+ return { ok: false, reason: (e && e.message) || String(e) };
113
+ }
114
+ const r = raw && typeof raw === 'object' ? raw : {};
115
+ const list = (v) => (Array.isArray(v) ? v.map(String) : []);
116
+ return {
117
+ ok: true,
118
+ source: 'store',
119
+ rules: {
120
+ defaultMode: r.defaultMode === 'allow' || r.defaultMode === 'deny' ? r.defaultMode : 'ask',
121
+ deny: list(r.deny),
122
+ allow: list(r.allow),
123
+ ask: list(r.ask),
124
+ },
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Does this rule actually parse, and does it match the subject a user's own
130
+ * example would produce?
131
+ *
132
+ * `RULE_RE` is `^(\w+)(?:\((.*)\))?$`, so "parses" and "matches something" are
133
+ * different questions: `exec(` parses as nothing at all, while `nonsense(*)`
134
+ * parses fine and can never match, because no tool is called `nonsense`. Both
135
+ * are useless rules, and both are refused here rather than stored as a line the
136
+ * user will stare at wondering why it does nothing.
137
+ *
138
+ * The tool-name half is checked with `canonTool`, so a user typing the
139
+ * reference spelling (`Bash`, `Edit`) is accepted exactly as the gate would
140
+ * accept it — one vocabulary, two spellings.
141
+ *
142
+ * @param {string} rule
143
+ * @param {object} [opts]
144
+ * @param {string} [opts.dir] layout override (tests)
145
+ * @returns {{ok: boolean, reason?: string, warning?: string}}
146
+ */
147
+ function validateRule(rule, opts = {}) {
148
+ const text = String(rule == null ? '' : rule).trim();
149
+ if (!text) return { ok: false, reason: 'a rule cannot be empty' };
150
+ if (/[\n\r]/.test(text)) return { ok: false, reason: 'a rule must be a single line' };
151
+
152
+ const shared = loadShared(opts.dir);
153
+ if (!shared) return { ok: false, reason: 'one/src/permissions.js not found' };
154
+
155
+ let evaluator;
156
+ try {
157
+ evaluator = shared.permissions.loadEvaluator();
158
+ } catch (e) {
159
+ return { ok: false, reason: (e && e.message) || String(e) };
160
+ }
161
+ const { matchRule, subjectFor, canonTool } = evaluator;
162
+ if (typeof matchRule !== 'function' || typeof subjectFor !== 'function') {
163
+ return { ok: false, reason: 'the rule evaluator is incomplete' };
164
+ }
165
+
166
+ // The grammar itself. Duplicating RULE_RE here would be a second dialect that
167
+ // could drift from the one the gate uses; instead, a rule that matches
168
+ // nothing is rejected, and the reason names the shape.
169
+ const m = /^(\w+)(?:\((.*)\))?$/.exec(text);
170
+ if (!m) return { ok: false, reason: 'a rule has the form tool(pattern), e.g. exec(npm test)' };
171
+
172
+ const tool = m[1];
173
+ const known = typeof canonTool === 'function' ? KNOWN_TOOLS.has(canonTool(tool)) : true;
174
+ if (!known) {
175
+ return { ok: false, reason: `"${tool}" is not a tool this app calls — nothing would ever match it` };
176
+ }
177
+
178
+ // Self-match: build a subject the rule claims to govern and ask the matcher.
179
+ // `exec(npm test)` must match "npm test"; a rule that cannot match its own
180
+ // pattern is one the grammar stored but the gate will never honour.
181
+ const pattern = m[2];
182
+ if (pattern !== undefined && pattern !== '') {
183
+ let selfMatch = false;
184
+ try {
185
+ selfMatch = matchRule(text, tool, pattern);
186
+ } catch {
187
+ selfMatch = false;
188
+ }
189
+ if (!selfMatch) {
190
+ return { ok: false, reason: 'this pattern cannot match itself, so it would never fire' };
191
+ }
192
+ }
193
+ // A bare tool rule matches EVERY call to that tool, and an allow is consulted
194
+ // before the multi-`cd` rail (`evalPermission`: deny, allow,
195
+ // isMultiDirCommand, ask, explicitAsk) — so `allow: ["exec"]` permanently
196
+ // disables that rail, silently, while the card still looks healthy. It is a
197
+ // legitimate thing to want (it is what "full access" means), so it is not
198
+ // refused the way perm-write.js refuses an empty subject: it is *warned*.
199
+ // Removing the ability to express it would push users to `/confirm off`,
200
+ // which is the same state with no visible rule at all.
201
+ if (pattern === undefined || pattern === '') {
202
+ return {
203
+ ok: true,
204
+ warning: `a bare ${tool}() rule matches every ${tool} call, including commands that change directory more than once`,
205
+ };
206
+ }
207
+ return { ok: true };
208
+ }
209
+
210
+ /** The capabilities `cli/src/permissions.js`'s TOOL_ALIAS folds onto. A rule
211
+ * naming anything else is inert, which `validateRule` refuses. */
212
+ const KNOWN_TOOLS = new Set(['shell', 'read', 'write', 'edit', 'list', 'glob', 'grep', 'task']);
213
+
214
+ /** The file shape, with `explicitAsk` deliberately absent — see listRules. */
215
+ function toFileShape(rules) {
216
+ const r = rules && typeof rules === 'object' ? rules : {};
217
+ const list = (v) => (Array.isArray(v) ? v.map(String) : []);
218
+ return {
219
+ defaultMode: r.defaultMode === 'allow' || r.defaultMode === 'deny' ? r.defaultMode : 'ask',
220
+ deny: list(r.deny),
221
+ allow: list(r.allow),
222
+ ask: list(r.ask),
223
+ };
224
+ }
225
+
226
+ /**
227
+ * Add one rule to one list.
228
+ *
229
+ * @param {string} list 'allow' | 'deny' | 'ask'
230
+ * @param {string} rule the pattern, e.g. `exec(npm test)`
231
+ * @returns {{ok: boolean, added?: boolean, rules?: object, reason?: string}}
232
+ */
233
+ function addRule(list, rule, opts = {}) {
234
+ const key = String(list || '');
235
+ if (!LISTS.includes(key)) return { ok: false, reason: `unknown list "${key}"` };
236
+
237
+ const valid = validateRule(rule, opts);
238
+ if (!valid.ok) return { ok: false, reason: valid.reason };
239
+ const warning = valid.warning;
240
+
241
+ const store = resolveStore(opts);
242
+ if (!store.ok) return { ok: false, reason: store.reason };
243
+
244
+ const pattern = String(rule).trim();
245
+ try {
246
+ const current = toFileShape(store.config.loadPermissions());
247
+ const res = store.config.addPermissionRule(key, pattern, current);
248
+ const next = res && res.rules ? toFileShape(res.rules) : current;
249
+ if (res && res.added === false) {
250
+ return { ok: true, added: false, rules: next, ...(warning ? { warning } : {}) };
251
+ }
252
+ store.config.savePermissions(next);
253
+ return { ok: true, added: true, rules: next, ...(warning ? { warning } : {}) };
254
+ } catch (e) {
255
+ return { ok: false, reason: (e && e.message) || String(e) };
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Remove one rule from one list.
261
+ *
262
+ * Not validated: removing an unparseable rule is how a user repairs a file they
263
+ * (or an older build) got wrong, so a broken pattern must remain removable. The
264
+ * read-back is what proves it happened.
265
+ *
266
+ * @returns {{ok: boolean, removed?: boolean, rules?: object, reason?: string}}
267
+ */
268
+ function removeRule(list, rule, opts = {}) {
269
+ const key = String(list || '');
270
+ if (!LISTS.includes(key)) return { ok: false, reason: `unknown list "${key}"` };
271
+
272
+ const store = resolveStore(opts);
273
+ if (!store.ok) return { ok: false, reason: store.reason };
274
+
275
+ const pattern = String(rule == null ? '' : rule).trim();
276
+ if (!pattern) return { ok: false, reason: 'no rule named' };
277
+
278
+ try {
279
+ const current = toFileShape(store.config.loadPermissions());
280
+ const res = store.config.removePermissionRule(key, pattern, current);
281
+ const next = res && res.rules ? toFileShape(res.rules) : current;
282
+ if (res && res.removed === false) return { ok: true, removed: false, rules: next };
283
+ store.config.savePermissions(next);
284
+ return { ok: true, removed: true, rules: next };
285
+ } catch (e) {
286
+ return { ok: false, reason: (e && e.message) || String(e) };
287
+ }
288
+ }
289
+
290
+ module.exports = {
291
+ LISTS,
292
+ KNOWN_TOOLS,
293
+ toFileShape,
294
+ validateRule,
295
+ listRules,
296
+ addRule,
297
+ removeRule,
298
+ };