ctxtop 0.0.0-stage → 4.1.0

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 (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,1523 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { canonicalizePath } from './paths.mjs';
6
+ import { loadHorizonConfig, filterFindingsByHorizonConfig } from './horizon_config.mjs';
7
+ import { inspectGitArgs } from '../shims/agy_git_guard.mjs';
8
+ import { detectShadowedFileBloat } from './telemetry/shadow_file_detector.mjs';
9
+ import { loadScopeLockRegistry, detectScopeCollision } from './telemetry/scope_lock_registry.mjs';
10
+ import { isProtectedPrefixFile, isWarmCacheState } from './prefix_cache_shield.mjs';
11
+
12
+ /**
13
+ * Phase 1: Real-Time Event Multiplexer (`HookStateMachine`) &
14
+ * 20 Canonical Deterministic Anti-Pattern Circuit Breakers (`DET-01` through `DET-20`).
15
+ *
16
+ * Executes 100% locally in Node.js with zero LLM API tokens and sub-10ms latency.
17
+ */
18
+
19
+ export const UNTRUSTED_SETTINGS_FILES = Object.freeze([
20
+ '.gemini/settings.json',
21
+ '.gemini/hooks.json',
22
+ '.agents/hooks.json',
23
+ 'hooks.json',
24
+ '.vscode/settings.json',
25
+ '.vscode/tasks.json',
26
+ '.mcp.json'
27
+ ]);
28
+
29
+ const PROTECTED_SETTINGS_OR_HOOKS_RE =
30
+ /(^|[\\/])(\.gemini[\\/](settings|hooks)\.json|\.agents[\\/]hooks\.json|hooks\.json|\.vscode[\\/](settings|tasks)\.json|\.mcp\.json)$/i;
31
+
32
+ export function isProtectedSettingsOrHooksFile(filePath = '') {
33
+ if (!filePath || typeof filePath !== 'string') return false;
34
+ return PROTECTED_SETTINGS_OR_HOOKS_RE.test(filePath.trim());
35
+ }
36
+
37
+ export function evaluateDet17ShadowFileBloat(steps = []) {
38
+ const shadowRes = detectShadowedFileBloat(steps);
39
+ return {
40
+ detectorId: 'DET-17',
41
+ triggered: Boolean(shadowRes.triggered && shadowRes.totalShadowWastedTokens > 0),
42
+ severity: 'WARN',
43
+ haltsGeneration: false,
44
+ ...shadowRes,
45
+ message: shadowRes.triggered
46
+ ? `⚠️ DET-17 Alert: Shadow file context bloat (${shadowRes.shadowedFileCount} shadowed file(s), ~${shadowRes.totalShadowWastedTokens} wasted tokens).`
47
+ : null
48
+ };
49
+ }
50
+
51
+ function inspectSettingsContentHazards(rawContent = '', relLabel = '') {
52
+ const text = String(rawContent || '');
53
+ const hazards = [];
54
+
55
+ if (
56
+ /\b(?:curl|wget)\b[^\n|]*\|\s*(?:ba|z)?sh\b/i.test(text) ||
57
+ /\b(?:Invoke-WebRequest|iwr|irm|Invoke-RestMethod)\b[^\n|]*\|\s*(?:iex|Invoke-Expression)\b/i.test(text) ||
58
+ /\b(?:powershell|pwsh)(?:\.exe)?\b[^\n]*\s-(?:e|enc|encodedcommand)\b/i.test(text) ||
59
+ /\bbase64\b[^\n|]*-d[^\n|]*\|\s*(?:ba|z)?sh\b/i.test(text) ||
60
+ /\beval\s+\$\(/i.test(text)
61
+ ) {
62
+ hazards.push('REMOTE_OR_ENCODED_SHELL_RCE');
63
+ }
64
+
65
+ if (
66
+ /"(?:autoApprove|yolo|dangerouslySkipPermissions|allowUnsandboxedCommands|bypassPermissions)"\s*:\s*true/i.test(text) ||
67
+ /"chat\.tools\.autoApprove"\s*:\s*true/i.test(text) ||
68
+ /"permissionMode"\s*:\s*"bypassPermissions"/i.test(text) ||
69
+ /"runOn"\s*:\s*"folderOpen"/i.test(text)
70
+ ) {
71
+ hazards.push('PERMISSION_OR_AUTO_APPROVE_BYPASS');
72
+ }
73
+
74
+ const isCanonicalPluginHooksFile =
75
+ /(?:^|[\\/])hooks\.json$/i.test(relLabel) &&
76
+ !/\.agents[\\/]hooks\.json|\.gemini[\\/]hooks\.json/i.test(relLabel);
77
+
78
+ if (
79
+ /(?:^|["'\s])(?:\.\/|\.\.\\|\$\{workspaceFolder\}\/|\$WORKSPACE\/|\.agents\/plugins\/)[^\s"']+/i.test(text)
80
+ ) {
81
+ const strippedOfficialHooks = isCanonicalPluginHooksFile
82
+ ? text.replace(/node\s+(?:--no-warnings\s+)?\.\/hooks\/(?:session_start|pre_invocation|post_invocation|pre_tool_use|post_tool_use|stop)\.mjs\b/g, () => 'TRUSTED_PLUGIN_HOOK')
83
+ : text;
84
+ if (/(?:^|["'\s])(?:\.\/|\.\.\\|\$\{workspaceFolder\}\/|\$WORKSPACE\/|\.agents\/plugins\/)[^\s"']+/i.test(strippedOfficialHooks)) {
85
+ hazards.push('WORKSPACE_RELATIVE_HOOK_RCE');
86
+ }
87
+ }
88
+
89
+ if (/(hooks\.json|\.mcp\.json)$/i.test(relLabel) && text.trim()) {
90
+ try {
91
+ const parsed = JSON.parse(text);
92
+ const commandStrings = [];
93
+ const collectCommands = (node) => {
94
+ if (!node || typeof node !== 'object') return;
95
+ if (Array.isArray(node)) {
96
+ for (const item of node) collectCommands(item);
97
+ return;
98
+ }
99
+ if (typeof node.command === 'string') {
100
+ commandStrings.push({ id: node.id || '', cmd: node.command });
101
+ }
102
+ for (const val of Object.values(node)) {
103
+ if (val && typeof val === 'object') collectCommands(val);
104
+ }
105
+ };
106
+ collectCommands(parsed);
107
+ for (const entry of commandStrings) {
108
+ const isTrustedPluginRootRelHook =
109
+ isCanonicalPluginHooksFile &&
110
+ /^node\s+(?:--no-warnings\s+)?\.\/hooks\/(?:session_start|pre_invocation|post_invocation|pre_tool_use|post_tool_use|stop)\.mjs$/.test(entry.cmd.trim());
111
+ const isTrustedHorizonPlugin =
112
+ entry.cmd.includes('.gemini/config/plugins/agy-horizon') &&
113
+ !entry.cmd.includes('./') &&
114
+ !/\b(curl|wget|Invoke-WebRequest|iex)\b/i.test(entry.cmd);
115
+ const isBenignDampener =
116
+ entry.id === 'horizon-cli-dampener' &&
117
+ entry.cmd.includes('[CLI Output Dampener]') &&
118
+ !entry.cmd.includes('child_process') &&
119
+ !/\b(curl|wget|Invoke-WebRequest|iex|spawn|exec)\b/i.test(entry.cmd);
120
+ if (!isTrustedPluginRootRelHook && !isTrustedHorizonPlugin && !isBenignDampener) {
121
+ hazards.push('UNTRUSTED_HOOK_OR_MCP_COMMAND');
122
+ break;
123
+ }
124
+ }
125
+ } catch {
126
+ hazards.push('MALFORMED_HOOKS_CONFIG');
127
+ }
128
+ }
129
+
130
+ return hazards;
131
+ }
132
+
133
+ export function evaluateDet18UntrustedWorkspaceSettings(paramsOrSteps = {}, context = {}) {
134
+ if (Array.isArray(paramsOrSteps)) {
135
+ const ctx = context && typeof context === 'object' ? context : {};
136
+ if (ctx.scanWorkspace) {
137
+ const scanRes = evaluateDet18UntrustedWorkspaceSettings({ ...ctx, scanWorkspace: true });
138
+ if (scanRes.blocked) return scanRes;
139
+ }
140
+ for (const step of paramsOrSteps) {
141
+ if (!step || typeof step !== 'object') continue;
142
+ const calls = Array.isArray(step.toolCalls)
143
+ ? step.toolCalls
144
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : [step]);
145
+ for (const call of calls) {
146
+ if (!call || typeof call !== 'object') continue;
147
+ const toolName = String(call.name || call.toolName || call.tool || step.toolName || '').trim();
148
+ const args = call.args || call.arguments || call.input || {};
149
+ const userAuth = Boolean(ctx.userAuthorizedSettingsEdit || step.userAuthorizedSettingsEdit);
150
+ const cmdStr = String(args.CommandLine || args.command || args.cmd || call.command || '').trim();
151
+ if (cmdStr) {
152
+ const execRes = evaluateDet18UntrustedWorkspaceSettings({
153
+ command: cmdStr,
154
+ userAuthorizedSettingsEdit: userAuth
155
+ });
156
+ if (execRes.blocked) return execRes;
157
+ }
158
+ const targetPath = String(
159
+ args.Path || args.path || args.TargetFile || args.AbsolutePath || call.targetPath || ''
160
+ ).trim();
161
+ if (targetPath && /write|edit|replace|create|patch/i.test(toolName || 'write_file')) {
162
+ const newContent = String(
163
+ args.Content ?? args.CodeContent ?? args.Replacement ?? args.ReplacementContent ?? args.newContent ?? ''
164
+ );
165
+ const writeRes = evaluateDet18UntrustedWorkspaceSettings({
166
+ targetPath,
167
+ newContent,
168
+ toolName,
169
+ userAuthorizedSettingsEdit: userAuth
170
+ });
171
+ if (writeRes.blocked) return writeRes;
172
+ }
173
+ }
174
+ }
175
+ return null;
176
+ }
177
+
178
+ const params = paramsOrSteps && typeof paramsOrSteps === 'object' ? paramsOrSteps : {};
179
+ const userAuthorized = Boolean(params.userAuthorizedSettingsEdit || params.userAuthorized);
180
+ if (userAuthorized) {
181
+ return {
182
+ id: 'DET-18',
183
+ detectorId: 'DET-18',
184
+ blocked: false,
185
+ triggered: false,
186
+ severity: 'CRITICAL',
187
+ haltsGeneration: false,
188
+ hazards: []
189
+ };
190
+ }
191
+
192
+ // Mode 1: Scan existing workspace config files on disk (used by PreInvocation / SessionStart checks)
193
+ if (params.scanWorkspace) {
194
+ const wsRoot = params.workspacePath || params.cwd || process.cwd();
195
+ for (const relFile of UNTRUSTED_SETTINGS_FILES) {
196
+ const fullPath = path.join(wsRoot, relFile);
197
+ if (!fs.existsSync(fullPath)) continue;
198
+ let raw = '';
199
+ try {
200
+ raw = fs.readFileSync(fullPath, 'utf8');
201
+ } catch {
202
+ continue;
203
+ }
204
+ const hazards = inspectSettingsContentHazards(raw, relFile);
205
+ if (hazards.length > 0) {
206
+ return {
207
+ id: 'DET-18',
208
+ detectorId: 'DET-18',
209
+ blocked: true,
210
+ triggered: true,
211
+ severity: 'CRITICAL',
212
+ haltsGeneration: true,
213
+ targetPath: fullPath,
214
+ hazards,
215
+ message: `🚨 DET-18 Blocked: Untrusted workspace settings/hook injection detected in ${relFile} (${hazards.join(', ')}).`
216
+ };
217
+ }
218
+ }
219
+ return {
220
+ id: 'DET-18',
221
+ detectorId: 'DET-18',
222
+ blocked: false,
223
+ triggered: false,
224
+ severity: 'CRITICAL',
225
+ haltsGeneration: false,
226
+ hazards: []
227
+ };
228
+ }
229
+
230
+ // Mode 2: Inspect shell command writing/redirecting to protected settings/hooks files
231
+ const cmdStr = String(params.command || params.cmdStr || '').trim();
232
+ if (cmdStr) {
233
+ const writesSettingsViaShell =
234
+ /(?:>|>>|\btee\b|\bSet-Content\b|\bAdd-Content\b|\bOut-File\b|\bcp\b|\bmv\b|\bCopy-Item\b|\bMove-Item\b).*?(?:\.gemini[\\/](?:settings|hooks)\.json|\.agents[\\/]hooks\.json|(?:^|[\s"'\\/])hooks\.json|\.vscode[\\/](?:settings|tasks)\.json|\.mcp\.json)/i.test(
235
+ cmdStr
236
+ );
237
+ if (writesSettingsViaShell) {
238
+ const cmdHazards = inspectSettingsContentHazards(cmdStr, 'hooks.json');
239
+ const hazards = cmdHazards.length > 0 ? cmdHazards : ['SHELL_SETTINGS_WRITE'];
240
+ return {
241
+ id: 'DET-18',
242
+ detectorId: 'DET-18',
243
+ blocked: true,
244
+ triggered: true,
245
+ severity: 'CRITICAL',
246
+ haltsGeneration: true,
247
+ command: cmdStr,
248
+ hazards,
249
+ message: `🚨 DET-18 Blocked: Unauthorized shell mutation of workspace settings/hooks config (${hazards.join(', ')}).`
250
+ };
251
+ }
252
+ }
253
+
254
+ // Mode 3: Direct write/edit tool targeting protected settings/hooks file
255
+ const targetPath = String(params.targetPath || params.filePath || '').trim();
256
+ if (!isProtectedSettingsOrHooksFile(targetPath)) {
257
+ return {
258
+ id: 'DET-18',
259
+ detectorId: 'DET-18',
260
+ blocked: false,
261
+ triggered: false,
262
+ severity: 'CRITICAL',
263
+ haltsGeneration: false,
264
+ hazards: []
265
+ };
266
+ }
267
+
268
+ const newContent = String(params.newContent ?? params.content ?? '');
269
+ const detectedHazards = inspectSettingsContentHazards(newContent, targetPath);
270
+ const hazards = detectedHazards.length > 0 ? detectedHazards : ['UNAUTHORIZED_WORKSPACE_SETTINGS_MUTATION'];
271
+ return {
272
+ id: 'DET-18',
273
+ detectorId: 'DET-18',
274
+ blocked: true,
275
+ triggered: true,
276
+ severity: 'CRITICAL',
277
+ haltsGeneration: true,
278
+ targetPath,
279
+ hazards,
280
+ message: `🚨 DET-18 Blocked: Unauthorized workspace settings/hook mutation targeting ${path.basename(targetPath)} (${hazards.join(', ')}).`
281
+ };
282
+ }
283
+
284
+ export function evaluateDet19GitHookBypass(cmdOrArgs, env = {}) {
285
+ if (Array.isArray(cmdOrArgs)) {
286
+ const isStepArray =
287
+ cmdOrArgs.length === 0 || (typeof cmdOrArgs[0] === 'object' && cmdOrArgs[0] !== null);
288
+ if (isStepArray) {
289
+ const baseEnv = env && typeof env === 'object' ? (env.env || env) : {};
290
+ for (const step of cmdOrArgs) {
291
+ if (!step || typeof step !== 'object') continue;
292
+ const calls = Array.isArray(step.toolCalls)
293
+ ? step.toolCalls
294
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : [step]);
295
+ for (const call of calls) {
296
+ if (!call || typeof call !== 'object') continue;
297
+ const args = call.args || call.arguments || call.input || {};
298
+ const cmdStr = String(
299
+ args.CommandLine || args.command || args.cmd || call.command || step.command || ''
300
+ ).trim();
301
+ if (!cmdStr) continue;
302
+ const res = evaluateDet19GitHookBypass(cmdStr, call.env || step.env || baseEnv);
303
+ if (res.blocked) return res;
304
+ }
305
+ }
306
+ return null;
307
+ }
308
+
309
+ const res = inspectGitArgs(cmdOrArgs, env);
310
+ return {
311
+ id: 'DET-19',
312
+ detectorId: 'DET-19',
313
+ blocked: Boolean(res.blocked),
314
+ triggered: Boolean(res.blocked),
315
+ severity: 'CRITICAL',
316
+ haltsGeneration: Boolean(res.blocked),
317
+ reason: res.reason || null,
318
+ subcommand: res.subcommand || null,
319
+ flags: res.flags || [],
320
+ message: res.blocked ? `🚨 DET-19 Blocked: ${res.reason}` : null
321
+ };
322
+ }
323
+
324
+ const cmdStr = String(cmdOrArgs || '').trim();
325
+ if (!cmdStr) {
326
+ return { id: 'DET-19', detectorId: 'DET-19', blocked: false, triggered: false, severity: 'CRITICAL', haltsGeneration: false };
327
+ }
328
+
329
+ const segments = tokenizeShellCommandSegments(cmdStr);
330
+ for (const rawTokens of segments) {
331
+ const segEnv = { ...(env && typeof env === 'object' ? env : {}) };
332
+ let idx = 0;
333
+ while (idx < rawTokens.length) {
334
+ const tok = rawTokens[idx];
335
+ if (!tok.quoted && tok.value === '&') {
336
+ idx++;
337
+ continue;
338
+ }
339
+ if (!tok.quoted && /^(sudo|env|command)$/i.test(tok.value)) {
340
+ idx++;
341
+ continue;
342
+ }
343
+ const envMatch = !tok.quoted && tok.value.match(/^(?:\$env:)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
344
+ if (envMatch) {
345
+ segEnv[envMatch[1]] = envMatch[2].replace(/^['"]|['"]$/g, '');
346
+ idx++;
347
+ continue;
348
+ }
349
+ break;
350
+ }
351
+ if (idx >= rawTokens.length) continue;
352
+ const exeBase = path.posix
353
+ .basename(rawTokens[idx].value.replace(/\\/g, '/'))
354
+ .toLowerCase()
355
+ .replace(/\.(exe|cmd|bat|ps1)$/i, '');
356
+ const argTokens = rawTokens.slice(idx + 1);
357
+
358
+ if (['bash', 'sh', 'zsh', 'cmd', 'powershell', 'pwsh'].includes(exeBase)) {
359
+ for (let j = 0; j < argTokens.length; j++) {
360
+ const flagLow = argTokens[j].value.toLowerCase();
361
+ if (!argTokens[j].quoted && (flagLow === '-c' || flagLow === '/c' || flagLow === '-command') && j + 1 < argTokens.length) {
362
+ const nested = evaluateDet19GitHookBypass(argTokens[j + 1].value, segEnv);
363
+ if (nested.blocked) return nested;
364
+ }
365
+ }
366
+ }
367
+
368
+ if (exeBase === 'git') {
369
+ const guardRes = inspectGitArgs(argTokens.map((t) => t.value), segEnv);
370
+ if (guardRes.blocked) {
371
+ return {
372
+ id: 'DET-19',
373
+ detectorId: 'DET-19',
374
+ blocked: true,
375
+ triggered: true,
376
+ severity: 'CRITICAL',
377
+ haltsGeneration: true,
378
+ reason: guardRes.reason,
379
+ subcommand: guardRes.subcommand,
380
+ flags: guardRes.flags,
381
+ message: `🚨 DET-19 Blocked: ${guardRes.reason}`
382
+ };
383
+ }
384
+ }
385
+ }
386
+
387
+ return { id: 'DET-19', detectorId: 'DET-19', blocked: false, triggered: false, severity: 'CRITICAL', haltsGeneration: false };
388
+ }
389
+
390
+ export function evaluateDet20ScopeCollision(paramsOrSteps = {}, context = {}) {
391
+ if (Array.isArray(paramsOrSteps)) {
392
+ const ctx = context && typeof context === 'object' ? context : {};
393
+ const stepPaths = [];
394
+ for (const step of paramsOrSteps) {
395
+ if (!step || typeof step !== 'object') continue;
396
+ const calls = Array.isArray(step.toolCalls)
397
+ ? step.toolCalls
398
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : []);
399
+ for (const call of calls) {
400
+ if (/write|edit|replace|create|patch/i.test(String(call?.name || call?.tool || ''))) {
401
+ const args = call?.args || call?.arguments || call?.input || {};
402
+ const p = args.Path || args.path || args.TargetFile || args.AbsolutePath;
403
+ if (p) stepPaths.push(p);
404
+ }
405
+ }
406
+ }
407
+ const mergedClaims = Array.isArray(ctx.claimedPaths)
408
+ ? [...ctx.claimedPaths, ...stepPaths]
409
+ : stepPaths;
410
+ const res = evaluateDet20ScopeCollision({
411
+ sessionId: ctx.sessionId || ctx.currentTrajectoryId || ctx.trajectoryId || 'active-session',
412
+ workspacePath: ctx.workspacePath || ctx.workspaceDir || ctx.cwd || '',
413
+ claimedPaths: mergedClaims,
414
+ leases: ctx.leases || ctx.activeLeases,
415
+ enforceBlock: ctx.enforceBlock !== undefined ? Boolean(ctx.enforceBlock) : true
416
+ });
417
+ return res.triggered ? res : null;
418
+ }
419
+
420
+ const params = paramsOrSteps && typeof paramsOrSteps === 'object' ? paramsOrSteps : {};
421
+ const sessionId = String(params.sessionId || params.currentTrajectoryId || params.trajectoryId || 'active-session');
422
+ const wsDir = params.workspacePath || params.workspaceDir || params.cwd || '';
423
+ const rawPaths = Array.isArray(params.claimedPaths)
424
+ ? params.claimedPaths
425
+ : (params.targetPath ? [params.targetPath] : []);
426
+ const normalizedClaimed = rawPaths
427
+ .filter(Boolean)
428
+ .map((p) => {
429
+ const s = String(p);
430
+ if (wsDir && path.isAbsolute(s)) {
431
+ return path.relative(wsDir, s).replace(/\\/g, '/');
432
+ }
433
+ return s.replace(/\\/g, '/');
434
+ });
435
+
436
+ const activeLeases = Array.isArray(params.leases)
437
+ ? params.leases
438
+ : (Array.isArray(params.activeLeases) ? params.activeLeases : (wsDir ? loadScopeLockRegistry(wsDir).leases : []));
439
+
440
+ const collision = detectScopeCollision(sessionId, normalizedClaimed, activeLeases);
441
+ if (!collision) {
442
+ return {
443
+ id: 'DET-20',
444
+ detectorId: 'DET-20',
445
+ blocked: false,
446
+ triggered: false,
447
+ severity: 'CRITICAL',
448
+ haltsGeneration: false
449
+ };
450
+ }
451
+
452
+ return {
453
+ id: 'DET-20',
454
+ detectorId: 'DET-20',
455
+ blocked: Boolean(params.enforceBlock),
456
+ triggered: true,
457
+ severity: 'CRITICAL',
458
+ haltsGeneration: Boolean(params.enforceBlock),
459
+ conflictingTrajectoryId: collision.trajectoryId,
460
+ conflictingPid: collision.pid,
461
+ overlappingPaths: collision.overlappingPaths,
462
+ source: collision.source || 'local',
463
+ message: `🚨 DET-20 Scope Collision: [${collision.overlappingPaths.join(', ')}] leased by "${collision.trajectoryId}".`
464
+ };
465
+ }
466
+
467
+ export const DETECTOR_CATALOG = Object.freeze({
468
+ 'DET-01': { id: 'DET-01', name: 'Retry Churn', severity: 'CRITICAL', haltsGeneration: true },
469
+ 'DET-02': { id: 'DET-02', name: 'Edit Oscillation', severity: 'CRITICAL', haltsGeneration: true },
470
+ 'DET-03': { id: 'DET-03', name: 'Test-Assertion Weakening', severity: 'CRITICAL', haltsGeneration: true },
471
+ 'DET-04': { id: 'DET-04', name: 'Synthetic Proof / Fake Screenshot Fabrication', severity: 'CRITICAL', haltsGeneration: true },
472
+ 'DET-05': { id: 'DET-05', name: 'Unverified [x] Task Completion', severity: 'HIGH', haltsGeneration: true },
473
+ 'DET-06': { id: 'DET-06', name: 'Redundant Full-File Re-Reads', severity: 'WARN', haltsGeneration: false },
474
+ 'DET-07': { id: 'DET-07', name: '<rrthought> Panic & Instruction-Loop Spiral', severity: 'CRITICAL', haltsGeneration: true },
475
+ 'DET-08': { id: 'DET-08', name: 'Unauthorized Brain / Git Destructive Command', severity: 'CRITICAL', haltsGeneration: true },
476
+ 'DET-09': { id: 'DET-09', name: 'Prefix-Busting Config Mutation', severity: 'HIGH', haltsGeneration: true },
477
+ 'DET-10': { id: 'DET-10', name: 'Unbounded CLI Output Flood', severity: 'WARN', haltsGeneration: false },
478
+ 'DET-11': { id: 'DET-11', name: 'Phantom File / Identifier Confabulation', severity: 'HIGH', haltsGeneration: false },
479
+ 'DET-12': { id: 'DET-12', name: 'Zombie Background Subprocess Leak', severity: 'HIGH', haltsGeneration: false },
480
+ 'DET-13': { id: 'DET-13', name: 'Premature Execution Without Plan Approval', severity: 'CRITICAL', haltsGeneration: true },
481
+ 'DET-14': { id: 'DET-14', name: 'Subagent File-Write Collision', severity: 'CRITICAL', haltsGeneration: true },
482
+ 'DET-15': { id: 'DET-15', name: 'Secret / Credential Leakage in Brain Artifacts', severity: 'CRITICAL', haltsGeneration: true },
483
+ 'DET-16': { id: 'DET-16', name: 'Silent Truncation / Placeholder Slop Injection', severity: 'CRITICAL', haltsGeneration: true },
484
+ 'DET-17': { id: 'DET-17', name: 'Shadow File Context Bloat', severity: 'WARN', haltsGeneration: false, evaluate: evaluateDet17ShadowFileBloat },
485
+ 'DET-18': { id: 'DET-18', name: 'Untrusted Workspace Settings & Hook Injection Guard', severity: 'CRITICAL', haltsGeneration: true, evaluate: evaluateDet18UntrustedWorkspaceSettings },
486
+ 'DET-19': { id: 'DET-19', name: 'Git Hook-Bypass Guard', severity: 'CRITICAL', haltsGeneration: true, evaluate: evaluateDet19GitHookBypass },
487
+ 'DET-20': { id: 'DET-20', name: 'Concurrent File-Scope Collision', severity: 'CRITICAL', haltsGeneration: false, evaluate: evaluateDet20ScopeCollision }
488
+ });
489
+
490
+ export function sha256Hex(content = '') {
491
+ return crypto.createHash('sha256').update(String(content), 'utf8').digest('hex');
492
+ }
493
+
494
+ function normalizeToolSignature(toolName = '', args = {}) {
495
+ const cleanName = String(toolName || '').toLowerCase().trim();
496
+ const sortedKeys = Object.keys(args || {}).sort();
497
+ const normObj = {};
498
+ for (const k of sortedKeys) {
499
+ const val = args[k];
500
+ normObj[k] = typeof val === 'string' ? val.trim().replace(/\s+/g, ' ') : val;
501
+ }
502
+ return `${cleanName}::${JSON.stringify(normObj)}`;
503
+ }
504
+
505
+ export function isTestFilePath(filePath = '') {
506
+ const s = String(filePath || '').replace(/\\/g, '/').toLowerCase();
507
+ return (
508
+ /\.(test|spec)\.[a-z0-9]+$/i.test(s) ||
509
+ /(^|\/)(test|tests|__tests__)\/.*\.(js|mjs|cjs|ts|tsx|py)$/i.test(s) ||
510
+ /_test\.py$/i.test(s) ||
511
+ /verify_.*\.(mjs|js|ts)$/i.test(s)
512
+ );
513
+ }
514
+
515
+ export function tokenizeShellCommandSegments(cmdStr = '') {
516
+ const input = String(cmdStr || '');
517
+ const segments = [];
518
+ let currentSegment = [];
519
+ let buf = '';
520
+ let tokenQuoted = false;
521
+ let hasChars = false;
522
+ let inSingle = false;
523
+ let inDouble = false;
524
+
525
+ const flushToken = () => {
526
+ if (hasChars) {
527
+ currentSegment.push({ value: buf, quoted: tokenQuoted });
528
+ buf = '';
529
+ tokenQuoted = false;
530
+ hasChars = false;
531
+ }
532
+ };
533
+
534
+ const flushSegment = () => {
535
+ flushToken();
536
+ if (currentSegment.length > 0) {
537
+ segments.push(currentSegment);
538
+ currentSegment = [];
539
+ }
540
+ };
541
+
542
+ for (let i = 0; i < input.length; i++) {
543
+ const ch = input[i];
544
+
545
+ if (inSingle) {
546
+ if (ch === "'") {
547
+ inSingle = false;
548
+ } else {
549
+ buf += ch;
550
+ }
551
+ continue;
552
+ }
553
+
554
+ if (inDouble) {
555
+ if (ch === '\\' && i + 1 < input.length && (input[i + 1] === '"' || input[i + 1] === '\\')) {
556
+ buf += input[i + 1];
557
+ i++;
558
+ } else if (ch === '`' && i + 1 < input.length && input[i + 1] === '"') {
559
+ buf += '"';
560
+ i++;
561
+ } else if (ch === '"') {
562
+ inDouble = false;
563
+ } else {
564
+ buf += ch;
565
+ }
566
+ continue;
567
+ }
568
+
569
+ if (ch === "'") {
570
+ inSingle = true;
571
+ tokenQuoted = true;
572
+ hasChars = true;
573
+ continue;
574
+ }
575
+
576
+ if (ch === '"') {
577
+ inDouble = true;
578
+ tokenQuoted = true;
579
+ hasChars = true;
580
+ continue;
581
+ }
582
+
583
+ if (ch === ' ' || ch === '\t') {
584
+ flushToken();
585
+ continue;
586
+ }
587
+
588
+ if (ch === ';' || ch === '\n' || ch === '\r') {
589
+ flushSegment();
590
+ continue;
591
+ }
592
+
593
+ if (ch === '&' && input[i + 1] === '&') {
594
+ flushSegment();
595
+ i++;
596
+ continue;
597
+ }
598
+
599
+ if (ch === '|') {
600
+ if (input[i + 1] === '|') i++;
601
+ flushSegment();
602
+ continue;
603
+ }
604
+
605
+ buf += ch;
606
+ hasChars = true;
607
+ }
608
+
609
+ flushSegment();
610
+ return segments;
611
+ }
612
+
613
+ export function isDestructiveOrBypassShellCommand(cmdStr = '', depth = 0, options = {}) {
614
+ if (!cmdStr || depth > 2) return false;
615
+ const userExplicitTestIntent = Boolean(options?.userExplicitTestIntent);
616
+ const segments = tokenizeShellCommandSegments(cmdStr);
617
+
618
+ for (const rawTokens of segments) {
619
+ const segEnv = {};
620
+ let idx = 0;
621
+
622
+ while (idx < rawTokens.length) {
623
+ const tok = rawTokens[idx];
624
+ if (!tok.quoted && tok.value === '&') {
625
+ idx++;
626
+ continue;
627
+ }
628
+ if (!tok.quoted && /^(sudo|env|command)$/i.test(tok.value)) {
629
+ idx++;
630
+ continue;
631
+ }
632
+ const envMatch = !tok.quoted && tok.value.match(/^(?:\$env:)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
633
+ if (envMatch) {
634
+ segEnv[envMatch[1]] = envMatch[2].replace(/^['"]|['"]$/g, '');
635
+ idx++;
636
+ continue;
637
+ }
638
+ break;
639
+ }
640
+
641
+ if (idx >= rawTokens.length) continue;
642
+
643
+ const exeRaw = rawTokens[idx].value.replace(/\\/g, '/');
644
+ const exeBase = path.posix
645
+ .basename(exeRaw)
646
+ .toLowerCase()
647
+ .replace(/\.(exe|cmd|bat|ps1)$/i, '');
648
+ const argTokens = rawTokens.slice(idx + 1);
649
+
650
+ if (['echo', 'printf', 'write-host', 'write-output'].includes(exeBase)) {
651
+ continue;
652
+ }
653
+
654
+ if (['bash', 'sh', 'zsh', 'cmd', 'powershell', 'pwsh'].includes(exeBase)) {
655
+ for (let j = 0; j < argTokens.length; j++) {
656
+ const flagLow = argTokens[j].value.toLowerCase();
657
+ if (!argTokens[j].quoted && (flagLow === '-c' || flagLow === '/c' || flagLow === '-command')) {
658
+ if (j + 1 < argTokens.length && isDestructiveOrBypassShellCommand(argTokens[j + 1].value, depth + 1)) {
659
+ return true;
660
+ }
661
+ }
662
+ }
663
+ }
664
+
665
+ if (exeBase === 'git') {
666
+ const gitArgs = argTokens.map(t => t.value);
667
+ const guardRes = inspectGitArgs(gitArgs, segEnv);
668
+ if (guardRes.blocked) {
669
+ return true;
670
+ }
671
+
672
+ // Inspect unquoted destructive git subcommand flags (`reset --hard`, `push --force`, `clean -fd`)
673
+ let subIdx = -1;
674
+ for (let j = 0; j < argTokens.length; j++) {
675
+ const val = argTokens[j].value;
676
+ if (val === '--') break;
677
+ if (val.startsWith('-')) {
678
+ if (['-c', '-C', '--git-dir', '--work-tree', '--namespace', '--config-env'].includes(val)) {
679
+ j++;
680
+ }
681
+ continue;
682
+ }
683
+ subIdx = j;
684
+ break;
685
+ }
686
+
687
+ if (subIdx !== -1) {
688
+ const sub = argTokens[subIdx].value.toLowerCase();
689
+ const subTokens = argTokens.slice(subIdx + 1);
690
+ if (sub === 'reset') {
691
+ if (subTokens.some(t => !t.quoted && t.value === '--hard')) return true;
692
+ } else if (sub === 'push') {
693
+ if (subTokens.some(t => !t.quoted && (t.value === '--force' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(t.value)))) {
694
+ return true;
695
+ }
696
+ } else if (sub === 'clean') {
697
+ if (subTokens.some(t => !t.quoted && (t.value === '--force' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(t.value)))) {
698
+ return true;
699
+ }
700
+ } else if (sub === 'checkout') {
701
+ const isBranchCreate = subTokens.some(t => !t.quoted && (t.value === '-b' || t.value === '-B' || t.value === '--orphan'));
702
+ if (!isBranchCreate) {
703
+ const isDiscard = subTokens.some(
704
+ t => !t.quoted && (t.value === '--' || t.value === '.' || t.value === '-f' || t.value === '--force')
705
+ );
706
+ if (isDiscard) return true;
707
+ }
708
+ } else if (sub === 'restore') {
709
+ const stagedOnly =
710
+ subTokens.some(t => !t.quoted && (t.value === '--staged' || t.value === '-S')) &&
711
+ !subTokens.some(t => !t.quoted && (t.value === '--worktree' || t.value === '-W'));
712
+ if (!stagedOnly && subTokens.some(t => t.value !== '--help' && t.value !== '-h')) {
713
+ return true;
714
+ }
715
+ } else if (sub === 'fsck' || sub === 'cat-file' || sub === 'reflog') {
716
+ return true;
717
+ } else if (
718
+ sub === 'log' &&
719
+ subTokens.some(t => !t.quoted && t.value === '--all') &&
720
+ subTokens.some(t => !t.quoted && (t.value === '-p' || t.value === '--patch'))
721
+ ) {
722
+ return true;
723
+ }
724
+ }
725
+ continue;
726
+ }
727
+
728
+ if (exeBase === 'rm' || exeBase === 'unlink') {
729
+ let hasRec = false;
730
+ let hasForce = false;
731
+ for (const t of argTokens) {
732
+ if (/\.gemini[\\/]antigravity[\\/]brain/i.test(t.value)) return true;
733
+ if (
734
+ !userExplicitTestIntent &&
735
+ !t.value.startsWith('-') &&
736
+ isTestFilePath(t.value) &&
737
+ !/^(?:\/tmp\/|\/var\/folders\/)/i.test(t.value) &&
738
+ !/(?:^|[\\/])(?:tmp|temp|\.claude[\\/]cache|\.agents[\\/]tmp)[\\/]/i.test(t.value) &&
739
+ !/appdata[\\/]local[\\/]temp[\\/]/i.test(t.value)
740
+ ) {
741
+ return true;
742
+ }
743
+ if (!t.quoted && t.value.startsWith('-')) {
744
+ if (t.value === '--recursive') hasRec = true;
745
+ else if (t.value === '--force') hasForce = true;
746
+ else if (/^-[a-zA-Z]+$/.test(t.value)) {
747
+ if (/[rR]/.test(t.value)) hasRec = true;
748
+ if (/f/.test(t.value)) hasForce = true;
749
+ }
750
+ }
751
+ }
752
+ if (hasRec && hasForce) return true;
753
+ continue;
754
+ }
755
+
756
+ if (['del', 'erase', 'remove-item', 'ri', 'rd', 'rmdir'].includes(exeBase)) {
757
+ let hasRec = false;
758
+ let hasForce = false;
759
+ for (const t of argTokens) {
760
+ if (/\.gemini[\\/]antigravity[\\/]brain/i.test(t.value)) return true;
761
+ if (
762
+ !userExplicitTestIntent &&
763
+ !t.value.startsWith('-') &&
764
+ !t.value.startsWith('/') &&
765
+ isTestFilePath(t.value) &&
766
+ !/(?:^|[\\/])(?:tmp|temp|\.claude[\\/]cache|\.agents[\\/]tmp)[\\/]/i.test(t.value) &&
767
+ !/appdata[\\/]local[\\/]temp[\\/]/i.test(t.value)
768
+ ) {
769
+ return true;
770
+ }
771
+ if (!t.quoted) {
772
+ if (/^-recurse$/i.test(t.value)) hasRec = true;
773
+ if (/^-force$/i.test(t.value)) hasForce = true;
774
+ }
775
+ }
776
+ if ((exeBase === 'remove-item' || exeBase === 'ri') && hasRec && hasForce) {
777
+ return true;
778
+ }
779
+ }
780
+ }
781
+
782
+ return false;
783
+ }
784
+
785
+ export function evaluateDet08DestructiveShell(stepsOrCmd = [], _context = {}) {
786
+ const shellOpts = {
787
+ userExplicitTestIntent: Boolean(
788
+ _context?.userExplicitTestIntent || _context?.userAuthorizedTestDeletion
789
+ )
790
+ };
791
+ if (typeof stepsOrCmd === 'string') {
792
+ const blocked = isDestructiveOrBypassShellCommand(stepsOrCmd, 0, shellOpts);
793
+ return {
794
+ id: 'DET-08',
795
+ detectorId: 'DET-08',
796
+ blocked,
797
+ triggered: blocked,
798
+ severity: 'CRITICAL',
799
+ haltsGeneration: blocked,
800
+ command: stepsOrCmd,
801
+ message: blocked
802
+ ? `🚨 DET-08 Blocked: Unauthorized destructive command intercepted ("${stepsOrCmd.slice(0, 80)}").`
803
+ : null
804
+ };
805
+ }
806
+
807
+ const list = Array.isArray(stepsOrCmd) ? stepsOrCmd : [];
808
+ for (const step of list) {
809
+ if (!step || typeof step !== 'object') continue;
810
+ const calls = Array.isArray(step.toolCalls)
811
+ ? step.toolCalls
812
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : [step]);
813
+ for (const call of calls) {
814
+ if (!call || typeof call !== 'object') continue;
815
+ const toolName = String(call.name || call.toolName || call.tool || step.toolName || '').toLowerCase().trim();
816
+ const args = call.args || call.arguments || call.input || {};
817
+ const cmdStr = String(args.CommandLine || args.command || args.cmd || call.command || step.command || '').trim();
818
+ const targetPath = String(args.Path || args.path || args.TargetFile || args.AbsolutePath || call.targetPath || '').trim();
819
+ if (cmdStr && isDestructiveOrBypassShellCommand(cmdStr, 0, shellOpts)) {
820
+ return {
821
+ id: 'DET-08',
822
+ detectorId: 'DET-08',
823
+ blocked: true,
824
+ triggered: true,
825
+ severity: 'CRITICAL',
826
+ haltsGeneration: true,
827
+ command: cmdStr,
828
+ message: `🚨 DET-08 Blocked: Unauthorized destructive command intercepted ("${cmdStr.slice(0, 80)}").`
829
+ };
830
+ }
831
+ if (/delete|remove/i.test(toolName) && /\.gemini[\\/]antigravity[\\/]brain/i.test(targetPath)) {
832
+ return {
833
+ id: 'DET-08',
834
+ detectorId: 'DET-08',
835
+ blocked: true,
836
+ triggered: true,
837
+ severity: 'CRITICAL',
838
+ haltsGeneration: true,
839
+ targetPath,
840
+ message: `🚨 DET-08 Blocked: Unauthorized brain artifact deletion targeting ${targetPath}.`
841
+ };
842
+ }
843
+ }
844
+ }
845
+ return null;
846
+ }
847
+
848
+ export function evaluateDet09MidSessionRuleMutate(steps = [], context = {}) {
849
+ const cachedTokens = Number(context.cachedTokens ?? context.session?.cachedTokens ?? 0);
850
+ const cacheTtlSeconds = Number(context.cacheTtlSeconds ?? context.session?.cacheTtlSeconds ?? 0);
851
+ const warm = isWarmCacheState({
852
+ cachedTokens,
853
+ cacheTtlSeconds,
854
+ cacheState: context.cacheState || context.session?.cacheState
855
+ });
856
+ if (!warm) return null;
857
+
858
+ const list = Array.isArray(steps) ? steps : [];
859
+ for (const step of list) {
860
+ if (!step || typeof step !== 'object') continue;
861
+ const calls = Array.isArray(step.toolCalls)
862
+ ? step.toolCalls
863
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : [step]);
864
+ for (const call of calls) {
865
+ if (!call || typeof call !== 'object') continue;
866
+ const toolName = String(call.name || call.toolName || call.tool || step.toolName || '').trim();
867
+ if (toolName && !/write|edit|replace|delete|remove|create|patch/i.test(toolName)) continue;
868
+ const args = call.args || call.arguments || call.input || {};
869
+ const targetPath = String(
870
+ args.Path || args.path || args.TargetFile || args.AbsolutePath || call.targetPath || ''
871
+ ).trim();
872
+ if (targetPath && isProtectedPrefixFile(targetPath)) {
873
+ return {
874
+ id: 'DET-09',
875
+ detectorId: 'DET-09',
876
+ blocked: true,
877
+ triggered: true,
878
+ severity: 'HIGH',
879
+ haltsGeneration: true,
880
+ targetPath,
881
+ message: `🚨 DET-09 Blocked: Mid-session mutation of ${path.basename(targetPath)} while prompt cache is warm (${cachedTokens} tok, TTL ${cacheTtlSeconds}s).`
882
+ };
883
+ }
884
+ }
885
+ }
886
+ return null;
887
+ }
888
+
889
+ function countAssertionsInCode(code = '') {
890
+ const text = String(code || '');
891
+ const assertMatches = text.match(/\b(assert(?:\.[a-zA-Z0-9_]+)?|expect|should)\s*\(/g) || [];
892
+ const pyAssertMatches = text.match(/^\s*assert\s+/gm) || [];
893
+ return assertMatches.length + pyAssertMatches.length;
894
+ }
895
+
896
+ function countSkipsInCode(code = '') {
897
+ const text = String(code || '');
898
+ const skips = text.match(/(\.(?:skip|todo)\s*\(|@pytest\.mark\.skip\b|\bxit\s*\(|\bxdescribe\s*\(|\bxtest\s*\()/g) || [];
899
+ return skips.length;
900
+ }
901
+
902
+ /**
903
+ * Evaluates a step or stream of steps across all 16 deterministic detectors (`DET-01` .. `DET-16`).
904
+ */
905
+ export function evaluateDetectorsOnSteps(steps = [], context = {}) {
906
+ const startHr = process.hrtime.bigint();
907
+ const list = Array.isArray(steps) ? steps : [];
908
+ const findings = [];
909
+
910
+ const cachedTokens = Number(context.cachedTokens ?? context.session?.cachedTokens ?? 0);
911
+ const cacheTtlSeconds = Number(context.cacheTtlSeconds ?? context.session?.cacheTtlSeconds ?? 0);
912
+ const approvalGateEnabled = context.approvalGateEnabled !== false;
913
+ const userAuthorizedTestDeletion = Boolean(context.userAuthorizedTestDeletion);
914
+ const workspacePath = context.workspacePath || '';
915
+ const existingFilesSet = context.existingFiles instanceof Set
916
+ ? new Set(Array.from(context.existingFiles).map(p => canonicalizePath(p)))
917
+ : null;
918
+ const concurrentSessionTargets = context.concurrentSessionTargets || {}; // sessionId -> Set/Array of paths
919
+ const currentSessionId = String(context.sessionId || 'active-session');
920
+
921
+ // State trackers across turns
922
+ let consecutiveRetrySig = '';
923
+ let consecutiveRetryCount = 0;
924
+
925
+ // DET-02: path -> Array<{ turnIndex, hash }>
926
+ const fileHashHistory = new Map();
927
+
928
+ // DET-04: track whether a recent screenshot was black / 0-byte / failed
929
+ let recentBlackScreenshotTurn = -100;
930
+
931
+ // DET-05: track most recent test runner exit code
932
+ let lastTestRunnerExitCode = 0;
933
+ let lastTestRunnerSeen = false;
934
+
935
+ // DET-06: path::range::hash -> Array<turnIndex>
936
+ const readHistory = new Map();
937
+
938
+ // DET-07: consecutive task_boundary errors
939
+ let consecutiveTaskBoundaryErrors = 0;
940
+
941
+ // DET-13: track PLANNING phase & whether user approved
942
+ let inPlanningPhase = false;
943
+ let userApprovedPlan = Boolean(context.userApprovedPlan);
944
+ const destructiveEditedFilesInPlan = new Set();
945
+
946
+ for (let idx = 0; idx < list.length; idx++) {
947
+ const step = list[idx] || {};
948
+ const stepType = String(step.type || '').toUpperCase();
949
+ const role = String(step.role || step.source || '').toLowerCase();
950
+ const content = String(step.content || '');
951
+ const thinking = String(step.thinking || step.rrthought || '');
952
+ const calls = Array.isArray(step.toolCalls)
953
+ ? step.toolCalls
954
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : []);
955
+
956
+ // Check if user turn authorized test deletion or approved plan
957
+ if (stepType === 'USER_INPUT' || role === 'user') {
958
+ if (/\b(approve|approved|proceed|lgtm|looks good|go ahead)\b/i.test(content)) {
959
+ userApprovedPlan = true;
960
+ inPlanningPhase = false;
961
+ }
962
+ }
963
+
964
+ // DET-07: <rrthought> Panic & Instruction-Loop Spiral
965
+ const thoughtBlob = `${thinking}\n${content}`;
966
+ const capsMatches = thoughtBlob.match(/\b(CRITICAL INSTRUCTIONS|MUST NOT FAIL|PANIC|DO NOT REPEAT THIS ERROR|IMPOSSIBLE STATE)\b/g) || [];
967
+ const circularMatches = thoughtBlob.match(/\b(wait, no, actually|no wait that's wrong|wait let me rethink from scratch)\b/gi) || [];
968
+ if (capsMatches.length >= 2 || circularMatches.length >= 3) {
969
+ findings.push({
970
+ detectorId: 'DET-07',
971
+ turnIndex: idx,
972
+ severity: 'CRITICAL',
973
+ haltsGeneration: true,
974
+ message: `🚨 DET-07 Blocked: <rrthought> panic or high-entropy instruction loop detected at turn #${idx}.`
975
+ });
976
+ }
977
+
978
+ // DET-15: Secret / Credential Leakage in Brain Artifacts or Transcript
979
+ const secretRe = /(\bsk-(?:proj-|live-|ant-(?:api\d+-)?)?[A-Za-z0-9_-]{20,}|\bghp_[A-Za-z0-9]{24,}|\bAIza[0-9A-Za-z_-]{30,}|\bAKIA[0-9A-Z]{16}\b|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\bBearer\s+[A-Za-z0-9._-]{28,})/;
980
+ if (secretRe.test(content)) {
981
+ findings.push({
982
+ detectorId: 'DET-15',
983
+ turnIndex: idx,
984
+ severity: 'CRITICAL',
985
+ haltsGeneration: true,
986
+ message: `🚨 DET-15 Blocked: Secret or credential token leakage detected in transcript/artifact at turn #${idx}.`
987
+ });
988
+ }
989
+
990
+ // Check screenshot status for DET-04
991
+ if (
992
+ step.blackScreenshot === true ||
993
+ step.screenshotByteLength === 0 ||
994
+ /black screenshot|zero-byte screenshot|blank_screenshot|0 bytes screenshot/i.test(content)
995
+ ) {
996
+ recentBlackScreenshotTurn = idx;
997
+ }
998
+
999
+ for (const call of calls) {
1000
+ const toolName = String(call.name || call.tool || '').toLowerCase();
1001
+ const args = call.args || call.arguments || call.parameters || call.Arguments || {};
1002
+ const targetPath = String(
1003
+ args.Path || args.path || args.TargetFile || args.AbsolutePath || step.targetPath || ''
1004
+ ).trim();
1005
+ const canonTarget = targetPath ? canonicalizePath(targetPath) : '';
1006
+ const cmdStr = String(args.CommandLine || args.command || args.cmd || '');
1007
+ const exitCode = call.exitCode ?? step.exitCode ?? (step.status === 'ERROR' ? 1 : 0);
1008
+ const stderrStr = String(call.stderr || step.stderr || (exitCode !== 0 ? content : ''));
1009
+ const stdoutStr = String(call.stdout || step.stdout || content || '');
1010
+
1011
+ // DET-01: Retry Churn (>=3 consecutive identical tool calls returning error)
1012
+ const sig = normalizeToolSignature(toolName, args);
1013
+ const isFailure = (typeof exitCode === 'number' && exitCode !== 0) || step.status === 'ERROR' || Boolean(call.error);
1014
+ if (isFailure) {
1015
+ if (sig === consecutiveRetrySig) {
1016
+ consecutiveRetryCount++;
1017
+ } else {
1018
+ consecutiveRetrySig = sig;
1019
+ consecutiveRetryCount = 1;
1020
+ }
1021
+ if (consecutiveRetryCount >= 3) {
1022
+ findings.push({
1023
+ detectorId: 'DET-01',
1024
+ turnIndex: idx,
1025
+ severity: 'CRITICAL',
1026
+ haltsGeneration: true,
1027
+ toolName,
1028
+ message: `🚨 DET-01 Blocked: Retry Churn (${consecutiveRetryCount} consecutive failed calls to ${toolName}).`
1029
+ });
1030
+ }
1031
+ } else {
1032
+ consecutiveRetrySig = '';
1033
+ consecutiveRetryCount = 0;
1034
+ }
1035
+
1036
+ // DET-07 (task_boundary consecutive errors)
1037
+ if (toolName === 'task_boundary' && isFailure) {
1038
+ consecutiveTaskBoundaryErrors++;
1039
+ if (consecutiveTaskBoundaryErrors >= 2) {
1040
+ findings.push({
1041
+ detectorId: 'DET-07',
1042
+ turnIndex: idx,
1043
+ severity: 'CRITICAL',
1044
+ haltsGeneration: true,
1045
+ message: `🚨 DET-07 Blocked: Consecutive task_boundary tool errors (${consecutiveTaskBoundaryErrors}).`
1046
+ });
1047
+ }
1048
+ } else if (toolName === 'task_boundary') {
1049
+ consecutiveTaskBoundaryErrors = 0;
1050
+ }
1051
+
1052
+ // Track test runner executions for DET-05
1053
+ const isExecTool = /^(run_command|execute_bash|bash|execute_command)$/.test(toolName);
1054
+ if (isExecTool && /\b(pytest|jest|vitest|cargo\s+test|npm\s+test|node\s+--test|go\s+test)\b/i.test(cmdStr)) {
1055
+ lastTestRunnerSeen = true;
1056
+ lastTestRunnerExitCode = typeof exitCode === 'number' ? exitCode : (isFailure ? 1 : 0);
1057
+ }
1058
+
1059
+ // DET-08: Unauthorized Brain / Git Destructive Command (shell-tokenized to avoid quoted string false positives)
1060
+ const isWriteOrDelete = /write|edit|replace|delete|remove/i.test(toolName);
1061
+ if (isExecTool) {
1062
+ if (isDestructiveOrBypassShellCommand(cmdStr)) {
1063
+ findings.push({
1064
+ detectorId: 'DET-08',
1065
+ turnIndex: idx,
1066
+ severity: 'CRITICAL',
1067
+ haltsGeneration: true,
1068
+ command: cmdStr,
1069
+ message: `🚨 DET-08 Blocked: Unauthorized destructive command intercepted ("${cmdStr.slice(0, 80)}").`
1070
+ });
1071
+ }
1072
+ const det19Exec = evaluateDet19GitHookBypass(cmdStr, call.env || step.env || {});
1073
+ if (det19Exec.blocked) {
1074
+ findings.push({
1075
+ detectorId: 'DET-19',
1076
+ turnIndex: idx,
1077
+ severity: 'CRITICAL',
1078
+ haltsGeneration: true,
1079
+ command: cmdStr,
1080
+ reason: det19Exec.reason,
1081
+ message: det19Exec.message
1082
+ });
1083
+ }
1084
+ const det18Exec = evaluateDet18UntrustedWorkspaceSettings({
1085
+ command: cmdStr,
1086
+ userAuthorizedSettingsEdit: Boolean(context.userAuthorizedSettingsEdit || step.userAuthorizedSettingsEdit)
1087
+ });
1088
+ if (det18Exec.blocked) {
1089
+ findings.push({
1090
+ detectorId: 'DET-18',
1091
+ turnIndex: idx,
1092
+ severity: 'CRITICAL',
1093
+ haltsGeneration: true,
1094
+ command: cmdStr,
1095
+ hazards: det18Exec.hazards,
1096
+ message: det18Exec.message
1097
+ });
1098
+ }
1099
+ }
1100
+ if (/delete|remove/i.test(toolName) && /\.gemini[\\/]antigravity[\\/]brain/i.test(targetPath)) {
1101
+ findings.push({
1102
+ detectorId: 'DET-08',
1103
+ turnIndex: idx,
1104
+ severity: 'CRITICAL',
1105
+ haltsGeneration: true,
1106
+ targetPath,
1107
+ message: `🚨 DET-08 Blocked: Unauthorized brain artifact deletion targeting ${targetPath}.`
1108
+ });
1109
+ }
1110
+
1111
+ // DET-10: Unbounded CLI Output Flood (>12,000 chars)
1112
+ if (isExecTool && (stdoutStr.length > 12000 || stderrStr.length > 12000)) {
1113
+ findings.push({
1114
+ detectorId: 'DET-10',
1115
+ turnIndex: idx,
1116
+ severity: 'WARN',
1117
+ haltsGeneration: false,
1118
+ charCount: Math.max(stdoutStr.length, stderrStr.length),
1119
+ message: `⚠️ DET-10 Alert: Unbounded CLI output flood (${Math.max(stdoutStr.length, stderrStr.length)} chars > 12,000 limit).`
1120
+ });
1121
+ }
1122
+
1123
+ // File read detectors (DET-06)
1124
+ const isReadTool = /^(read_file|view_file|read)$/.test(toolName);
1125
+ if (isReadTool && canonTarget) {
1126
+ const startLine = args.StartLine ?? args.start_line ?? 1;
1127
+ const endLine = args.EndLine ?? args.end_line ?? 'EOF';
1128
+ const fileHash = call.fileHash || step.fileHash || sha256Hex(stdoutStr || canonTarget);
1129
+ const readKey = `${canonTarget}::${startLine}-${endLine}::${fileHash}`;
1130
+ const prevReads = readHistory.get(readKey) || [];
1131
+ const recentReads = prevReads.filter(prevTurn => (idx - prevTurn) <= 15);
1132
+ recentReads.push(idx);
1133
+ readHistory.set(readKey, recentReads);
1134
+
1135
+ if (recentReads.length >= 2) {
1136
+ findings.push({
1137
+ detectorId: 'DET-06',
1138
+ turnIndex: idx,
1139
+ severity: 'WARN',
1140
+ haltsGeneration: false,
1141
+ targetPath,
1142
+ message: `⚠️ DET-06 Alert: Redundant unchanged file re-read on ${path.basename(targetPath)} (${recentReads.length}x within 15 turns).`
1143
+ });
1144
+ }
1145
+ }
1146
+
1147
+ // File write / edit detectors (DET-02, DET-03, DET-04, DET-05, DET-09, DET-11, DET-13, DET-14, DET-15, DET-16)
1148
+ if (isWriteOrDelete && targetPath) {
1149
+ const replacementChunks = Array.isArray(args.ReplacementChunks) ? args.ReplacementChunks : null;
1150
+ const chunksNew = replacementChunks
1151
+ ? replacementChunks.map(ch => String(ch?.ReplacementContent ?? ch?.Replacement ?? ch?.newContent ?? '')).filter(Boolean).join('\n')
1152
+ : undefined;
1153
+ const chunksOld = replacementChunks
1154
+ ? replacementChunks.map(ch => String(ch?.TargetContent ?? ch?.Target ?? ch?.oldContent ?? '')).filter(Boolean).join('\n')
1155
+ : undefined;
1156
+ const newContent = String(
1157
+ args.Content ?? args.CodeContent ?? args.Replacement ?? args.ReplacementContent ?? chunksNew ?? args.newContent ?? call.newContent ?? step.newContent ?? ''
1158
+ );
1159
+ const oldContent = String(
1160
+ args.Target ?? args.TargetContent ?? chunksOld ?? args.oldContent ?? call.oldContent ?? step.oldContent ?? ''
1161
+ );
1162
+
1163
+ // DET-18: Untrusted Workspace Settings & Hook Injection Guard
1164
+ const det18Write = evaluateDet18UntrustedWorkspaceSettings({
1165
+ targetPath,
1166
+ newContent,
1167
+ toolName,
1168
+ userAuthorizedSettingsEdit: Boolean(context.userAuthorizedSettingsEdit || step.userAuthorizedSettingsEdit)
1169
+ });
1170
+ if (det18Write.blocked) {
1171
+ findings.push({
1172
+ detectorId: 'DET-18',
1173
+ turnIndex: idx,
1174
+ severity: 'CRITICAL',
1175
+ haltsGeneration: true,
1176
+ targetPath,
1177
+ hazards: det18Write.hazards,
1178
+ message: det18Write.message
1179
+ });
1180
+ }
1181
+
1182
+ // DET-15 on written content
1183
+ if (/walkthrough\.md|transcript\.jsonl/i.test(targetPath) && secretRe.test(newContent)) {
1184
+ findings.push({
1185
+ detectorId: 'DET-15',
1186
+ turnIndex: idx,
1187
+ severity: 'CRITICAL',
1188
+ haltsGeneration: true,
1189
+ targetPath,
1190
+ message: `🚨 DET-15 Blocked: Secret/credential leakage in brain artifact ${path.basename(targetPath)}.`
1191
+ });
1192
+ }
1193
+
1194
+ // DET-02: Edit Oscillation (H1 -> H2 -> H1 within 6 turns)
1195
+ const nextHash = call.afterHash || step.afterHash || (newContent ? sha256Hex(newContent) : null);
1196
+ const prevHash = call.beforeHash || step.beforeHash || (oldContent ? sha256Hex(oldContent) : null);
1197
+ if (canonTarget && nextHash && !isFailure) {
1198
+ const hist = fileHashHistory.get(canonTarget) || [];
1199
+ if (hist.length === 0 && prevHash) {
1200
+ hist.push({ turnIndex: Math.max(0, idx - 1), hash: prevHash });
1201
+ }
1202
+ const oscillating = hist.some(
1203
+ h => h.hash === nextHash && (idx - h.turnIndex) <= 6 && hist[hist.length - 1]?.hash !== nextHash
1204
+ );
1205
+ hist.push({ turnIndex: idx, hash: nextHash });
1206
+ fileHashHistory.set(canonTarget, hist);
1207
+
1208
+ if (oscillating) {
1209
+ findings.push({
1210
+ detectorId: 'DET-02',
1211
+ turnIndex: idx,
1212
+ severity: 'CRITICAL',
1213
+ haltsGeneration: true,
1214
+ targetPath,
1215
+ message: `🚨 DET-02 Blocked: Edit oscillation (H1 -> H2 -> H1 SHA-256 revert within 6 turns) on ${path.basename(targetPath)}.`
1216
+ });
1217
+ }
1218
+ }
1219
+
1220
+ // DET-03: Test-Assertion Weakening
1221
+ if (isTestFilePath(targetPath) && !userAuthorizedTestDeletion && !step.userAuthorizedTestDeletion) {
1222
+ const beforeAssertions = countAssertionsInCode(oldContent);
1223
+ const afterAssertions = countAssertionsInCode(newContent);
1224
+ const beforeSkips = countSkipsInCode(oldContent);
1225
+ const afterSkips = countSkipsInCode(newContent);
1226
+
1227
+ const deletedAssertions = Math.max(0, beforeAssertions - afterAssertions);
1228
+ const addedSkips = Math.max(0, afterSkips - beforeSkips);
1229
+
1230
+ if (deletedAssertions > 0 || addedSkips > 0) {
1231
+ findings.push({
1232
+ detectorId: 'DET-03',
1233
+ turnIndex: idx,
1234
+ severity: 'CRITICAL',
1235
+ haltsGeneration: true,
1236
+ targetPath,
1237
+ deletedAssertions,
1238
+ addedSkips,
1239
+ message: `🚨 DET-03 Blocked: Agent attempted to delete ${deletedAssertions} expect()/assert() assertion(s) or add ${addedSkips} skip(s) in ${path.basename(targetPath)}`
1240
+ });
1241
+ }
1242
+ }
1243
+
1244
+ // DET-04: Synthetic Proof / Fake Screenshot Fabrication
1245
+ const isBrainOrScratchScript =
1246
+ /(\.gemini[\\/]antigravity[\\/]brain|scratch)[\\/].*\.(py|js|mjs)$/i.test(targetPath);
1247
+ const importsVisionFabricator =
1248
+ /\b(PIL|ImageDraw|matplotlib|cv2|createCanvas)\b/.test(newContent);
1249
+ if (isBrainOrScratchScript && importsVisionFabricator && (idx - recentBlackScreenshotTurn) <= 4) {
1250
+ findings.push({
1251
+ detectorId: 'DET-04',
1252
+ turnIndex: idx,
1253
+ severity: 'CRITICAL',
1254
+ haltsGeneration: true,
1255
+ targetPath,
1256
+ message: `🚨 DET-04 Blocked: Synthetic proof / fake screenshot generator script detected in ${path.basename(targetPath)} following black screenshot.`
1257
+ });
1258
+ }
1259
+
1260
+ // DET-05: Unverified [x] Task Completion
1261
+ if (/task\.md$/i.test(targetPath) && /[-*]\s*\[x\]/i.test(newContent) && lastTestRunnerSeen && lastTestRunnerExitCode !== 0) {
1262
+ findings.push({
1263
+ detectorId: 'DET-05',
1264
+ turnIndex: idx,
1265
+ severity: 'HIGH',
1266
+ haltsGeneration: true,
1267
+ targetPath,
1268
+ message: `🚨 DET-05 Blocked: Agent marked task.md item [x] while most recent test run exited with code ${lastTestRunnerExitCode}.`
1269
+ });
1270
+ }
1271
+ if (/walkthrough\.md$/i.test(targetPath) && /\b(all tests pass|tests passed|0 errors)\b/i.test(newContent) && lastTestRunnerSeen && lastTestRunnerExitCode !== 0) {
1272
+ findings.push({
1273
+ detectorId: 'DET-05',
1274
+ turnIndex: idx,
1275
+ severity: 'HIGH',
1276
+ haltsGeneration: true,
1277
+ targetPath,
1278
+ message: `🚨 DET-05 Blocked: Agent claimed passing tests in walkthrough.md while most recent test run exited with code ${lastTestRunnerExitCode}.`
1279
+ });
1280
+ }
1281
+
1282
+ // DET-09: Prefix-Busting Config Mutation (aligned Antigravity rule globs; excludes CLAUDE.md / .claude/)
1283
+ const warmForDet09 = isWarmCacheState({
1284
+ cachedTokens,
1285
+ cacheTtlSeconds,
1286
+ cacheState: context.cacheState || context.session?.cacheState
1287
+ });
1288
+ if (isProtectedPrefixFile(targetPath) && warmForDet09) {
1289
+ findings.push({
1290
+ detectorId: 'DET-09',
1291
+ turnIndex: idx,
1292
+ severity: 'HIGH',
1293
+ haltsGeneration: true,
1294
+ targetPath,
1295
+ message: `🚨 DET-09 Blocked: Mid-session mutation of ${path.basename(targetPath)} while prompt cache is warm (${cachedTokens} tok, TTL ${cacheTtlSeconds}s).`
1296
+ });
1297
+ }
1298
+
1299
+ // DET-11: Phantom File / Identifier Confabulation in implementation_plan.md or walkthrough.md
1300
+ if (/(implementation_plan|walkthrough)\.md$/i.test(targetPath) && (existingFilesSet || workspacePath)) {
1301
+ const lines = newContent.split(/\r?\n/);
1302
+ for (const line of lines) {
1303
+ if (/\[NEW\]/i.test(line)) continue;
1304
+ const pathMatches = line.match(/\b(?:src|lib|app|sidecars|scripts|tests)\/[A-Za-z0-9_./-]+\.(?:mjs|js|ts|tsx|py|json|html)\b/g) || [];
1305
+ for (const refRel of pathMatches) {
1306
+ const absCandidate = workspacePath ? path.resolve(workspacePath, refRel) : refRel;
1307
+ const canonCandidate = canonicalizePath(absCandidate);
1308
+ const existsInSet = existingFilesSet
1309
+ ? (existingFilesSet.has(canonCandidate) || existingFilesSet.has(canonicalizePath(refRel)))
1310
+ : (workspacePath ? fs.existsSync(absCandidate) : true);
1311
+ if (!existsInSet) {
1312
+ findings.push({
1313
+ detectorId: 'DET-11',
1314
+ turnIndex: idx,
1315
+ severity: 'HIGH',
1316
+ haltsGeneration: false,
1317
+ phantomPath: refRel,
1318
+ message: `⚠️ DET-11 Alert: Phantom file path "${refRel}" referenced in ${path.basename(targetPath)} does not exist in workspace.`
1319
+ });
1320
+ }
1321
+ }
1322
+ }
1323
+ }
1324
+
1325
+ // DET-13: Premature Execution Without Plan Approval
1326
+ if (/implementation_plan\.md$/i.test(targetPath)) {
1327
+ inPlanningPhase = true;
1328
+ } else if (
1329
+ inPlanningPhase &&
1330
+ approvalGateEnabled &&
1331
+ !userApprovedPlan &&
1332
+ !/(\.gemini[\\/]antigravity[\\/]brain|task\.md|implementation_plan\.md)/i.test(targetPath)
1333
+ ) {
1334
+ destructiveEditedFilesInPlan.add(canonTarget);
1335
+ if (destructiveEditedFilesInPlan.size >= 2) {
1336
+ findings.push({
1337
+ detectorId: 'DET-13',
1338
+ turnIndex: idx,
1339
+ severity: 'CRITICAL',
1340
+ haltsGeneration: true,
1341
+ targetPath,
1342
+ message: `🚨 DET-13 Blocked: Premature multi-file execution (${destructiveEditedFilesInPlan.size} files) without user approval after implementation_plan.md creation.`
1343
+ });
1344
+ }
1345
+ }
1346
+
1347
+ // DET-14: Subagent File-Write Collision
1348
+ if (canonTarget && concurrentSessionTargets && typeof concurrentSessionTargets === 'object') {
1349
+ for (const [otherSid, targets] of Object.entries(concurrentSessionTargets)) {
1350
+ if (otherSid === currentSessionId) continue;
1351
+ const targetList = Array.isArray(targets) ? targets : Array.from(targets || []);
1352
+ if (targetList.some(t => canonicalizePath(t) === canonTarget)) {
1353
+ findings.push({
1354
+ detectorId: 'DET-14',
1355
+ turnIndex: idx,
1356
+ severity: 'CRITICAL',
1357
+ haltsGeneration: true,
1358
+ targetPath,
1359
+ conflictingSessionId: otherSid,
1360
+ message: `🚨 DET-14 Blocked: Subagent file-write collision on ${path.basename(targetPath)} with concurrent session ${otherSid}.`
1361
+ });
1362
+ }
1363
+ }
1364
+ }
1365
+
1366
+ // DET-16: Silent Truncation / Placeholder Slop Injection
1367
+ const slopRe = /(\/\/\s*TODO:\s*implement\s+rest|\/\/\s*\.\.\.\s*existing\s+code\s*\.\.\.|#\s*\.\.\.\s*existing\s+code\s*\.\.\.|\/\*\s*\.\.\.\s*rest\s+of\s+code\s*\.\.\.\s*\*\/)/i;
1368
+ const oldLines = oldContent ? oldContent.split(/\r?\n/).length : 0;
1369
+ const newLines = newContent ? newContent.split(/\r?\n/).length : 0;
1370
+ const suddenLineDrop = oldLines >= 20 && newLines > 0 && ((oldLines - newLines) / oldLines) > 0.40;
1371
+ if (slopRe.test(newContent) || suddenLineDrop) {
1372
+ findings.push({
1373
+ detectorId: 'DET-16',
1374
+ turnIndex: idx,
1375
+ severity: 'CRITICAL',
1376
+ haltsGeneration: true,
1377
+ targetPath,
1378
+ message: `🚨 DET-16 Blocked: Silent truncation or placeholder slop injection detected in ${path.basename(targetPath)}.`
1379
+ });
1380
+ }
1381
+ }
1382
+ }
1383
+
1384
+ // DET-12: Zombie Background Subprocess Leak on turn completion
1385
+ const orphans = Array.isArray(step.orphanedProcesses)
1386
+ ? step.orphanedProcesses
1387
+ : (idx === list.length - 1 && Array.isArray(context.orphanedProcesses) ? context.orphanedProcesses : []);
1388
+ for (const proc of orphans) {
1389
+ const pName = String(proc.name || '').toLowerCase();
1390
+ if (/(python|python3|node|cargo|pytest)/.test(pName) && (proc.cpuPct === 0 || proc.orphaned === true || proc.parentAlive === false)) {
1391
+ findings.push({
1392
+ detectorId: 'DET-12',
1393
+ turnIndex: idx,
1394
+ severity: 'HIGH',
1395
+ haltsGeneration: false,
1396
+ pid: proc.pid,
1397
+ processName: proc.name,
1398
+ message: `⚠️ DET-12 Alert: Zombie background subprocess leak (${proc.name} PID ${proc.pid}, 0% CPU / orphaned).`
1399
+ });
1400
+ }
1401
+ }
1402
+ }
1403
+
1404
+ // DET-17: Shadow File Context Bloat across transcript steps
1405
+ if (list.length > 0) {
1406
+ const det17Res = evaluateDet17ShadowFileBloat(list);
1407
+ if (det17Res.triggered) {
1408
+ findings.push({
1409
+ detectorId: 'DET-17',
1410
+ turnIndex: list.length - 1,
1411
+ severity: 'WARN',
1412
+ haltsGeneration: false,
1413
+ shadowedFileCount: det17Res.shadowedFileCount,
1414
+ totalShadowWastedTokens: det17Res.totalShadowWastedTokens,
1415
+ message: det17Res.message
1416
+ });
1417
+ }
1418
+ }
1419
+
1420
+ // DET-20: Concurrent Multi-Agent Scope Lock Collision
1421
+ if (Array.isArray(context.scopeLeases) || context.checkScopeLocks === true) {
1422
+ const editedStepPaths = [];
1423
+ for (const s of list) {
1424
+ const cList = Array.isArray(s?.toolCalls) ? s.toolCalls : (Array.isArray(s?.tool_calls) ? s.tool_calls : []);
1425
+ for (const c of cList) {
1426
+ if (/write|edit|replace|create|patch/i.test(String(c?.name || c?.tool || ''))) {
1427
+ const p = c?.args?.Path || c?.args?.path || c?.args?.TargetFile || c?.args?.AbsolutePath;
1428
+ if (p) editedStepPaths.push(p);
1429
+ }
1430
+ }
1431
+ }
1432
+ const claimedForDet20 = Array.isArray(context.claimedPaths)
1433
+ ? [...context.claimedPaths, ...editedStepPaths]
1434
+ : editedStepPaths;
1435
+ if (claimedForDet20.length > 0) {
1436
+ const det20Res = evaluateDet20ScopeCollision({
1437
+ sessionId: currentSessionId,
1438
+ claimedPaths: claimedForDet20,
1439
+ workspacePath: workspacePath || context.cwd || '',
1440
+ leases: context.scopeLeases,
1441
+ enforceBlock: Boolean(context.enforceScopeBlock)
1442
+ });
1443
+ if (det20Res.triggered) {
1444
+ findings.push({
1445
+ detectorId: 'DET-20',
1446
+ turnIndex: Math.max(0, list.length - 1),
1447
+ severity: 'CRITICAL',
1448
+ haltsGeneration: Boolean(det20Res.haltsGeneration),
1449
+ conflictingTrajectoryId: det20Res.conflictingTrajectoryId,
1450
+ overlappingPaths: det20Res.overlappingPaths,
1451
+ message: det20Res.message
1452
+ });
1453
+ }
1454
+ }
1455
+ }
1456
+
1457
+ const normalizedFindings = findings.map((f) => ({
1458
+ ...f,
1459
+ id: f.id || f.detectorId,
1460
+ detectorId: f.detectorId || f.id
1461
+ }));
1462
+ const activeConfig =
1463
+ context.horizonConfig ||
1464
+ (context.cwd || context.workspacePath || context.configPath
1465
+ ? loadHorizonConfig(context)
1466
+ : null);
1467
+ const filteredFindings = filterFindingsByHorizonConfig(normalizedFindings, activeConfig);
1468
+
1469
+ const elapsedMs = Number(process.hrtime.bigint() - startHr) / 1e6;
1470
+ const shouldHalt = filteredFindings.some(f => f.haltsGeneration);
1471
+
1472
+ return {
1473
+ findings: filteredFindings,
1474
+ shouldHalt,
1475
+ haltFinding: filteredFindings.find(f => f.haltsGeneration) || null,
1476
+ elapsedMs: Number(elapsedMs.toFixed(3))
1477
+ };
1478
+ }
1479
+
1480
+ /**
1481
+ * Real-Time Event Multiplexer (`HookStateMachine`) synthesizing `PreInvocation`,
1482
+ * `PreToolUse`, `PostToolUse`, and `Stop` events and triggering `AgBridgeService.pauseActiveGeneration`
1483
+ * when a critical detector trips.
1484
+ */
1485
+ export class HookStateMachine extends EventEmitter {
1486
+ constructor(options = {}) {
1487
+ super();
1488
+ this.bridge = options.bridge || null;
1489
+ this.sessionId = options.sessionId || 'default-session';
1490
+ this.context = options.context || {};
1491
+ this.steps = [];
1492
+ this.activeFindings = [];
1493
+ this.paused = false;
1494
+ }
1495
+
1496
+ async ingestStep(step = {}, eventType = 'PostToolUse') {
1497
+ this.steps.push(step);
1498
+ this.emit(eventType, step);
1499
+
1500
+ const evalRes = evaluateDetectorsOnSteps(this.steps, {
1501
+ ...this.context,
1502
+ sessionId: this.sessionId
1503
+ });
1504
+ this.activeFindings = evalRes.findings;
1505
+
1506
+ if (evalRes.shouldHalt && !this.paused) {
1507
+ this.paused = true;
1508
+ const haltReason = evalRes.haltFinding?.detectorId || 'CIRCUIT_BREAKER';
1509
+ this.emit('CircuitBreakerTrip', evalRes.haltFinding);
1510
+ if (this.bridge && typeof this.bridge.pauseActiveGeneration === 'function') {
1511
+ await this.bridge.pauseActiveGeneration(this.sessionId, {
1512
+ reason: haltReason,
1513
+ finding: evalRes.haltFinding
1514
+ });
1515
+ }
1516
+ this.emit('Stop', { reason: haltReason, finding: evalRes.haltFinding });
1517
+ }
1518
+
1519
+ return evalRes;
1520
+ }
1521
+ }
1522
+
1523
+ export default HookStateMachine;