@aisac/cli 0.4.0-beta.21 → 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.
@@ -1,12 +1,13 @@
1
1
  // @ts-check
2
2
  /**
3
3
  * Block guardrails for PreToolUse (spec aisac-engineering-extensions FR2,
4
- * FR2.1, FR2.2). Each guard is a pure decision from the tool name and input;
5
- * it returns a refusal reason or null. Guards decide from names only and
6
- * never open the files they protect. They lower risk; they are not a sandbox.
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.
7
8
  */
8
9
  import { execFileSync } from 'node:child_process';
9
- import { isAbsolute, resolve } from 'node:path';
10
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
10
11
  import { PATCH_TOOL, patchPaths } from './patch.mjs';
11
12
  import { effectiveWords, programName, splitShell } from './shell-words.mjs';
12
13
 
@@ -34,13 +35,27 @@ const NAME_DELIMITERS = /[\s'"=<>:(),;|&`$]+/u;
34
35
  // A quoted name inside a word that contains spaces (`python -c "open('.env')"`).
35
36
  const QUOTED_NAME = /['"]([^'"\s]+)['"]/gu;
36
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', '.']);
37
48
  const SEARCH_PROGRAMS = new Set(['grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack']);
38
- const MAX_NESTING = 2;
39
- const AISAC_PROGRAMS = new Set(['aisac', 'aibrain']);
40
- const AISAC_PACKAGE = /^@(?:aisac\/cli|brunobracaioli\/aibrain)(?:@\S*)?$/u;
49
+ export const MAX_NESTING = 2;
41
50
  const EXTENSION_COMMANDS = new Set(['hooks', 'mcp']);
42
51
  const EXTENSION_CHANGES = new Set(['enable', 'disable', 'reset', 'login']);
43
- const GIT_OPTIONS_WITH_VALUE = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace']);
52
+ export const GIT_OPTIONS_WITH_VALUE = new Set([
53
+ '-C',
54
+ '-c',
55
+ '--git-dir',
56
+ '--work-tree',
57
+ '--namespace',
58
+ ]);
44
59
  const PROTECTED_BRANCHES = new Set(['main', 'master']);
45
60
  const GIT_TIMEOUT_MS = 2_000;
46
61
  const DANGEROUS_RM_TARGETS = new Set([
@@ -90,6 +105,9 @@ const MESSAGES = {
90
105
  'refused: force push. Use --force-with-lease on your own branch if it is really needed.',
91
106
  rm: 'refused: rm -rf on %s.',
92
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).',
93
111
  },
94
112
  'pt-BR': {
95
113
  secret:
@@ -103,6 +121,9 @@ const MESSAGES = {
103
121
  'recusado: push forçado. Use --force-with-lease na sua branch, se for mesmo preciso.',
104
122
  rm: 'recusado: rm -rf em %s.',
105
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).',
106
127
  },
107
128
  };
108
129
 
@@ -174,32 +195,24 @@ function pathCandidates(word) {
174
195
  return equals === -1 ? [word] : [word, word.slice(equals + 1)];
175
196
  }
176
197
 
177
- /** @param {string[]} words */
178
- function changesExtensions(words) {
179
- const effective = effectiveWords(words);
180
- const program = programName(effective[0] ?? '');
181
- const aisacEntry =
182
- AISAC_PROGRAMS.has(program) ||
183
- AISAC_PACKAGE.test(effective[0] ?? '') ||
184
- (program === 'node' && /(?:@aisac\/cli|aibrain)[\\/].*cli\.mjs$/u.test(effective[1] ?? ''));
185
- if (!aisacEntry) return false;
186
- const rest = effective.slice(program === 'node' ? 2 : 1);
187
- const commandIndex = rest.findIndex((word) => EXTENSION_COMMANDS.has(word));
188
- return (
189
- commandIndex !== -1 && rest.slice(commandIndex + 1).some((word) => EXTENSION_CHANGES.has(word))
190
- );
191
- }
192
-
193
198
  /**
194
- * `secrets-guard` (FR2.1) with the FR2.2 self-protection.
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.
195
203
  * @param {ToolEvent} event @param {GuardContext} context
196
204
  * @returns {string | null}
197
205
  */
198
206
  export function secretsGuard(event, context) {
199
207
  const tool = typeof event.tool_name === 'string' ? event.tool_name : '';
200
208
  const input = record(event.tool_input);
201
- if (tool === 'Bash')
202
- return secretsInCommand(typeof input.command === 'string' ? input.command : '', context);
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
+ }
203
216
  // A Codex patch writes every file its headers name (E6b).
204
217
  if (tool === PATCH_TOOL) {
205
218
  for (const path of patchPaths(input.command)) {
@@ -302,6 +315,60 @@ function searchPatternIndexes(words) {
302
315
  return indexes;
303
316
  }
304
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
+
305
372
  /** @param {string} command @param {GuardContext} context @param {number} [depth] @returns {string | null} */
306
373
  function secretsInCommand(command, context, depth = 0) {
307
374
  if (command.length === 0) return null;
@@ -316,7 +383,6 @@ function secretsInCommand(command, context, depth = 0) {
316
383
  return null;
317
384
  }
318
385
  for (const item of parsed.commands) {
319
- if (changesExtensions(item.words)) return message(context, 'extensions');
320
386
  const words = effectiveWords(item.words);
321
387
  const program = programName(words[0] ?? '');
322
388
  const patterns = searchPatternIndexes(words);
@@ -330,19 +396,18 @@ function secretsInCommand(command, context, depth = 0) {
330
396
  const refusal = wordRefusal(target, context, depth);
331
397
  if (refusal !== null) return refusal;
332
398
  }
333
- // `bash -c "cat .env"` and `eval "..."` carry a whole command in one word.
334
- const script =
335
- SHELLS.has(program) && words.includes('-c')
336
- ? words[words.indexOf('-c') + 1]
337
- : program === 'eval'
338
- ? words.slice(1).join(' ')
339
- : undefined;
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;
340
405
  if (script !== undefined && depth < MAX_NESTING) {
341
406
  const refusal = secretsInCommand(script, context, depth + 1);
342
407
  if (refusal !== null) return refusal;
343
408
  }
344
409
  }
345
- return null;
410
+ return hereStringSecrets(command, parsed.commands, context, depth);
346
411
  }
347
412
 
348
413
  /** Destination branch of a push refspec (`HEAD:main`, `+main`, `refs/heads/main`). @param {string} refspec */
@@ -441,9 +506,1052 @@ export function destructiveGuard(event, context) {
441
506
  return databaseClient && DESTRUCTIVE_SQL.test(command) ? message(context, 'sql') : null;
442
507
  }
443
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
+
444
1551
  /** Guards by catalog id, in the order they run. */
445
1552
  export const GUARDS = Object.freeze({
446
1553
  'secrets-guard': secretsGuard,
447
1554
  'git-guard': gitGuard,
448
1555
  'destructive-guard': destructiveGuard,
1556
+ 'bus-guard': busGuard,
449
1557
  });