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

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 (47) hide show
  1. package/README.md +115 -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 +243 -5
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +6 -0
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +584 -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 +259 -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 +373 -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 +449 -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 +278 -34
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/mcp-servers.mjs +192 -0
  35. package/dist/mcp.mjs +10 -2
  36. package/dist/monitor.mjs +76 -1
  37. package/dist/package.json +1 -1
  38. package/dist/platform.mjs +78 -29
  39. package/dist/release-manifest-public-keys.json +10 -0
  40. package/dist/release-manifest.json +328 -0
  41. package/dist/release-manifest.mjs +817 -0
  42. package/dist/release-settings.mjs +210 -0
  43. package/dist/self-update.mjs +1036 -0
  44. package/dist/state.mjs +25 -1
  45. package/dist/token-guide.mjs +132 -0
  46. package/dist/update-actions.mjs +442 -0
  47. package/package.json +1 -1
@@ -0,0 +1,449 @@
1
+ // @ts-check
2
+ /**
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.
7
+ */
8
+ import { execFileSync } from 'node:child_process';
9
+ import { isAbsolute, resolve } from 'node:path';
10
+ import { PATCH_TOOL, patchPaths } from './patch.mjs';
11
+ import { effectiveWords, programName, splitShell } from './shell-words.mjs';
12
+
13
+ /**
14
+ * @typedef {object} GuardContext
15
+ * @property {string} projectDir
16
+ * @property {string} home
17
+ * @property {string} prefsPath The extensions preferences file (FR2.2).
18
+ * @property {readonly string[]} [codexConfigs] Codex's user config files, which hold
19
+ * the switches for the AISAC hooks in Codex (FR2.2, E6b).
20
+ * @property {'pt-BR' | 'en'} locale
21
+ */
22
+ /** @typedef {{ tool_name?: unknown, tool_input?: unknown, cwd?: unknown }} ToolEvent */
23
+
24
+ const TEMPLATE_SUFFIXES = new Set(['example', 'sample', 'template']);
25
+ const SECRET_DIRECTORIES = new Set(['.ssh', '.aws', '.gnupg']);
26
+ const SECRET_NAMES = new Set(['.envrc', '.npmrc', '.netrc', '.pgpass', 'credentials.json']);
27
+ const PRIVATE_KEY_NAME = /^id_(?:rsa|dsa|ecdsa|ed25519)(?:[._-].*)?$/u;
28
+ const CERTIFICATE_EXTENSION = /\.(?:pem|p12|pfx)$/iu;
29
+ const KEY_EXTENSION = /\.key$/iu;
30
+ const SERVICE_ACCOUNT = /^service-account.*\.json$/iu;
31
+ // Splits a word into the names it mentions (`open('.env')` -> `open`, `.env`),
32
+ // so `process.env.HOME` stays one name and passes.
33
+ const NAME_DELIMITERS = /[\s'"=<>:(),;|&`$]+/u;
34
+ // A quoted name inside a word that contains spaces (`python -c "open('.env')"`).
35
+ const QUOTED_NAME = /['"]([^'"\s]+)['"]/gu;
36
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash', 'ksh']);
37
+ 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;
41
+ const EXTENSION_COMMANDS = new Set(['hooks', 'mcp']);
42
+ const EXTENSION_CHANGES = new Set(['enable', 'disable', 'reset', 'login']);
43
+ const GIT_OPTIONS_WITH_VALUE = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace']);
44
+ const PROTECTED_BRANCHES = new Set(['main', 'master']);
45
+ const GIT_TIMEOUT_MS = 2_000;
46
+ const DANGEROUS_RM_TARGETS = new Set([
47
+ '/',
48
+ '/*',
49
+ '~',
50
+ '~/',
51
+ '~/*',
52
+ '.',
53
+ './',
54
+ './*',
55
+ '..',
56
+ '../',
57
+ '*',
58
+ '$HOME',
59
+ '$HOME/',
60
+ '$HOME/*',
61
+ '${HOME}',
62
+ '${HOME}/',
63
+ ]);
64
+ const DATABASE_CLIENTS = new Set([
65
+ 'psql',
66
+ 'mysql',
67
+ 'mariadb',
68
+ 'sqlite3',
69
+ 'sqlcmd',
70
+ 'clickhouse-client',
71
+ 'cockroach',
72
+ 'duckdb',
73
+ ]);
74
+ // Codex's user config named through a variable or `~` (`~/.codex/config.toml`,
75
+ // `$CODEX_HOME/config.toml`); resolved paths are compared as well.
76
+ const CODEX_CONFIG_MENTION =
77
+ /(?:~|\$\{?HOME\}?)\/\.codex\/config\.toml|\$\{?CODEX_HOME\}?\/config\.toml/u;
78
+ const DESTRUCTIVE_SQL =
79
+ /\b(?:DROP\s+(?:DATABASE|TABLE|SCHEMA)|TRUNCATE(?:\s+TABLE)?\s+[A-Za-z_"`])/iu;
80
+
81
+ const MESSAGES = {
82
+ en: {
83
+ secret: 'refused: this touches a secret file (rule: %s). Ask the user to do it themselves.',
84
+ extensions:
85
+ 'refused: AISAC extensions are changed only by the user, from their own terminal (aisac hooks / aisac mcp).',
86
+ codexConfig:
87
+ "refused: Codex's config.toml holds the switches for the AISAC guardrails; only the user changes it, from their own terminal.",
88
+ pushProtected: 'refused: push to %s. Open a pull request instead.',
89
+ pushForce:
90
+ 'refused: force push. Use --force-with-lease on your own branch if it is really needed.',
91
+ rm: 'refused: rm -rf on %s.',
92
+ sql: 'refused: destructive SQL (DROP or TRUNCATE) sent to a database client.',
93
+ },
94
+ 'pt-BR': {
95
+ secret:
96
+ 'recusado: isto mexe num arquivo de segredo (regra: %s). Peça ao usuário para fazer isso.',
97
+ extensions:
98
+ 'recusado: as extensões do AISAC só são mudadas pelo usuário, no terminal dele (aisac hooks / aisac mcp).',
99
+ codexConfig:
100
+ 'recusado: o config.toml do Codex guarda os interruptores dos guardrails do AISAC; só o usuário muda esse arquivo, no terminal dele.',
101
+ pushProtected: 'recusado: push na %s. Abra um pull request.',
102
+ pushForce:
103
+ 'recusado: push forçado. Use --force-with-lease na sua branch, se for mesmo preciso.',
104
+ rm: 'recusado: rm -rf em %s.',
105
+ sql: 'recusado: SQL destrutivo (DROP ou TRUNCATE) enviado a um cliente de banco.',
106
+ },
107
+ };
108
+
109
+ /** @param {GuardContext} context @param {keyof typeof MESSAGES.en} key @param {string} [value] */
110
+ function message(context, key, value = '') {
111
+ return (MESSAGES[context.locale] ?? MESSAGES.en)[key].replace('%s', value);
112
+ }
113
+
114
+ /** @param {unknown} value @returns {Record<string, unknown>} */
115
+ function record(value) {
116
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
117
+ ? /** @type {Record<string, unknown>} */ (value)
118
+ : {};
119
+ }
120
+
121
+ /**
122
+ * The secret rule a path matches, or null. Names only. With `extensions`
123
+ * false, only dot names, key names and private directories count: used for
124
+ * names found inside code, where `obj.key` is not a file.
125
+ * @param {string} path
126
+ * @param {{ extensions?: boolean }} [options]
127
+ * @returns {string | null}
128
+ */
129
+ export function secretRule(path, options = {}) {
130
+ const segments = path.split(/[/\\]/u).filter((segment) => segment.length > 0);
131
+ if (segments.some((segment) => SECRET_DIRECTORIES.has(segment))) return 'private directory';
132
+ const name = segments.at(-1) ?? '';
133
+ if (name === '.env') return '.env';
134
+ if (name.startsWith('.env.')) {
135
+ const suffix = name.slice('.env.'.length);
136
+ return TEMPLATE_SUFFIXES.has(suffix) ? null : '.env.*';
137
+ }
138
+ if (/^\.env[*?[]/u.test(name)) return '.env*';
139
+ if (SECRET_NAMES.has(name)) return name;
140
+ if (PRIVATE_KEY_NAME.test(name) && !name.endsWith('.pub')) return 'private key';
141
+ if (options.extensions === false) return null;
142
+ if (CERTIFICATE_EXTENSION.test(name)) return 'key or certificate file';
143
+ if (KEY_EXTENSION.test(name) && !name.startsWith('.')) return 'key file';
144
+ if (SERVICE_ACCOUNT.test(name)) return 'service account key';
145
+ return null;
146
+ }
147
+
148
+ /** Resolve `~`, `$HOME` and relative paths for comparison. @param {string} path @param {GuardContext} context */
149
+ function resolvePath(path, context) {
150
+ const expanded = path
151
+ .replace(/^~(?=\/|$)/u, context.home)
152
+ .replace(/^\$\{?HOME\}?(?=\/|$)/u, context.home);
153
+ return isAbsolute(expanded) ? resolve(expanded) : resolve(context.projectDir, expanded);
154
+ }
155
+
156
+ /**
157
+ * The FR2.2 refusal for a path that names a file only the user may change: the
158
+ * preferences file, or Codex's user config. Null for any other path.
159
+ * @param {string} path @param {GuardContext} context
160
+ * @returns {string | null}
161
+ */
162
+ function protectedRefusal(path, context) {
163
+ if (path.length === 0) return null;
164
+ const resolved = resolvePath(path, context);
165
+ if (resolved === resolve(context.prefsPath)) return message(context, 'extensions');
166
+ if ((context.codexConfigs ?? []).some((config) => resolved === resolve(config)))
167
+ return message(context, 'codexConfig');
168
+ return null;
169
+ }
170
+
171
+ /** Path-like parts of a word: the word itself and a `--flag=value` / `VAR=value` value. @param {string} word */
172
+ function pathCandidates(word) {
173
+ const equals = word.lastIndexOf('=');
174
+ return equals === -1 ? [word] : [word, word.slice(equals + 1)];
175
+ }
176
+
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
+ /**
194
+ * `secrets-guard` (FR2.1) with the FR2.2 self-protection.
195
+ * @param {ToolEvent} event @param {GuardContext} context
196
+ * @returns {string | null}
197
+ */
198
+ export function secretsGuard(event, context) {
199
+ const tool = typeof event.tool_name === 'string' ? event.tool_name : '';
200
+ const input = record(event.tool_input);
201
+ if (tool === 'Bash')
202
+ return secretsInCommand(typeof input.command === 'string' ? input.command : '', context);
203
+ // A Codex patch writes every file its headers name (E6b).
204
+ if (tool === PATCH_TOOL) {
205
+ for (const path of patchPaths(input.command)) {
206
+ const refusal = writeRefusal(path, context);
207
+ if (refusal !== null) return refusal;
208
+ }
209
+ return null;
210
+ }
211
+ const pathValue = tool === 'Grep' ? input.path : (input.file_path ?? input.notebook_path);
212
+ if (typeof pathValue !== 'string' || pathValue.length === 0) return null;
213
+ if (tool === 'Read' || tool === 'Grep') {
214
+ const rule = secretRule(pathValue);
215
+ return rule === null ? null : message(context, 'secret', rule);
216
+ }
217
+ return writeRefusal(pathValue, context);
218
+ }
219
+
220
+ /** A write to a protected file or a secret file. @param {string} path @param {GuardContext} context */
221
+ function writeRefusal(path, context) {
222
+ const refusal = protectedRefusal(path, context);
223
+ if (refusal !== null) return refusal;
224
+ const rule = secretRule(path);
225
+ return rule === null ? null : message(context, 'secret', rule);
226
+ }
227
+
228
+ /**
229
+ * The FR2.2 refusal for text that names a protected file anywhere in it.
230
+ * @param {string} text @param {GuardContext} context
231
+ * @returns {string | null}
232
+ */
233
+ function mentionsProtected(text, context) {
234
+ if (text.includes(resolve(context.prefsPath)) || text.includes('.aibrain/extensions.json'))
235
+ return message(context, 'extensions');
236
+ if (
237
+ CODEX_CONFIG_MENTION.test(text) ||
238
+ (context.codexConfigs ?? []).some((config) => text.includes(resolve(config)))
239
+ )
240
+ return message(context, 'codexConfig');
241
+ return null;
242
+ }
243
+
244
+ /** Contents of `$(...)` and backtick substitutions in a word. @param {string} word */
245
+ function substitutions(word) {
246
+ /** @type {string[]} */
247
+ const found = [];
248
+ for (const match of word.matchAll(/\$\(([^()]*(?:\([^()]*\)[^()]*)*)\)|`([^`]*)`/gu))
249
+ found.push(match[1] ?? match[2] ?? '');
250
+ return found;
251
+ }
252
+
253
+ /**
254
+ * A word's refusal. A word without spaces is a path candidate and a list of
255
+ * names; a word with spaces (a quoted script or message) counts only for
256
+ * quoted names inside it, so `git commit -m "ignore .env files"` passes.
257
+ * @param {string} word @param {GuardContext} context @param {number} depth
258
+ * @returns {string | null}
259
+ */
260
+ function wordRefusal(word, context, depth) {
261
+ const mention = mentionsProtected(word, context);
262
+ if (mention !== null) return mention;
263
+ if (!/\s/u.test(word)) {
264
+ for (const candidate of pathCandidates(word)) {
265
+ const refusal = protectedRefusal(candidate, context);
266
+ if (refusal !== null) return refusal;
267
+ const rule = secretRule(candidate);
268
+ if (rule !== null) return message(context, 'secret', rule);
269
+ }
270
+ for (const name of word.split(NAME_DELIMITERS)) {
271
+ const rule = name.length > 0 ? secretRule(name, { extensions: false }) : null;
272
+ if (rule !== null) return message(context, 'secret', rule);
273
+ }
274
+ } else {
275
+ for (const match of word.matchAll(QUOTED_NAME)) {
276
+ const rule = secretRule(match[1] ?? '', { extensions: false });
277
+ if (rule !== null) return message(context, 'secret', rule);
278
+ }
279
+ }
280
+ if (depth < MAX_NESTING)
281
+ for (const inner of substitutions(word)) {
282
+ const refusal = secretsInCommand(inner, context, depth + 1);
283
+ if (refusal !== null) return refusal;
284
+ }
285
+ return null;
286
+ }
287
+
288
+ /** Words that are search patterns, not files (`grep PATTERN`, `rg -e PATTERN`). @param {string[]} words */
289
+ function searchPatternIndexes(words) {
290
+ const indexes = new Set();
291
+ if (!SEARCH_PROGRAMS.has(programName(words[0] ?? ''))) return indexes;
292
+ let explicit = false;
293
+ for (let index = 1; index < words.length; index += 1)
294
+ if (words[index] === '-e' || words[index] === '--regexp') {
295
+ indexes.add(index + 1);
296
+ explicit = true;
297
+ }
298
+ if (!explicit) {
299
+ const first = words.findIndex((word, index) => index > 0 && !word.startsWith('-'));
300
+ if (first !== -1) indexes.add(first);
301
+ }
302
+ return indexes;
303
+ }
304
+
305
+ /** @param {string} command @param {GuardContext} context @param {number} [depth] @returns {string | null} */
306
+ function secretsInCommand(command, context, depth = 0) {
307
+ if (command.length === 0) return null;
308
+ const parsed = splitShell(command);
309
+ if (!parsed.ok) {
310
+ const mention = mentionsProtected(command, context);
311
+ if (mention !== null) return mention;
312
+ for (const name of command.split(NAME_DELIMITERS)) {
313
+ const rule = name.length > 0 ? secretRule(name, { extensions: false }) : null;
314
+ if (rule !== null) return message(context, 'secret', rule);
315
+ }
316
+ return null;
317
+ }
318
+ for (const item of parsed.commands) {
319
+ if (changesExtensions(item.words)) return message(context, 'extensions');
320
+ const words = effectiveWords(item.words);
321
+ const program = programName(words[0] ?? '');
322
+ const patterns = searchPatternIndexes(words);
323
+ const prefix = item.words.slice(0, item.words.length - words.length);
324
+ for (const [index, word] of [...prefix, ...words].entries()) {
325
+ if (patterns.has(index - prefix.length)) continue;
326
+ const refusal = wordRefusal(word, context, depth);
327
+ if (refusal !== null) return refusal;
328
+ }
329
+ for (const target of item.targets) {
330
+ const refusal = wordRefusal(target, context, depth);
331
+ if (refusal !== null) return refusal;
332
+ }
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;
340
+ if (script !== undefined && depth < MAX_NESTING) {
341
+ const refusal = secretsInCommand(script, context, depth + 1);
342
+ if (refusal !== null) return refusal;
343
+ }
344
+ }
345
+ return null;
346
+ }
347
+
348
+ /** Destination branch of a push refspec (`HEAD:main`, `+main`, `refs/heads/main`). @param {string} refspec */
349
+ function refspecDestination(refspec) {
350
+ const unforced = refspec.startsWith('+') ? refspec.slice(1) : refspec;
351
+ const colon = unforced.lastIndexOf(':');
352
+ const destination = colon === -1 ? unforced : unforced.slice(colon + 1);
353
+ return destination.replace(/^refs\/heads\//u, '');
354
+ }
355
+
356
+ /** @param {string} directory */
357
+ function currentBranch(directory) {
358
+ try {
359
+ return execFileSync('git', ['-C', directory, 'symbolic-ref', '--short', 'HEAD'], {
360
+ encoding: 'utf8',
361
+ timeout: GIT_TIMEOUT_MS,
362
+ stdio: ['ignore', 'pipe', 'ignore'],
363
+ }).trim();
364
+ } catch {
365
+ return '';
366
+ }
367
+ }
368
+
369
+ /**
370
+ * `git-guard`: pushes to main or master, and force pushes.
371
+ * @param {ToolEvent} event @param {GuardContext} context
372
+ * @returns {string | null}
373
+ */
374
+ export function gitGuard(event, context) {
375
+ const command = record(event.tool_input).command;
376
+ if (event.tool_name !== 'Bash' || typeof command !== 'string') return null;
377
+ const parsed = splitShell(command);
378
+ if (!parsed.ok) return null;
379
+ for (const item of parsed.commands) {
380
+ const words = effectiveWords(item.words);
381
+ if (programName(words[0] ?? '') !== 'git') continue;
382
+ let index = 1;
383
+ let directory = context.projectDir;
384
+ while (index < words.length && (words[index] ?? '').startsWith('-')) {
385
+ const option = words[index] ?? '';
386
+ if (GIT_OPTIONS_WITH_VALUE.has(option)) {
387
+ if (option === '-C') directory = resolve(directory, words[index + 1] ?? '.');
388
+ index += 2;
389
+ } else index += 1;
390
+ }
391
+ if (words[index] !== 'push') continue;
392
+ const args = words.slice(index + 1);
393
+ const flags = args.filter((word) => word.startsWith('-'));
394
+ const positional = args.filter((word) => !word.startsWith('-'));
395
+ const forced =
396
+ flags.some(
397
+ (flag) =>
398
+ flag === '--force' ||
399
+ flag === '--mirror' ||
400
+ (/^-[A-Za-z]+$/u.test(flag) && flag.includes('f')),
401
+ ) || positional.slice(1).some((refspec) => refspec.startsWith('+'));
402
+ if (forced) return message(context, 'pushForce');
403
+ if (flags.includes('--all')) return message(context, 'pushProtected', 'main/master (--all)');
404
+ const refspecs = positional.slice(1);
405
+ const destinations =
406
+ refspecs.length > 0 ? refspecs.map(refspecDestination) : [currentBranch(directory)];
407
+ const protectedBranch = destinations.find((branch) => PROTECTED_BRANCHES.has(branch));
408
+ if (protectedBranch !== undefined) return message(context, 'pushProtected', protectedBranch);
409
+ }
410
+ return null;
411
+ }
412
+
413
+ /**
414
+ * `destructive-guard`: rm -rf on a root-like target, and destructive SQL sent to a client.
415
+ * @param {ToolEvent} event @param {GuardContext} context
416
+ * @returns {string | null}
417
+ */
418
+ export function destructiveGuard(event, context) {
419
+ const command = record(event.tool_input).command;
420
+ if (event.tool_name !== 'Bash' || typeof command !== 'string') return null;
421
+ const parsed = splitShell(command);
422
+ if (!parsed.ok) return null;
423
+ let databaseClient = false;
424
+ for (const item of parsed.commands) {
425
+ const words = effectiveWords(item.words);
426
+ const program = programName(words[0] ?? '');
427
+ if (DATABASE_CLIENTS.has(program)) databaseClient = true;
428
+ if (program !== 'rm') continue;
429
+ const flags = words.slice(1).filter((word) => word.startsWith('-'));
430
+ const recursive = flags.some(
431
+ (flag) => flag === '--recursive' || (/^-[A-Za-z]+$/u.test(flag) && /[rR]/u.test(flag)),
432
+ );
433
+ const force = flags.some(
434
+ (flag) => flag === '--force' || (/^-[A-Za-z]+$/u.test(flag) && flag.includes('f')),
435
+ );
436
+ const target = words
437
+ .slice(1)
438
+ .find((word) => !word.startsWith('-') && DANGEROUS_RM_TARGETS.has(word));
439
+ if (recursive && force && target !== undefined) return message(context, 'rm', target);
440
+ }
441
+ return databaseClient && DESTRUCTIVE_SQL.test(command) ? message(context, 'sql') : null;
442
+ }
443
+
444
+ /** Guards by catalog id, in the order they run. */
445
+ export const GUARDS = Object.freeze({
446
+ 'secrets-guard': secretsGuard,
447
+ 'git-guard': gitGuard,
448
+ 'destructive-guard': destructiveGuard,
449
+ });
@@ -0,0 +1,33 @@
1
+ // @ts-check
2
+ /**
3
+ * Paths a Codex patch touches (spec aisac-engineering-extensions FR6, E6b).
4
+ * Codex sends an edit as `tool_name: "apply_patch"` with the whole patch text in
5
+ * `tool_input.command` and no `file_path` (measured on Codex 0.166.0), so the
6
+ * guardrails read the file names from the patch headers. Names only: the patch
7
+ * body is never interpreted.
8
+ */
9
+
10
+ export const PATCH_TOOL = 'apply_patch';
11
+
12
+ // `*** Add File: <path>`, `*** Update File: <path>`, `*** Delete File: <path>`
13
+ // and `*** Move to: <path>` (the new name of an updated file).
14
+ const HEADER = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/u;
15
+
16
+ /**
17
+ * The paths named in a patch, in order and without repeats. Anything that is
18
+ * not a string, or has no header, names no path. There is no cap: the hook
19
+ * input is already bounded (1 MiB), and a cap would let a patch hide a secret
20
+ * file after the limit.
21
+ * @param {unknown} patch
22
+ * @returns {string[]}
23
+ */
24
+ export function patchPaths(patch) {
25
+ if (typeof patch !== 'string' || patch.length === 0) return [];
26
+ /** @type {Set<string>} */
27
+ const paths = new Set();
28
+ for (const line of patch.split(/\r?\n/u)) {
29
+ const path = HEADER.exec(line)?.[1]?.trim();
30
+ if (path !== undefined && path.length > 0) paths.add(path);
31
+ }
32
+ return [...paths];
33
+ }