@hasna/hooks 0.12.9 → 0.12.14

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 (58) hide show
  1. package/README.md +69 -6
  2. package/bin/hooks/stop-review.js +1235 -0
  3. package/bin/hooks-mcp.js +298 -85
  4. package/bin/index.js +3309 -1086
  5. package/bin/native-readiness-entry.js +5 -1
  6. package/bin/native-safety-entry.js +27 -25
  7. package/bin/native-safety-worker.cjs +27 -25
  8. package/bin/serve.js +1362 -70
  9. package/dist/db/remote-storage.d.ts +7 -1
  10. package/dist/index.d.ts +4 -1
  11. package/dist/index.js +1665 -257
  12. package/dist/lib/codex-safety-check.d.ts +1 -1
  13. package/dist/lib/hosted-registry.d.ts +70 -0
  14. package/dist/lib/legacy-registry-artifact.d.ts +23 -0
  15. package/dist/lib/manifest.d.ts +7 -0
  16. package/dist/lib/native-safety.d.ts +1 -0
  17. package/dist/lib/native-target.d.ts +7 -0
  18. package/dist/lib/opencode-stop-plugin.d.ts +55 -0
  19. package/dist/lib/registry-artifact.d.ts +36 -0
  20. package/dist/lib/registry.d.ts +4 -0
  21. package/dist/lib/stop-review-context.d.ts +12 -0
  22. package/dist/lib/store.d.ts +4 -0
  23. package/dist/lib/sumi-stop-plugin.d.ts +129 -0
  24. package/dist/lib/sync.d.ts +10 -0
  25. package/dist/lib/transport.d.ts +1 -1
  26. package/dist/native-readiness.d.ts +1 -1
  27. package/dist/native-readiness.js +5 -1
  28. package/dist/openapi.d.ts +160 -16
  29. package/dist/opencode-stop-plugin.js +384 -0
  30. package/dist/registry-auth.d.ts +5 -0
  31. package/dist/registry-http.d.ts +4 -0
  32. package/dist/sdk/generated.d.ts +32 -12
  33. package/dist/sdk/index.d.ts +28 -5
  34. package/dist/sdk/index.js +49 -24
  35. package/dist/sdk/registry-client.d.ts +1 -1
  36. package/dist/serve.d.ts +4 -4
  37. package/dist/storage.js +33 -2
  38. package/dist/sumi-stop-plugin.js +380 -0
  39. package/hooks/hook-scanoutput/src/hook.ts +33 -3
  40. package/hooks/hook-stop-review/README.md +109 -0
  41. package/hooks/hook-stop-review/manifest.json +10 -0
  42. package/hooks/hook-stop-review/package.json +11 -0
  43. package/hooks/hook-stop-review/src/hook.ts +59 -0
  44. package/hooks/hook-stop-review/src/index.ts +3 -0
  45. package/hooks/hook-stop-review/src/jev.ts +121 -0
  46. package/hooks/hook-stop-review/src/native.ts +246 -0
  47. package/hooks/hook-stop-review/src/policy.ts +145 -0
  48. package/hooks/hook-stop-review/src/runtime.ts +309 -0
  49. package/hooks/hook-stop-review/src/types.ts +121 -0
  50. package/hooks/hook-trash-guard/src/hook.ts +96 -0
  51. package/hooks/hook-workspace-repos-guard/src/hook.ts +231 -3
  52. package/hooks/local-executors.ts +841 -0
  53. package/package.json +22 -4
  54. package/scripts/build-bundled-hooks.ts +40 -0
  55. package/scripts/validate-bundled-hooks.ts +78 -0
  56. package/scripts/validate-opencode-stop-plugin.ts +42 -0
  57. package/scripts/validate-package.ts +9 -0
  58. package/scripts/validate-sumi-stop-plugin.ts +47 -0
@@ -90,6 +90,7 @@ import {
90
90
  type WrapperSpec,
91
91
  } from "../../shell-words";
92
92
  export { expandBraces } from "../../shell-words";
93
+ import { launchedCommands, localExecutor, shellProgram } from "../../local-executors";
93
94
 
94
95
  const RULE = "trash-guard";
95
96
 
@@ -1399,6 +1400,17 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
1399
1400
 
1400
1401
  if (Object.hasOwn(REFUSED_VERBS, verb)) return { kind: "refuse", reason: REFUSED_VERBS[verb] };
1401
1402
 
1403
+ // Local executors (interpreters with an inline program, ssh/scp/sftp
1404
+ // local-exec options, rsync -e, git sshCommand, sed e/s///e) run a command
1405
+ // this hook cannot rewrite into trash. UNDER a protected repo-checkout root a
1406
+ // delete they could run — or a program we cannot read (fail closed) — is
1407
+ // refused; outside those roots the behaviour is unchanged, so this never
1408
+ // broadens refusals beyond a checkout. Checked before the verb-specific
1409
+ // branches so git/find/xargs do not short-circuit it. rm is never an
1410
+ // executor here, so the rewrite path below is unaffected.
1411
+ const execReading = readLocalExecutor(segment, index, cwd, ctx);
1412
+ if (execReading) return execReading;
1413
+
1402
1414
  if (verb === "rm") {
1403
1415
  const operands = rmOperands(segment, index);
1404
1416
  // `rm` with no operand deletes nothing (GNU `rm` exits "missing
@@ -1511,9 +1523,93 @@ function readCommandAt(segment: Segment, index: number, cwd: string, ctx: ScanCo
1511
1523
  };
1512
1524
  }
1513
1525
  }
1526
+
1514
1527
  return { kind: "none" };
1515
1528
  }
1516
1529
 
1530
+ /**
1531
+ * If the command at `index` of `segment` is a local executor — an interpreter
1532
+ * with an inline program (awk system(), perl/ruby/python/node -e/-c, …), an
1533
+ * ssh/scp/sftp local-exec option (ProxyCommand and friends) or `-F` config,
1534
+ * rsync's `-e` remote shell, git's local sshCommand, or sed's `e`/`s///e` — and
1535
+ * it runs UNDER a protected repo-checkout root, and a delete it could run is
1536
+ * visible or a program cannot be read (fail closed), refuse: the delete cannot
1537
+ * be redirected into trash. Outside the roots this reads nothing, so trash-guard
1538
+ * keeps its behaviour there, exactly as `sh -c` did. Returns null otherwise.
1539
+ */
1540
+ function readLocalExecutor(
1541
+ segment: Segment,
1542
+ index: number,
1543
+ cwd: string,
1544
+ ctx: ScanContext,
1545
+ scope: { segment: Segment; index: number } = { segment, index },
1546
+ depth = 0,
1547
+ ): Reading | null {
1548
+ const verb = commandName(segment.words[index].text);
1549
+ // A launcher (find -exec/-execdir/-ok/-okdir, xargs) runs a command of its
1550
+ // own: read it as a command in its own right, by both command-position
1551
+ // models, with the launcher's operands (find's start paths) and cwd deciding
1552
+ // whether it runs under a checkout.
1553
+ for (const launched of launchedCommands(segment.words.map((word) => decodeWord(word.text)), index, (at) => segment.redirects.has(at))) {
1554
+ if (depth >= 8) return executorTargetsHandoff(scope.segment, scope.index, cwd, ctx.home) ? { kind: "refuse", reason: LAUNCHER_DEPTH_REASON } : null;
1555
+ const sub: Segment = {
1556
+ words: segment.words.slice(launched.start, launched.end),
1557
+ redirects: new Set([...segment.redirects].filter((at) => at >= launched.start && at < launched.end).map((at) => at - launched.start)),
1558
+ };
1559
+ const strict = strictCommandIndex(sub);
1560
+ for (const inner of new Set([commandWordIndex(sub), strict ?? -1])) {
1561
+ if (inner < 0) continue;
1562
+ const reading = readLocalExecutor(sub, inner, cwd, ctx, scope, depth + 1);
1563
+ if (reading) return reading;
1564
+ }
1565
+ }
1566
+ // `sh|bash|… -c PROGRAM` / `eval WORD…` whose program is not a plain literal
1567
+ // (an expansion, a substitution, several eval words) cannot be read at all;
1568
+ // under a checkout it is refused. A literal program keeps the shell-string
1569
+ // reading below (OPAQUE_COMMANDS), as before.
1570
+ const kept = segment.words.map((word, at) => ({ word, at })).filter(({ at }) => !segment.redirects.has(at));
1571
+ const keptIndex = kept.findIndex(({ at }) => at === index);
1572
+ const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex);
1573
+ if (shell && !shell.literal && (executorTargetsHandoff(segment, index, cwd, ctx.home) || executorTargetsHandoff(scope.segment, scope.index, cwd, ctx.home))) {
1574
+ return {
1575
+ kind: "refuse",
1576
+ reason: `\`${verb}\` runs a shell program that is not a plain literal (an expansion, a substitution or several words), so this hook cannot read what it would delete under a protected repository checkout. Write the program out literally, or run it from outside the checkout.`,
1577
+ };
1578
+ }
1579
+ const exec = localExecutor(
1580
+ segment.words.map((word) => decodeWord(word.text)),
1581
+ index,
1582
+ (at) => at >= 0 && at < segment.words.length && (segment.redirects.has(at) || expandsWord(segment.words[at].text)),
1583
+ );
1584
+ if (!exec || !(executorTargetsHandoff(segment, index, cwd, ctx.home) || executorTargetsHandoff(scope.segment, scope.index, cwd, ctx.home))) return null;
1585
+ if (!exec.unresolved && !exec.programs.some((program) => mentionsDeleteVerb(program.text))) return null;
1586
+ return {
1587
+ kind: "refuse",
1588
+ reason: `\`${verb}\` runs a program locally (an interpreter's inline program or a command-running option) this hook cannot rewrite, and it could delete a file under a protected repository checkout. Run the delete directly as \`rm -- <path>\` (intercepted and redirected into trash), or run the command from outside the checkout.`,
1589
+ };
1590
+ }
1591
+
1592
+ const LAUNCHER_DEPTH_REASON =
1593
+ "This command nests find/xargs launchers too deeply for this hook to read what they run under a protected repository checkout. Run the inner command directly.";
1594
+
1595
+ /**
1596
+ * Whether a local executor's effective cwd, or one of its literal operands,
1597
+ * sits under a protected repo-checkout root — the only place trash-guard adds a
1598
+ * new refusal for this class. Operands are every word after the command word;
1599
+ * a word the shell would expand cannot be resolved and is ignored here (the
1600
+ * cwd test still applies, and workspace-repos-guard fails those closed).
1601
+ */
1602
+ function executorTargetsHandoff(segment: Segment, index: number, cwd: string, home: string): boolean {
1603
+ const roots = handoffRoots(home);
1604
+ const underRoot = (target: string | null): boolean => target !== null && roots.some((root) => isUnder(target, root));
1605
+ if (roots.some((root) => isUnder(cwd, root))) return true;
1606
+ for (let at = index + 1; at < segment.words.length; at++) {
1607
+ if (segment.redirects.has(at)) continue;
1608
+ if (underRoot(resolveLiteralTarget(segment.words[at].text, cwd, home))) return true;
1609
+ }
1610
+ return false;
1611
+ }
1612
+
1517
1613
  /**
1518
1614
  * Classify a command string: which `rm` verbs are ours to rewrite, which are
1519
1615
  * handed to the guarded-roots hook, and why anything else is refused.
@@ -44,7 +44,10 @@
44
44
  * the command and its operands are read (see unwrapCommand); arguments they
45
45
  * cannot be parsed from fail closed. A Trash capture is read the way
46
46
  * @hasna/trash parses it, with options before, between or after its paths
47
- * until `--` (see trashOperands).
47
+ * until `--` (see trashOperands). A quoted command list that the `;`, `&&`,
48
+ * `||` and newline split cuts (`ssh host 'a; trash --version'`) is read as
49
+ * the commands it holds, and clears its parts only when none of them, nor
50
+ * the command it is an argument of, can delete or write (see cutPartReads).
48
51
  *
49
52
  * Allowed orgs default to hasna,hasnaxyz,hasna-products and are overridable
50
53
  * with the WORKSPACE_REPOS_GUARD_ORGS env var (comma-separated) or, where
@@ -79,6 +82,7 @@ import {
79
82
  type CodewithHookOutput,
80
83
  } from "../../codewith-native-common";
81
84
  import { ASSIGNMENT, baseName, expandBraces, splitsOrMoves, unwrapCommand, type ShellWord } from "../../shell-words";
85
+ import { embeddedProgramIsReadOnly, launchedCommands, localExecutor, shellProgram, type ExecutorFinding } from "../../local-executors";
82
86
 
83
87
  export { expandBraces, unwrapCommand };
84
88
 
@@ -459,6 +463,9 @@ function expandsAtRuntime(raw: string): boolean {
459
463
  function segmentOperation(segment: string): Operation {
460
464
  const trimmed = segment.trim();
461
465
  if (!trimmed) return "read";
466
+ // A destructive local executor counts wherever it hides: in a substitution
467
+ // body, or in a command the opaque reading below would not take apart.
468
+ if (hidesDestructiveExecutor(trimmed)) return "delete";
462
469
  const parsed = lexCommand(trimmed);
463
470
  // Preserve conservative classification where the shell body is opaque.
464
471
  if (!parsed.trustworthy || parsed.substitutions.length || /\$\{[^}]*[|;()]|[<>]\(/.test(trimmed)) return opaqueOperation(trimmed);
@@ -490,8 +497,82 @@ function partOperation(part: ReturnType<typeof lexCommand>["segments"][number]):
490
497
  return strongest(shared, commandOperation(part, kept[strict.index].at));
491
498
  }
492
499
 
500
+ /**
501
+ * Whether the simple command at `index` of `part` runs a program or option
502
+ * value locally that is not provably read-only — awk/perl/python/ruby/node/…
503
+ * inline programs, an ssh/scp/sftp local-exec option (ProxyCommand and friends)
504
+ * or `-F` config, rsync's `-e` remote shell, git's local sshCommand, and sed's
505
+ * `e`/`s///e` execute forms. A shell option value (ProxyCommand, rsync `-e`,
506
+ * sshCommand) is judged as the shell command it is; an interpreter program by
507
+ * its grammar (embeddedProgramIsReadOnly); an unreadable value fails closed.
508
+ * Such a command is treated as a delete so the structural guard refuses it at
509
+ * any depth under a protected root (a write would be allowed inside a repo).
510
+ */
511
+ function runsDestructiveLocalProgram(part: ReturnType<typeof lexCommand>["segments"][number], index: number, depth = 0): boolean {
512
+ if (index < 0 || depth > 8) return depth > 8;
513
+ // `sh|bash|… -c PROGRAM` and `eval WORD…`: a program that is not a plain
514
+ // literal fails closed; a literal one keeps its existing (opaque) reading,
515
+ // except that a destructive local executor inside it counts here too.
516
+ const kept = part.words.map((word, at) => ({ word, at })).filter(({ at }) => !part.redirects.has(at));
517
+ const keptIndex = kept.findIndex(({ at }) => at === index);
518
+ const shell = keptIndex < 0 ? null : shellProgram(kept.map(({ word }) => word.text), keptIndex);
519
+ if (shell) {
520
+ if (!shell.literal) return true;
521
+ const inner = lexCommand(shell.program!);
522
+ if (inner.trustworthy && inner.segments.some((segment) => segmentRunsDestructive(segment, depth + 1))) return true;
523
+ }
524
+ const decoded = part.words.map((word) => decodeWord(word.text));
525
+ // A launcher (find -exec/-execdir/-ok/-okdir, xargs) runs a command of its
526
+ // own; that command is read like one in command position, wrappers included.
527
+ for (const launched of launchedCommands(decoded, index, (at) => part.redirects.has(at))) {
528
+ if (segmentRunsDestructive(subSegment(part, launched.start, launched.end), depth + 1)) return true;
529
+ }
530
+ const opaqueAt = (at: number) => at >= 0 && at < part.words.length && (part.redirects.has(at) || expandsAtRuntime(part.words[at].text));
531
+ const exec: ExecutorFinding | null = localExecutor(decoded, index, opaqueAt);
532
+ if (!exec) return false;
533
+ if (exec.unresolved) return true;
534
+ return exec.programs.some((program) =>
535
+ program.kind === "shell" ? segmentOperation(program.text) !== "read" : !embeddedProgramIsReadOnly(program));
536
+ }
537
+
538
+ /** The words `[start, end)` of a lexed simple command as a command of their own, redirections kept. */
539
+ function subSegment(part: ReturnType<typeof lexCommand>["segments"][number], start: number, end: number): ReturnType<typeof lexCommand>["segments"][number] {
540
+ const redirects = new Set([...part.redirects].filter((at) => at >= start && at < end).map((at) => at - start));
541
+ return { words: part.words.slice(start, end), redirects };
542
+ }
543
+
544
+ /** Whether a lexed simple command, read by both command-position models, runs a destructive local program. */
545
+ function segmentRunsDestructive(segment: ReturnType<typeof lexCommand>["segments"][number], depth = 0): boolean {
546
+ const shared = commandWordIndex(segment);
547
+ if (shared >= 0 && runsDestructiveLocalProgram(segment, shared, depth)) return true;
548
+ const kept = segment.words.map((word, at) => ({ word, at })).filter(({ at }) => !segment.redirects.has(at));
549
+ const strict = unwrapCommand(kept.map(({ word }) => ({ text: decodeWord(word.text), opaque: /[$\x60]/.test(word.text) })));
550
+ return strict !== null && strict.index >= 0 && kept[strict.index].at !== shared && runsDestructiveLocalProgram(segment, kept[strict.index].at, depth);
551
+ }
552
+
553
+ /**
554
+ * Whether `text` holds a destructive local executor anywhere the lexer can see
555
+ * one: in its own simple commands, or in a `$( )`/backtick substitution body
556
+ * (quoted or not), at any nesting. The rule-based reading short-circuits to the
557
+ * opaque reading when a command holds a substitution, and never reads a quoted
558
+ * substitution's body, so without this an executor whose program arrives
559
+ * through one (`perl -e $(cat p)`, `echo "$(awk 'BEGIN{system(…)}')"`) would
560
+ * escape the fail-closed rule.
561
+ */
562
+ function hidesDestructiveExecutor(text: string, depth = 0): boolean {
563
+ if (depth > 4) return false;
564
+ const lexed = lexCommand(text);
565
+ if (lexed.trustworthy && lexed.segments.some((segment) => segmentRunsDestructive(segment))) return true;
566
+ const bodies = commandSubstitutions(text);
567
+ return (bodies ?? lexed.substitutions).some((body) => hidesDestructiveExecutor(body, depth + 1));
568
+ }
569
+
493
570
  /** The operation of the command whose word is at `index` of `part`. */
494
571
  function commandOperation(part: ReturnType<typeof lexCommand>["segments"][number], index: number): Operation {
572
+ // A command that runs a destructive program or option value locally (awk
573
+ // system(), perl -e, ssh ProxyCommand, sed e, …) is a delete here, whatever
574
+ // its own command word would otherwise read as.
575
+ if (runsDestructiveLocalProgram(part, index)) return "delete";
495
576
  const kept = part.words.filter((_, at) => at >= index && !part.redirects.has(at));
496
577
  const words = kept.map((word) => decodeWord(word.text));
497
578
  const tool = words[0].split("/").pop();
@@ -1117,6 +1198,135 @@ export function bashTargets(command: string, home: string, cwd: string): PathTar
1117
1198
  return [...segmentTargets(data.outer, home, cwd), ...data.bodies.flatMap((body) => bashTargets(body, home, DETACHED_CWD))];
1118
1199
  }
1119
1200
 
1201
+ /** Where segmentTargets splits a command into parts; the capture keeps each separator as a part. */
1202
+ const LIST_SEPARATOR = /(\s*&&\s*|\s*\|\|\s*|;\s*|\n+)/;
1203
+
1204
+ /** A word written whole in one pair of quotes, whose text bash takes literally. */
1205
+ const LITERAL_QUOTED_WORD = /^(?:'[^']*'|"[^"$\x60\\]*")$/;
1206
+
1207
+ type LexedCommand = ReturnType<typeof lexCommand>;
1208
+ type LexedSegment = LexedCommand["segments"][number];
1209
+ type LexedWord = LexedSegment["words"][number];
1210
+
1211
+ interface ListSplitCuts {
1212
+ lexed: LexedCommand;
1213
+ /** Offset of each part of the split in the command. */
1214
+ offsets: number[];
1215
+ /** The words of the command a separator of the split lies inside. */
1216
+ words: LexedWord[];
1217
+ }
1218
+
1219
+ /**
1220
+ * The words segmentTargets' split cuts through. The split ignores quoting,
1221
+ * so a separator inside a quoted word (`ssh h 'a; trash --version'`) cuts
1222
+ * that word, and each part holding a piece of it carries an unbalanced
1223
+ * quote, which leaves only the opaque reading of the part. Null when no word
1224
+ * is cut, or the command cannot be lexed to its end or holds a substitution:
1225
+ * every part then keeps its own reading.
1226
+ */
1227
+ function listSplitCuts(command: string, parts: string[], allowSubstitutions = false): ListSplitCuts | null {
1228
+ const offsets: number[] = [];
1229
+ let at = 0;
1230
+ for (const part of parts) {
1231
+ offsets.push(at);
1232
+ at += part.length;
1233
+ }
1234
+ const lexed = lexCommand(command);
1235
+ // Clearing a part to a read (cutPartReads) needs a command with no
1236
+ // substitution; refusing one (cutPartExecutes) only needs it lexed whole.
1237
+ if (!lexed.trustworthy || (!allowSubstitutions && lexed.substitutions.length > 0)) return null;
1238
+ const words = lexed.segments.flatMap((segment) => segment.words).filter((word) =>
1239
+ parts.some((part, k) => k % 2 === 1 && offsets[k] < word.end && offsets[k] + part.length > word.start));
1240
+ return words.length > 0 ? { lexed, offsets, words } : null;
1241
+ }
1242
+
1243
+ /**
1244
+ * Whether one lexed simple command, whose text is `text`, only reads:
1245
+ * - its rule-based reading (segmentOperation) is a read;
1246
+ * - no assignment precedes its command word: one can change what the word
1247
+ * runs (`PATH=...`), and in an option value (`ProxyCommand=mkdir x`) the
1248
+ * rest is itself a command;
1249
+ * - unless its command word, under both command-position models, runs no
1250
+ * command (`command -v`) or is a DATA_COMMANDS word, which never runs its
1251
+ * arguments as code, its words other than `skip`, as written and unquoted,
1252
+ * hold no delete or write under the opaque reading and no find action
1253
+ * (`-delete`, `-exec`), since it may run one of them.
1254
+ */
1255
+ function onlyReads(segment: LexedSegment, text: string, skip: LexedWord[] = []): boolean {
1256
+ if (segmentOperation(text) !== "read") return false;
1257
+ const index = commandWordIndex(segment);
1258
+ const kept = segment.words.filter((_, at) => !segment.redirects.has(at));
1259
+ const strict = unwrapCommand(kept.map((word) => ({ text: decodeWord(word.text), opaque: /[$\x60]/.test(word.text) })));
1260
+ if (strict === null) return false;
1261
+ const runsAt = [index < 0 ? Infinity : index, strict.index < 0 ? Infinity : segment.words.indexOf(kept[strict.index])];
1262
+ if (segment.words.some((word, at) => at < Math.max(...runsAt) && !segment.redirects.has(at) && ASSIGNMENT.test(decodeWord(word.text)))) return false;
1263
+ const names = [index < 0 ? null : segment.words[index].text, strict.index < 0 ? null : kept[strict.index].text];
1264
+ if (names.every((name) => name === null || DATA_COMMANDS.has(baseName(decodeWord(name))))) return true;
1265
+ const words = kept.filter((word) => !skip.includes(word));
1266
+ const decoded = words.map((word) => decodeWord(word.text));
1267
+ return opaqueOperation(words.map((word) => word.text).join(" ")) === "read" && opaqueOperation(decoded.join(" ")) === "read"
1268
+ && !decoded.some((word) => FIND_ACTIONS.has(word));
1269
+ }
1270
+
1271
+ /**
1272
+ * Whether the part of `command` from `from` to `to` holds a piece of a quoted
1273
+ * word that is the inline program of a destructive local executor. The `;`,
1274
+ * `&&`, `||` and newline split cuts an executor's quoted program at a separator
1275
+ * inside it (`python3 -c 'import os; os.remove("x")'`), so no single part reads
1276
+ * as the delete it is. The lexed command keeps the program whole, so here the
1277
+ * owning lexed command is read as one: when it runs a destructive local program
1278
+ * (runsDestructiveLocalProgram), the part counts as a delete, whatever its
1279
+ * unbalanced quote makes the opaque reading say. Only a cut quoted word counts,
1280
+ * so a plain `a; rm` list is unaffected (its `rm` part already reads as a
1281
+ * delete).
1282
+ */
1283
+ function cutPartExecutes(command: string, cuts: ListSplitCuts, from: number, to: number): boolean {
1284
+ const overlaps = (word: LexedWord) => word.start < to && word.end > from;
1285
+ if (!cuts.words.some(overlaps)) return false;
1286
+ return cuts.lexed.segments
1287
+ .filter((segment) => segment.words.some(overlaps))
1288
+ .some((segment) => segmentRunsDestructive(segment));
1289
+ }
1290
+
1291
+ /** The text of the lexed simple commands in `text`, first word to last. */
1292
+ const segmentText = (text: string, segment: LexedSegment): string =>
1293
+ text.slice(segment.words[0].start, segment.words[segment.words.length - 1].end);
1294
+
1295
+ /**
1296
+ * Whether the part of `command` from `from` to `to`, which holds a piece of a
1297
+ * word the split cut (listSplitCuts), only reads once every word in it is
1298
+ * read where it belongs (onlyReads):
1299
+ * - every command one of the part's words belongs to, read whole, with each
1300
+ * cut word as the one word it is (its own text is read next);
1301
+ * - the whole text of each cut word in the part, read as the command list it
1302
+ * would be if it ran: every command in it.
1303
+ * So a quoted list clears its parts only when no command in it, nor the
1304
+ * command it is an argument of, can delete or write. Only a word written
1305
+ * whole in one pair of quotes, with no expansion, is read this way; any other
1306
+ * cut word, or a list that cannot be lexed to its end or holds a
1307
+ * substitution, keeps the part's own reading. Redirections are not judged
1308
+ * here: segmentTargets still reads every redirect operand in the part as a
1309
+ * write. This only ever replaces a stronger reading with "read"; it never
1310
+ * makes a part stronger.
1311
+ */
1312
+ function cutPartReads(command: string, cuts: ListSplitCuts, from: number, to: number): boolean {
1313
+ const overlaps = (word: LexedWord) => word.start < to && word.end > from;
1314
+ const cut = cuts.words.filter(overlaps);
1315
+ if (cut.length === 0 || cut.some((word) => !LITERAL_QUOTED_WORD.test(word.text))) return false;
1316
+ for (const segment of cuts.lexed.segments.filter((segment) => segment.words.some(overlaps))) {
1317
+ if (!onlyReads(segment, segmentText(command, segment), cuts.words)) return false;
1318
+ }
1319
+ for (const word of cut) {
1320
+ const list = word.text.slice(1, -1);
1321
+ // The lexer drops a here-document body, which a shell in the list could run.
1322
+ if (list.includes("<<")) return false;
1323
+ const inner = lexCommand(list);
1324
+ if (!inner.trustworthy || inner.substitutions.length > 0) return false;
1325
+ if (!inner.segments.every((segment) => onlyReads(segment, segmentText(list, segment)))) return false;
1326
+ }
1327
+ return true;
1328
+ }
1329
+
1120
1330
  /**
1121
1331
  * Extract protected-repo-checkout targets from a Bash command. Recognises
1122
1332
  * explicit `~/...`, `$HOME/...`, `${HOME}/...` and literal-home references
@@ -1141,7 +1351,9 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1141
1351
  if (!command) return [];
1142
1352
  const roots = protectedRoots(home);
1143
1353
  const underRoot = (path: string) => roots.some((root) => path === root || path.startsWith(`${root}${sep}`));
1144
- const parts = command.split(/(\s*&&\s*|\s*\|\|\s*|;\s*|\n+)/);
1354
+ const parts = command.split(LIST_SEPARATOR);
1355
+ const cuts = listSplitCuts(command, parts);
1356
+ const execCuts = cuts ?? listSplitCuts(command, parts, true);
1145
1357
 
1146
1358
  const targets: PathTarget[] = [];
1147
1359
  // Every directory the current segment can run in, every directory any
@@ -1164,6 +1376,18 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1164
1376
  for (let i = 0; i < opens; i++) subshells.push({ current: [...current], reachable: new Set(reachable), certain });
1165
1377
 
1166
1378
  const segment = unwrapSegment(rawSegment);
1379
+ // A part the split cut out of a quoted word is read as the commands its
1380
+ // words belong to (cutPartReads); when every one only reads, so does the
1381
+ // part, whatever its unbalanced quote makes the opaque reading say.
1382
+ const readsOnly = cuts !== null && cutPartReads(command, cuts, cuts.offsets[index], cuts.offsets[index] + rawSegment.length);
1383
+ // The converse: a part holding a piece of a destructive local executor's
1384
+ // quoted program (`python3 -c 'import os; os.remove("x")'` cut at its `;`)
1385
+ // is a delete of every protected directory it can run in, so a split
1386
+ // program is refused just as the whole command is.
1387
+ // The part itself is also read whole before any group unwrapping, which
1388
+ // strips a trailing `)` and would cut `perl -e $(cat p)` short.
1389
+ const executes = !readsOnly && ((execCuts !== null && cutPartExecutes(command, execCuts, execCuts.offsets[index], execCuts.offsets[index] + rawSegment.length))
1390
+ || hidesDestructiveExecutor(rawSegment.trim()));
1167
1391
 
1168
1392
  const plainCd = segment.match(/^cd(?:\s+(?:-[A-Za-z@]+|--))*(?:\s+([^\s;&|<>()\x60]+))?$/);
1169
1393
  const embeddedCd = plainCd ? null : segment.match(/(?:^|\s)cd(?:\s+(?:-[A-Za-z]+|--))*\s+([^\s;&|<>()\x60]+)/);
@@ -1204,7 +1428,7 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1204
1428
  if (operand) operands.push(operand);
1205
1429
  return " ";
1206
1430
  });
1207
- const commandOp = segmentOperation(commandPart);
1431
+ const commandOp: Operation = readsOnly ? "read" : executes ? "delete" : segmentOperation(commandPart);
1208
1432
  return { commandPart, operands, op: opaqueRedirect && commandOp === "read" ? ("write" as Operation) : commandOp };
1209
1433
  });
1210
1434
 
@@ -1219,6 +1443,10 @@ function segmentTargets(command: string, home: string, cwd: string): PathTarget[
1219
1443
  ? "write"
1220
1444
  : "read";
1221
1445
  const bases = current.filter(underRoot);
1446
+ // A part cut out of a destructive executor's quoted program is a delete of
1447
+ // every protected directory it can run in; its own words no longer parse,
1448
+ // so it is read from the whole lexed command, not its stages.
1449
+ if (executes) for (const base of bases) targets.push({ path: base, op: "delete" });
1222
1450
  for (const stage of stages) {
1223
1451
  let foundExplicit = false;
1224
1452
  for (const path of explicitTargets(stage.commandPart)) {