fullcourtdefense-cli 1.35.10 → 1.36.2

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 (74) hide show
  1. package/dist/actionPolicyEngine.d.ts +24 -0
  2. package/dist/actionPolicyEngine.js +79 -19
  3. package/dist/approvalPrompt.d.ts +15 -0
  4. package/dist/approvalPrompt.js +157 -20
  5. package/dist/askDialog.d.ts +2 -0
  6. package/dist/askDialog.js +15 -1
  7. package/dist/askHeader.d.ts +81 -0
  8. package/dist/askHeader.js +573 -0
  9. package/dist/blockExplanation.d.ts +9 -0
  10. package/dist/blockExplanation.js +14 -0
  11. package/dist/callerEnv.d.ts +1 -1
  12. package/dist/callerEnv.js +14 -0
  13. package/dist/cloudGrant.d.ts +46 -0
  14. package/dist/cloudGrant.js +420 -0
  15. package/dist/cloudGrantTools.d.ts +97 -0
  16. package/dist/cloudGrantTools.js +1112 -0
  17. package/dist/commandNarrative.d.ts +8 -0
  18. package/dist/commandNarrative.js +222 -49
  19. package/dist/commands/cmdGuard.js +3 -1
  20. package/dist/commands/daemon.js +56 -2
  21. package/dist/commands/deterministicGuard.d.ts +70 -4
  22. package/dist/commands/deterministicGuard.js +494 -63
  23. package/dist/commands/discover.js +50 -16
  24. package/dist/commands/discoverAgentFiles.d.ts +2 -0
  25. package/dist/commands/discoverAgentFiles.js +1 -0
  26. package/dist/commands/discoverPaths.d.ts +4 -0
  27. package/dist/commands/discoverPaths.js +19 -1
  28. package/dist/commands/discoverProjectRoots.d.ts +72 -0
  29. package/dist/commands/discoverProjectRoots.js +327 -0
  30. package/dist/commands/discoverProxy.d.ts +1 -1
  31. package/dist/commands/discoverProxy.js +1 -1
  32. package/dist/commands/discoverSecrets.d.ts +44 -0
  33. package/dist/commands/discoverSecrets.js +158 -14
  34. package/dist/commands/hook.js +25 -10
  35. package/dist/commands/knownMcpServers.d.ts +8 -2
  36. package/dist/commands/knownMcpServers.js +33 -2
  37. package/dist/commands/mcpGateway.js +9 -7
  38. package/dist/commands/posixShellGuard.js +1 -1
  39. package/dist/commands/shellGuard.js +86 -26
  40. package/dist/commands/uninstallAll.d.ts +1 -7
  41. package/dist/commands/uninstallAll.js +6 -45
  42. package/dist/commands/watchdog.js +17 -3
  43. package/dist/config.d.ts +1 -1
  44. package/dist/config.js +3 -3
  45. package/dist/credentialGrant.d.ts +48 -0
  46. package/dist/credentialGrant.js +29 -18
  47. package/dist/credentialStore.js +1 -1
  48. package/dist/devConfirm.d.ts +51 -3
  49. package/dist/devConfirm.js +226 -33
  50. package/dist/distress.d.ts +2 -0
  51. package/dist/distress.js +2 -0
  52. package/dist/grantTargets.d.ts +21 -0
  53. package/dist/grantTargets.js +235 -0
  54. package/dist/localSafetySnapshot.js +2 -0
  55. package/dist/msiProductCode.d.ts +10 -0
  56. package/dist/msiProductCode.js +124 -0
  57. package/dist/notify.js +1 -0
  58. package/dist/selfTest.d.ts +1 -1
  59. package/dist/selfTest.js +1 -1
  60. package/dist/selfUpdate.d.ts +108 -0
  61. package/dist/selfUpdate.js +353 -18
  62. package/dist/shellAst.d.ts +2 -0
  63. package/dist/shellAst.js +7 -1
  64. package/dist/shellAstLoader.js +14 -1
  65. package/dist/telemetry.d.ts +3 -0
  66. package/dist/telemetry.js +1 -0
  67. package/dist/version.json +1 -1
  68. package/installer/macos/guardian/ai.fullcourtdefense.guardian.plist +19 -0
  69. package/installer/macos/guardian/fcd-guardian.sh +590 -0
  70. package/installer/macos/guardian/install-guardian.sh +32 -0
  71. package/installer/macos/guardian/uninstall-guardian.sh +12 -0
  72. package/installer/windows/README.md +88 -0
  73. package/installer/windows/rescue/FullCourtDefense-Rescue.ps1 +229 -0
  74. package/package.json +11 -1
@@ -33,8 +33,15 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.CREDENTIAL_COMMAND_RULES = exports.DEFAULT_DISABLED_BUILT_INS = void 0;
36
+ exports.REMOTE_CONTROL_COMMAND_RULES = exports.REMOTE_CONTROL_BRIDGES = exports.REMOTE_CONTROL_CATALOG_VERSION = exports.CREDENTIAL_COMMAND_RULES = exports.DEFAULT_DISABLED_BUILT_INS = void 0;
37
37
  exports.toLocalSafetyRuleAction = toLocalSafetyRuleAction;
38
+ exports.remoteControlBridgePattern = remoteControlBridgePattern;
39
+ exports.remoteControlBridgeInCommand = remoteControlBridgeInCommand;
40
+ exports.classifyRemoteMcpLaunch = classifyRemoteMcpLaunch;
41
+ exports.sanitizeRemoteControlFacts = sanitizeRemoteControlFacts;
42
+ exports.remoteControlFactFor = remoteControlFactFor;
43
+ exports.remoteControlGrantKey = remoteControlGrantKey;
44
+ exports.remoteControlLaunches = remoteControlLaunches;
38
45
  exports.setShellAstProvider = setShellAstProvider;
39
46
  exports.setShellAstMode = setShellAstMode;
40
47
  exports.getShellAstMode = getShellAstMode;
@@ -214,15 +221,6 @@ exports.DEFAULT_DISABLED_BUILT_INS = new Set([
214
221
  // IDE). Off by default — orgs opt in via the Local Safety console toggle,
215
222
  // which the runtime snapshot then applies on every machine.
216
223
  'contextual_secret',
217
- // Cloud token printers / secret fetchers used constantly by LEGITIMATE
218
- // deploy tooling and dev loops. Off by default; orgs with stricter posture
219
- // opt in via the console. (The rarely-legitimate forms — gh auth token,
220
- // git credential fill, keychain dumps — are ON by default.)
221
- 'gcloud_access_token_cmd',
222
- 'gcloud_secret_access_cmd',
223
- 'az_access_token_cmd',
224
- 'aws_secret_fetch_cmd',
225
- 'vault_read_cmd',
226
224
  ]);
227
225
  function evidence(value) {
228
226
  const compact = value.replace(/\s+/g, ' ').trim();
@@ -439,14 +437,24 @@ function isEnabled(itemId, options) {
439
437
  * the snapshot carries no explicit action for the item — an org override to
440
438
  * 'block' ships explicitly in the snapshot and wins. Keeps offline machines
441
439
  * and stale snapshots on the warn-first rollout instead of hard-blocking.
440
+ * The cloud token printers / secret fetchers are used constantly by
441
+ * legitimate deploy tooling and dev loops: recorded, never stopped, unless an
442
+ * org sets them to Ask / Block / Off (#1837).
442
443
  */
443
- const DEFAULT_WARN_BUILT_INS = new Set(['env_workspace']);
444
+ const DEFAULT_WARN_BUILT_INS = new Set([
445
+ 'env_workspace',
446
+ 'gcloud_access_token_cmd',
447
+ 'gcloud_secret_access_cmd',
448
+ 'az_access_token_cmd',
449
+ 'aws_secret_fetch_cmd',
450
+ 'vault_read_cmd',
451
+ ]);
444
452
  /**
445
453
  * Items that ASK by default when the snapshot carries no action for them — a
446
454
  * snapshot built before the item existed (older backend) must not turn a new
447
455
  * ask-first rule into a hard block. An explicit org 'block' still wins.
448
456
  */
449
- const DEFAULT_ASK_BUILT_INS = new Set(['agent_hooks_switched_off', 'agent_hook_config_removed', 'fcd_uninstalled_by_agent']);
457
+ const DEFAULT_ASK_BUILT_INS = new Set(['agent_hooks_switched_off', 'agent_hook_config_removed', 'fcd_uninstalled_by_agent', 'remote_control_bridge']);
450
458
  function actionFor(itemId, options) {
451
459
  const action = toLocalSafetyRuleAction(options?.itemActions?.[itemId]);
452
460
  if (action)
@@ -676,8 +684,8 @@ function envFileClass(token) {
676
684
  * useless against them because the secret never comes from a watched file
677
685
  * ("gh auth token" emits the same token that lives in hosts.yml). Obvious,
678
686
  * rarely-legitimate-for-agents forms are on by default; cloud token printers
679
- * that legitimate deploy tooling uses constantly are strict (off by default,
680
- * see DEFAULT_DISABLED_BUILT_INS). Ids match local-safety-catalog.ts.
687
+ * that legitimate deploy tooling uses constantly are strict (warn by default,
688
+ * see DEFAULT_WARN_BUILT_INS). Ids match local-safety-catalog.ts.
681
689
  */
682
690
  exports.CREDENTIAL_COMMAND_RULES = [
683
691
  { itemId: 'gh_auth_token_cmd', categoryId: 'credential_commands', severity: 'critical', commands: ['gh'],
@@ -726,13 +734,190 @@ function credentialCommandReason(value, options) {
726
734
  return undefined;
727
735
  });
728
736
  }
737
+ // ─────────────────────────────────────────────────────────────────────────────
738
+ // Remote-control AI bridges: tools that hand THIS machine's terminal / files /
739
+ // MCP tools to an AI running somewhere else (a remote MCP device, a local MCP
740
+ // server re-published on a network port). The catalog is the one place these
741
+ // are named; every surface — IDE hooks, the PowerShell / cmd / bash guards,
742
+ // MCP config discovery, the action-policy engine fact — matches through the
743
+ // patterns generated below. A package matches only in its REMOTE mode, chosen
744
+ // by the argument after the package (`desktop-commander remote`) or by the
745
+ // serving flag (`supergateway --stdio`); the same package in local stdio mode is
746
+ // an ordinary local MCP server.
747
+ //
748
+ // `remote_connector` entries (mcp-remote, supergateway --sse) connect a LOCAL
749
+ // agent to a remote server — they do not give an outside AI this machine, so
750
+ // they are labelled in the MCP inventory and never asked about.
751
+ // ─────────────────────────────────────────────────────────────────────────────
752
+ exports.REMOTE_CONTROL_CATALOG_VERSION = '2026-09-26.1';
753
+ // The first positional argument after the package (flags may precede it).
754
+ const RC_FIRST_POSITIONAL_REMOTE = String.raw `(?:\s+-{1,2}[a-z][\w-]*(?:=[^\s;&|]*)?)*\s+["']?remote["']?(?=[\s;&|)]|$)`;
755
+ const RC_SERVES_STDIO = String.raw `(?=[^;&|\n]*\s--stdio(?:[=\s]|$))`;
756
+ const RC_SERVES_PORT = String.raw `(?=[^;&|\n]*\s--(?:sse-)?(?:port|host)(?:[=\s]|$))`;
757
+ const RC_CONNECTS_URL = String.raw `(?=[^;&|\n]*\s["']?https?://)`;
758
+ exports.REMOTE_CONTROL_BRIDGES = [
759
+ {
760
+ id: 'desktop_commander_remote', title: 'Desktop Commander', kind: 'remote_control',
761
+ packages: ['@wonderwhy-er/desktop-commander'], bins: ['desktop-commander'],
762
+ mode: 'remote', modePattern: RC_FIRST_POSITIONAL_REMOTE,
763
+ label: 'Desktop Commander in remote mode',
764
+ card: "This starts Desktop Commander in remote mode, which lets an AI outside your company control this computer's terminal and files.",
765
+ },
766
+ {
767
+ id: 'supergateway_stdio_serve', title: 'Supergateway', kind: 'remote_control',
768
+ packages: ['supergateway'], bins: ['supergateway'],
769
+ mode: 'serve', modePattern: RC_SERVES_STDIO,
770
+ label: 'Supergateway publishing a local MCP server',
771
+ card: "This starts Supergateway, which publishes a local MCP server on a network port so an AI outside this computer can use its tools — often this computer's terminal and files.",
772
+ },
773
+ {
774
+ id: 'mcp_proxy_serve', title: 'mcp-proxy', kind: 'remote_control',
775
+ packages: ['mcp-proxy'], bins: ['mcp-proxy'],
776
+ mode: 'serve', modePattern: RC_SERVES_PORT,
777
+ label: 'mcp-proxy publishing a local MCP server',
778
+ card: "This starts mcp-proxy in server mode, which publishes a local MCP server on a network port so an AI outside this computer can use its tools — often this computer's terminal and files.",
779
+ },
780
+ {
781
+ id: 'mcp_remote_connector', title: 'mcp-remote', kind: 'remote_connector',
782
+ packages: ['mcp-remote'], bins: ['mcp-remote'],
783
+ mode: 'connect', modePattern: RC_CONNECTS_URL,
784
+ label: 'mcp-remote connecting to a remote MCP server',
785
+ card: 'This connects a local AI client to an MCP server on the internet. It does not give an outside AI control of this computer.',
786
+ },
787
+ {
788
+ id: 'supergateway_connector', title: 'Supergateway', kind: 'remote_connector',
789
+ packages: ['supergateway'], bins: ['supergateway'],
790
+ mode: 'connect', modePattern: String.raw `(?![^;&|\n]*\s--stdio(?:[=\s]|$))(?=[^;&|\n]*\s--(?:sse|streamablehttp)(?:[=\s]|$))`,
791
+ label: 'Supergateway connecting to a remote MCP server',
792
+ card: 'This connects a local AI client to an MCP server on the internet. It does not give an outside AI control of this computer.',
793
+ },
794
+ ];
795
+ function escapeRegexLiteral(value) {
796
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
797
+ }
798
+ const RC_EXT = String.raw `(?:\.cmd|\.exe|\.ps1)?`;
799
+ // Statement start, then transparent wrappers (`sudo`, `env X=1`, `cmd /c`, `bash -c "`, `pwsh -Command "`).
800
+ const RC_START = String.raw `(?:^|[;&|(\n])\s*`;
801
+ const RC_WRAPPERS = String.raw `(?:(?:(?:sudo|doas)(?:\s+-[a-z]+)*|env|nohup|time|exec|command|call|start|[a-z_][a-z0-9_]*=[^\s;&|]*|(?:ba|z|da|k)?sh\s+-l?c|cmd(?:\.exe)?\s+/[ck]|(?:powershell|pwsh)(?:\.exe)?(?:\s+-[a-z]+)*?\s+-c(?:ommand)?)\s+["']?)*`;
802
+ // No `(` in the path: `(` is itself a statement start above, and a path class that
803
+ // spans it re-scanned a whole `(((…` run from every `(` (quadratic, 8 KB ~0.2 s per rule).
804
+ const RC_PATH = String.raw `(?:[^\s;&|"'(]*[\\/])?`;
805
+ const RC_LAUNCHER = String.raw `(?:(?:npx|pnpx|bunx|uvx)${RC_EXT}|npm${RC_EXT}\s+(?:exec|x)|pnpm${RC_EXT}\s+(?:dlx|exec)|yarn${RC_EXT}\s+dlx|bun${RC_EXT}\s+x|uv${RC_EXT}\s+tool\s+run|pipx${RC_EXT}\s+run)`;
806
+ // Launcher options (`-y`, `--package=x`, `-p x`, `--from x`); a value never starts with `-`.
807
+ const RC_LAUNCHER_OPTIONS = String.raw `(?:\s+-{1,2}[a-z][\w-]*(?:=[^\s;&|]*)?(?:\s+[^\s;&|-][^\s;&|]*)?)*?`;
808
+ const RC_TOKEN_END = String.raw `(?=[\s;&|)]|$)`;
809
+ /** The positional pattern for one catalog entry: program at a statement start, package, then its mode. */
810
+ function remoteControlBridgePattern(bridge) {
811
+ const names = Array.from(new Set([...bridge.packages, ...bridge.bins]))
812
+ .sort((a, b) => b.length - a.length).map(escapeRegexLiteral).join('|');
813
+ const bins = bridge.bins.slice().sort((a, b) => b.length - a.length).map(escapeRegexLiteral).join('|');
814
+ const packageToken = String.raw `["']?(?:${names})(?:@[^\s"';&|)]*|==[^\s"';&|)]*|\[[^\]\s]*\])?["']?${RC_TOKEN_END}`;
815
+ const binToken = String.raw `(?:${bins})${RC_EXT}${RC_TOKEN_END}`;
816
+ return `${RC_START}${RC_WRAPPERS}${RC_PATH}(?:${RC_LAUNCHER}${RC_LAUNCHER_OPTIONS}(?:\\s+--)?\\s+${packageToken}|${binToken})${bridge.modePattern}`;
817
+ }
818
+ const REMOTE_CONTROL_BRIDGE_REGEXES = exports.REMOTE_CONTROL_BRIDGES.map(bridge => ({ bridge, re: new RegExp(remoteControlBridgePattern(bridge), 'i') }));
819
+ /** Shared command rules for the terminal guards: one per remote-control entry, same Local Safety item. */
820
+ exports.REMOTE_CONTROL_COMMAND_RULES = exports.REMOTE_CONTROL_BRIDGES
821
+ .filter(bridge => bridge.kind === 'remote_control')
822
+ .map(bridge => ({
823
+ itemId: 'remote_control_bridge',
824
+ categoryId: 'remote_control',
825
+ severity: 'critical',
826
+ reason: bridge.card,
827
+ pattern: remoteControlBridgePattern(bridge),
828
+ commands: ['npx', 'pnpx', 'bunx', 'uvx', 'pipx', 'npm', 'pnpm', 'yarn', 'bun', 'uv', ...bridge.bins],
829
+ }));
830
+ const RC_LAUNCHER_NAME = /(?:^|[\s\\/"'(;&|])(npx|pnpx|bunx|uvx|npm\s+(?:exec|x)|pnpm\s+(?:dlx|exec)|yarn\s+dlx|bun\s+x|uv\s+tool\s+run|pipx\s+run)(?=\s)/i;
831
+ function launcherOf(matched) {
832
+ const hit = RC_LAUNCHER_NAME.exec(matched.replace(/\.(?:cmd|exe|ps1)\b/gi, ''));
833
+ return hit ? hit[1].toLowerCase().replace(/\s+/g, ' ') : 'direct';
834
+ }
835
+ function matchRemoteBridge(text, kind) {
836
+ for (const { bridge, re } of REMOTE_CONTROL_BRIDGE_REGEXES) {
837
+ if (bridge.kind !== kind)
838
+ continue;
839
+ const hit = re.exec(text);
840
+ if (hit)
841
+ return { bridge, facts: { bridge: bridge.id, mode: bridge.mode, launcher: launcherOf(hit[0]) } };
842
+ }
843
+ return undefined;
844
+ }
845
+ /** A shell line that starts a remote-control bridge (any statement, any de-obfuscated variant). */
846
+ function remoteControlBridgeInCommand(command) {
847
+ if (!command || command.length > 32_000)
848
+ return undefined;
849
+ return matchCommand(stripInertDataSegments(command), text => matchRemoteBridge(text, 'remote_control'));
850
+ }
851
+ /**
852
+ * An MCP server launch (config `command` + `args`) that is a catalogued bridge:
853
+ * a remote-control bridge first, else a remote connector. Arguments with
854
+ * spaces are re-quoted so a `--stdio "npx server"` value stays one argument.
855
+ */
856
+ function classifyRemoteMcpLaunch(command, args = []) {
857
+ if (!command)
858
+ return undefined;
859
+ const line = [command, ...args].map(part => (/\s/.test(part) ? `"${part.replace(/"/g, '')}"` : part)).join(' ');
860
+ return matchRemoteBridge(line, 'remote_control') || matchRemoteBridge(line, 'remote_connector');
861
+ }
862
+ const RC_LAUNCHERS = new Set(['npx', 'pnpx', 'bunx', 'uvx', 'npm exec', 'npm x', 'pnpm dlx', 'pnpm exec', 'yarn dlx', 'bun x', 'uv tool run', 'pipx run', 'direct']);
863
+ /** Wire-supplied facts constrained to the catalog vocabulary (backend ingest); anything else is dropped. */
864
+ function sanitizeRemoteControlFacts(raw) {
865
+ if (!raw || typeof raw !== 'object')
866
+ return undefined;
867
+ const value = raw;
868
+ const bridge = exports.REMOTE_CONTROL_BRIDGES.find(entry => entry.id === value.bridge);
869
+ if (!bridge || value.mode !== bridge.mode || typeof value.launcher !== 'string' || !RC_LAUNCHERS.has(value.launcher))
870
+ return undefined;
871
+ return { bridge: bridge.id, mode: bridge.mode, launcher: value.launcher };
872
+ }
873
+ /** The engine fact provider: the catalog id of the remote-control bridge this line starts. */
874
+ function remoteControlFactFor(command) {
875
+ return remoteControlBridgeInCommand(command)?.bridge.id;
876
+ }
877
+ /** What an "Always allow" on a bridge is bound to: the package and its mode, never the launcher that ran it. */
878
+ function remoteControlGrantKey(bridge) {
879
+ return `${bridge.packages[0]} ${bridge.mode}`;
880
+ }
881
+ /**
882
+ * Every distinct remote-control bridge a line starts (as grant keys), plus the
883
+ * line with each verbatim launch cut out — statement separators kept — so the
884
+ * caller can still read the OTHER programs on the line. A launch seen only in a
885
+ * de-obfuscated variant is not cut: the rest is over-counted, never under-counted.
886
+ */
887
+ function remoteControlLaunches(command) {
888
+ if (!command || command.length > 32_000)
889
+ return { bridges: [], rest: command || '' };
890
+ const seen = new Set();
891
+ matchCommand(stripInertDataSegments(command), text => {
892
+ for (const { bridge, re } of REMOTE_CONTROL_BRIDGE_REGEXES) {
893
+ if (bridge.kind === 'remote_control' && !seen.has(bridge.id) && re.test(text))
894
+ seen.add(bridge.id);
895
+ }
896
+ return undefined;
897
+ });
898
+ const bridges = new Set();
899
+ let rest = command;
900
+ for (const { bridge, re } of REMOTE_CONTROL_BRIDGE_REGEXES) {
901
+ if (!seen.has(bridge.id))
902
+ continue;
903
+ bridges.add(remoteControlGrantKey(bridge));
904
+ rest = rest.replace(new RegExp(re.source, 'gi'), hit => `${/^[;&|(\n]/.test(hit) ? hit[0] : ''} `);
905
+ }
906
+ return { bridges: [...bridges].sort(), rest };
907
+ }
908
+ function canonicalRemoteLaunch(match) {
909
+ const direct = match.facts.launcher === 'direct';
910
+ const program = direct ? match.bridge.bins[0] : `${match.facts.launcher} ${match.bridge.packages[0]}`;
911
+ const mode = match.bridge.mode === 'remote' ? ' remote' : match.bridge.id === 'supergateway_stdio_serve' ? ' --stdio' : ' --port';
912
+ return `${program}${mode}`;
913
+ }
729
914
  // Container-scoped execution context immediately before an `rm` hit: a
730
915
  // docker/podman/nerdctl/kubectl exec|run (incl. `compose exec/run`) earlier in
731
916
  // the SAME statement (no ; & | between). Inside that context a bare `rm -rf *`
732
917
  // wipes the CONTAINER's workdir — routine build/image cleanup on a
733
918
  // docker-heavy fleet — not the developer's machine, so it must never warn or
734
919
  // stall. Root targets (`/`, `/*`) stay blocked even inside containers (the
735
- // Patria case: an agent nuking a running container's filesystem).
920
+ // Contoso case: an agent nuking a running container's filesystem).
736
921
  const CONTAINER_EXEC_BEFORE = /\b(?:docker|podman|nerdctl|kubectl)(?:\.exe)?\s+(?:compose\s+)?(?:exec|run)\b[^;&|]*$/i;
737
922
  let shellAstProvider;
738
923
  let shellAstMode = 'shadow';
@@ -765,10 +950,10 @@ const AST_TRANSPARENT_WRAPPERS = new Set(['sudo', 'doas', 'pkexec', 'run0', 'gos
765
950
  * of `bash -c` / `docker run … sh -c` are included; inside a container a bare
766
951
  * `*` is the container workdir (cleanup), the root `/` is still the root.
767
952
  */
768
- function astDestructiveRm(facts, inContainer = false) {
953
+ function astDestructiveRm(facts, inContainer = false, text = '') {
769
954
  for (const command of facts.commands) {
770
955
  if (command.wrapper?.inner) {
771
- const hit = astDestructiveRm(command.wrapper.inner, inContainer || command.wrapper.kind === 'container');
956
+ const hit = astDestructiveRm(command.wrapper.inner, inContainer || command.wrapper.kind === 'container', text);
772
957
  if (hit)
773
958
  return hit;
774
959
  }
@@ -832,7 +1017,8 @@ function astDestructiveRm(facts, inContainer = false) {
832
1017
  if (/^(?:\*|\.\/+\*)$/.test(t)) {
833
1018
  if (inContainer || command.cwdScope === 'scoped')
834
1019
  continue;
835
- return { itemId: 'rm_rf_root', reason: 'recursive force delete of the current directory tree (rm -rf *)' };
1020
+ // Wording from the `cd` before the removal, as on the regex path.
1021
+ return bareStarRemoval(text.slice(0, Math.max(0, text.toLowerCase().lastIndexOf('rm '))));
836
1022
  }
837
1023
  }
838
1024
  }
@@ -846,9 +1032,12 @@ const RM_SCOPE_ITEMS = new Set(['rm_rf_root', 'rm_rf_home']);
846
1032
  * a regex false positive or adding a structurally proven hit the regex missed —
847
1033
  * while every other destructive rule keeps its regex verdict.
848
1034
  */
849
- function destructiveCommandDecision(value) {
1035
+ function destructiveCommandDecision(value, commandContext) {
850
1036
  const regexHit = destructiveCommandReason(value);
851
- if (shellAstMode === 'off' || !shellAstProvider)
1037
+ // Text outside a command position (file content, a search query, a path) is
1038
+ // gated out of destructive findings by scanBuiltInRules, so a parse cannot
1039
+ // change its verdict; the bash grammar is super-linear on long non-shell text.
1040
+ if (shellAstMode === 'off' || !shellAstProvider || !commandContext)
852
1041
  return regexHit;
853
1042
  let facts;
854
1043
  try {
@@ -858,7 +1047,7 @@ function destructiveCommandDecision(value) {
858
1047
  facts = undefined;
859
1048
  }
860
1049
  const complete = shellAstFactsFullyComplete(facts);
861
- const astHit = complete && facts ? astDestructiveRm(facts) : undefined;
1050
+ const astHit = complete && facts ? astDestructiveRm(facts, false, value) : undefined;
862
1051
  const regexRm = regexHit && RM_SCOPE_ITEMS.has(regexHit.itemId) ? regexHit.itemId : undefined;
863
1052
  lastShellAstComparison = { mode: shellAstMode, complete, regex: regexRm, ast: astHit?.itemId, agree: !complete || regexRm === astHit?.itemId };
864
1053
  if (shellAstMode !== 'primary' || !complete)
@@ -879,6 +1068,34 @@ function destructiveCommandDecision(value) {
879
1068
  // Every `cd <target>` statement start (cwd persists across `&&`, `;`, `|`,
880
1069
  // newlines and `then`/`do`); the caller keeps the LAST one before the `rm`.
881
1070
  const CD_STATEMENT = /(?:^|[;&|\n(]|\bthen\b|\bdo\b)\s*cd\s+(?:--\s+)?("[^"]*"|'[^']*'|[^\s;&|)]+)/gi;
1071
+ /** The directory the LAST `cd` before this point changed into (dequoted, `/` separators); undefined when none applies. */
1072
+ function lastCdTarget(before) {
1073
+ let last = null;
1074
+ CD_STATEMENT.lastIndex = 0;
1075
+ for (let m = CD_STATEMENT.exec(before); m; m = CD_STATEMENT.exec(before))
1076
+ last = m;
1077
+ if (!last)
1078
+ return undefined;
1079
+ // A `)` after the cd closes a subshell: `(cd x && …); rm -rf *` runs the rm
1080
+ // back in the ORIGINAL directory, which the cd never changed.
1081
+ if (before.slice(last.index + last[0].length).includes(')'))
1082
+ return undefined;
1083
+ const target = last[1].replace(/^["']|["']$/g, '').trim().replace(/\\/g, '/');
1084
+ return target || undefined;
1085
+ }
1086
+ /**
1087
+ * The finding for a bare `rm -rf *` that is not scoped: it wipes the CURRENT
1088
+ * folder — the filesystem root or the home folder only when a `cd` said so.
1089
+ * Wording only; the item (and so the verdict) is `rm_rf_root` in every case.
1090
+ */
1091
+ function bareStarRemoval(before) {
1092
+ const target = (lastCdTarget(before) || '').toLowerCase();
1093
+ if (/^(?:\/+\*?|[a-z]:\/*\*?)$/.test(target))
1094
+ return { itemId: 'rm_rf_root', reason: 'recursive force delete of filesystem root' };
1095
+ if (/^(?:~\/*\*?|\$home\/?|\$\{home\}\/?|%userprofile%\/?|\$env:userprofile\/?)$/.test(target))
1096
+ return { itemId: 'rm_rf_root', reason: 'recursive force delete of the home directory' };
1097
+ return { itemId: 'rm_rf_root', reason: 'recursive force delete of everything in the current folder (rm -rf *)' };
1098
+ }
882
1099
  /**
883
1100
  * Bare `rm -rf *` wipes whatever the CURRENT directory is. When the same
884
1101
  * script has already `cd`'d into a scoped directory — a literal subpath such
@@ -890,17 +1107,7 @@ const CD_STATEMENT = /(?:^|[;&|\n(]|\bthen\b|\bdo\b)\s*cd\s+(?:--\s+)?("[^"]*"|'
890
1107
  * conservative reading: the agent's cwd is usually the project.
891
1108
  */
892
1109
  function cdScopedBeforeBareStar(before) {
893
- let last = null;
894
- CD_STATEMENT.lastIndex = 0;
895
- for (let m = CD_STATEMENT.exec(before); m; m = CD_STATEMENT.exec(before))
896
- last = m;
897
- if (!last)
898
- return false;
899
- // A `)` after the cd closes a subshell: `(cd x && …); rm -rf *` runs the rm
900
- // back in the ORIGINAL directory, which the cd never changed.
901
- if (before.slice(last.index + last[0].length).includes(')'))
902
- return false;
903
- const target = last[1].replace(/^["']|["']$/g, '').trim().replace(/\\/g, '/');
1110
+ const target = lastCdTarget(before);
904
1111
  if (!target)
905
1112
  return false;
906
1113
  const lower = target.toLowerCase();
@@ -994,9 +1201,8 @@ function destructiveCommandReason(value, opts = {}) {
994
1201
  const bareStars = /\b(?:sudo\s+)?rm\s+-(?=[a-z]*r)(?=[a-z]*f)[a-z]+\s+\*(?:\s|$|[;&|)])/g;
995
1202
  for (let bareStar = bareStars.exec(lower); bareStar; bareStar = bareStars.exec(lower)) {
996
1203
  const before = lower.slice(0, bareStar.index);
997
- if (!CONTAINER_EXEC_BEFORE.test(before) && !cdScopedBeforeBareStar(before)) {
998
- return { itemId: 'rm_rf_root', reason: 'recursive force delete of the current directory tree (rm -rf *)' };
999
- }
1204
+ if (!CONTAINER_EXEC_BEFORE.test(before) && !cdScopedBeforeBareStar(before))
1205
+ return bareStarRemoval(before);
1000
1206
  }
1001
1207
  }
1002
1208
  // Windows recursive quiet drive delete via del/erase/rd/rmdir. Flag order
@@ -1140,8 +1346,16 @@ function isCommandContext(toolName, candidate) {
1140
1346
  || COMMAND_KEYS.has(lastKey) || COMMAND_KEYS.has(candidate.keyPath);
1141
1347
  }
1142
1348
  function isSqlContext(toolName, candidate) {
1349
+ if (SQL_TOOL_HINT.test(toolName))
1350
+ return true;
1143
1351
  const lastKey = candidate.keyPath.split('.').pop() || '';
1144
- return SQL_TOOL_HINT.test(toolName) || SQL_KEYS.has(lastKey) || SQL_KEYS.has(candidate.keyPath);
1352
+ // A search / list tool's `query` is the text it looks for (`list_issues {
1353
+ // query: "… drop schema …" }`), not a statement it runs; `sql` still runs.
1354
+ const nameWords = toolName.toLowerCase().replace(/[_\-.]+/g, ' ');
1355
+ if (lastKey === 'query' && /\b(?:search|grep|find|lookup|locate|list)\b/.test(nameWords)
1356
+ && !/\b(?:delete|remove|drop|write|update|insert|replace|create)\b/.test(nameWords))
1357
+ return false;
1358
+ return SQL_KEYS.has(lastKey) || SQL_KEYS.has(candidate.keyPath);
1145
1359
  }
1146
1360
  function isWebLookupTarget(toolName, candidate) {
1147
1361
  return WEB_LOOKUP_TOOL_HINT.test(toolName) && candidate.keyPath.split('.').pop() === 'ref_id';
@@ -1173,12 +1387,32 @@ const METADATA_SEARCH_PROGRAMS = new Set([
1173
1387
  * Split on unquoted `;` / `&&` / `||` / `|` / newline so a pipe cannot hide a
1174
1388
  * later client (`rg … | curl http://169.254…`) while `rg "a|b"` stays one segment.
1175
1389
  */
1176
- function splitUnquotedCommandSegments(command) {
1390
+ /**
1391
+ * PowerShell escape: inside `"…"` a backtick makes the next character literal
1392
+ * (`` `" `` does not close the string); outside quotes `` `" `` / `` `' `` /
1393
+ * `` `$ `` and a trailing backtick (line continuation) are escapes, not a
1394
+ * POSIX command substitution.
1395
+ */
1396
+ function isPowerShellBacktickEscape(text, i, quote) {
1397
+ if (text[i] !== '`' || i + 1 >= text.length)
1398
+ return false;
1399
+ if (quote === '"')
1400
+ return true;
1401
+ return quote === null && /["'$\s]/.test(text[i + 1]);
1402
+ }
1403
+ /** Unquoted statements (`;`, newline, `&&`, `||`), each split into its single-`|` pipeline stages. */
1404
+ function splitUnquotedPipelines(command) {
1177
1405
  const out = [];
1406
+ let stages = [];
1178
1407
  let cur = '';
1179
1408
  let quote = null;
1409
+ const endStatement = () => { stages.push(cur); out.push(stages); stages = []; cur = ''; };
1180
1410
  for (let i = 0; i < command.length; i++) {
1181
1411
  const c = command[i];
1412
+ if (isPowerShellBacktickEscape(command, i, quote)) {
1413
+ cur += c + command[++i];
1414
+ continue;
1415
+ }
1182
1416
  if (quote) {
1183
1417
  cur += c;
1184
1418
  if (c === '\\' && i + 1 < command.length) {
@@ -1195,29 +1429,35 @@ function splitUnquotedCommandSegments(command) {
1195
1429
  continue;
1196
1430
  }
1197
1431
  if (c === '\n' || c === ';') {
1198
- out.push(cur);
1199
- cur = '';
1432
+ endStatement();
1200
1433
  continue;
1201
1434
  }
1202
1435
  if (c === '&' && command[i + 1] === '&') {
1203
- out.push(cur);
1204
- cur = '';
1436
+ endStatement();
1205
1437
  i += 1;
1206
1438
  continue;
1207
1439
  }
1208
1440
  if (c === '|') {
1209
- if (command[i + 1] === '|')
1441
+ if (command[i + 1] === '|') {
1442
+ endStatement();
1210
1443
  i += 1;
1211
- out.push(cur);
1444
+ continue;
1445
+ }
1446
+ stages.push(cur);
1212
1447
  cur = '';
1213
1448
  continue;
1214
1449
  }
1215
1450
  cur += c;
1216
1451
  }
1217
1452
  if (cur)
1218
- out.push(cur);
1453
+ stages.push(cur);
1454
+ if (stages.length)
1455
+ out.push(stages);
1219
1456
  return out;
1220
1457
  }
1458
+ function splitUnquotedCommandSegments(command) {
1459
+ return [].concat(...splitUnquotedPipelines(command));
1460
+ }
1221
1461
  /** True when every segment that mentions a metadata endpoint is a searcher, not a client. */
1222
1462
  function commandOnlySearchesMetadata(command) {
1223
1463
  if (!containsMetadataEndpoint(command))
@@ -1276,7 +1516,7 @@ function isSensitivePathContext(toolName, candidate) {
1276
1516
  // remote executor earlier in the same statement) are kept.
1277
1517
  // 5. Secret-literal rules and honeypot/custom rules never use this view —
1278
1518
  // a token pasted into a commit message still leaks.
1279
- const DATA_TO_INTERPRETER = /\b(?:iex|invoke-expression|invoke-command)\b|\beval\b|\bxargs\b|\bbase64\b[^\n]*(?:-d\b|--decode\b)|frombase64string|-encodedcommand\b|\s-enc\s|\|\s*&?\s*(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?|node|python[0-9.]*|perl|ruby)\b|\b(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?)\s+(?:-c|\/c|-e|-command|-scriptblock)\b|\b(?:ssh|wsl(?:\.exe)?|chroot)\b|\b(?:docker|kubectl|podman|nerdctl)(?:\.exe)?\s+(?:exec|run)\b/i;
1519
+ const DATA_TO_INTERPRETER = /\b(?:iex|invoke-expression|invoke-command)\b|\beval\b|\bxargs\b|\bbase64\b[^\n]*(?:-d\b|--decode\b)|frombase64string|-encodedcommand\b|\s-enc\s|(?<!\|)\|(?!\|)\s*&?\s*(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?|node|python[0-9.]*|perl|ruby)\b|\b(?:sh|bash|zsh|dash|ksh|csh|pwsh|powershell(?:\.exe)?|cmd(?:\.exe)?)\s+(?:-c|\/c|-e|-command|-scriptblock)\b|\b(?:ssh|wsl(?:\.exe)?|chroot)\b|\b(?:docker|kubectl|podman|nerdctl)(?:\.exe)?\s+(?:exec|run)\b/i;
1280
1520
  // A LANGUAGE interpreter's `-c` / `-e` argument is CODE in another language, not
1281
1521
  // a shell command line. `node -e "console.log('rm -rf /')"` prints a string;
1282
1522
  // `python -c "print('DROP TABLE')"` prints a string. That code only reaches the
@@ -1344,11 +1584,15 @@ function unquotedCode(text) {
1344
1584
  let out = '';
1345
1585
  for (let i = 0; i < text.length; i++) {
1346
1586
  const c = text[i];
1587
+ if (isPowerShellBacktickEscape(text, i, null)) {
1588
+ out += c + text[++i];
1589
+ continue;
1590
+ }
1347
1591
  if (c === "'" || c === '"' || c === '`') {
1348
1592
  const q = c;
1349
1593
  i += 1;
1350
1594
  while (i < text.length) {
1351
- if (text[i] === '\\') {
1595
+ if (text[i] === '\\' || (q === '"' && text[i] === '`')) {
1352
1596
  i += 2;
1353
1597
  continue;
1354
1598
  }
@@ -1363,20 +1607,93 @@ function unquotedCode(text) {
1363
1607
  }
1364
1608
  return out;
1365
1609
  }
1610
+ /**
1611
+ * `text.replace(/OPEN[\s\S]*?CLOSE/g, fn)` in one pass: the lazy regex re-scans
1612
+ * to the end from every OPEN once no CLOSE follows (quadratic on a long body of
1613
+ * unclosed `@'`); once no CLOSE remains, no later OPEN can match either.
1614
+ */
1615
+ function replaceDelimited(text, open, close, fn) {
1616
+ let out = '';
1617
+ let from = 0;
1618
+ for (;;) {
1619
+ const start = text.indexOf(open, from);
1620
+ if (start < 0)
1621
+ break;
1622
+ const end = text.indexOf(close, start + open.length);
1623
+ if (end < 0)
1624
+ break;
1625
+ out += text.slice(from, start) + fn(text.slice(start, end + close.length));
1626
+ from = end + close.length;
1627
+ }
1628
+ return out + text.slice(from);
1629
+ }
1630
+ const LINE_TERMINATOR = new Set(['\n', '\r', '\u2028', '\u2029']);
1631
+ /**
1632
+ * `src.replace(/"((?:[^"\\`]|\\.|`[\s\S])*)"|'((?:[^'\\]|\\.)*)'/g, fn)` in one
1633
+ * pass, same matches and callback arguments (a PowerShell backtick escapes any
1634
+ * character inside double quotes). After an unclosed quote the regex retried
1635
+ * every later quote of that kind; each one before the dead end is the tail of an
1636
+ * escape pair and walks the same path to the same dead end (quadratic on a body
1637
+ * of `\"`).
1638
+ */
1639
+ function replaceQuotedSpans(src, fn) {
1640
+ const deadUntil = { '"': -1, "'": -1 };
1641
+ let out = '';
1642
+ let from = 0;
1643
+ let i = 0;
1644
+ while (i < src.length) {
1645
+ const quote = src[i];
1646
+ if ((quote !== '"' && quote !== "'") || i < deadUntil[quote]) {
1647
+ i++;
1648
+ continue;
1649
+ }
1650
+ let j = i + 1;
1651
+ let closed = -1;
1652
+ while (j < src.length) {
1653
+ const c = src[j];
1654
+ if (c === quote) {
1655
+ closed = j;
1656
+ break;
1657
+ }
1658
+ if (c === '`' && quote === '"') {
1659
+ if (j + 1 >= src.length)
1660
+ break;
1661
+ j += 2;
1662
+ continue;
1663
+ }
1664
+ if (c === '\\') {
1665
+ if (j + 1 >= src.length || LINE_TERMINATOR.has(src[j + 1]))
1666
+ break;
1667
+ j += 2;
1668
+ continue;
1669
+ }
1670
+ j++;
1671
+ }
1672
+ if (closed < 0) {
1673
+ deadUntil[quote] = j;
1674
+ i++;
1675
+ continue;
1676
+ }
1677
+ const body = src.slice(i + 1, closed);
1678
+ out += src.slice(from, i) + fn(src.slice(i, closed + 1), quote === '"' ? body : undefined, quote === "'" ? body : undefined, i);
1679
+ from = i = closed + 1;
1680
+ }
1681
+ return out + src.slice(from);
1682
+ }
1366
1683
  function stripInertDataSegments(text) {
1367
1684
  if (DATA_TO_INTERPRETER.test(unquotedCode(text)))
1368
1685
  return text;
1369
1686
  let out = text;
1370
1687
  // PowerShell here-strings: @'…'@ is fully literal; @"…"@ interpolates $( ).
1371
- out = out.replace(/@'[\s\S]*?'@/g, INERT_DATA);
1372
- out = out.replace(/@"[\s\S]*?"@/g, m => (m.includes('$(') ? m : INERT_DATA));
1688
+ out = replaceDelimited(out, "@'", "'@", () => INERT_DATA);
1689
+ out = replaceDelimited(out, '@"', '"@', m => (m.includes('$(') ? m : INERT_DATA));
1373
1690
  // POSIX heredocs: quoted delimiter (<<'EOF') is literal; unquoted interpolates.
1374
1691
  out = out.replace(/<<-?\s*'(\w+)'[\s\S]*?(?:\n\1\b|$)/g, INERT_DATA);
1375
1692
  out = out.replace(/<<-?\s*"?(\w+)"?[\s\S]*?(?:\n\1\b|$)/g, m => (INTERPOLATES.test(m) ? m : INERT_DATA));
1376
1693
  // Generic quoted-span pass: whitespace inside quotes ⇒ free text ⇒ inert,
1377
1694
  // unless the span sits in a code position (invariants 2–4 above).
1378
1695
  const src = out;
1379
- out = src.replace(/"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'/g, (whole, dq, sq, offset) => {
1696
+ out = replaceQuotedSpans(src, (whole, dq, sq, offset) => {
1380
1697
  const body = dq !== undefined ? dq : (sq || '');
1381
1698
  if (!/\s/.test(body))
1382
1699
  return whole; // single token: argv, not prose
@@ -1671,7 +1988,14 @@ function scanTextValue(toolName, rawValue, options, commandContext = false) {
1671
1988
  if (finding)
1672
1989
  return finding;
1673
1990
  }
1674
- const destructive = destructiveCommandDecision(value);
1991
+ const remoteBridge = remoteControlBridgeInCommand(value);
1992
+ if (remoteBridge) {
1993
+ // Evidence is the canonical launch (launcher, package, mode) — never the argument text.
1994
+ const finding = builtIn('remote_control_bridge', 'remote_control', 'remote_control', 'local-remote-control-bridge', remoteBridge.bridge.card, canonicalRemoteLaunch(remoteBridge), remoteBridge.bridge.label, options);
1995
+ if (finding)
1996
+ return { ...finding, remoteControl: remoteBridge.facts };
1997
+ }
1998
+ const destructive = destructiveCommandDecision(value, commandContext);
1675
1999
  if (destructive) {
1676
2000
  return builtIn(destructive.itemId, 'destructive_filesystem', 'destructive_command', 'local-destructive-command', `Blocked ${destructive.reason}.`, value, destructive.reason, options);
1677
2001
  }
@@ -1716,7 +2040,7 @@ function mentionsAgentHookConfig(text) {
1716
2040
  return AGENT_HOOK_CONFIG_RE.test(normalizeForPath(text));
1717
2041
  }
1718
2042
  function segmentTokens(segment) {
1719
- return (segment.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || []).map(token => token.replace(/^["']|["']$/g, ''));
2043
+ return (segment.match(/(?:[^\s"']+|"(?:[^"`]|`[\s\S])*"|'[^']*')+/g) || []).map(token => token.replace(/^["']|["']$/g, ''));
1720
2044
  }
1721
2045
  function segmentProgram(tokens) {
1722
2046
  let i = 0;
@@ -1732,7 +2056,22 @@ function redirectTargets(segment) {
1732
2056
  out.push(match[2]);
1733
2057
  return out;
1734
2058
  }
1735
- function isFcdUninstall(program, rest, segment) {
2059
+ const MSI_PRODUCT_CODE_RE = /^\{?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}?/i;
2060
+ /** `msiexec /x <target>` whose target is a FullCourtDefense package path/name or the recorded FCD ProductCode. */
2061
+ function msiexecRemovesFcd(argText, productCodes) {
2062
+ const at = argText.match(/(?:^|[\s,'"])[/-](?:x|uninstall)(?=[\s,'"{]|$)/i);
2063
+ if (!at || at.index === undefined)
2064
+ return false;
2065
+ const target = argText.slice(at.index + at[0].length).replace(/^[\s,'"]+/, '').split(/[\s,'"]+[/-][a-z]/i)[0];
2066
+ if (/fullcourtdefense/i.test(target))
2067
+ return true;
2068
+ const guid = target.match(MSI_PRODUCT_CODE_RE);
2069
+ if (!guid)
2070
+ return false;
2071
+ const code = guid[1].toLowerCase();
2072
+ return productCodes.some(recorded => (recorded.match(MSI_PRODUCT_CODE_RE)?.[1] || '').toLowerCase() === code);
2073
+ }
2074
+ function isFcdUninstall(program, rest, productCodes = []) {
1736
2075
  let prog = program;
1737
2076
  let args = rest;
1738
2077
  if (prog === 'npx' || prog === 'pnpx' || prog === 'bunx') {
@@ -1746,16 +2085,105 @@ function isFcdUninstall(program, rest, segment) {
1746
2085
  return args.some(token => /^(?:uninstall|remove|rm|r|un|unlink)$/i.test(token))
1747
2086
  && args.some(token => /^fullcourtdefense-cli(?:@|$)/i.test(token));
1748
2087
  }
1749
- if (!/fullcourtdefense/i.test(segment))
1750
- return false;
1751
2088
  if (prog === 'msiexec')
1752
- return args.some(token => /^[/-](?:x|uninstall)$/i.test(token));
1753
- if (prog === 'schtasks')
1754
- return args.some(token => /^[/-](?:delete|disable)$/i.test(token));
1755
- if (prog === 'unregister-scheduledtask' || prog === 'disable-scheduledtask')
1756
- return true;
2089
+ return msiexecRemovesFcd(args.join(' '), productCodes);
2090
+ if (prog === 'start-process' || prog === 'saps' || prog === 'start') {
2091
+ const at = args.findIndex(token => /^(?:.*[\\/])?msiexec(?:\.exe)?$/i.test(token));
2092
+ return at >= 0 && msiexecRemovesFcd(args.slice(at + 1).join(' '), productCodes);
2093
+ }
2094
+ if (prog === 'schtasks') {
2095
+ if (!args.some(token => /^[/-](?:delete|disable)$/i.test(token)))
2096
+ return false;
2097
+ const at = args.findIndex(token => /^[/-]tn$/i.test(token));
2098
+ return at >= 0 && isFcdTaskName(args[at + 1] || '');
2099
+ }
2100
+ if (prog === 'unregister-scheduledtask' || prog === 'disable-scheduledtask') {
2101
+ return optionValues(args, /^-taskname$/i, /^-(?:taskpath|cimsession)$/i).some(isFcdTaskName);
2102
+ }
1757
2103
  if (prog === 'winget')
1758
- return /^(?:uninstall|remove)$/i.test(args[0] || '');
2104
+ return /^(?:uninstall|remove)$/i.test(args[0] || '') && args.slice(1).some(token => /fullcourtdefense/i.test(token));
2105
+ if (prog === 'taskkill') {
2106
+ const at = args.findIndex(token => /^[/-]im$/i.test(token));
2107
+ return at >= 0 && /^fullcourtdefense/i.test(args[at + 1] || '');
2108
+ }
2109
+ if (prog === 'stop-process' || prog === 'spps' || prog === 'kill' || prog === 'pkill' || prog === 'killall') {
2110
+ return optionValues(args, /^-(?:name|processname)$/i, /^-id$/i).some(name => /^fullcourtdefense/i.test(name));
2111
+ }
2112
+ if (INSTALL_ROOT_REMOVERS.has(prog)) {
2113
+ return args.filter(token => !/^-/.test(token) && !/^\/[a-z]{1,3}$/i.test(token)).some(isFcdInstallRoot);
2114
+ }
2115
+ return false;
2116
+ }
2117
+ /** Scheduled tasks the installer and CLI register. A name outside the product namespace is not ours. */
2118
+ const FCD_TASK_NAMES = [
2119
+ 'FullCourtDefense Updater', 'FullCourtDefense Daemon', 'FullCourtDefense Daemon Watchdog',
2120
+ 'FullCourtDefense Recovery', 'FullCourtDefense Auto-Protect', 'FullCourtDefenseDesktopDiscover',
2121
+ ];
2122
+ const INSTALL_ROOT_REMOVERS = new Set(['rm', 'rmdir', 'unlink', 'del', 'erase', 'rd', 'remove-item', 'ri', 'rimraf', 'mv', 'move', 'move-item', 'mi', 'ren', 'rename-item', 'rni']);
2123
+ /** A task name (or wildcard) that selects a FullCourtDefense task — by its product-namespace name, not a substring. */
2124
+ function isFcdTaskName(raw) {
2125
+ const name = raw.replace(/^["']|["']$/g, '').replace(/\\$/, '').replace(/^.*\\/, '').trim();
2126
+ if (!name)
2127
+ return false;
2128
+ if (!/[*?]/.test(name))
2129
+ return /^fullcourtdefense/i.test(name);
2130
+ const glob = new RegExp(`^${name.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`, 'i');
2131
+ return FCD_TASK_NAMES.some(task => glob.test(task));
2132
+ }
2133
+ /** The install root (`Program Files\FullCourtDefense`) or the machine state root (`ProgramData\FullCourtDefense`), or a path inside them. */
2134
+ function isFcdInstallRoot(raw) {
2135
+ const path = raw.replace(/^["']|["']$/g, '').replace(/\\/g, '/').toLowerCase();
2136
+ return /(?:^|\/|%|\$(?:env:|\{env:))(?:program ?files(?: ?\(x86\))?|programfiles\(x86\)|programdata|allusersprofile)[%}]?\/fullcourtdefense(?:\/|$)/.test(path);
2137
+ }
2138
+ /** Values of a named parameter plus positional operands (skipping the values of `skipNamed`). */
2139
+ function optionValues(args, named, skipNamed) {
2140
+ const out = [];
2141
+ for (let i = 0; i < args.length; i++) {
2142
+ const token = args[i];
2143
+ if (named.test(token)) {
2144
+ if (args[i + 1] !== undefined)
2145
+ out.push(...args[i + 1].split(','));
2146
+ i++;
2147
+ continue;
2148
+ }
2149
+ if (skipNamed.test(token)) {
2150
+ i++;
2151
+ continue;
2152
+ }
2153
+ if (/^-/.test(token))
2154
+ continue;
2155
+ out.push(...token.split(','));
2156
+ }
2157
+ return out;
2158
+ }
2159
+ const PROCESS_SOURCE_PROGRAMS = new Set(['get-process', 'gps', 'ps', 'get-ciminstance', 'gcim', 'get-wmiobject', 'gwmi', 'pgrep', 'get-package']);
2160
+ const PROCESS_STOP_PROGRAMS = new Set(['stop-process', 'spps', 'kill', 'uninstall-package']);
2161
+ const EACH_STOP_RE = /\b(?:stop-process|spps|taskkill|kill|uninstall-package)\b|\.(?:kill|terminate)\s*\(/i;
2162
+ /** A filter that EXCLUDES FullCourtDefense (`-notlike '*FullCourtDefense*'`, `grep -v fullcourtdefense`) selects other processes. */
2163
+ const NEGATED_FCD_FILTER_RE = /-(?:notlike|notmatch|ne|notcontains|notin)\s+['"]?[^\s'"}|]*fullcourtdefense[^\s'"}|]*['"]?|\b(?:grep|findstr)\s+(?:-[a-z]*\s+)*-[a-z]*[v][a-z]*\s+(?:-[a-z]+\s+)*['"]?[^\s'"|]*fullcourtdefense[^\s'"|]*['"]?|\/v\s+['"]?[^\s'"|]*fullcourtdefense[^\s'"|]*['"]?/gi;
2164
+ function stageSelectsFcd(stage) {
2165
+ return /fullcourtdefense/i.test(stage.replace(NEGATED_FCD_FILTER_RE, ' '));
2166
+ }
2167
+ /**
2168
+ * Pipeline view: a stop/uninstall stage fed by a process (or package) source
2169
+ * whose upstream stages select FullCourtDefense by name or path, e.g.
2170
+ * `Get-Process | Where-Object { $_.Path -like '*FullCourtDefense*' } | Stop-Process`.
2171
+ * The per-segment view sees a bare `Stop-Process` there.
2172
+ */
2173
+ function fcdPipelineStop(stages) {
2174
+ if (stages.length < 2)
2175
+ return false;
2176
+ const programs = stages.map(stage => segmentProgram(segmentTokens(stage.trim())));
2177
+ if (!PROCESS_SOURCE_PROGRAMS.has(programs[0].program))
2178
+ return false;
2179
+ for (let i = 1; i < stages.length; i++) {
2180
+ const { program, rest } = programs[i];
2181
+ const stops = PROCESS_STOP_PROGRAMS.has(program)
2182
+ || (program === 'invoke-cimmethod' && rest.some(token => /^(?:terminate|uninstall)$/i.test(token)))
2183
+ || ((program === 'foreach-object' || program === '%' || program === 'foreach' || program === 'xargs') && EACH_STOP_RE.test(stages[i]));
2184
+ if (stops && stages.slice(0, i).some(stageSelectsFcd))
2185
+ return true;
2186
+ }
1759
2187
  return false;
1760
2188
  }
1761
2189
  /**
@@ -1763,13 +2191,16 @@ function isFcdUninstall(program, rest, segment) {
1763
2191
  * (commit messages, issue bodies, echo text) is removed before redirections
1764
2192
  * and off-switch keys are judged, so writing ABOUT the setting never matches.
1765
2193
  */
1766
- function hookConfigShellChange(command) {
2194
+ function hookConfigShellChange(command, productCodes = []) {
2195
+ if (splitUnquotedPipelines(command).some(fcdPipelineStop)) {
2196
+ return { itemId: 'fcd_uninstalled_by_agent', reason: 'agent stopping FullCourtDefense processes' };
2197
+ }
1767
2198
  for (const rawSegment of splitUnquotedCommandSegments(command)) {
1768
2199
  const raw = rawSegment.trim();
1769
2200
  if (!raw)
1770
2201
  continue;
1771
2202
  const { program, rest } = segmentProgram(segmentTokens(raw));
1772
- if (isFcdUninstall(program, rest, raw)) {
2203
+ if (isFcdUninstall(program, rest, productCodes)) {
1773
2204
  return { itemId: 'fcd_uninstalled_by_agent', reason: 'agent removing FullCourtDefense from this machine' };
1774
2205
  }
1775
2206
  const stripped = stripInertDataSegments(raw);
@@ -1827,7 +2258,7 @@ function agentGuardTamperFinding(toolName, candidates, options) {
1827
2258
  for (const candidate of candidates) {
1828
2259
  if (!isCommandContext(toolName, candidate))
1829
2260
  continue;
1830
- const hit = hookConfigShellChange(candidate.value);
2261
+ const hit = hookConfigShellChange(candidate.value, options?.fcdProductCodes);
1831
2262
  const found = hit && finding(hit, candidate.value);
1832
2263
  if (found)
1833
2264
  return found;