ctxtop 0.0.0-stage → 4.0.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 (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  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 +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -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 +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,1474 @@
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) {
614
+ if (!cmdStr || depth > 2) return false;
615
+ const segments = tokenizeShellCommandSegments(cmdStr);
616
+
617
+ for (const rawTokens of segments) {
618
+ const segEnv = {};
619
+ let idx = 0;
620
+
621
+ while (idx < rawTokens.length) {
622
+ const tok = rawTokens[idx];
623
+ if (!tok.quoted && tok.value === '&') {
624
+ idx++;
625
+ continue;
626
+ }
627
+ if (!tok.quoted && /^(sudo|env|command)$/i.test(tok.value)) {
628
+ idx++;
629
+ continue;
630
+ }
631
+ const envMatch = !tok.quoted && tok.value.match(/^(?:\$env:)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);
632
+ if (envMatch) {
633
+ segEnv[envMatch[1]] = envMatch[2].replace(/^['"]|['"]$/g, '');
634
+ idx++;
635
+ continue;
636
+ }
637
+ break;
638
+ }
639
+
640
+ if (idx >= rawTokens.length) continue;
641
+
642
+ const exeRaw = rawTokens[idx].value.replace(/\\/g, '/');
643
+ const exeBase = path.posix
644
+ .basename(exeRaw)
645
+ .toLowerCase()
646
+ .replace(/\.(exe|cmd|bat|ps1)$/i, '');
647
+ const argTokens = rawTokens.slice(idx + 1);
648
+
649
+ if (['echo', 'printf', 'write-host', 'write-output'].includes(exeBase)) {
650
+ continue;
651
+ }
652
+
653
+ if (['bash', 'sh', 'zsh', 'cmd', 'powershell', 'pwsh'].includes(exeBase)) {
654
+ for (let j = 0; j < argTokens.length; j++) {
655
+ const flagLow = argTokens[j].value.toLowerCase();
656
+ if (!argTokens[j].quoted && (flagLow === '-c' || flagLow === '/c' || flagLow === '-command')) {
657
+ if (j + 1 < argTokens.length && isDestructiveOrBypassShellCommand(argTokens[j + 1].value, depth + 1)) {
658
+ return true;
659
+ }
660
+ }
661
+ }
662
+ }
663
+
664
+ if (exeBase === 'git') {
665
+ const gitArgs = argTokens.map(t => t.value);
666
+ const guardRes = inspectGitArgs(gitArgs, segEnv);
667
+ if (guardRes.blocked) {
668
+ return true;
669
+ }
670
+
671
+ // Inspect unquoted destructive git subcommand flags (`reset --hard`, `push --force`, `clean -fd`)
672
+ let subIdx = -1;
673
+ for (let j = 0; j < argTokens.length; j++) {
674
+ const val = argTokens[j].value;
675
+ if (val === '--') break;
676
+ if (val.startsWith('-')) {
677
+ if (['-c', '-C', '--git-dir', '--work-tree', '--namespace', '--config-env'].includes(val)) {
678
+ j++;
679
+ }
680
+ continue;
681
+ }
682
+ subIdx = j;
683
+ break;
684
+ }
685
+
686
+ if (subIdx !== -1) {
687
+ const sub = argTokens[subIdx].value.toLowerCase();
688
+ const subTokens = argTokens.slice(subIdx + 1);
689
+ if (sub === 'reset') {
690
+ if (subTokens.some(t => !t.quoted && t.value === '--hard')) return true;
691
+ } else if (sub === 'push') {
692
+ if (subTokens.some(t => !t.quoted && (t.value === '--force' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(t.value)))) {
693
+ return true;
694
+ }
695
+ } else if (sub === 'clean') {
696
+ if (subTokens.some(t => !t.quoted && (t.value === '--force' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(t.value)))) {
697
+ return true;
698
+ }
699
+ }
700
+ }
701
+ continue;
702
+ }
703
+
704
+ if (exeBase === 'rm') {
705
+ let hasRec = false;
706
+ let hasForce = false;
707
+ for (const t of argTokens) {
708
+ if (/\.gemini[\\/]antigravity[\\/]brain/i.test(t.value)) return true;
709
+ if (!t.quoted && t.value.startsWith('-')) {
710
+ if (t.value === '--recursive') hasRec = true;
711
+ else if (t.value === '--force') hasForce = true;
712
+ else if (/^-[a-zA-Z]+$/.test(t.value)) {
713
+ if (/[rR]/.test(t.value)) hasRec = true;
714
+ if (/f/.test(t.value)) hasForce = true;
715
+ }
716
+ }
717
+ }
718
+ if (hasRec && hasForce) return true;
719
+ continue;
720
+ }
721
+
722
+ if (['del', 'erase', 'remove-item', 'ri', 'rd', 'rmdir', 'unlink'].includes(exeBase)) {
723
+ let hasRec = false;
724
+ let hasForce = false;
725
+ for (const t of argTokens) {
726
+ if (/\.gemini[\\/]antigravity[\\/]brain/i.test(t.value)) return true;
727
+ if (!t.quoted) {
728
+ if (/^-recurse$/i.test(t.value)) hasRec = true;
729
+ if (/^-force$/i.test(t.value)) hasForce = true;
730
+ }
731
+ }
732
+ if ((exeBase === 'remove-item' || exeBase === 'ri') && hasRec && hasForce) {
733
+ return true;
734
+ }
735
+ }
736
+ }
737
+
738
+ return false;
739
+ }
740
+
741
+ export function evaluateDet08DestructiveShell(stepsOrCmd = [], _context = {}) {
742
+ if (typeof stepsOrCmd === 'string') {
743
+ const blocked = isDestructiveOrBypassShellCommand(stepsOrCmd);
744
+ return {
745
+ id: 'DET-08',
746
+ detectorId: 'DET-08',
747
+ blocked,
748
+ triggered: blocked,
749
+ severity: 'CRITICAL',
750
+ haltsGeneration: blocked,
751
+ command: stepsOrCmd,
752
+ message: blocked
753
+ ? `🚨 DET-08 Blocked: Unauthorized destructive command intercepted ("${stepsOrCmd.slice(0, 80)}").`
754
+ : null
755
+ };
756
+ }
757
+
758
+ const list = Array.isArray(stepsOrCmd) ? stepsOrCmd : [];
759
+ for (const step of list) {
760
+ if (!step || typeof step !== 'object') continue;
761
+ const calls = Array.isArray(step.toolCalls)
762
+ ? step.toolCalls
763
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : [step]);
764
+ for (const call of calls) {
765
+ if (!call || typeof call !== 'object') continue;
766
+ const toolName = String(call.name || call.toolName || call.tool || step.toolName || '').toLowerCase().trim();
767
+ const args = call.args || call.arguments || call.input || {};
768
+ const cmdStr = String(args.CommandLine || args.command || args.cmd || call.command || step.command || '').trim();
769
+ const targetPath = String(args.Path || args.path || args.TargetFile || args.AbsolutePath || call.targetPath || '').trim();
770
+ if (cmdStr && isDestructiveOrBypassShellCommand(cmdStr)) {
771
+ return {
772
+ id: 'DET-08',
773
+ detectorId: 'DET-08',
774
+ blocked: true,
775
+ triggered: true,
776
+ severity: 'CRITICAL',
777
+ haltsGeneration: true,
778
+ command: cmdStr,
779
+ message: `🚨 DET-08 Blocked: Unauthorized destructive command intercepted ("${cmdStr.slice(0, 80)}").`
780
+ };
781
+ }
782
+ if (/delete|remove/i.test(toolName) && /\.gemini[\\/]antigravity[\\/]brain/i.test(targetPath)) {
783
+ return {
784
+ id: 'DET-08',
785
+ detectorId: 'DET-08',
786
+ blocked: true,
787
+ triggered: true,
788
+ severity: 'CRITICAL',
789
+ haltsGeneration: true,
790
+ targetPath,
791
+ message: `🚨 DET-08 Blocked: Unauthorized brain artifact deletion targeting ${targetPath}.`
792
+ };
793
+ }
794
+ }
795
+ }
796
+ return null;
797
+ }
798
+
799
+ export function evaluateDet09MidSessionRuleMutate(steps = [], context = {}) {
800
+ const cachedTokens = Number(context.cachedTokens ?? context.session?.cachedTokens ?? 0);
801
+ const cacheTtlSeconds = Number(context.cacheTtlSeconds ?? context.session?.cacheTtlSeconds ?? 0);
802
+ const warm = isWarmCacheState({
803
+ cachedTokens,
804
+ cacheTtlSeconds,
805
+ cacheState: context.cacheState || context.session?.cacheState
806
+ });
807
+ if (!warm) return null;
808
+
809
+ const list = Array.isArray(steps) ? steps : [];
810
+ for (const step of list) {
811
+ if (!step || typeof step !== 'object') continue;
812
+ const calls = Array.isArray(step.toolCalls)
813
+ ? step.toolCalls
814
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : [step]);
815
+ for (const call of calls) {
816
+ if (!call || typeof call !== 'object') continue;
817
+ const toolName = String(call.name || call.toolName || call.tool || step.toolName || '').trim();
818
+ if (toolName && !/write|edit|replace|delete|remove|create|patch/i.test(toolName)) continue;
819
+ const args = call.args || call.arguments || call.input || {};
820
+ const targetPath = String(
821
+ args.Path || args.path || args.TargetFile || args.AbsolutePath || call.targetPath || ''
822
+ ).trim();
823
+ if (targetPath && isProtectedPrefixFile(targetPath)) {
824
+ return {
825
+ id: 'DET-09',
826
+ detectorId: 'DET-09',
827
+ blocked: true,
828
+ triggered: true,
829
+ severity: 'HIGH',
830
+ haltsGeneration: true,
831
+ targetPath,
832
+ message: `🚨 DET-09 Blocked: Mid-session mutation of ${path.basename(targetPath)} while prompt cache is warm (${cachedTokens} tok, TTL ${cacheTtlSeconds}s).`
833
+ };
834
+ }
835
+ }
836
+ }
837
+ return null;
838
+ }
839
+
840
+ function countAssertionsInCode(code = '') {
841
+ const text = String(code || '');
842
+ const assertMatches = text.match(/\b(assert(?:\.[a-zA-Z0-9_]+)?|expect|should)\s*\(/g) || [];
843
+ const pyAssertMatches = text.match(/^\s*assert\s+/gm) || [];
844
+ return assertMatches.length + pyAssertMatches.length;
845
+ }
846
+
847
+ function countSkipsInCode(code = '') {
848
+ const text = String(code || '');
849
+ const skips = text.match(/(\.(?:skip|todo)\s*\(|@pytest\.mark\.skip\b|\bxit\s*\(|\bxdescribe\s*\(|\bxtest\s*\()/g) || [];
850
+ return skips.length;
851
+ }
852
+
853
+ /**
854
+ * Evaluates a step or stream of steps across all 16 deterministic detectors (`DET-01` .. `DET-16`).
855
+ */
856
+ export function evaluateDetectorsOnSteps(steps = [], context = {}) {
857
+ const startHr = process.hrtime.bigint();
858
+ const list = Array.isArray(steps) ? steps : [];
859
+ const findings = [];
860
+
861
+ const cachedTokens = Number(context.cachedTokens ?? context.session?.cachedTokens ?? 0);
862
+ const cacheTtlSeconds = Number(context.cacheTtlSeconds ?? context.session?.cacheTtlSeconds ?? 0);
863
+ const approvalGateEnabled = context.approvalGateEnabled !== false;
864
+ const userAuthorizedTestDeletion = Boolean(context.userAuthorizedTestDeletion);
865
+ const workspacePath = context.workspacePath || '';
866
+ const existingFilesSet = context.existingFiles instanceof Set
867
+ ? new Set(Array.from(context.existingFiles).map(p => canonicalizePath(p)))
868
+ : null;
869
+ const concurrentSessionTargets = context.concurrentSessionTargets || {}; // sessionId -> Set/Array of paths
870
+ const currentSessionId = String(context.sessionId || 'active-session');
871
+
872
+ // State trackers across turns
873
+ let consecutiveRetrySig = '';
874
+ let consecutiveRetryCount = 0;
875
+
876
+ // DET-02: path -> Array<{ turnIndex, hash }>
877
+ const fileHashHistory = new Map();
878
+
879
+ // DET-04: track whether a recent screenshot was black / 0-byte / failed
880
+ let recentBlackScreenshotTurn = -100;
881
+
882
+ // DET-05: track most recent test runner exit code
883
+ let lastTestRunnerExitCode = 0;
884
+ let lastTestRunnerSeen = false;
885
+
886
+ // DET-06: path::range::hash -> Array<turnIndex>
887
+ const readHistory = new Map();
888
+
889
+ // DET-07: consecutive task_boundary errors
890
+ let consecutiveTaskBoundaryErrors = 0;
891
+
892
+ // DET-13: track PLANNING phase & whether user approved
893
+ let inPlanningPhase = false;
894
+ let userApprovedPlan = Boolean(context.userApprovedPlan);
895
+ const destructiveEditedFilesInPlan = new Set();
896
+
897
+ for (let idx = 0; idx < list.length; idx++) {
898
+ const step = list[idx] || {};
899
+ const stepType = String(step.type || '').toUpperCase();
900
+ const role = String(step.role || step.source || '').toLowerCase();
901
+ const content = String(step.content || '');
902
+ const thinking = String(step.thinking || step.rrthought || '');
903
+ const calls = Array.isArray(step.toolCalls)
904
+ ? step.toolCalls
905
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : []);
906
+
907
+ // Check if user turn authorized test deletion or approved plan
908
+ if (stepType === 'USER_INPUT' || role === 'user') {
909
+ if (/\b(approve|approved|proceed|lgtm|looks good|go ahead)\b/i.test(content)) {
910
+ userApprovedPlan = true;
911
+ inPlanningPhase = false;
912
+ }
913
+ }
914
+
915
+ // DET-07: <rrthought> Panic & Instruction-Loop Spiral
916
+ const thoughtBlob = `${thinking}\n${content}`;
917
+ const capsMatches = thoughtBlob.match(/\b(CRITICAL INSTRUCTIONS|MUST NOT FAIL|PANIC|DO NOT REPEAT THIS ERROR|IMPOSSIBLE STATE)\b/g) || [];
918
+ const circularMatches = thoughtBlob.match(/\b(wait, no, actually|no wait that's wrong|wait let me rethink from scratch)\b/gi) || [];
919
+ if (capsMatches.length >= 2 || circularMatches.length >= 3) {
920
+ findings.push({
921
+ detectorId: 'DET-07',
922
+ turnIndex: idx,
923
+ severity: 'CRITICAL',
924
+ haltsGeneration: true,
925
+ message: `🚨 DET-07 Blocked: <rrthought> panic or high-entropy instruction loop detected at turn #${idx}.`
926
+ });
927
+ }
928
+
929
+ // DET-15: Secret / Credential Leakage in Brain Artifacts or Transcript
930
+ 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,})/;
931
+ if (secretRe.test(content)) {
932
+ findings.push({
933
+ detectorId: 'DET-15',
934
+ turnIndex: idx,
935
+ severity: 'CRITICAL',
936
+ haltsGeneration: true,
937
+ message: `🚨 DET-15 Blocked: Secret or credential token leakage detected in transcript/artifact at turn #${idx}.`
938
+ });
939
+ }
940
+
941
+ // Check screenshot status for DET-04
942
+ if (
943
+ step.blackScreenshot === true ||
944
+ step.screenshotByteLength === 0 ||
945
+ /black screenshot|zero-byte screenshot|blank_screenshot|0 bytes screenshot/i.test(content)
946
+ ) {
947
+ recentBlackScreenshotTurn = idx;
948
+ }
949
+
950
+ for (const call of calls) {
951
+ const toolName = String(call.name || call.tool || '').toLowerCase();
952
+ const args = call.args || call.arguments || call.parameters || call.Arguments || {};
953
+ const targetPath = String(
954
+ args.Path || args.path || args.TargetFile || args.AbsolutePath || step.targetPath || ''
955
+ ).trim();
956
+ const canonTarget = targetPath ? canonicalizePath(targetPath) : '';
957
+ const cmdStr = String(args.CommandLine || args.command || args.cmd || '');
958
+ const exitCode = call.exitCode ?? step.exitCode ?? (step.status === 'ERROR' ? 1 : 0);
959
+ const stderrStr = String(call.stderr || step.stderr || (exitCode !== 0 ? content : ''));
960
+ const stdoutStr = String(call.stdout || step.stdout || content || '');
961
+
962
+ // DET-01: Retry Churn (>=3 consecutive identical tool calls returning error)
963
+ const sig = normalizeToolSignature(toolName, args);
964
+ const isFailure = (typeof exitCode === 'number' && exitCode !== 0) || step.status === 'ERROR' || Boolean(call.error);
965
+ if (isFailure) {
966
+ if (sig === consecutiveRetrySig) {
967
+ consecutiveRetryCount++;
968
+ } else {
969
+ consecutiveRetrySig = sig;
970
+ consecutiveRetryCount = 1;
971
+ }
972
+ if (consecutiveRetryCount >= 3) {
973
+ findings.push({
974
+ detectorId: 'DET-01',
975
+ turnIndex: idx,
976
+ severity: 'CRITICAL',
977
+ haltsGeneration: true,
978
+ toolName,
979
+ message: `🚨 DET-01 Blocked: Retry Churn (${consecutiveRetryCount} consecutive failed calls to ${toolName}).`
980
+ });
981
+ }
982
+ } else {
983
+ consecutiveRetrySig = '';
984
+ consecutiveRetryCount = 0;
985
+ }
986
+
987
+ // DET-07 (task_boundary consecutive errors)
988
+ if (toolName === 'task_boundary' && isFailure) {
989
+ consecutiveTaskBoundaryErrors++;
990
+ if (consecutiveTaskBoundaryErrors >= 2) {
991
+ findings.push({
992
+ detectorId: 'DET-07',
993
+ turnIndex: idx,
994
+ severity: 'CRITICAL',
995
+ haltsGeneration: true,
996
+ message: `🚨 DET-07 Blocked: Consecutive task_boundary tool errors (${consecutiveTaskBoundaryErrors}).`
997
+ });
998
+ }
999
+ } else if (toolName === 'task_boundary') {
1000
+ consecutiveTaskBoundaryErrors = 0;
1001
+ }
1002
+
1003
+ // Track test runner executions for DET-05
1004
+ const isExecTool = /^(run_command|execute_bash|bash|execute_command)$/.test(toolName);
1005
+ if (isExecTool && /\b(pytest|jest|vitest|cargo\s+test|npm\s+test|node\s+--test|go\s+test)\b/i.test(cmdStr)) {
1006
+ lastTestRunnerSeen = true;
1007
+ lastTestRunnerExitCode = typeof exitCode === 'number' ? exitCode : (isFailure ? 1 : 0);
1008
+ }
1009
+
1010
+ // DET-08: Unauthorized Brain / Git Destructive Command (shell-tokenized to avoid quoted string false positives)
1011
+ const isWriteOrDelete = /write|edit|replace|delete|remove/i.test(toolName);
1012
+ if (isExecTool) {
1013
+ if (isDestructiveOrBypassShellCommand(cmdStr)) {
1014
+ findings.push({
1015
+ detectorId: 'DET-08',
1016
+ turnIndex: idx,
1017
+ severity: 'CRITICAL',
1018
+ haltsGeneration: true,
1019
+ command: cmdStr,
1020
+ message: `🚨 DET-08 Blocked: Unauthorized destructive command intercepted ("${cmdStr.slice(0, 80)}").`
1021
+ });
1022
+ }
1023
+ const det19Exec = evaluateDet19GitHookBypass(cmdStr, call.env || step.env || {});
1024
+ if (det19Exec.blocked) {
1025
+ findings.push({
1026
+ detectorId: 'DET-19',
1027
+ turnIndex: idx,
1028
+ severity: 'CRITICAL',
1029
+ haltsGeneration: true,
1030
+ command: cmdStr,
1031
+ reason: det19Exec.reason,
1032
+ message: det19Exec.message
1033
+ });
1034
+ }
1035
+ const det18Exec = evaluateDet18UntrustedWorkspaceSettings({
1036
+ command: cmdStr,
1037
+ userAuthorizedSettingsEdit: Boolean(context.userAuthorizedSettingsEdit || step.userAuthorizedSettingsEdit)
1038
+ });
1039
+ if (det18Exec.blocked) {
1040
+ findings.push({
1041
+ detectorId: 'DET-18',
1042
+ turnIndex: idx,
1043
+ severity: 'CRITICAL',
1044
+ haltsGeneration: true,
1045
+ command: cmdStr,
1046
+ hazards: det18Exec.hazards,
1047
+ message: det18Exec.message
1048
+ });
1049
+ }
1050
+ }
1051
+ if (/delete|remove/i.test(toolName) && /\.gemini[\\/]antigravity[\\/]brain/i.test(targetPath)) {
1052
+ findings.push({
1053
+ detectorId: 'DET-08',
1054
+ turnIndex: idx,
1055
+ severity: 'CRITICAL',
1056
+ haltsGeneration: true,
1057
+ targetPath,
1058
+ message: `🚨 DET-08 Blocked: Unauthorized brain artifact deletion targeting ${targetPath}.`
1059
+ });
1060
+ }
1061
+
1062
+ // DET-10: Unbounded CLI Output Flood (>12,000 chars)
1063
+ if (isExecTool && (stdoutStr.length > 12000 || stderrStr.length > 12000)) {
1064
+ findings.push({
1065
+ detectorId: 'DET-10',
1066
+ turnIndex: idx,
1067
+ severity: 'WARN',
1068
+ haltsGeneration: false,
1069
+ charCount: Math.max(stdoutStr.length, stderrStr.length),
1070
+ message: `⚠️ DET-10 Alert: Unbounded CLI output flood (${Math.max(stdoutStr.length, stderrStr.length)} chars > 12,000 limit).`
1071
+ });
1072
+ }
1073
+
1074
+ // File read detectors (DET-06)
1075
+ const isReadTool = /^(read_file|view_file|read)$/.test(toolName);
1076
+ if (isReadTool && canonTarget) {
1077
+ const startLine = args.StartLine ?? args.start_line ?? 1;
1078
+ const endLine = args.EndLine ?? args.end_line ?? 'EOF';
1079
+ const fileHash = call.fileHash || step.fileHash || sha256Hex(stdoutStr || canonTarget);
1080
+ const readKey = `${canonTarget}::${startLine}-${endLine}::${fileHash}`;
1081
+ const prevReads = readHistory.get(readKey) || [];
1082
+ const recentReads = prevReads.filter(prevTurn => (idx - prevTurn) <= 15);
1083
+ recentReads.push(idx);
1084
+ readHistory.set(readKey, recentReads);
1085
+
1086
+ if (recentReads.length >= 2) {
1087
+ findings.push({
1088
+ detectorId: 'DET-06',
1089
+ turnIndex: idx,
1090
+ severity: 'WARN',
1091
+ haltsGeneration: false,
1092
+ targetPath,
1093
+ message: `⚠️ DET-06 Alert: Redundant unchanged file re-read on ${path.basename(targetPath)} (${recentReads.length}x within 15 turns).`
1094
+ });
1095
+ }
1096
+ }
1097
+
1098
+ // File write / edit detectors (DET-02, DET-03, DET-04, DET-05, DET-09, DET-11, DET-13, DET-14, DET-15, DET-16)
1099
+ if (isWriteOrDelete && targetPath) {
1100
+ const replacementChunks = Array.isArray(args.ReplacementChunks) ? args.ReplacementChunks : null;
1101
+ const chunksNew = replacementChunks
1102
+ ? replacementChunks.map(ch => String(ch?.ReplacementContent ?? ch?.Replacement ?? ch?.newContent ?? '')).filter(Boolean).join('\n')
1103
+ : undefined;
1104
+ const chunksOld = replacementChunks
1105
+ ? replacementChunks.map(ch => String(ch?.TargetContent ?? ch?.Target ?? ch?.oldContent ?? '')).filter(Boolean).join('\n')
1106
+ : undefined;
1107
+ const newContent = String(
1108
+ args.Content ?? args.CodeContent ?? args.Replacement ?? args.ReplacementContent ?? chunksNew ?? args.newContent ?? call.newContent ?? step.newContent ?? ''
1109
+ );
1110
+ const oldContent = String(
1111
+ args.Target ?? args.TargetContent ?? chunksOld ?? args.oldContent ?? call.oldContent ?? step.oldContent ?? ''
1112
+ );
1113
+
1114
+ // DET-18: Untrusted Workspace Settings & Hook Injection Guard
1115
+ const det18Write = evaluateDet18UntrustedWorkspaceSettings({
1116
+ targetPath,
1117
+ newContent,
1118
+ toolName,
1119
+ userAuthorizedSettingsEdit: Boolean(context.userAuthorizedSettingsEdit || step.userAuthorizedSettingsEdit)
1120
+ });
1121
+ if (det18Write.blocked) {
1122
+ findings.push({
1123
+ detectorId: 'DET-18',
1124
+ turnIndex: idx,
1125
+ severity: 'CRITICAL',
1126
+ haltsGeneration: true,
1127
+ targetPath,
1128
+ hazards: det18Write.hazards,
1129
+ message: det18Write.message
1130
+ });
1131
+ }
1132
+
1133
+ // DET-15 on written content
1134
+ if (/walkthrough\.md|transcript\.jsonl/i.test(targetPath) && secretRe.test(newContent)) {
1135
+ findings.push({
1136
+ detectorId: 'DET-15',
1137
+ turnIndex: idx,
1138
+ severity: 'CRITICAL',
1139
+ haltsGeneration: true,
1140
+ targetPath,
1141
+ message: `🚨 DET-15 Blocked: Secret/credential leakage in brain artifact ${path.basename(targetPath)}.`
1142
+ });
1143
+ }
1144
+
1145
+ // DET-02: Edit Oscillation (H1 -> H2 -> H1 within 6 turns)
1146
+ const nextHash = call.afterHash || step.afterHash || (newContent ? sha256Hex(newContent) : null);
1147
+ const prevHash = call.beforeHash || step.beforeHash || (oldContent ? sha256Hex(oldContent) : null);
1148
+ if (canonTarget && nextHash && !isFailure) {
1149
+ const hist = fileHashHistory.get(canonTarget) || [];
1150
+ if (hist.length === 0 && prevHash) {
1151
+ hist.push({ turnIndex: Math.max(0, idx - 1), hash: prevHash });
1152
+ }
1153
+ const oscillating = hist.some(
1154
+ h => h.hash === nextHash && (idx - h.turnIndex) <= 6 && hist[hist.length - 1]?.hash !== nextHash
1155
+ );
1156
+ hist.push({ turnIndex: idx, hash: nextHash });
1157
+ fileHashHistory.set(canonTarget, hist);
1158
+
1159
+ if (oscillating) {
1160
+ findings.push({
1161
+ detectorId: 'DET-02',
1162
+ turnIndex: idx,
1163
+ severity: 'CRITICAL',
1164
+ haltsGeneration: true,
1165
+ targetPath,
1166
+ message: `🚨 DET-02 Blocked: Edit oscillation (H1 -> H2 -> H1 SHA-256 revert within 6 turns) on ${path.basename(targetPath)}.`
1167
+ });
1168
+ }
1169
+ }
1170
+
1171
+ // DET-03: Test-Assertion Weakening
1172
+ if (isTestFilePath(targetPath) && !userAuthorizedTestDeletion && !step.userAuthorizedTestDeletion) {
1173
+ const beforeAssertions = countAssertionsInCode(oldContent);
1174
+ const afterAssertions = countAssertionsInCode(newContent);
1175
+ const beforeSkips = countSkipsInCode(oldContent);
1176
+ const afterSkips = countSkipsInCode(newContent);
1177
+
1178
+ const deletedAssertions = Math.max(0, beforeAssertions - afterAssertions);
1179
+ const addedSkips = Math.max(0, afterSkips - beforeSkips);
1180
+
1181
+ if (deletedAssertions > 0 || addedSkips > 0) {
1182
+ findings.push({
1183
+ detectorId: 'DET-03',
1184
+ turnIndex: idx,
1185
+ severity: 'CRITICAL',
1186
+ haltsGeneration: true,
1187
+ targetPath,
1188
+ deletedAssertions,
1189
+ addedSkips,
1190
+ message: `🚨 DET-03 Blocked: Agent attempted to delete ${deletedAssertions} expect()/assert() assertion(s) or add ${addedSkips} skip(s) in ${path.basename(targetPath)}`
1191
+ });
1192
+ }
1193
+ }
1194
+
1195
+ // DET-04: Synthetic Proof / Fake Screenshot Fabrication
1196
+ const isBrainOrScratchScript =
1197
+ /(\.gemini[\\/]antigravity[\\/]brain|scratch)[\\/].*\.(py|js|mjs)$/i.test(targetPath);
1198
+ const importsVisionFabricator =
1199
+ /\b(PIL|ImageDraw|matplotlib|cv2|createCanvas)\b/.test(newContent);
1200
+ if (isBrainOrScratchScript && importsVisionFabricator && (idx - recentBlackScreenshotTurn) <= 4) {
1201
+ findings.push({
1202
+ detectorId: 'DET-04',
1203
+ turnIndex: idx,
1204
+ severity: 'CRITICAL',
1205
+ haltsGeneration: true,
1206
+ targetPath,
1207
+ message: `🚨 DET-04 Blocked: Synthetic proof / fake screenshot generator script detected in ${path.basename(targetPath)} following black screenshot.`
1208
+ });
1209
+ }
1210
+
1211
+ // DET-05: Unverified [x] Task Completion
1212
+ if (/task\.md$/i.test(targetPath) && /[-*]\s*\[x\]/i.test(newContent) && lastTestRunnerSeen && lastTestRunnerExitCode !== 0) {
1213
+ findings.push({
1214
+ detectorId: 'DET-05',
1215
+ turnIndex: idx,
1216
+ severity: 'HIGH',
1217
+ haltsGeneration: true,
1218
+ targetPath,
1219
+ message: `🚨 DET-05 Blocked: Agent marked task.md item [x] while most recent test run exited with code ${lastTestRunnerExitCode}.`
1220
+ });
1221
+ }
1222
+ if (/walkthrough\.md$/i.test(targetPath) && /\b(all tests pass|tests passed|0 errors)\b/i.test(newContent) && lastTestRunnerSeen && lastTestRunnerExitCode !== 0) {
1223
+ findings.push({
1224
+ detectorId: 'DET-05',
1225
+ turnIndex: idx,
1226
+ severity: 'HIGH',
1227
+ haltsGeneration: true,
1228
+ targetPath,
1229
+ message: `🚨 DET-05 Blocked: Agent claimed passing tests in walkthrough.md while most recent test run exited with code ${lastTestRunnerExitCode}.`
1230
+ });
1231
+ }
1232
+
1233
+ // DET-09: Prefix-Busting Config Mutation (aligned Antigravity rule globs; excludes CLAUDE.md / .claude/)
1234
+ const warmForDet09 = isWarmCacheState({
1235
+ cachedTokens,
1236
+ cacheTtlSeconds,
1237
+ cacheState: context.cacheState || context.session?.cacheState
1238
+ });
1239
+ if (isProtectedPrefixFile(targetPath) && warmForDet09) {
1240
+ findings.push({
1241
+ detectorId: 'DET-09',
1242
+ turnIndex: idx,
1243
+ severity: 'HIGH',
1244
+ haltsGeneration: true,
1245
+ targetPath,
1246
+ message: `🚨 DET-09 Blocked: Mid-session mutation of ${path.basename(targetPath)} while prompt cache is warm (${cachedTokens} tok, TTL ${cacheTtlSeconds}s).`
1247
+ });
1248
+ }
1249
+
1250
+ // DET-11: Phantom File / Identifier Confabulation in implementation_plan.md or walkthrough.md
1251
+ if (/(implementation_plan|walkthrough)\.md$/i.test(targetPath) && (existingFilesSet || workspacePath)) {
1252
+ const lines = newContent.split(/\r?\n/);
1253
+ for (const line of lines) {
1254
+ if (/\[NEW\]/i.test(line)) continue;
1255
+ const pathMatches = line.match(/\b(?:src|lib|app|sidecars|scripts|tests)\/[A-Za-z0-9_./-]+\.(?:mjs|js|ts|tsx|py|json|html)\b/g) || [];
1256
+ for (const refRel of pathMatches) {
1257
+ const absCandidate = workspacePath ? path.resolve(workspacePath, refRel) : refRel;
1258
+ const canonCandidate = canonicalizePath(absCandidate);
1259
+ const existsInSet = existingFilesSet
1260
+ ? (existingFilesSet.has(canonCandidate) || existingFilesSet.has(canonicalizePath(refRel)))
1261
+ : (workspacePath ? fs.existsSync(absCandidate) : true);
1262
+ if (!existsInSet) {
1263
+ findings.push({
1264
+ detectorId: 'DET-11',
1265
+ turnIndex: idx,
1266
+ severity: 'HIGH',
1267
+ haltsGeneration: false,
1268
+ phantomPath: refRel,
1269
+ message: `⚠️ DET-11 Alert: Phantom file path "${refRel}" referenced in ${path.basename(targetPath)} does not exist in workspace.`
1270
+ });
1271
+ }
1272
+ }
1273
+ }
1274
+ }
1275
+
1276
+ // DET-13: Premature Execution Without Plan Approval
1277
+ if (/implementation_plan\.md$/i.test(targetPath)) {
1278
+ inPlanningPhase = true;
1279
+ } else if (
1280
+ inPlanningPhase &&
1281
+ approvalGateEnabled &&
1282
+ !userApprovedPlan &&
1283
+ !/(\.gemini[\\/]antigravity[\\/]brain|task\.md|implementation_plan\.md)/i.test(targetPath)
1284
+ ) {
1285
+ destructiveEditedFilesInPlan.add(canonTarget);
1286
+ if (destructiveEditedFilesInPlan.size >= 2) {
1287
+ findings.push({
1288
+ detectorId: 'DET-13',
1289
+ turnIndex: idx,
1290
+ severity: 'CRITICAL',
1291
+ haltsGeneration: true,
1292
+ targetPath,
1293
+ message: `🚨 DET-13 Blocked: Premature multi-file execution (${destructiveEditedFilesInPlan.size} files) without user approval after implementation_plan.md creation.`
1294
+ });
1295
+ }
1296
+ }
1297
+
1298
+ // DET-14: Subagent File-Write Collision
1299
+ if (canonTarget && concurrentSessionTargets && typeof concurrentSessionTargets === 'object') {
1300
+ for (const [otherSid, targets] of Object.entries(concurrentSessionTargets)) {
1301
+ if (otherSid === currentSessionId) continue;
1302
+ const targetList = Array.isArray(targets) ? targets : Array.from(targets || []);
1303
+ if (targetList.some(t => canonicalizePath(t) === canonTarget)) {
1304
+ findings.push({
1305
+ detectorId: 'DET-14',
1306
+ turnIndex: idx,
1307
+ severity: 'CRITICAL',
1308
+ haltsGeneration: true,
1309
+ targetPath,
1310
+ conflictingSessionId: otherSid,
1311
+ message: `🚨 DET-14 Blocked: Subagent file-write collision on ${path.basename(targetPath)} with concurrent session ${otherSid}.`
1312
+ });
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ // DET-16: Silent Truncation / Placeholder Slop Injection
1318
+ 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;
1319
+ const oldLines = oldContent ? oldContent.split(/\r?\n/).length : 0;
1320
+ const newLines = newContent ? newContent.split(/\r?\n/).length : 0;
1321
+ const suddenLineDrop = oldLines >= 20 && newLines > 0 && ((oldLines - newLines) / oldLines) > 0.40;
1322
+ if (slopRe.test(newContent) || suddenLineDrop) {
1323
+ findings.push({
1324
+ detectorId: 'DET-16',
1325
+ turnIndex: idx,
1326
+ severity: 'CRITICAL',
1327
+ haltsGeneration: true,
1328
+ targetPath,
1329
+ message: `🚨 DET-16 Blocked: Silent truncation or placeholder slop injection detected in ${path.basename(targetPath)}.`
1330
+ });
1331
+ }
1332
+ }
1333
+ }
1334
+
1335
+ // DET-12: Zombie Background Subprocess Leak on turn completion
1336
+ const orphans = Array.isArray(step.orphanedProcesses)
1337
+ ? step.orphanedProcesses
1338
+ : (idx === list.length - 1 && Array.isArray(context.orphanedProcesses) ? context.orphanedProcesses : []);
1339
+ for (const proc of orphans) {
1340
+ const pName = String(proc.name || '').toLowerCase();
1341
+ if (/(python|python3|node|cargo|pytest)/.test(pName) && (proc.cpuPct === 0 || proc.orphaned === true || proc.parentAlive === false)) {
1342
+ findings.push({
1343
+ detectorId: 'DET-12',
1344
+ turnIndex: idx,
1345
+ severity: 'HIGH',
1346
+ haltsGeneration: false,
1347
+ pid: proc.pid,
1348
+ processName: proc.name,
1349
+ message: `⚠️ DET-12 Alert: Zombie background subprocess leak (${proc.name} PID ${proc.pid}, 0% CPU / orphaned).`
1350
+ });
1351
+ }
1352
+ }
1353
+ }
1354
+
1355
+ // DET-17: Shadow File Context Bloat across transcript steps
1356
+ if (list.length > 0) {
1357
+ const det17Res = evaluateDet17ShadowFileBloat(list);
1358
+ if (det17Res.triggered) {
1359
+ findings.push({
1360
+ detectorId: 'DET-17',
1361
+ turnIndex: list.length - 1,
1362
+ severity: 'WARN',
1363
+ haltsGeneration: false,
1364
+ shadowedFileCount: det17Res.shadowedFileCount,
1365
+ totalShadowWastedTokens: det17Res.totalShadowWastedTokens,
1366
+ message: det17Res.message
1367
+ });
1368
+ }
1369
+ }
1370
+
1371
+ // DET-20: Concurrent Multi-Agent Scope Lock Collision
1372
+ if (Array.isArray(context.scopeLeases) || context.checkScopeLocks === true) {
1373
+ const editedStepPaths = [];
1374
+ for (const s of list) {
1375
+ const cList = Array.isArray(s?.toolCalls) ? s.toolCalls : (Array.isArray(s?.tool_calls) ? s.tool_calls : []);
1376
+ for (const c of cList) {
1377
+ if (/write|edit|replace|create|patch/i.test(String(c?.name || c?.tool || ''))) {
1378
+ const p = c?.args?.Path || c?.args?.path || c?.args?.TargetFile || c?.args?.AbsolutePath;
1379
+ if (p) editedStepPaths.push(p);
1380
+ }
1381
+ }
1382
+ }
1383
+ const claimedForDet20 = Array.isArray(context.claimedPaths)
1384
+ ? [...context.claimedPaths, ...editedStepPaths]
1385
+ : editedStepPaths;
1386
+ if (claimedForDet20.length > 0) {
1387
+ const det20Res = evaluateDet20ScopeCollision({
1388
+ sessionId: currentSessionId,
1389
+ claimedPaths: claimedForDet20,
1390
+ workspacePath: workspacePath || context.cwd || '',
1391
+ leases: context.scopeLeases,
1392
+ enforceBlock: Boolean(context.enforceScopeBlock)
1393
+ });
1394
+ if (det20Res.triggered) {
1395
+ findings.push({
1396
+ detectorId: 'DET-20',
1397
+ turnIndex: Math.max(0, list.length - 1),
1398
+ severity: 'CRITICAL',
1399
+ haltsGeneration: Boolean(det20Res.haltsGeneration),
1400
+ conflictingTrajectoryId: det20Res.conflictingTrajectoryId,
1401
+ overlappingPaths: det20Res.overlappingPaths,
1402
+ message: det20Res.message
1403
+ });
1404
+ }
1405
+ }
1406
+ }
1407
+
1408
+ const normalizedFindings = findings.map((f) => ({
1409
+ ...f,
1410
+ id: f.id || f.detectorId,
1411
+ detectorId: f.detectorId || f.id
1412
+ }));
1413
+ const activeConfig =
1414
+ context.horizonConfig ||
1415
+ (context.cwd || context.workspacePath || context.configPath
1416
+ ? loadHorizonConfig(context)
1417
+ : null);
1418
+ const filteredFindings = filterFindingsByHorizonConfig(normalizedFindings, activeConfig);
1419
+
1420
+ const elapsedMs = Number(process.hrtime.bigint() - startHr) / 1e6;
1421
+ const shouldHalt = filteredFindings.some(f => f.haltsGeneration);
1422
+
1423
+ return {
1424
+ findings: filteredFindings,
1425
+ shouldHalt,
1426
+ haltFinding: filteredFindings.find(f => f.haltsGeneration) || null,
1427
+ elapsedMs: Number(elapsedMs.toFixed(3))
1428
+ };
1429
+ }
1430
+
1431
+ /**
1432
+ * Real-Time Event Multiplexer (`HookStateMachine`) synthesizing `PreInvocation`,
1433
+ * `PreToolUse`, `PostToolUse`, and `Stop` events and triggering `AgBridgeService.pauseActiveGeneration`
1434
+ * when a critical detector trips.
1435
+ */
1436
+ export class HookStateMachine extends EventEmitter {
1437
+ constructor(options = {}) {
1438
+ super();
1439
+ this.bridge = options.bridge || null;
1440
+ this.sessionId = options.sessionId || 'default-session';
1441
+ this.context = options.context || {};
1442
+ this.steps = [];
1443
+ this.activeFindings = [];
1444
+ this.paused = false;
1445
+ }
1446
+
1447
+ async ingestStep(step = {}, eventType = 'PostToolUse') {
1448
+ this.steps.push(step);
1449
+ this.emit(eventType, step);
1450
+
1451
+ const evalRes = evaluateDetectorsOnSteps(this.steps, {
1452
+ ...this.context,
1453
+ sessionId: this.sessionId
1454
+ });
1455
+ this.activeFindings = evalRes.findings;
1456
+
1457
+ if (evalRes.shouldHalt && !this.paused) {
1458
+ this.paused = true;
1459
+ const haltReason = evalRes.haltFinding?.detectorId || 'CIRCUIT_BREAKER';
1460
+ this.emit('CircuitBreakerTrip', evalRes.haltFinding);
1461
+ if (this.bridge && typeof this.bridge.pauseActiveGeneration === 'function') {
1462
+ await this.bridge.pauseActiveGeneration(this.sessionId, {
1463
+ reason: haltReason,
1464
+ finding: evalRes.haltFinding
1465
+ });
1466
+ }
1467
+ this.emit('Stop', { reason: haltReason, finding: evalRes.haltFinding });
1468
+ }
1469
+
1470
+ return evalRes;
1471
+ }
1472
+ }
1473
+
1474
+ export default HookStateMachine;