@aisac/cli 0.4.0-beta.2 → 0.4.0-beta.22

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 (60) hide show
  1. package/README.md +146 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +846 -14
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +12 -1
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +641 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +276 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +390 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +1557 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +403 -47
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/manager/bus.mjs +1921 -0
  35. package/dist/manager/delegation.mjs +354 -0
  36. package/dist/manager/hooks.mjs +918 -0
  37. package/dist/manager/launch-role.mjs +476 -0
  38. package/dist/manager/mcp-stdio.mjs +463 -0
  39. package/dist/manager/messages.mjs +791 -0
  40. package/dist/manager/reserve.mjs +2166 -0
  41. package/dist/manager/room.mjs +106 -0
  42. package/dist/manager/server.mjs +1792 -0
  43. package/dist/manager/status.mjs +118 -0
  44. package/dist/manager/watch.mjs +87 -0
  45. package/dist/manager/worker.mjs +2793 -0
  46. package/dist/manager/workers-cli.mjs +1403 -0
  47. package/dist/mcp-servers.mjs +192 -0
  48. package/dist/mcp.mjs +10 -2
  49. package/dist/monitor.mjs +76 -1
  50. package/dist/package.json +1 -1
  51. package/dist/platform.mjs +78 -29
  52. package/dist/release-manifest-public-keys.json +10 -0
  53. package/dist/release-manifest.json +328 -0
  54. package/dist/release-manifest.mjs +817 -0
  55. package/dist/release-settings.mjs +210 -0
  56. package/dist/self-update.mjs +1036 -0
  57. package/dist/state.mjs +25 -1
  58. package/dist/token-guide.mjs +132 -0
  59. package/dist/update-actions.mjs +442 -0
  60. package/package.json +1 -1
@@ -0,0 +1,1557 @@
1
+ // @ts-check
2
+ /**
3
+ * Block guardrails for PreToolUse (spec aisac-engineering-extensions FR2,
4
+ * FR2.1, FR2.2; spec aisac-engineering-manager FR10 for `bus-guard`). Each
5
+ * guard is a pure decision from the tool name and input; it returns a refusal
6
+ * reason or null. Guards decide from names only and never open the files they
7
+ * protect. They lower risk; they are not a sandbox.
8
+ */
9
+ import { execFileSync } from 'node:child_process';
10
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
+ import { PATCH_TOOL, patchPaths } from './patch.mjs';
12
+ import { effectiveWords, programName, splitShell } from './shell-words.mjs';
13
+
14
+ /**
15
+ * @typedef {object} GuardContext
16
+ * @property {string} projectDir
17
+ * @property {string} home
18
+ * @property {string} prefsPath The extensions preferences file (FR2.2).
19
+ * @property {readonly string[]} [codexConfigs] Codex's user config files, which hold
20
+ * the switches for the AISAC hooks in Codex (FR2.2, E6b).
21
+ * @property {'pt-BR' | 'en'} locale
22
+ */
23
+ /** @typedef {{ tool_name?: unknown, tool_input?: unknown, cwd?: unknown }} ToolEvent */
24
+
25
+ const TEMPLATE_SUFFIXES = new Set(['example', 'sample', 'template']);
26
+ const SECRET_DIRECTORIES = new Set(['.ssh', '.aws', '.gnupg']);
27
+ const SECRET_NAMES = new Set(['.envrc', '.npmrc', '.netrc', '.pgpass', 'credentials.json']);
28
+ const PRIVATE_KEY_NAME = /^id_(?:rsa|dsa|ecdsa|ed25519)(?:[._-].*)?$/u;
29
+ const CERTIFICATE_EXTENSION = /\.(?:pem|p12|pfx)$/iu;
30
+ const KEY_EXTENSION = /\.key$/iu;
31
+ const SERVICE_ACCOUNT = /^service-account.*\.json$/iu;
32
+ // Splits a word into the names it mentions (`open('.env')` -> `open`, `.env`),
33
+ // so `process.env.HOME` stays one name and passes.
34
+ const NAME_DELIMITERS = /[\s'"=<>:(),;|&`$]+/u;
35
+ // A quoted name inside a word that contains spaces (`python -c "open('.env')"`).
36
+ const QUOTED_NAME = /['"]([^'"\s]+)['"]/gu;
37
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh']);
38
+ // `bash -c`, and short-option clusters such as `bash -lc` (how Codex runs commands).
39
+ const SHELL_COMMAND_FLAG = /^-[A-Za-z]*c[A-Za-z]*$/u;
40
+ // Between `-c` and its script a shell still reads options: `--` and `-` end them,
41
+ // and a short cluster with `o` or `O` (`-o`, `-eo`, `-co`, `+O`) takes the next
42
+ // word as its value.
43
+ const SHELL_OPTION = /^[-+]/u;
44
+ const SHELL_END_OF_OPTIONS = new Set(['--', '-']);
45
+ const SHELL_VALUE_OPTION = /^[-+][A-Za-z]*[oO][A-Za-z]*$/u;
46
+ // Programs that make the running shell read a file (`source /dev/stdin`).
47
+ const SOURCE_PROGRAMS = new Set(['source', '.']);
48
+ const SEARCH_PROGRAMS = new Set(['grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack']);
49
+ export const MAX_NESTING = 2;
50
+ const EXTENSION_COMMANDS = new Set(['hooks', 'mcp']);
51
+ const EXTENSION_CHANGES = new Set(['enable', 'disable', 'reset', 'login']);
52
+ export const GIT_OPTIONS_WITH_VALUE = new Set([
53
+ '-C',
54
+ '-c',
55
+ '--git-dir',
56
+ '--work-tree',
57
+ '--namespace',
58
+ ]);
59
+ const PROTECTED_BRANCHES = new Set(['main', 'master']);
60
+ const GIT_TIMEOUT_MS = 2_000;
61
+ const DANGEROUS_RM_TARGETS = new Set([
62
+ '/',
63
+ '/*',
64
+ '~',
65
+ '~/',
66
+ '~/*',
67
+ '.',
68
+ './',
69
+ './*',
70
+ '..',
71
+ '../',
72
+ '*',
73
+ '$HOME',
74
+ '$HOME/',
75
+ '$HOME/*',
76
+ '${HOME}',
77
+ '${HOME}/',
78
+ ]);
79
+ const DATABASE_CLIENTS = new Set([
80
+ 'psql',
81
+ 'mysql',
82
+ 'mariadb',
83
+ 'sqlite3',
84
+ 'sqlcmd',
85
+ 'clickhouse-client',
86
+ 'cockroach',
87
+ 'duckdb',
88
+ ]);
89
+ // Codex's user config named through a variable or `~` (`~/.codex/config.toml`,
90
+ // `$CODEX_HOME/config.toml`); resolved paths are compared as well.
91
+ const CODEX_CONFIG_MENTION =
92
+ /(?:~|\$\{?HOME\}?)\/\.codex\/config\.toml|\$\{?CODEX_HOME\}?\/config\.toml/u;
93
+ const DESTRUCTIVE_SQL =
94
+ /\b(?:DROP\s+(?:DATABASE|TABLE|SCHEMA)|TRUNCATE(?:\s+TABLE)?\s+[A-Za-z_"`])/iu;
95
+
96
+ const MESSAGES = {
97
+ en: {
98
+ secret: 'refused: this touches a secret file (rule: %s). Ask the user to do it themselves.',
99
+ extensions:
100
+ 'refused: AISAC extensions are changed only by the user, from their own terminal (aisac hooks / aisac mcp).',
101
+ codexConfig:
102
+ "refused: Codex's config.toml holds the switches for the AISAC guardrails; only the user changes it, from their own terminal.",
103
+ pushProtected: 'refused: push to %s. Open a pull request instead.',
104
+ pushForce:
105
+ 'refused: force push. Use --force-with-lease on your own branch if it is really needed.',
106
+ rm: 'refused: rm -rf on %s.',
107
+ sql: 'refused: destructive SQL (DROP or TRUNCATE) sent to a database client.',
108
+ bus: 'refused: this names the AISAC manager bus directory, which only the client reads and writes (aisac workers lists the sessions).',
109
+ delegate:
110
+ 'refused: approvals are delegated only by the user, from their own terminal (aisac workers delegate).',
111
+ },
112
+ 'pt-BR': {
113
+ secret:
114
+ 'recusado: isto mexe num arquivo de segredo (regra: %s). Peça ao usuário para fazer isso.',
115
+ extensions:
116
+ 'recusado: as extensões do AISAC só são mudadas pelo usuário, no terminal dele (aisac hooks / aisac mcp).',
117
+ codexConfig:
118
+ 'recusado: o config.toml do Codex guarda os interruptores dos guardrails do AISAC; só o usuário muda esse arquivo, no terminal dele.',
119
+ pushProtected: 'recusado: push na %s. Abra um pull request.',
120
+ pushForce:
121
+ 'recusado: push forçado. Use --force-with-lease na sua branch, se for mesmo preciso.',
122
+ rm: 'recusado: rm -rf em %s.',
123
+ sql: 'recusado: SQL destrutivo (DROP ou TRUNCATE) enviado a um cliente de banco.',
124
+ bus: 'recusado: isto nomeia o diretório do bus do gerente do AISAC, que só o cliente lê e grava (aisac workers lista as sessões).',
125
+ delegate:
126
+ 'recusado: só o usuário delega aprovações, no terminal dele (aisac workers delegate).',
127
+ },
128
+ };
129
+
130
+ /** @param {GuardContext} context @param {keyof typeof MESSAGES.en} key @param {string} [value] */
131
+ function message(context, key, value = '') {
132
+ return (MESSAGES[context.locale] ?? MESSAGES.en)[key].replace('%s', value);
133
+ }
134
+
135
+ /** @param {unknown} value @returns {Record<string, unknown>} */
136
+ function record(value) {
137
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
138
+ ? /** @type {Record<string, unknown>} */ (value)
139
+ : {};
140
+ }
141
+
142
+ /**
143
+ * The secret rule a path matches, or null. Names only. With `extensions`
144
+ * false, only dot names, key names and private directories count: used for
145
+ * names found inside code, where `obj.key` is not a file.
146
+ * @param {string} path
147
+ * @param {{ extensions?: boolean }} [options]
148
+ * @returns {string | null}
149
+ */
150
+ export function secretRule(path, options = {}) {
151
+ const segments = path.split(/[/\\]/u).filter((segment) => segment.length > 0);
152
+ if (segments.some((segment) => SECRET_DIRECTORIES.has(segment))) return 'private directory';
153
+ const name = segments.at(-1) ?? '';
154
+ if (name === '.env') return '.env';
155
+ if (name.startsWith('.env.')) {
156
+ const suffix = name.slice('.env.'.length);
157
+ return TEMPLATE_SUFFIXES.has(suffix) ? null : '.env.*';
158
+ }
159
+ if (/^\.env[*?[]/u.test(name)) return '.env*';
160
+ if (SECRET_NAMES.has(name)) return name;
161
+ if (PRIVATE_KEY_NAME.test(name) && !name.endsWith('.pub')) return 'private key';
162
+ if (options.extensions === false) return null;
163
+ if (CERTIFICATE_EXTENSION.test(name)) return 'key or certificate file';
164
+ if (KEY_EXTENSION.test(name) && !name.startsWith('.')) return 'key file';
165
+ if (SERVICE_ACCOUNT.test(name)) return 'service account key';
166
+ return null;
167
+ }
168
+
169
+ /** Resolve `~`, `$HOME` and relative paths for comparison. @param {string} path @param {GuardContext} context */
170
+ function resolvePath(path, context) {
171
+ const expanded = path
172
+ .replace(/^~(?=\/|$)/u, context.home)
173
+ .replace(/^\$\{?HOME\}?(?=\/|$)/u, context.home);
174
+ return isAbsolute(expanded) ? resolve(expanded) : resolve(context.projectDir, expanded);
175
+ }
176
+
177
+ /**
178
+ * The FR2.2 refusal for a path that names a file only the user may change: the
179
+ * preferences file, or Codex's user config. Null for any other path.
180
+ * @param {string} path @param {GuardContext} context
181
+ * @returns {string | null}
182
+ */
183
+ function protectedRefusal(path, context) {
184
+ if (path.length === 0) return null;
185
+ const resolved = resolvePath(path, context);
186
+ if (resolved === resolve(context.prefsPath)) return message(context, 'extensions');
187
+ if ((context.codexConfigs ?? []).some((config) => resolved === resolve(config)))
188
+ return message(context, 'codexConfig');
189
+ return null;
190
+ }
191
+
192
+ /** Path-like parts of a word: the word itself and a `--flag=value` / `VAR=value` value. @param {string} word */
193
+ function pathCandidates(word) {
194
+ const equals = word.lastIndexOf('=');
195
+ return equals === -1 ? [word] : [word, word.slice(equals + 1)];
196
+ }
197
+
198
+ /**
199
+ * `secrets-guard` (FR2.1) with the FR2.2 self-protection. A shell command that runs
200
+ * the client to change an extension is found by the walk the bus guard uses
201
+ * (`walkCommand`, below): the client anywhere in a command and in the command lines
202
+ * nested in it.
203
+ * @param {ToolEvent} event @param {GuardContext} context
204
+ * @returns {string | null}
205
+ */
206
+ export function secretsGuard(event, context) {
207
+ const tool = typeof event.tool_name === 'string' ? event.tool_name : '';
208
+ const input = record(event.tool_input);
209
+ if (tool === 'Bash') {
210
+ const command = typeof input.command === 'string' ? input.command : '';
211
+ const scope = busScope(context);
212
+ const directories = startDirectories(event, context);
213
+ const change = walkCommand(command, scope, directories, 0, EXTENSION_RULES);
214
+ return change === null ? secretsInCommand(command, context) : message(context, change);
215
+ }
216
+ // A Codex patch writes every file its headers name (E6b).
217
+ if (tool === PATCH_TOOL) {
218
+ for (const path of patchPaths(input.command)) {
219
+ const refusal = writeRefusal(path, context);
220
+ if (refusal !== null) return refusal;
221
+ }
222
+ return null;
223
+ }
224
+ const pathValue = tool === 'Grep' ? input.path : (input.file_path ?? input.notebook_path);
225
+ if (typeof pathValue !== 'string' || pathValue.length === 0) return null;
226
+ if (tool === 'Read' || tool === 'Grep') {
227
+ const rule = secretRule(pathValue);
228
+ return rule === null ? null : message(context, 'secret', rule);
229
+ }
230
+ return writeRefusal(pathValue, context);
231
+ }
232
+
233
+ /** A write to a protected file or a secret file. @param {string} path @param {GuardContext} context */
234
+ function writeRefusal(path, context) {
235
+ const refusal = protectedRefusal(path, context);
236
+ if (refusal !== null) return refusal;
237
+ const rule = secretRule(path);
238
+ return rule === null ? null : message(context, 'secret', rule);
239
+ }
240
+
241
+ /**
242
+ * The FR2.2 refusal for text that names a protected file anywhere in it.
243
+ * @param {string} text @param {GuardContext} context
244
+ * @returns {string | null}
245
+ */
246
+ function mentionsProtected(text, context) {
247
+ if (text.includes(resolve(context.prefsPath)) || text.includes('.aibrain/extensions.json'))
248
+ return message(context, 'extensions');
249
+ if (
250
+ CODEX_CONFIG_MENTION.test(text) ||
251
+ (context.codexConfigs ?? []).some((config) => text.includes(resolve(config)))
252
+ )
253
+ return message(context, 'codexConfig');
254
+ return null;
255
+ }
256
+
257
+ /** Contents of `$(...)` and backtick substitutions in a word. @param {string} word */
258
+ function substitutions(word) {
259
+ /** @type {string[]} */
260
+ const found = [];
261
+ for (const match of word.matchAll(/\$\(([^()]*(?:\([^()]*\)[^()]*)*)\)|`([^`]*)`/gu))
262
+ found.push(match[1] ?? match[2] ?? '');
263
+ return found;
264
+ }
265
+
266
+ /**
267
+ * A word's refusal. A word without spaces is a path candidate and a list of
268
+ * names; a word with spaces (a quoted script or message) counts only for
269
+ * quoted names inside it, so `git commit -m "ignore .env files"` passes.
270
+ * @param {string} word @param {GuardContext} context @param {number} depth
271
+ * @returns {string | null}
272
+ */
273
+ function wordRefusal(word, context, depth) {
274
+ const mention = mentionsProtected(word, context);
275
+ if (mention !== null) return mention;
276
+ if (!/\s/u.test(word)) {
277
+ for (const candidate of pathCandidates(word)) {
278
+ const refusal = protectedRefusal(candidate, context);
279
+ if (refusal !== null) return refusal;
280
+ const rule = secretRule(candidate);
281
+ if (rule !== null) return message(context, 'secret', rule);
282
+ }
283
+ for (const name of word.split(NAME_DELIMITERS)) {
284
+ const rule = name.length > 0 ? secretRule(name, { extensions: false }) : null;
285
+ if (rule !== null) return message(context, 'secret', rule);
286
+ }
287
+ } else {
288
+ for (const match of word.matchAll(QUOTED_NAME)) {
289
+ const rule = secretRule(match[1] ?? '', { extensions: false });
290
+ if (rule !== null) return message(context, 'secret', rule);
291
+ }
292
+ }
293
+ if (depth < MAX_NESTING)
294
+ for (const inner of substitutions(word)) {
295
+ const refusal = secretsInCommand(inner, context, depth + 1);
296
+ if (refusal !== null) return refusal;
297
+ }
298
+ return null;
299
+ }
300
+
301
+ /** Words that are search patterns, not files (`grep PATTERN`, `rg -e PATTERN`). @param {string[]} words */
302
+ function searchPatternIndexes(words) {
303
+ const indexes = new Set();
304
+ if (!SEARCH_PROGRAMS.has(programName(words[0] ?? ''))) return indexes;
305
+ let explicit = false;
306
+ for (let index = 1; index < words.length; index += 1)
307
+ if (words[index] === '-e' || words[index] === '--regexp') {
308
+ indexes.add(index + 1);
309
+ explicit = true;
310
+ }
311
+ if (!explicit) {
312
+ const first = words.findIndex((word, index) => index > 0 && !word.startsWith('-'));
313
+ if (first !== -1) indexes.add(first);
314
+ }
315
+ return indexes;
316
+ }
317
+
318
+ /**
319
+ * The script a shell runs from its arguments: after `-c` or a short-option cluster
320
+ * that contains `c` (`-lc`, `-euc`), the first word that is not an option, as the
321
+ * shell reads it (`bash -c -- "..."`, `sh -c -e "..."`, `bash -c -o pipefail "..."`).
322
+ * @param {string[]} words Effective words, the shell first. @returns {string | undefined}
323
+ */
324
+ function shellScript(words) {
325
+ const flag = words.findIndex((word, index) => index > 0 && SHELL_COMMAND_FLAG.test(word));
326
+ if (flag === -1) return undefined;
327
+ const first = SHELL_VALUE_OPTION.test(words[flag] ?? '') ? flag + 2 : flag + 1;
328
+ for (let index = first; index < words.length; index += 1) {
329
+ const word = words[index] ?? '';
330
+ if (SHELL_END_OF_OPTIONS.has(word)) return words[index + 1];
331
+ if (SHELL_VALUE_OPTION.test(word)) index += 1;
332
+ else if (!SHELL_OPTION.test(word)) return word;
333
+ }
334
+ return undefined;
335
+ }
336
+
337
+ /**
338
+ * Does a line feed its here-strings to a shell that reads its script from standard
339
+ * input: a shell with no `-c` script (`bash <<< "..."`, `sh -s <<< "..."`), or
340
+ * `source`/`.` (`source /dev/stdin <<< "..."`)?
341
+ * @param {import('./shell-words.mjs').ShellCommand[]} commands
342
+ */
343
+ function feedsShellStdin(commands) {
344
+ return commands.some((item) => {
345
+ const words = effectiveWords(item.words);
346
+ const program = programName(words[0] ?? '');
347
+ if (SOURCE_PROGRAMS.has(words[0] ?? '')) return true;
348
+ return SHELLS.has(program) && shellScript(words) === undefined;
349
+ });
350
+ }
351
+
352
+ /**
353
+ * The refusal of a line's here-string bodies, which the splitter drops: each is a
354
+ * word of the line (`cat <<< "$(cat .env)"`) and, fed to a shell, a nested script.
355
+ * @param {string} command @param {import('./shell-words.mjs').ShellCommand[]} commands
356
+ * @param {GuardContext} context @param {number} depth
357
+ * @returns {string | null}
358
+ */
359
+ function hereStringSecrets(command, commands, context, depth) {
360
+ if (!command.includes(HERE_STRING)) return null;
361
+ const bodies = hereStrings(command);
362
+ const isScript = depth < MAX_NESTING && feedsShellStdin(commands);
363
+ for (const body of bodies) {
364
+ const refusal =
365
+ wordRefusal(body, context, depth) ??
366
+ (isScript ? secretsInCommand(body, context, depth + 1) : null);
367
+ if (refusal !== null) return refusal;
368
+ }
369
+ return null;
370
+ }
371
+
372
+ /** @param {string} command @param {GuardContext} context @param {number} [depth] @returns {string | null} */
373
+ function secretsInCommand(command, context, depth = 0) {
374
+ if (command.length === 0) return null;
375
+ const parsed = splitShell(command);
376
+ if (!parsed.ok) {
377
+ const mention = mentionsProtected(command, context);
378
+ if (mention !== null) return mention;
379
+ for (const name of command.split(NAME_DELIMITERS)) {
380
+ const rule = name.length > 0 ? secretRule(name, { extensions: false }) : null;
381
+ if (rule !== null) return message(context, 'secret', rule);
382
+ }
383
+ return null;
384
+ }
385
+ for (const item of parsed.commands) {
386
+ const words = effectiveWords(item.words);
387
+ const program = programName(words[0] ?? '');
388
+ const patterns = searchPatternIndexes(words);
389
+ const prefix = item.words.slice(0, item.words.length - words.length);
390
+ for (const [index, word] of [...prefix, ...words].entries()) {
391
+ if (patterns.has(index - prefix.length)) continue;
392
+ const refusal = wordRefusal(word, context, depth);
393
+ if (refusal !== null) return refusal;
394
+ }
395
+ for (const target of item.targets) {
396
+ const refusal = wordRefusal(target, context, depth);
397
+ if (refusal !== null) return refusal;
398
+ }
399
+ // `bash -c "cat .env"`, `bash -lc "..."` and `eval "..."` carry a whole command in one word.
400
+ const script = SHELLS.has(program)
401
+ ? shellScript(words)
402
+ : program === 'eval'
403
+ ? words.slice(1).join(' ')
404
+ : undefined;
405
+ if (script !== undefined && depth < MAX_NESTING) {
406
+ const refusal = secretsInCommand(script, context, depth + 1);
407
+ if (refusal !== null) return refusal;
408
+ }
409
+ }
410
+ return hereStringSecrets(command, parsed.commands, context, depth);
411
+ }
412
+
413
+ /** Destination branch of a push refspec (`HEAD:main`, `+main`, `refs/heads/main`). @param {string} refspec */
414
+ function refspecDestination(refspec) {
415
+ const unforced = refspec.startsWith('+') ? refspec.slice(1) : refspec;
416
+ const colon = unforced.lastIndexOf(':');
417
+ const destination = colon === -1 ? unforced : unforced.slice(colon + 1);
418
+ return destination.replace(/^refs\/heads\//u, '');
419
+ }
420
+
421
+ /** @param {string} directory */
422
+ function currentBranch(directory) {
423
+ try {
424
+ return execFileSync('git', ['-C', directory, 'symbolic-ref', '--short', 'HEAD'], {
425
+ encoding: 'utf8',
426
+ timeout: GIT_TIMEOUT_MS,
427
+ stdio: ['ignore', 'pipe', 'ignore'],
428
+ }).trim();
429
+ } catch {
430
+ return '';
431
+ }
432
+ }
433
+
434
+ /**
435
+ * `git-guard`: pushes to main or master, and force pushes.
436
+ * @param {ToolEvent} event @param {GuardContext} context
437
+ * @returns {string | null}
438
+ */
439
+ export function gitGuard(event, context) {
440
+ const command = record(event.tool_input).command;
441
+ if (event.tool_name !== 'Bash' || typeof command !== 'string') return null;
442
+ const parsed = splitShell(command);
443
+ if (!parsed.ok) return null;
444
+ for (const item of parsed.commands) {
445
+ const words = effectiveWords(item.words);
446
+ if (programName(words[0] ?? '') !== 'git') continue;
447
+ let index = 1;
448
+ let directory = context.projectDir;
449
+ while (index < words.length && (words[index] ?? '').startsWith('-')) {
450
+ const option = words[index] ?? '';
451
+ if (GIT_OPTIONS_WITH_VALUE.has(option)) {
452
+ if (option === '-C') directory = resolve(directory, words[index + 1] ?? '.');
453
+ index += 2;
454
+ } else index += 1;
455
+ }
456
+ if (words[index] !== 'push') continue;
457
+ const args = words.slice(index + 1);
458
+ const flags = args.filter((word) => word.startsWith('-'));
459
+ const positional = args.filter((word) => !word.startsWith('-'));
460
+ const forced =
461
+ flags.some(
462
+ (flag) =>
463
+ flag === '--force' ||
464
+ flag === '--mirror' ||
465
+ (/^-[A-Za-z]+$/u.test(flag) && flag.includes('f')),
466
+ ) || positional.slice(1).some((refspec) => refspec.startsWith('+'));
467
+ if (forced) return message(context, 'pushForce');
468
+ if (flags.includes('--all')) return message(context, 'pushProtected', 'main/master (--all)');
469
+ const refspecs = positional.slice(1);
470
+ const destinations =
471
+ refspecs.length > 0 ? refspecs.map(refspecDestination) : [currentBranch(directory)];
472
+ const protectedBranch = destinations.find((branch) => PROTECTED_BRANCHES.has(branch));
473
+ if (protectedBranch !== undefined) return message(context, 'pushProtected', protectedBranch);
474
+ }
475
+ return null;
476
+ }
477
+
478
+ /**
479
+ * `destructive-guard`: rm -rf on a root-like target, and destructive SQL sent to a client.
480
+ * @param {ToolEvent} event @param {GuardContext} context
481
+ * @returns {string | null}
482
+ */
483
+ export function destructiveGuard(event, context) {
484
+ const command = record(event.tool_input).command;
485
+ if (event.tool_name !== 'Bash' || typeof command !== 'string') return null;
486
+ const parsed = splitShell(command);
487
+ if (!parsed.ok) return null;
488
+ let databaseClient = false;
489
+ for (const item of parsed.commands) {
490
+ const words = effectiveWords(item.words);
491
+ const program = programName(words[0] ?? '');
492
+ if (DATABASE_CLIENTS.has(program)) databaseClient = true;
493
+ if (program !== 'rm') continue;
494
+ const flags = words.slice(1).filter((word) => word.startsWith('-'));
495
+ const recursive = flags.some(
496
+ (flag) => flag === '--recursive' || (/^-[A-Za-z]+$/u.test(flag) && /[rR]/u.test(flag)),
497
+ );
498
+ const force = flags.some(
499
+ (flag) => flag === '--force' || (/^-[A-Za-z]+$/u.test(flag) && flag.includes('f')),
500
+ );
501
+ const target = words
502
+ .slice(1)
503
+ .find((word) => !word.startsWith('-') && DANGEROUS_RM_TARGETS.has(word));
504
+ if (recursive && force && target !== undefined) return message(context, 'rm', target);
505
+ }
506
+ return databaseClient && DESTRUCTIVE_SQL.test(command) ? message(context, 'sql') : null;
507
+ }
508
+
509
+ // bus-guard (spec aisac-engineering-manager FR10, D13). Same name as
510
+ // BUS_DIRECTORY in manager/bus.mjs; a test keeps them equal.
511
+ const BUS_DIRECTORY = 'bus';
512
+ // The default bus location under any home, as code or a script spells it.
513
+ const DEFAULT_BUS_MENTION = '.aibrain/bus';
514
+ // The state-root variable (state.mjs) at the start of a word, also `${VAR:-default}`.
515
+ // The default part is bounded (256), so a long text stays linear.
516
+ const STATE_ROOT_PREFIX =
517
+ /^\$(?:AIBRAIN_STATE_DIR(?![A-Za-z0-9_])|\{AIBRAIN_STATE_DIR(?::?[-=?+][^}]{0,256})?\})/u;
518
+ // The state-root variable followed by `/bus` anywhere in a text, quotes allowed.
519
+ const STATE_ROOT_BUS_MENTION =
520
+ /\$(?:AIBRAIN_STATE_DIR(?![A-Za-z0-9_])|\{AIBRAIN_STATE_DIR(?::?[-=?+][^}]{0,256})?\})["']?\/+["']?bus(?![A-Za-z0-9._-])/iu;
521
+ const HOME_PREFIX = /^(?:~|\$(?:HOME(?![A-Za-z0-9_])|\{HOME\}))(?=\/|$)/u;
522
+ const USER_HOME_PREFIX = /^~([A-Za-z0-9._-]+)(?=\/|$)/u;
523
+ const PWD_PREFIX = /^(?:~\+|\$(?:PWD(?![A-Za-z0-9_])|\{PWD\}))(?=\/|$)/u;
524
+ const OTHER_VARIABLE_OR_HOME = /^[~$]/u;
525
+ const ROOTED_WORD = /^[/~$]/u;
526
+ const VARIABLE_PREFIX = /^\$(?:[A-Za-z_][A-Za-z0-9_]*|[0-9]|\{[^}]*\})/u;
527
+ const PATH_CHARACTER = /[A-Za-z0-9._-]/u;
528
+ const GLOB_CHARACTER = /[*?[]/u;
529
+ const GLOBSTAR = '**';
530
+ const STAR_TOKEN = '*';
531
+ const ANY_TOKEN = '?';
532
+ const MAX_BRACKET_LENGTH = 256;
533
+ // PATH_MAX on Linux: a longer word is no path a tool can open, so it counts for
534
+ // mentions only, and the path work per word stays bounded.
535
+ const MAX_PATH_WORD_LENGTH = 4096;
536
+ const WHITESPACE = /\s/u;
537
+ const DIRECTORY_CHANGES = new Set(['cd', 'pushd']);
538
+ const DIRECTORY_LOSSES = new Set(['popd']);
539
+ // Shells beyond SHELLS (which the secrets guard reads): their command lines are read
540
+ // here only, so the secrets guard keeps its behaviour for commands without the client.
541
+ const OTHER_SHELLS = new Set([
542
+ 'fish',
543
+ 'busybox',
544
+ 'ash',
545
+ 'mksh',
546
+ 'yash',
547
+ 'tcsh',
548
+ 'csh',
549
+ 'elvish',
550
+ 'nu',
551
+ 'xonsh',
552
+ 'pwsh',
553
+ 'powershell',
554
+ 'cmd',
555
+ ]);
556
+ // Programs that take a whole command line as one argument (`script -qc "..."`,
557
+ // `su -c "..."`, `tmux new-session "..."`, `ssh host "..."`, `socat - EXEC:"..."`),
558
+ // the way a session reaches a pseudo-terminal. A command with any of them, or with
559
+ // a shell, has every word with whitespace read as a command line.
560
+ const COMMAND_LINE_PROGRAMS = new Set([
561
+ ...OTHER_SHELLS,
562
+ 'script',
563
+ 'su',
564
+ 'runuser',
565
+ 'tmux',
566
+ 'screen',
567
+ 'zellij',
568
+ 'byobu',
569
+ 'dtach',
570
+ 'abduco',
571
+ 'watch',
572
+ 'ssh',
573
+ 'expect',
574
+ 'unbuffer',
575
+ 'flock',
576
+ 'setsid',
577
+ 'timeout',
578
+ 'xargs',
579
+ 'parallel',
580
+ 'socat',
581
+ 'entr',
582
+ ]);
583
+ // `env -S "..."` and `env --split-string="..."` split a string into a command.
584
+ const ENV_PROGRAM = 'env';
585
+ const ENV_SPLIT_FLAG = /^(?:-[A-Za-z]*S|--split-string)$/u;
586
+ const ENV_SPLIT_PREFIX = '--split-string=';
587
+ const OPTION_VALUE = /^--?[A-Za-z][\w-]*=/u;
588
+ // Programs that run what arrives on standard input, as arguments or as a script.
589
+ const STDIN_RUNNERS = new Set(['xargs', 'parallel', ...SHELLS, ...OTHER_SHELLS]);
590
+ const SOURCE_COMMANDS = new Set(['source', '.']);
591
+ const JS_RUNTIMES = new Set(['node', 'nodejs', 'bun', 'deno', 'tsx', 'ts-node']);
592
+ // Programs whose `-c` or `-e` word is code that may start a process.
593
+ const INTERPRETERS =
594
+ /^(?:node|nodejs|bun|deno|tsx|ts-node|python[0-9.]*|pypy[0-9.]*|perl[0-9.]*|ruby|php[0-9.]*|lua(?:jit)?[0-9.]*|osascript|rscript|julia|tclsh|g?awk)$/u;
595
+ // A git alias that runs a shell command line (`alias.x=!cmd`, `git config alias.x "!cmd"`).
596
+ const GIT_SHELL_ALIAS = /^(?:alias\.[^=]*=)?!(.*)$/su;
597
+ // The client by name (its two bins), lower case, also with an extension (`aisac.mjs`).
598
+ const CLIENT_NAME = /^(?:aisac|aibrain)(?:\.[a-z0-9]+)?$/u;
599
+ const CLIENT_PACKAGE = /^@(?:aisac\/cli|brunobracaioli\/aibrain)(?:@\S*)?$/u;
600
+ // The installed package folder, or anything in it.
601
+ const CLIENT_INSTALL_PATH = /(?:^|\/)@(?:aisac\/cli|brunobracaioli\/aibrain)(?:\/|$)/u;
602
+ const CLIENT_BIN_PATH = /(?:^|\/)\.?bin\/(?:aisac|aibrain)(?:\.[a-z0-9]+)?$/u;
603
+ // This repository's client folder (`clients/aibrain`) and a `cli.mjs` inside it,
604
+ // which count only where a runtime runs them: a path to them is also an operand.
605
+ const CLIENT_FOLDER = 'aibrain';
606
+ const CLIENT_SCRIPT = /^cli\.[cm]?js$/u;
607
+ const WORKERS_COMMAND = 'workers';
608
+ const DELEGATE_ACTION = 'delegate';
609
+ const HERE_STRING = '<<<';
610
+ const MAX_HERE_STRINGS = 8;
611
+ const ANSI_C_QUOTE = "$'";
612
+ // A word the shell rewrites before it runs: a parameter, a substitution, a glob, a
613
+ // brace expansion. The splitter has removed the quotes, so a quoted `*` counts too.
614
+ const EXPANDING_CHARACTER = /[$`*?[]/u;
615
+ const SEQUENCE_EXPANSION = /\{[^{}]*\.\.[^{}]*\}/u;
616
+ // Rough words for reading code and text: names, paths and package names stay whole.
617
+ const LOOSE_TOKEN_SEPARATOR = /[^a-z0-9_.@/-]+/u;
618
+ const ESCAPE_SEQUENCE =
619
+ /\\(?:x([0-9A-Fa-f]{1,2})|u([0-9A-Fa-f]{4})|([0-7]{1,3})|([abefnrtv\\'"]))/gu;
620
+ /** @type {Readonly<Record<string, string>>} */
621
+ const NAMED_ESCAPES = Object.freeze({
622
+ a: '\u0007',
623
+ b: '\b',
624
+ e: '\u001b',
625
+ f: '\f',
626
+ n: '\n',
627
+ r: '\r',
628
+ t: '\t',
629
+ v: '\v',
630
+ '\\': '\\',
631
+ "'": "'",
632
+ '"': '"',
633
+ });
634
+ const OCTAL = 8;
635
+ const HEXADECIMAL = 16;
636
+ const MAX_BRACE_EXPANSIONS = 64;
637
+
638
+ /**
639
+ * @typedef {object} BusScope
640
+ * @property {string} root The state root, resolved.
641
+ * @property {string} rootKey The state root, lower case, for comparisons.
642
+ * @property {string} home
643
+ * @property {readonly string[]} busSegments The bus directory's names, lower case.
644
+ * @property {readonly string[]} absoluteMentions The bus directory's absolute path, lower case.
645
+ * @property {readonly string[]} relativeMentions `.aibrain/bus`, and the bus path from home.
646
+ */
647
+ /**
648
+ * What one command line names, across its simple commands.
649
+ * @typedef {object} LineState
650
+ * @property {boolean} namesRoot A word is the state root.
651
+ * @property {boolean} busTail A word is a path with a `bus` tail.
652
+ * @property {boolean} feedsStdin A command runs what its standard input brings.
653
+ * @property {boolean} namesClient A word names the client.
654
+ * @property {boolean} computedDelegate A rewritten program word runs `workers` and a change.
655
+ * @property {boolean} computedExtension A rewritten program word runs `hooks` or `mcp` and a change.
656
+ * @property {Set<string>} tokens The rough words of the line, lower case.
657
+ */
658
+ /** @typedef {'bus' | 'delegate' | 'extensions'} WalkRefusal */
659
+ /** @typedef {{ bus: boolean, delegate: boolean, extensions: boolean }} WalkRules */
660
+ /** @typedef {(token: string) => boolean} TokenTest */
661
+
662
+ /** @type {Readonly<WalkRules>} */
663
+ const BUS_RULES = Object.freeze({ bus: true, delegate: true, extensions: false });
664
+ /** @type {Readonly<WalkRules>} */
665
+ const EXTENSION_RULES = Object.freeze({ bus: false, delegate: false, extensions: true });
666
+
667
+ // Work done by the walk and the path matching, in steps: characters scanned and
668
+ // match states visited. `busGuardWork` reports it, so the linear-time test needs no
669
+ // clock. It never changes a decision.
670
+ let workSteps = 0;
671
+ /** @param {number} steps */
672
+ function tick(steps) {
673
+ workSteps += steps;
674
+ }
675
+
676
+ /** @param {string} path */
677
+ function pathSegments(path) {
678
+ return path.split('/').filter((segment) => segment.length > 0);
679
+ }
680
+
681
+ /**
682
+ * The bus directory of this session, `<state root>/bus`, and the texts that name it.
683
+ * @param {GuardContext} context
684
+ * @returns {BusScope}
685
+ */
686
+ function busScope(context) {
687
+ // Both hosts give the guard `<state root>/extensions.json` (FR3); the dispatcher
688
+ // passes no state root of its own.
689
+ const root = resolve(dirname(context.prefsPath));
690
+ const home = resolve(context.home);
691
+ const bus = join(root, BUS_DIRECTORY).toLowerCase();
692
+ const fromHome = relative(home.toLowerCase(), bus);
693
+ const underHome =
694
+ fromHome.length > 0 &&
695
+ fromHome !== '..' &&
696
+ !fromHome.startsWith('../') &&
697
+ !isAbsolute(fromHome);
698
+ return {
699
+ root,
700
+ rootKey: root.toLowerCase(),
701
+ home,
702
+ busSegments: pathSegments(bus),
703
+ absoluteMentions: [bus],
704
+ relativeMentions: [...new Set([DEFAULT_BUS_MENTION, ...(underHome ? [fromHome] : [])])],
705
+ };
706
+ }
707
+
708
+ /** Where a relative path starts: the payload's cwd and the project. @param {ToolEvent} event @param {GuardContext} context */
709
+ function startDirectories(event, context) {
710
+ const cwd = typeof event.cwd === 'string' && isAbsolute(event.cwd) ? [resolve(event.cwd)] : [];
711
+ return [...new Set([...cwd, resolve(context.projectDir)])];
712
+ }
713
+
714
+ /**
715
+ * A word with a home, `~user` or state-root prefix made absolute, an absolute word
716
+ * as it is, null for anything else.
717
+ * @param {string} word @param {BusScope} scope
718
+ */
719
+ function rootedPath(word, scope) {
720
+ const home = HOME_PREFIX.exec(word);
721
+ if (home !== null) return scope.home + word.slice(home[0].length);
722
+ const user = USER_HOME_PREFIX.exec(word);
723
+ if (user !== null) return join(dirname(scope.home), user[1] ?? '') + word.slice(user[0].length);
724
+ const state = STATE_ROOT_PREFIX.exec(word);
725
+ if (state !== null) return scope.root + word.slice(state[0].length);
726
+ return isAbsolute(word) ? word : null;
727
+ }
728
+
729
+ /**
730
+ * The absolute paths a word can mean, normalized as text (no symlink is read): one
731
+ * for an absolute or home-based word, one per known directory for a relative word
732
+ * (`$PWD/x` and `~+/x` are relative), none behind any other variable.
733
+ * @param {string} word @param {BusScope} scope @param {readonly string[]} directories
734
+ */
735
+ function resolvedPaths(word, scope, directories) {
736
+ tick(word.length * (directories.length + 1));
737
+ const pwd = PWD_PREFIX.exec(word);
738
+ const local = pwd === null ? word : `.${word.slice(pwd[0].length)}`;
739
+ const rooted = rootedPath(local, scope);
740
+ if (rooted !== null) return [resolve(rooted)];
741
+ if (OTHER_VARIABLE_OR_HOME.test(local)) return [];
742
+ return directories.map((directory) => resolve(directory, local));
743
+ }
744
+
745
+ /**
746
+ * Index of the `]` that closes the bracket expression opening at `start`, or -1.
747
+ * POSIX classes inside it (`[:alpha:]`) are skipped; the scan is bounded.
748
+ * @param {string} pattern @param {number} start
749
+ */
750
+ function bracketEnd(pattern, start) {
751
+ const limit = Math.min(pattern.length, start + MAX_BRACKET_LENGTH);
752
+ let index = start + 1;
753
+ if (pattern[index] === '!' || pattern[index] === '^') index += 1;
754
+ if (pattern[index] === ']') index += 1;
755
+ let inClass = false;
756
+ for (; index < limit; index += 1) {
757
+ const character = pattern[index];
758
+ if (inClass && character === ':' && pattern[index + 1] === ']') {
759
+ inClass = false;
760
+ index += 1;
761
+ } else if (!inClass && character === '[' && pattern[index + 1] === ':') {
762
+ inClass = true;
763
+ index += 1;
764
+ } else if (!inClass && character === ']') return index;
765
+ }
766
+ return -1;
767
+ }
768
+
769
+ /**
770
+ * A glob segment as tokens: `*`, `?`, or one literal character. A bracket
771
+ * expression becomes `?`: it may match any one character, which errs on refusing.
772
+ * @param {string} pattern
773
+ */
774
+ function globTokens(pattern) {
775
+ /** @type {string[]} */
776
+ const tokens = [];
777
+ for (let index = 0; index < pattern.length; index += 1) {
778
+ const character = pattern[index] ?? '';
779
+ const end = character === '[' ? bracketEnd(pattern, index) : -1;
780
+ tick(character === '[' ? Math.min(MAX_BRACKET_LENGTH, pattern.length - index) : 1);
781
+ if (end !== -1) {
782
+ tokens.push(ANY_TOKEN);
783
+ index = end;
784
+ } else if (character !== STAR_TOKEN || tokens.at(-1) !== STAR_TOKEN) tokens.push(character);
785
+ }
786
+ return tokens;
787
+ }
788
+
789
+ /**
790
+ * Wildcard match that remembers the last star: no regular expression, so no
791
+ * backtracking blow-up, and at most tokens × name steps.
792
+ * @param {string[]} tokens @param {string} name
793
+ */
794
+ function globMatches(tokens, name) {
795
+ let token = 0;
796
+ let position = 0;
797
+ let star = -1;
798
+ let mark = 0;
799
+ while (position < name.length) {
800
+ tick(1);
801
+ const current = tokens[token];
802
+ if (current === STAR_TOKEN) {
803
+ star = token;
804
+ token += 1;
805
+ mark = position;
806
+ } else if (current !== undefined && (current === ANY_TOKEN || current === name[position])) {
807
+ token += 1;
808
+ position += 1;
809
+ } else if (star === -1) return false;
810
+ else {
811
+ token = star + 1;
812
+ mark += 1;
813
+ position = mark;
814
+ }
815
+ }
816
+ while (tokens[token] === STAR_TOKEN) token += 1;
817
+ return token === tokens.length;
818
+ }
819
+
820
+ /**
821
+ * Does one path segment (a name or a glob) match a name of the bus path? Case-blind,
822
+ * as macOS file systems are. A glob skips dot names, as the shell does.
823
+ * @param {string} pattern @param {string} name lower case
824
+ */
825
+ function segmentMatches(pattern, name) {
826
+ const lower = pattern.toLowerCase();
827
+ if (!GLOB_CHARACTER.test(lower)) return lower === name;
828
+ if (name.startsWith('.') && !lower.startsWith('.')) return false;
829
+ return globMatches(globTokens(lower), name);
830
+ }
831
+
832
+ /**
833
+ * Does an absolute path, globs allowed, name the bus directory or anything under
834
+ * it? `**` stands for any number of names that do not start with a dot.
835
+ * @param {string} path @param {BusScope} scope
836
+ */
837
+ function reachesBus(path, scope) {
838
+ const target = scope.busSegments;
839
+ let states = new Set([0]);
840
+ for (const segment of pathSegments(path)) {
841
+ if (states.has(target.length)) return true;
842
+ /** @type {Set<number>} */
843
+ const next = new Set();
844
+ tick(states.size + segment.length);
845
+ for (const state of states) {
846
+ if (segment === GLOBSTAR)
847
+ for (let index = state; index <= target.length; index += 1) {
848
+ next.add(index);
849
+ if ((target[index] ?? '.').startsWith('.')) break;
850
+ }
851
+ else if (state < target.length && segmentMatches(segment, target[state] ?? ''))
852
+ next.add(state + 1);
853
+ }
854
+ if (next.size === 0) return false;
855
+ states = next;
856
+ }
857
+ return states.has(target.length);
858
+ }
859
+
860
+ /**
861
+ * The first `{a,b}` group of a word to close (innermost first), in one pass, or
862
+ * null. `${...}` is a parameter, not a group.
863
+ * @param {string} text
864
+ * @returns {{ start: number, end: number, options: string[] } | null}
865
+ */
866
+ function braceGroup(text) {
867
+ /** @type {{ start: number, cuts: number[], parameter: boolean }[]} */
868
+ const open = [];
869
+ tick(text.length);
870
+ for (let index = 0; index < text.length; index += 1) {
871
+ const character = text[index];
872
+ if (character === '{')
873
+ open.push({ start: index, cuts: [], parameter: text[index - 1] === '$' });
874
+ else if (character === ',') open.at(-1)?.cuts.push(index);
875
+ else if (character === '}') {
876
+ const group = open.pop();
877
+ if (group === undefined || group.parameter || group.cuts.length === 0) continue;
878
+ const bounds = [group.start, ...group.cuts, index];
879
+ const options = bounds.slice(1).map((end, at) => text.slice((bounds[at] ?? 0) + 1, end));
880
+ return { start: group.start, end: index, options };
881
+ }
882
+ }
883
+ return null;
884
+ }
885
+
886
+ /**
887
+ * The words a shell brace expansion makes of a word (`~/.aibrain/{bus,x}`), at most
888
+ * MAX_BRACE_EXPANSIONS; past that, the rest is checked as written.
889
+ * @param {string} word
890
+ */
891
+ function expandBraces(word) {
892
+ /** @type {string[]} */
893
+ const done = [];
894
+ const pending = [word];
895
+ while (pending.length > 0 && done.length + pending.length <= MAX_BRACE_EXPANSIONS) {
896
+ const current = pending.shift() ?? '';
897
+ const group = braceGroup(current);
898
+ if (group === null) done.push(current);
899
+ else
900
+ for (const option of group.options)
901
+ pending.push(`${current.slice(0, group.start)}${option}${current.slice(group.end + 1)}`);
902
+ }
903
+ return [...done, ...pending];
904
+ }
905
+
906
+ /**
907
+ * Is `needle` in `text`, not followed by a name character (so `bus` is not
908
+ * `business`), and, when `boundedBefore`, not preceded by one either?
909
+ * @param {string} text @param {string} needle @param {boolean} boundedBefore
910
+ */
911
+ function containsName(text, needle, boundedBefore) {
912
+ tick(text.length);
913
+ for (let index = text.indexOf(needle); index !== -1; index = text.indexOf(needle, index + 1)) {
914
+ tick(needle.length);
915
+ const after = text[index + needle.length] ?? '';
916
+ const before = text[index - 1] ?? '';
917
+ if (!PATH_CHARACTER.test(after) && !(boundedBefore && PATH_CHARACTER.test(before))) return true;
918
+ }
919
+ return false;
920
+ }
921
+
922
+ /**
923
+ * Does a text name the bus anywhere in it: its absolute path, `.aibrain/bus`, its
924
+ * path from home, or the state-root variable followed by `/bus`? This reads scripts
925
+ * (`python -c "open('...')"`) and words a flag is glued to (`-f/path`).
926
+ * @param {string} text @param {BusScope} scope
927
+ */
928
+ function mentionsBus(text, scope) {
929
+ tick(text.length);
930
+ if (STATE_ROOT_BUS_MENTION.test(text)) return true;
931
+ const lower = text.toLowerCase();
932
+ return (
933
+ scope.absoluteMentions.some((needle) => containsName(lower, needle, false)) ||
934
+ scope.relativeMentions.some((needle) => containsName(lower, needle, true))
935
+ );
936
+ }
937
+
938
+ /**
939
+ * Does a path start with `bus` once another name in the line leads it? True for a
940
+ * relative path (`bus/x`, `./bus`) and for a path behind a variable (`$dir/bus/x`).
941
+ * @param {string} path
942
+ */
943
+ function hasBusTail(path) {
944
+ const variable = VARIABLE_PREFIX.exec(path);
945
+ const tail = variable === null ? path : path.slice(variable[0].length);
946
+ if (variable === null && ROOTED_WORD.test(path)) return false;
947
+ const first = pathSegments(tail).find((segment) => segment !== '.');
948
+ return first?.toLowerCase() === BUS_DIRECTORY;
949
+ }
950
+
951
+ /**
952
+ * Does one shell word name the bus directory? A word with spaces counts only for a
953
+ * mention. The word also notes, for the whole line, whether it names the state root
954
+ * and whether it is a path with a `bus` tail (`tar -C ~/.aibrain -cf x bus`,
955
+ * `d=~/.aibrain; ls $d/bus`).
956
+ * @param {string} word @param {BusScope} scope @param {readonly string[]} directories
957
+ * @param {LineState} line
958
+ */
959
+ function wordNamesBus(word, scope, directories, line) {
960
+ if (mentionsBus(word, scope)) return true;
961
+ if (WHITESPACE.test(word) || word.length > MAX_PATH_WORD_LENGTH) return false;
962
+ for (const candidate of pathCandidates(word))
963
+ for (const path of expandBraces(candidate)) {
964
+ if (path.length === 0) continue;
965
+ const resolved = resolvedPaths(path, scope, directories);
966
+ if (resolved.some((absolute) => reachesBus(absolute, scope))) return true;
967
+ if (resolved.some((absolute) => absolute.toLowerCase() === scope.rootKey))
968
+ line.namesRoot = true;
969
+ if (hasBusTail(path)) line.busTail = true;
970
+ }
971
+ return false;
972
+ }
973
+
974
+ /**
975
+ * C escapes decoded (`\x64` -> `d`, `\n` -> a newline), as `$'...'` and inline code
976
+ * read them. Unknown escapes stay as written.
977
+ * @param {string} text
978
+ */
979
+ function decodeEscapes(text) {
980
+ tick(text.length);
981
+ return text.replace(ESCAPE_SEQUENCE, (match, hex, unicode, octal, named) => {
982
+ if (typeof named === 'string') return NAMED_ESCAPES[named] ?? match;
983
+ const code = String(hex ?? unicode ?? octal);
984
+ return String.fromCharCode(Number.parseInt(code, octal === undefined ? HEXADECIMAL : OCTAL));
985
+ });
986
+ }
987
+
988
+ /**
989
+ * The rough words of a text, lower case and with escapes decoded: names, paths and
990
+ * package names stay whole (`os.system('aisac workers delegate')` -> `os.system`,
991
+ * `aisac`, `workers`, `delegate`).
992
+ * @param {string} text
993
+ */
994
+ function looseTokens(text) {
995
+ tick(text.length);
996
+ return decodeEscapes(text)
997
+ .toLowerCase()
998
+ .split(LOOSE_TOKEN_SEPARATOR)
999
+ .filter((token) => token.length > 0);
1000
+ }
1001
+
1002
+ /**
1003
+ * Does a list hold a token for each test, in this order? One pass.
1004
+ * @param {readonly string[]} tokens @param {readonly TokenTest[]} tests
1005
+ */
1006
+ function inOrder(tokens, tests) {
1007
+ let stage = 0;
1008
+ for (const token of tokens) {
1009
+ if (stage === tests.length) break;
1010
+ if (tests[stage]?.(token) === true) stage += 1;
1011
+ }
1012
+ return stage === tests.length;
1013
+ }
1014
+
1015
+ /**
1016
+ * Does a word, lower case, name the client by itself: a bin (`aisac`, `aibrain`,
1017
+ * `aisac.mjs`), the package (`@aisac/cli@beta`), its installed folder or anything in
1018
+ * it, or a bin path (`node_modules/.bin/aisac`)? A `--flag=value` counts by its value.
1019
+ * @param {string} token
1020
+ */
1021
+ function namesClient(token) {
1022
+ const value = token.slice(token.indexOf('=') + 1);
1023
+ return [token, value].some(
1024
+ (text) =>
1025
+ CLIENT_NAME.test(text) ||
1026
+ CLIENT_PACKAGE.test(text) ||
1027
+ CLIENT_INSTALL_PATH.test(text) ||
1028
+ CLIENT_BIN_PATH.test(text),
1029
+ );
1030
+ }
1031
+
1032
+ /** @type {TokenTest} */
1033
+ const isWorkers = (token) => token === WORKERS_COMMAND;
1034
+ /** @type {TokenTest} */
1035
+ const isDelegate = (token) => token === DELEGATE_ACTION;
1036
+ /** @type {TokenTest} */
1037
+ const isExtensionCommand = (token) => EXTENSION_COMMANDS.has(token);
1038
+ /** @type {TokenTest} */
1039
+ const isExtensionChange = (token) => EXTENSION_CHANGES.has(token);
1040
+ /** @type {readonly TokenTest[]} */
1041
+ const DELEGATE_SEQUENCE = [isWorkers, isDelegate];
1042
+ /** @type {readonly TokenTest[]} */
1043
+ const CLIENT_DELEGATE_SEQUENCE = [namesClient, ...DELEGATE_SEQUENCE];
1044
+ /** @type {readonly TokenTest[]} */
1045
+ const CLIENT_EXTENSION_SEQUENCE = [namesClient, isExtensionCommand, isExtensionChange];
1046
+
1047
+ /**
1048
+ * Does the shell run a word as written: no parameter, substitution, glob or brace
1049
+ * expansion in it?
1050
+ * @param {string} word
1051
+ */
1052
+ function isLiteral(word) {
1053
+ tick(word.length);
1054
+ return (
1055
+ !EXPANDING_CHARACTER.test(word) && !SEQUENCE_EXPANSION.test(word) && braceGroup(word) === null
1056
+ );
1057
+ }
1058
+
1059
+ /**
1060
+ * Is an absolute path, lower case, the installed package (or in it), this
1061
+ * repository's client folder, or a `cli.mjs` inside that folder?
1062
+ * @param {string} path
1063
+ */
1064
+ function isClientPath(path) {
1065
+ if (CLIENT_INSTALL_PATH.test(path)) return true;
1066
+ const segments = pathSegments(path);
1067
+ const last = segments.at(-1) ?? '';
1068
+ if (last === CLIENT_FOLDER) return true;
1069
+ return CLIENT_SCRIPT.test(last) && segments.slice(0, -1).includes(CLIENT_FOLDER);
1070
+ }
1071
+
1072
+ /**
1073
+ * Does a program word, or a word a JavaScript runtime runs, start the client? By its
1074
+ * name (`./aisac`, `"$(npm bin)/aisac"`), or as a path that resolves, against the
1075
+ * tracked directories, into the client (`node .` in the package folder).
1076
+ * @param {string} word @param {BusScope} scope @param {readonly string[]} directories
1077
+ */
1078
+ function runsClientPath(word, scope, directories) {
1079
+ if (CLIENT_NAME.test(programName(word.toLowerCase()))) return true;
1080
+ if (word.length > MAX_PATH_WORD_LENGTH) return false;
1081
+ return resolvedPaths(word, scope, directories).some((path) => isClientPath(path.toLowerCase()));
1082
+ }
1083
+
1084
+ /**
1085
+ * Which words of a simple command start the client: a word that names it, anywhere
1086
+ * (`timeout 60 aisac`, `npm exec -- aisac`, `pnpm dlx @aisac/cli`), and, by its path,
1087
+ * the program word or a word after a JavaScript runtime (`node --no-warnings <path>`,
1088
+ * `cd clients/aibrain && node src/cli.mjs`). Any case: macOS finds `AISAC` as `aisac`.
1089
+ * @param {string[]} words @param {BusScope} scope @param {readonly string[]} directories
1090
+ * @returns {boolean[]} One flag per word.
1091
+ */
1092
+ function clientWords(words, scope, directories) {
1093
+ const program = words.length - effectiveWords(words).length;
1094
+ let runtime = false;
1095
+ return words.map((word, index) => {
1096
+ const lower = word.toLowerCase();
1097
+ tick(word.length);
1098
+ const starts =
1099
+ namesClient(lower) ||
1100
+ ((runtime || index === program) && runsClientPath(word, scope, directories));
1101
+ // The runtime's script is the first client path; later words are its arguments.
1102
+ if (starts) runtime = false;
1103
+ if (JS_RUNTIMES.has(programName(lower))) runtime = true;
1104
+ return starts;
1105
+ });
1106
+ }
1107
+
1108
+ /**
1109
+ * After a word that starts the client, a word the shell rewrites, unless a literal
1110
+ * subcommand other than `workers` comes first: the client dispatches on its first
1111
+ * argument, so `aisac scan "$DIR"` passes and `aisac --json $X` does not.
1112
+ * @param {string[]} words @param {readonly boolean[]} clients
1113
+ */
1114
+ function rewritesAfterClient(words, clients) {
1115
+ let armed = false;
1116
+ let first = false;
1117
+ for (let index = 0; index < words.length; index += 1) {
1118
+ const word = words[index] ?? '';
1119
+ if (armed && !isLiteral(word)) return true;
1120
+ if (clients[index] === true) {
1121
+ armed = true;
1122
+ first = true;
1123
+ continue;
1124
+ }
1125
+ if (first && !word.startsWith('-') && word.toLowerCase() !== WORKERS_COMMAND) armed = false;
1126
+ first = false;
1127
+ }
1128
+ return false;
1129
+ }
1130
+
1131
+ /**
1132
+ * Does a simple command run `aisac workers delegate` (FR10, MG6)? An agent never
1133
+ * does, in any form, so this errs on refusing:
1134
+ * - `workers` and later `delegate`, any case, whatever runs them (`node dist/cli.mjs`,
1135
+ * `npx <fork>`, `$CLI`, `tmux send-keys`, `parallel`);
1136
+ * - the client, and after it any word the shell rewrites (`$(echo delegate)`, `d*`);
1137
+ * - a word whose rough words are the client, `workers` and `delegate`, in order
1138
+ * (inline code, `git -c alias.x=...`, `env -S`, `socat EXEC:...`, a commit message).
1139
+ * @param {string[]} words @param {readonly string[][]} loose Rough words of each word and target.
1140
+ * @param {readonly boolean[]} clients
1141
+ */
1142
+ function runsDelegate(words, loose, clients) {
1143
+ if (
1144
+ inOrder(
1145
+ words.map((word) => word.toLowerCase()),
1146
+ DELEGATE_SEQUENCE,
1147
+ )
1148
+ )
1149
+ return true;
1150
+ if (rewritesAfterClient(words, clients)) return true;
1151
+ return loose.some((tokens) => inOrder(tokens, CLIENT_DELEGATE_SEQUENCE));
1152
+ }
1153
+
1154
+ /**
1155
+ * Does a simple command change an extension (FR2.2)? The client anywhere in it, then
1156
+ * `hooks` or `mcp` and later a change (`disable`, `reset`, ...) or a word the shell
1157
+ * rewrites, or a rewritten word and later a change (`aisac $(echo hooks) disable`),
1158
+ * or a rewritten word right after the client. Any case.
1159
+ * @param {string[]} words @param {readonly boolean[]} clients
1160
+ */
1161
+ function changesExtensions(words, clients) {
1162
+ const entry = clients.indexOf(true);
1163
+ if (entry === -1) return false;
1164
+ // A rewritten first argument is the whole subcommand (`aisac $CMD`, CMD='hooks reset').
1165
+ const computed = clients.some(
1166
+ (starts, index) => starts && index + 1 < words.length && !isLiteral(words[index + 1] ?? ''),
1167
+ );
1168
+ if (computed) return true;
1169
+ const rest = words.slice(entry + 1).map((word) => word.toLowerCase());
1170
+ return (
1171
+ inOrder(rest, [isExtensionCommand, (word) => isExtensionChange(word) || !isLiteral(word)]) ||
1172
+ inOrder(rest, [(word) => !isLiteral(word), isExtensionChange])
1173
+ );
1174
+ }
1175
+
1176
+ /**
1177
+ * Inline code (`python3 -c "..."`, `node -e "..."`): the words with whitespace of a
1178
+ * command that runs an interpreter.
1179
+ * @param {string[]} all
1180
+ */
1181
+ function inlineCode(all) {
1182
+ if (!all.some((word) => INTERPRETERS.test(programName(word.toLowerCase())))) return [];
1183
+ return all.filter((word) => WHITESPACE.test(word));
1184
+ }
1185
+
1186
+ /**
1187
+ * Do rough words of a text run an extension change (`EXEC:aisac hooks disable`, inline
1188
+ * code)? Only for text that is code or a command line, so a commit message that names
1189
+ * the command passes.
1190
+ * @param {string} text
1191
+ */
1192
+ function codeChangesExtensions(text) {
1193
+ return inOrder(looseTokens(text), CLIENT_EXTENSION_SEQUENCE);
1194
+ }
1195
+
1196
+ /**
1197
+ * Is the program word one the shell rewrites (`$c`, `"$(command -v aisac)"`), and
1198
+ * after it a command word and then a change: a listed change or a rewritten word?
1199
+ * Counts only in a line that names the client (`c=aisac; $c workers $(echo delegate)`).
1200
+ * @param {string[]} words @param {TokenTest} isCommand @param {TokenTest} isChange
1201
+ */
1202
+ function computedProgramRuns(words, isCommand, isChange) {
1203
+ const effective = effectiveWords(words);
1204
+ if (effective.length === 0 || isLiteral(effective[0] ?? '')) return false;
1205
+ const rest = effective.slice(1);
1206
+ const command = rest.findIndex((word) => isCommand(word.toLowerCase()));
1207
+ return (
1208
+ command !== -1 &&
1209
+ rest.slice(command + 1).some((word) => isChange(word.toLowerCase()) || !isLiteral(word))
1210
+ );
1211
+ }
1212
+
1213
+ /**
1214
+ * Does a simple command run what arrives on its standard input, as arguments or as a
1215
+ * script (`| xargs aisac`, `| bash`, `. /dev/stdin`)?
1216
+ * @param {string[]} words
1217
+ */
1218
+ function feedsStdin(words) {
1219
+ const program = (effectiveWords(words)[0] ?? '').toLowerCase();
1220
+ if (SOURCE_COMMANDS.has(program)) return true;
1221
+ return words.some((word) => STDIN_RUNNERS.has(programName(word.toLowerCase())));
1222
+ }
1223
+
1224
+ /** Is a word a shell or a program that runs a command line? @param {string} word */
1225
+ function runsCommandLines(word) {
1226
+ const name = programName(word.toLowerCase());
1227
+ return SHELLS.has(name) || COMMAND_LINE_PROGRAMS.has(name);
1228
+ }
1229
+
1230
+ /** The strings `env -S` and `env --split-string` split into a command. @param {string[]} words */
1231
+ function envSplitStrings(words) {
1232
+ if (!words.some((word) => programName(word.toLowerCase()) === ENV_PROGRAM)) return [];
1233
+ /** @type {string[]} */
1234
+ const strings = [];
1235
+ for (let index = 0; index < words.length; index += 1) {
1236
+ const word = words[index] ?? '';
1237
+ if (ENV_SPLIT_FLAG.test(word)) strings.push(words[index + 1] ?? '');
1238
+ else if (word.startsWith(ENV_SPLIT_PREFIX)) strings.push(word.slice(ENV_SPLIT_PREFIX.length));
1239
+ }
1240
+ return strings;
1241
+ }
1242
+
1243
+ /**
1244
+ * The directories a relative path starts from after this command: `cd` and `pushd`
1245
+ * move them, `cd` alone goes home, `popd` and `cd -` make them unknown (none).
1246
+ * @param {string[]} words Effective words. @param {BusScope} scope
1247
+ * @param {readonly string[]} directories
1248
+ * @returns {readonly string[]}
1249
+ */
1250
+ function nextDirectories(words, scope, directories) {
1251
+ const program = programName(words[0] ?? '');
1252
+ if (DIRECTORY_LOSSES.has(program)) return [];
1253
+ if (!DIRECTORY_CHANGES.has(program)) return directories;
1254
+ const target = words.slice(1).find((word) => word === '-' || !word.startsWith('-'));
1255
+ if (target === undefined) return [scope.home];
1256
+ return target === '-' ? [] : resolvedPaths(target, scope, directories);
1257
+ }
1258
+
1259
+ /**
1260
+ * Command lines inside one simple command: `$(...)` and backticks, the script of
1261
+ * `bash -c` (or `-lc`), `eval`, the string of `env -S`, a git alias that runs a
1262
+ * command line (`!cmd`), and, when a shell or a program
1263
+ * that runs a command line is among the words (COMMAND_LINE_PROGRAMS), every word
1264
+ * with whitespace (an `--option=<line>` by its value).
1265
+ * @param {string[]} all Every word and redirection target. @param {string[]} words Effective words.
1266
+ */
1267
+ function nestedCommands(all, words) {
1268
+ const program = programName(words[0] ?? '').toLowerCase();
1269
+ /** @type {Set<string>} */
1270
+ const nested = new Set();
1271
+ for (const word of all) {
1272
+ tick(word.length);
1273
+ for (const inner of substitutions(word)) nested.add(inner);
1274
+ }
1275
+ if (program === 'eval') nested.add(words.slice(1).join(' '));
1276
+ const script = SHELLS.has(program) ? shellScript(words) : undefined;
1277
+ if (script !== undefined) nested.add(script);
1278
+ for (const text of envSplitStrings(all)) nested.add(text);
1279
+ if (program === 'git')
1280
+ for (const word of all) {
1281
+ const alias = GIT_SHELL_ALIAS.exec(word);
1282
+ if (alias !== null) nested.add(alias[1] ?? '');
1283
+ }
1284
+ if (all.some((word) => runsCommandLines(word)))
1285
+ for (const word of all)
1286
+ if (WHITESPACE.test(word))
1287
+ nested.add(OPTION_VALUE.test(word) ? word.slice(word.indexOf('=') + 1) : word);
1288
+ return [...nested];
1289
+ }
1290
+
1291
+ /**
1292
+ * The bodies of the first here-strings of a command line (`bash <<< "..."`), which
1293
+ * the splitter drops. A `$'...'` body has its escapes decoded.
1294
+ * @param {string} command
1295
+ */
1296
+ function hereStrings(command) {
1297
+ /** @type {string[]} */
1298
+ const bodies = [];
1299
+ let at = command.indexOf(HERE_STRING);
1300
+ for (let count = 0; at !== -1 && count < MAX_HERE_STRINGS; count += 1) {
1301
+ const rest = command.slice(at + HERE_STRING.length);
1302
+ tick(rest.length);
1303
+ const word = splitShell(rest).commands[0]?.words[0];
1304
+ // Only a `$'...'` token is decoded; `"$(...)"` and `"$X"` keep their `$`.
1305
+ const isAnsiC = rest.trimStart().startsWith(ANSI_C_QUOTE);
1306
+ if (word !== undefined) bodies.push(isAnsiC ? decodeEscapes(word.slice(1)) : word);
1307
+ at = command.indexOf(HERE_STRING, at + HERE_STRING.length);
1308
+ }
1309
+ return bodies;
1310
+ }
1311
+
1312
+ /** @returns {LineState} */
1313
+ function newLine() {
1314
+ return {
1315
+ namesRoot: false,
1316
+ busTail: false,
1317
+ feedsStdin: false,
1318
+ namesClient: false,
1319
+ computedDelegate: false,
1320
+ computedExtension: false,
1321
+ tokens: new Set(),
1322
+ };
1323
+ }
1324
+
1325
+ /** @param {LineState} line @param {readonly string[]} tokens */
1326
+ function noteTokens(line, tokens) {
1327
+ for (const token of tokens) {
1328
+ line.tokens.add(token);
1329
+ if (!line.namesClient && namesClient(token)) line.namesClient = true;
1330
+ }
1331
+ }
1332
+
1333
+ /** @param {ReadonlySet<string>} tokens @param {ReadonlySet<string>} values */
1334
+ function hasAny(tokens, values) {
1335
+ return [...values].some((value) => tokens.has(value));
1336
+ }
1337
+
1338
+ /**
1339
+ * The line's own refusal, once its commands are read: the state root next to a path
1340
+ * with a `bus` tail; in a line that names the client, a rewritten program word that
1341
+ * runs its command (`c=aisac; $c workers $(echo delegate)`), or, when a command runs
1342
+ * its standard input, the rest of the command anywhere in the line
1343
+ * (`echo workers delegate | xargs aisac`).
1344
+ * @param {LineState} line @param {Readonly<WalkRules>} rules
1345
+ * @returns {WalkRefusal | null}
1346
+ */
1347
+ function lineRefusal(line, rules) {
1348
+ if (rules.bus && line.namesRoot && line.busTail) return 'bus';
1349
+ if (!line.namesClient) return null;
1350
+ if (rules.delegate && (line.computedDelegate || (line.feedsStdin && feedsDelegate(line))))
1351
+ return 'delegate';
1352
+ if (rules.extensions && (line.computedExtension || (line.feedsStdin && feedsExtension(line))))
1353
+ return 'extensions';
1354
+ return null;
1355
+ }
1356
+
1357
+ /** @param {LineState} line */
1358
+ function feedsDelegate(line) {
1359
+ return line.tokens.has(WORKERS_COMMAND) && line.tokens.has(DELEGATE_ACTION);
1360
+ }
1361
+
1362
+ /** @param {LineState} line */
1363
+ function feedsExtension(line) {
1364
+ return hasAny(line.tokens, EXTENSION_COMMANDS) && hasAny(line.tokens, EXTENSION_CHANGES);
1365
+ }
1366
+
1367
+ /**
1368
+ * A command line nested past MAX_NESTING is not read; one that still names the client
1369
+ * (with `hooks` or `mcp`, for an extension change) is refused.
1370
+ * @param {string} text @param {Readonly<WalkRules>} rules
1371
+ * @returns {WalkRefusal | null}
1372
+ */
1373
+ function beyondRefusal(text, rules) {
1374
+ const tokens = looseTokens(text);
1375
+ if (!tokens.some((token) => namesClient(token))) return null;
1376
+ if (rules.delegate) return 'delegate';
1377
+ if (rules.extensions && tokens.some((token) => EXTENSION_COMMANDS.has(token)))
1378
+ return 'extensions';
1379
+ return null;
1380
+ }
1381
+
1382
+ /**
1383
+ * Text the splitter cannot read counts as rough words, for mentions and for the
1384
+ * client's commands.
1385
+ * @param {string} command @param {BusScope} scope @param {Readonly<WalkRules>} rules
1386
+ * @returns {WalkRefusal | null}
1387
+ */
1388
+ function unsplitRefusal(command, scope, rules) {
1389
+ const tokens = looseTokens(command);
1390
+ if (rules.extensions && inOrder(tokens, CLIENT_EXTENSION_SEQUENCE)) return 'extensions';
1391
+ if (rules.delegate && inOrder(tokens, DELEGATE_SEQUENCE)) return 'delegate';
1392
+ return rules.bus && mentionsBus(command, scope) ? 'bus' : null;
1393
+ }
1394
+
1395
+ /**
1396
+ * Does a simple command name the bus by one of its words or redirection targets?
1397
+ * Search patterns (`grep PATTERN`) are not paths.
1398
+ * @param {import('./shell-words.mjs').ShellCommand} item @param {BusScope} scope
1399
+ * @param {readonly string[]} directories @param {LineState} line
1400
+ */
1401
+ function namesBusIn(item, scope, directories, line) {
1402
+ const words = effectiveWords(item.words);
1403
+ const patterns = searchPatternIndexes(words);
1404
+ const prefix = item.words.slice(0, item.words.length - words.length);
1405
+ const named = [...prefix, ...words.filter((_, index) => !patterns.has(index)), ...item.targets];
1406
+ return named.some((word) => wordNamesBus(word, scope, directories, line));
1407
+ }
1408
+
1409
+ /**
1410
+ * @param {readonly string[]} texts @param {BusScope} scope
1411
+ * @param {readonly string[]} directories @param {number} depth @param {Readonly<WalkRules>} rules
1412
+ * @returns {WalkRefusal | null}
1413
+ */
1414
+ function nestedRefusal(texts, scope, directories, depth, rules) {
1415
+ for (const text of texts) {
1416
+ if (rules.extensions && codeChangesExtensions(text)) return 'extensions';
1417
+ const refusal =
1418
+ depth < MAX_NESTING
1419
+ ? walkCommand(text, scope, directories, depth + 1, rules)
1420
+ : beyondRefusal(text, rules);
1421
+ if (refusal !== null) return refusal;
1422
+ }
1423
+ return null;
1424
+ }
1425
+
1426
+ /**
1427
+ * @param {import('./shell-words.mjs').ShellCommand} item @param {BusScope} scope
1428
+ * @param {readonly string[]} directories @param {LineState} line @param {number} depth
1429
+ * @param {Readonly<WalkRules>} rules
1430
+ * @returns {WalkRefusal | null}
1431
+ */
1432
+ function simpleCommandRefusal(item, scope, directories, line, depth, rules) {
1433
+ const all = [...item.words, ...item.targets];
1434
+ const loose = all.map((word) => looseTokens(word));
1435
+ for (const tokens of loose) noteTokens(line, tokens);
1436
+ if (feedsStdin(item.words)) line.feedsStdin = true;
1437
+ if (computedProgramRuns(item.words, isWorkers, isDelegate)) line.computedDelegate = true;
1438
+ if (computedProgramRuns(item.words, isExtensionCommand, isExtensionChange))
1439
+ line.computedExtension = true;
1440
+ const clients = clientWords(item.words, scope, directories);
1441
+ if (
1442
+ rules.extensions &&
1443
+ (changesExtensions(item.words, clients) || inlineCode(all).some(codeChangesExtensions))
1444
+ )
1445
+ return 'extensions';
1446
+ if (rules.delegate && runsDelegate(item.words, loose, clients)) return 'delegate';
1447
+ if (rules.bus && namesBusIn(item, scope, directories, line)) return 'bus';
1448
+ const nested = nestedCommands(all, effectiveWords(item.words));
1449
+ return nestedRefusal(nested, scope, directories, depth, rules);
1450
+ }
1451
+
1452
+ /**
1453
+ * Walks a command line, and the command lines nested in it up to MAX_NESTING, for
1454
+ * the refusals `rules` asks for: the bus guard's (bus paths, `aisac workers
1455
+ * delegate`) and the secrets guard's FR2.2 check (an extension change). A `cd` moves
1456
+ * where the later relative paths of the line start. Here-string bodies are nested
1457
+ * lines. Text the splitter cannot read counts as rough words.
1458
+ * @param {string} command @param {BusScope} scope @param {readonly string[]} directories
1459
+ * @param {number} depth @param {Readonly<WalkRules>} rules
1460
+ * @returns {WalkRefusal | null}
1461
+ */
1462
+ function walkCommand(command, scope, directories, depth, rules) {
1463
+ if (command.length === 0) return null;
1464
+ tick(command.length);
1465
+ const parsed = splitShell(command);
1466
+ if (!parsed.ok) return unsplitRefusal(command, scope, rules);
1467
+ const line = newLine();
1468
+ let current = directories;
1469
+ for (const item of parsed.commands) {
1470
+ const refusal = simpleCommandRefusal(item, scope, current, line, depth, rules);
1471
+ if (refusal !== null) return refusal;
1472
+ current = nextDirectories(effectiveWords(item.words), scope, current);
1473
+ }
1474
+ const bodies = hereStrings(command);
1475
+ for (const body of bodies) noteTokens(line, looseTokens(body));
1476
+ return nestedRefusal(bodies, scope, directories, depth, rules) ?? lineRefusal(line, rules);
1477
+ }
1478
+
1479
+ /** A path argument of `base` and `pattern`, as Grep and Glob read them. @param {string} base @param {string} pattern */
1480
+ function underPath(base, pattern) {
1481
+ if (pattern.length === 0) return base;
1482
+ if (base.length === 0 || ROOTED_WORD.test(pattern)) return pattern;
1483
+ return `${base}/${pattern}`;
1484
+ }
1485
+
1486
+ /**
1487
+ * The paths a file tool names. Grep searches everything under its path, so it
1488
+ * counts as `<path>/**` (plus its `glob`); Glob as its pattern under its path; the
1489
+ * others by `file_path` or `notebook_path`.
1490
+ * @param {string} tool @param {Record<string, unknown>} input
1491
+ */
1492
+ function fileToolPaths(tool, input) {
1493
+ const text = (/** @type {unknown} */ value) => (typeof value === 'string' ? value : '');
1494
+ if (tool === 'Grep') return [underPath(text(input.path), GLOBSTAR), text(input.glob)];
1495
+ if (tool === 'Glob') return [underPath(text(input.path), text(input.pattern))];
1496
+ return [text(input.file_path ?? input.notebook_path)];
1497
+ }
1498
+
1499
+ /** A file tool's or a patch's path. @param {string} path @param {BusScope} scope @param {readonly string[]} directories */
1500
+ function pathNamesBus(path, scope, directories) {
1501
+ if (path.length === 0) return false;
1502
+ if (mentionsBus(path, scope)) return true;
1503
+ if (path.length > MAX_PATH_WORD_LENGTH) return false;
1504
+ return expandBraces(path).some((variant) =>
1505
+ resolvedPaths(variant, scope, directories).some((absolute) => reachesBus(absolute, scope)),
1506
+ );
1507
+ }
1508
+
1509
+ /**
1510
+ * `bus-guard` (spec aisac-engineering-manager FR10, D13): refuses a shell command, a
1511
+ * patch or a file tool call that names the manager's bus directory, by path, `~`,
1512
+ * `$HOME` or the state-root variable, and a tool call that runs `aisac workers
1513
+ * delegate`. `aisac workers` itself passes: it reads the bus through the client.
1514
+ * Names only: a second barrier, not a boundary (threat model).
1515
+ * @param {ToolEvent} event @param {GuardContext} context
1516
+ * @returns {string | null}
1517
+ */
1518
+ export function busGuard(event, context) {
1519
+ return busGuardWork(event, context).refusal;
1520
+ }
1521
+
1522
+ /**
1523
+ * `bus-guard`'s decision with the work it took, in steps (characters scanned, match
1524
+ * states visited), so a test can bound the work without a clock.
1525
+ * @param {ToolEvent} event @param {GuardContext} context
1526
+ * @returns {{ refusal: string | null, steps: number }}
1527
+ */
1528
+ export function busGuardWork(event, context) {
1529
+ const before = workSteps;
1530
+ const refusal = busRefusal(event, context);
1531
+ return {
1532
+ refusal: refusal === null ? null : message(context, refusal),
1533
+ steps: workSteps - before,
1534
+ };
1535
+ }
1536
+
1537
+ /** @param {ToolEvent} event @param {GuardContext} context @returns {WalkRefusal | null} */
1538
+ function busRefusal(event, context) {
1539
+ const tool = typeof event.tool_name === 'string' ? event.tool_name : '';
1540
+ const input = record(event.tool_input);
1541
+ const scope = busScope(context);
1542
+ const directories = startDirectories(event, context);
1543
+ if (tool === 'Bash') {
1544
+ const command = typeof input.command === 'string' ? input.command : '';
1545
+ return walkCommand(command, scope, directories, 0, BUS_RULES);
1546
+ }
1547
+ const paths = tool === PATCH_TOOL ? patchPaths(input.command) : fileToolPaths(tool, input);
1548
+ return paths.some((path) => pathNamesBus(path, scope, directories)) ? 'bus' : null;
1549
+ }
1550
+
1551
+ /** Guards by catalog id, in the order they run. */
1552
+ export const GUARDS = Object.freeze({
1553
+ 'secrets-guard': secretsGuard,
1554
+ 'git-guard': gitGuard,
1555
+ 'destructive-guard': destructiveGuard,
1556
+ 'bus-guard': busGuard,
1557
+ });