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,1342 @@
1
+ /**
2
+ * Pure Zero-I/O Cross-Repo Capability Portfolio Evaluators (Ranks 1–12)
3
+ * (`src/core/shared/detectors.mjs`)
4
+ *
5
+ * Normalized Cross-Repo Detector IDs:
6
+ * - DET-02 (Rank 11): Zero-Token PreInvocation Secret & Mega-Dump Hold + Sensitive File Guard
7
+ * - DET-04 (Rank 5) : 3-Strike Consecutive Tool Failure Breaker
8
+ * - DET-05 (Rank 1) : Pre-Write Destructive Code-Strip, Test-Assertion & 6-Turn FNV-1a Flip-Flop Guard
9
+ * - DET-06 (Rank 2) : Unmodified File Re-Read & GitClear Blind-Edit Guard
10
+ * - DET-06B (Rank 6) : Lean Flash Subagent Search Offloader (@ah-flash-scout)
11
+ * - DET-07 (Rank 3) : Exit-Safe CLI Compressor (30-head + 45-tail + 100% error recovery)
12
+ * - DET-08 (Rank 7) : KV-Cache Gravity & Same-Model Between-Turn Effort Router
13
+ * - DET-10 (Rank 8) : Idle 5m Implicit-Cache Watchdog & Cold-Resume Baton Pulse
14
+ * - DET-13 (Rank 10): Eager MCP Override & Startup Bloat Auditor
15
+ * - DET-16 (Rank 12): 80% Hybrid Quota Fan-Out Throttle & 40k/12-Turn Subagent Cap
16
+ * - DET-17 (Rank 4) : 70k Cascade Progressive Checkpoints & Premature /compact Suppressor
17
+ * - DET-20 (Rank 12): Vision Overage HTTP 400 Quirk Guard
18
+ * - RSI-01 (Rank 9) : Skill Fault Router & /evolve Prefix Diet (>8k tokens, >=5 instincts)
19
+ */
20
+
21
+ import { evaluateFnv1aRingBuffer, fnv1a64Hex } from './fnv1a64.mjs';
22
+ import {
23
+ LIVE_SECRET_DEFINITIONS,
24
+ isPlaceholderSecretValue,
25
+ computeShannonEntropy,
26
+ redactSecretsPure
27
+ } from './ipi_sanitizer.mjs';
28
+ import {
29
+ CASCADE_COMPACTION_CEILING_TOKENS,
30
+ CASCADE_CHECKPOINT_BANDS
31
+ } from './handoff_schema.mjs';
32
+
33
+ export const NORMALIZED_PORTFOLIO_DETECTORS = Object.freeze({
34
+ 'DET-02': { id: 'DET-02', rank: 11, name: 'Zero-Token PreInvocation Secret & Mega-Dump Hold' },
35
+ 'DET-04': { id: 'DET-04', rank: 5, name: '3-Strike Consecutive Tool Failure Breaker' },
36
+ 'DET-05': { id: 'DET-05', rank: 1, name: 'Pre-Write Destructive Code-Strip & Test-Assertion Guard' },
37
+ 'DET-06': { id: 'DET-06', rank: 2, name: 'Unmodified File Re-Read & GitClear Blind-Edit Guard' },
38
+ 'DET-06B': { id: 'DET-06B', rank: 6, name: 'Lean Flash Subagent Search Offloader' },
39
+ 'DET-07': { id: 'DET-07', rank: 3, name: 'Exit-Safe CLI Compressor & 5 MB FTS5 Archive' },
40
+ 'DET-08': { id: 'DET-08', rank: 7, name: 'KV-Cache Gravity & Between-Turn Effort Router' },
41
+ 'DET-10': { id: 'DET-10', rank: 8, name: 'Idle Implicit-Cache Watchdog & Cold-Resume Baton Pulse' },
42
+ 'DET-13': { id: 'DET-13', rank: 10, name: 'Eager MCP Override & Startup Bloat Auditor' },
43
+ 'DET-16': { id: 'DET-16', rank: 12, name: '80% Hybrid Quota Fan-Out Throttle & Subagent Cap' },
44
+ 'DET-17': { id: 'DET-17', rank: 4, name: '70k Cascade Progressive Checkpoints & Baton-Pass Coach' },
45
+ 'DET-20': { id: 'DET-20', rank: 12, name: 'Vision Overage HTTP 400 Quirk Guard' },
46
+ 'RSI-01': { id: 'RSI-01', rank: 9, name: 'Skill Fault Router & /evolve Prefix Diet' }
47
+ });
48
+
49
+ // ============================================================================
50
+ // Rank 1 (DET-05): Pre-Write Destructive Code-Strip & Test-Assertion Guard
51
+ // ============================================================================
52
+
53
+ export const CLEANUP_INTENT_RE = /\b(delete|remove|deprecate|drop|prune)\b/i;
54
+
55
+ export const LAZY_ELISION_PATTERNS = Object.freeze([
56
+ /\/\/\s*\.\.\.\s*(?:rest\s+of\s+(?:code|file|implementation|function|class)|existing\s+(?:code|implementation|logic)|unchanged|keep\s+existing|omitted|remaining\s+code)/i,
57
+ /\/\*\s*\.\.\.\s*(?:rest\s+of\s+(?:code|file|implementation)|existing\s+(?:code|implementation)|unchanged|omitted)[\s\S]*?\*\//i,
58
+ /#\s*\.\.\.\s*(?:rest\s+of\s+(?:code|file|implementation)|existing\s+(?:code|implementation)|unchanged|omitted)/i,
59
+ /\/\/\s*existing\s+implementation\b/i,
60
+ /\/\/\s*rest\s+of\s+code\b/i
61
+ ]);
62
+
63
+ export function isTestOrSpecFilePath(filePath = '') {
64
+ const norm = String(filePath || '').replace(/\\/g, '/');
65
+ return /(?:^|\/)(?:tests?|__tests__|specs?)\//i.test(norm) || /\.(?:test|spec)\.[a-z0-9]+$/i.test(norm);
66
+ }
67
+
68
+ export function countTryCatchBlocks(code = '') {
69
+ const matches = String(code || '').match(/\btry\s*\{[\s\S]*?\}\s*catch\b/g);
70
+ return matches ? matches.length : 0;
71
+ }
72
+
73
+ export function countTestAssertions(code = '') {
74
+ const text = String(code || '');
75
+ const matches = text.match(/(?:\bassert(?:\.[a-zA-Z0-9_]+|\s*\()|\bexpect\s*\(|\bt\.assert\b|\.[a-zA-Z0-9_]*should\b)/g);
76
+ return matches ? matches.length : 0;
77
+ }
78
+
79
+ /**
80
+ * Simulates the resulting file buffer BEFORE disk mutation for full-write and partial-replace tools.
81
+ */
82
+ export function simulateProposedFileBuffer(toolName = '', toolArgs = {}, currentDiskContent = '') {
83
+ const name = String(toolName || '').toLowerCase();
84
+ const args = toolArgs && typeof toolArgs === 'object' ? toolArgs : {};
85
+ const existing = String(currentDiskContent ?? '');
86
+
87
+ if (/^(write_to_file|write_file|write)$/.test(name)) {
88
+ const proposed = args.CodeContent ?? args.Content ?? args.content ?? args.newContent ?? '';
89
+ return { supported: true, isFullWrite: true, proposedContent: String(proposed) };
90
+ }
91
+
92
+ if (/^(replace_file_content|edit_file|edit)$/.test(name)) {
93
+ const target = args.TargetContent ?? args.Target ?? args.old_string ?? args.oldText;
94
+ const replacement = args.ReplacementContent ?? args.Replacement ?? args.new_string ?? args.newText ?? '';
95
+ if (typeof target === 'string' && target.length > 0 && existing.includes(target)) {
96
+ const nextBuf = existing.replace(target, () => String(replacement));
97
+ return { supported: true, isFullWrite: false, proposedContent: nextBuf, hunkText: String(replacement) };
98
+ }
99
+ if (typeof replacement === 'string') {
100
+ return { supported: true, isFullWrite: false, proposedContent: existing, hunkText: String(replacement), hunkUnmatched: true };
101
+ }
102
+ }
103
+
104
+ if (/^(multi_replace_file_content|multiedit|multi_edit)$/.test(name)) {
105
+ const chunks = Array.isArray(args.ReplacementChunks)
106
+ ? args.ReplacementChunks
107
+ : (Array.isArray(args.edits) ? args.edits : []);
108
+ let working = existing;
109
+ const hunkParts = [];
110
+ for (const chunk of chunks) {
111
+ if (!chunk || typeof chunk !== 'object') continue;
112
+ const t = chunk.TargetContent ?? chunk.Target ?? chunk.old_string;
113
+ const r = chunk.ReplacementContent ?? chunk.Replacement ?? chunk.new_string ?? '';
114
+ hunkParts.push(String(r));
115
+ if (typeof t === 'string' && t.length > 0 && working.includes(t)) {
116
+ working = working.replace(t, () => String(r));
117
+ }
118
+ }
119
+ return { supported: true, isFullWrite: false, proposedContent: working, hunkText: hunkParts.join('\n') };
120
+ }
121
+
122
+ return { supported: false, isFullWrite: false, proposedContent: existing };
123
+ }
124
+
125
+ export function evaluateDet05PreWriteIntegrity({
126
+ toolName = '',
127
+ toolArgs = {},
128
+ filePath = '',
129
+ currentDiskContent = null,
130
+ userPrompt = '',
131
+ flightMode = 'COACH',
132
+ fnvRing = [],
133
+ turn = 0
134
+ } = {}) {
135
+ const sim = simulateProposedFileBuffer(toolName, toolArgs, currentDiskContent ?? '');
136
+ if (!sim.supported) {
137
+ return { detectorId: 'DET-05', triggered: false, violations: [], ring: fnvRing };
138
+ }
139
+
140
+ const proposed = sim.proposedContent;
141
+ const checkSurface = sim.hunkUnmatched ? (sim.hunkText || '') : proposed;
142
+ const hasCleanupIntent = CLEANUP_INTENT_RE.test(String(userPrompt || ''));
143
+ const violations = [];
144
+
145
+ // 1. Lazy elision placeholder check (always active, even on new files or partial hunks)
146
+ const hadElisionBefore = typeof currentDiskContent === 'string'
147
+ && LAZY_ELISION_PATTERNS.some((re) => re.test(currentDiskContent));
148
+ if (!hadElisionBefore && LAZY_ELISION_PATTERNS.some((re) => re.test(checkSurface))) {
149
+ violations.push('LAZY_ELISION_PLACEHOLDER');
150
+ }
151
+
152
+ // 2. Compare against existing file on disk when present
153
+ if (typeof currentDiskContent === 'string' && currentDiskContent.length > 0 && !sim.hunkUnmatched) {
154
+ const beforeLinesArr = currentDiskContent.split(/\r?\n/);
155
+ const afterLinesArr = proposed.split(/\r?\n/);
156
+ const beforeLines = beforeLinesArr.length;
157
+ const afterLines = afterLinesArr.length;
158
+
159
+ if (!hasCleanupIntent) {
160
+ // Full-file regurgitation check on full-file writes (>= 300 lines with >= 90% lines unchanged)
161
+ if (sim.isFullWrite && beforeLines >= 300 && afterLines >= Math.floor(beforeLines * 0.9)) {
162
+ const beforeMap = new Map();
163
+ for (const line of beforeLinesArr) {
164
+ const trimmed = line.trim();
165
+ beforeMap.set(trimmed, (beforeMap.get(trimmed) || 0) + 1);
166
+ }
167
+ let unchangedCount = 0;
168
+ for (const line of afterLinesArr) {
169
+ const trimmed = line.trim();
170
+ const count = beforeMap.get(trimmed) || 0;
171
+ if (count > 0) {
172
+ unchangedCount++;
173
+ beforeMap.set(trimmed, count - 1);
174
+ }
175
+ }
176
+ const changedLines = beforeLines - unchangedCount;
177
+ if (unchangedCount / beforeLines >= 0.90 && changedLines <= Math.max(25, Math.floor(beforeLines * 0.10))) {
178
+ violations.push(`FULL_FILE_REGURGITATION (${unchangedCount}/${beforeLines} lines unchanged — use surgical edit_file/replace_file_content instead of rewriting the full file)`);
179
+ }
180
+ }
181
+
182
+ // > 50% shrinkage on files >= 40 lines
183
+ if (beforeLines >= 40 && afterLines < beforeLines * 0.5) {
184
+ const shrinkPct = Math.round(((beforeLines - afterLines) / beforeLines) * 100);
185
+ violations.push(`UNREQUESTED_FILE_SHRINKAGE_${shrinkPct}PCT (${beforeLines}->${afterLines} lines)`);
186
+ }
187
+
188
+ // Stripped try/catch without replacement
189
+ const beforeTry = countTryCatchBlocks(currentDiskContent);
190
+ const afterTry = countTryCatchBlocks(proposed);
191
+ if (beforeTry > 0 && afterTry < beforeTry) {
192
+ violations.push(`STRIPPED_TRY_CATCH (${beforeTry}->${afterTry})`);
193
+ }
194
+
195
+ // Deleted test assertions in test/spec files
196
+ if (isTestOrSpecFilePath(filePath)) {
197
+ const beforeAsserts = countTestAssertions(currentDiskContent);
198
+ const afterAsserts = countTestAssertions(proposed);
199
+ if (beforeAsserts > 0 && afterAsserts < beforeAsserts) {
200
+ violations.push(`DELETED_TEST_ASSERTIONS (${beforeAsserts}->${afterAsserts})`);
201
+ }
202
+ }
203
+ }
204
+ }
205
+
206
+ // 3. 6-Turn 64-bit FNV-1a Ring Buffer Flip-Flop Check (State A -> State B -> State A)
207
+ const ringEval = evaluateFnv1aRingBuffer(fnvRing, proposed, {
208
+ turn,
209
+ maxEntries: 6,
210
+ initialContent: typeof currentDiskContent === 'string' ? currentDiskContent : null
211
+ });
212
+ if (ringEval.oscillationDetected) {
213
+ violations.push(`EDIT_FLIP_FLOP_FNV1A64 (reverted to Turn ${ringEval.matchedTurn} hash ${ringEval.hash.slice(0, 8)})`);
214
+ }
215
+
216
+ if (violations.length === 0) {
217
+ return {
218
+ detectorId: 'DET-05',
219
+ triggered: false,
220
+ decision: 'allow',
221
+ violations: [],
222
+ hash: ringEval.hash,
223
+ ring: ringEval.ring
224
+ };
225
+ }
226
+
227
+ const mode = String(flightMode || 'COACH').toUpperCase();
228
+ const contractGuidance =
229
+ '3-Stage Design-by-Contract: (1) State invariant & pre-conditions, (2) Apply minimal surgical diff preserving error handling & assertions, (3) Verify post-conditions via test suite.';
230
+ const reason = `[DET-05] Pre-write integrity violation on ${filePath || 'target'}: ${violations.join('; ')}. ${contractGuidance}`;
231
+
232
+ return {
233
+ detectorId: 'DET-05',
234
+ triggered: true,
235
+ decision: mode === 'AUTO_PILOT' ? 'deny' : 'allow',
236
+ hudAlert: reason,
237
+ reason,
238
+ violations,
239
+ cleanupExempted: false,
240
+ hash: ringEval.hash,
241
+ ring: ringEval.ring
242
+ };
243
+ }
244
+
245
+ // ============================================================================
246
+ // Rank 2 (DET-06): Unmodified File Re-Read & GitClear Blind-Edit Guard
247
+ // ============================================================================
248
+
249
+ export const SOURCE_CODE_EXT_RE = /\.(mjs|js|ts|tsx|py|go|rs)$/i;
250
+ export const BLIND_EDIT_EXEMPT_PATH_RE =
251
+ /(?:^|\/)(?:migrations|docs)\/|\.(?:test|spec)\.[a-z0-9]+$|\.md$/i;
252
+
253
+ function isRangeCovered(prevStart, prevEnd, reqStart, reqEnd) {
254
+ // Full-file read previously covers any subsequent full or partial read
255
+ if (prevStart == null && prevEnd == null) return true;
256
+ // Previous read was partial, new read is full-file -> NOT covered
257
+ if (reqStart == null || reqEnd == null) return false;
258
+ const pS = Number(prevStart);
259
+ const pE = Number(prevEnd ?? Number.MAX_SAFE_INTEGER);
260
+ const rS = Number(reqStart);
261
+ const rE = Number(reqEnd);
262
+ return rS >= pS && rE <= pE;
263
+ }
264
+
265
+ export function evaluateDet06UnmodifiedReRead({
266
+ absPath = '',
267
+ sha256 = '',
268
+ mtimeMs = 0,
269
+ startLine = null,
270
+ endLine = null,
271
+ currentTurn = 1,
272
+ readLedger = [],
273
+ flightMode = 'COACH'
274
+ } = {}) {
275
+ const normPath = String(absPath || '').replace(/\\/g, '/');
276
+ const entries = Array.isArray(readLedger) ? readLedger : [];
277
+
278
+ const matchingPrior = entries.find((entry) => {
279
+ if (!entry || String(entry.absPath || '').replace(/\\/g, '/') !== normPath) return false;
280
+ const sameHash = Boolean(sha256 && entry.sha256 && sha256 === entry.sha256);
281
+ const sameMtime = !sha256 && !entry.sha256 && mtimeMs > 0 && entry.mtimeMs === mtimeMs;
282
+ if (!sameHash && !sameMtime) return false;
283
+ return isRangeCovered(entry.startLine, entry.endLine, startLine, endLine);
284
+ });
285
+
286
+ const nextEntry = {
287
+ absPath: normPath,
288
+ sha256: String(sha256 || ''),
289
+ mtimeMs: Number(mtimeMs || 0),
290
+ startLine: startLine != null ? Number(startLine) : null,
291
+ endLine: endLine != null ? Number(endLine) : null,
292
+ turnRead: Number(currentTurn || 1)
293
+ };
294
+
295
+ if (!matchingPrior) {
296
+ return {
297
+ detectorId: 'DET-06',
298
+ triggered: false,
299
+ decision: 'allow',
300
+ updatedLedger: [...entries, nextEntry]
301
+ };
302
+ }
303
+
304
+ const mode = String(flightMode || 'COACH').toUpperCase();
305
+ const reason = `[DET-06] Unmodified since Turn ${matchingPrior.turnRead}; reuse in-context buffer`;
306
+ return {
307
+ detectorId: 'DET-06',
308
+ subType: 'UNMODIFIED_REREAD',
309
+ triggered: true,
310
+ decision: mode === 'AUTO_PILOT' ? 'deny' : 'allow',
311
+ reason,
312
+ hudAlert: `${reason} (${normPath})`,
313
+ turnRead: matchingPrior.turnRead,
314
+ updatedLedger: entries
315
+ };
316
+ }
317
+
318
+ export function evaluateDet06BlindNewModule({
319
+ targetPath = '',
320
+ overwrite = false,
321
+ fileAlreadyExists = false,
322
+ discoveryCallsCount = 0,
323
+ siblingSourceFileCount = 3,
324
+ userPrompt = '',
325
+ flightMode = 'COACH',
326
+ editedFilesCount = 0,
327
+ turnCount = 1
328
+ } = {}) {
329
+ const mode = String(flightMode || 'COACH').toUpperCase();
330
+ const norm = String(targetPath || '').replace(/\\/g, '/');
331
+
332
+ if (norm && (!SOURCE_CODE_EXT_RE.test(norm) || BLIND_EDIT_EXEMPT_PATH_RE.test(norm))) {
333
+ return { detectorId: 'DET-06', triggered: false, decision: 'allow', exemptReason: 'PATH_EXEMPT' };
334
+ }
335
+
336
+ // Turn 1 blind multi-file edit check on non-exempt source files (TDD *.test.*/*.spec.* companion files exempted)
337
+ const hasSpecificAnchor = /(?:^|\s)@[A-Za-z0-9_./\\-]+\.[A-Za-z0-9]+/.test(String(userPrompt || ''));
338
+ const nonTestEditedCount = Array.isArray(arguments[0]?.editedFiles)
339
+ ? arguments[0].editedFiles.filter((p) => {
340
+ const np = String(p || '').replace(/\\/g, '/');
341
+ return SOURCE_CODE_EXT_RE.test(np) && !BLIND_EDIT_EXEMPT_PATH_RE.test(np) && !isTestOrSpecFilePath(np);
342
+ }).length
343
+ : Number(editedFilesCount || 0);
344
+
345
+ if (turnCount <= 1 && nonTestEditedCount >= 2 && Number(discoveryCallsCount) === 0 && !hasSpecificAnchor) {
346
+ const reason = `[DET-06] Blind unplanned multi-file edit on Turn 1 (${nonTestEditedCount} non-test source files modified) with 0 prior read/search discovery calls; verify existing code or create a plan first.`;
347
+ return {
348
+ detectorId: 'DET-06',
349
+ subType: 'BLIND_UNPLANNED_MULTI_EDIT',
350
+ triggered: true,
351
+ decision: mode === 'AUTO_PILOT' ? 'ask' : 'allow',
352
+ reason,
353
+ hudAlert: reason
354
+ };
355
+ }
356
+
357
+ if (!norm || overwrite === true || fileAlreadyExists === true) {
358
+ return { detectorId: 'DET-06', triggered: false, decision: 'allow' };
359
+ }
360
+ if (Number(siblingSourceFileCount) < 3) {
361
+ return { detectorId: 'DET-06', triggered: false, decision: 'allow', exemptReason: 'GREENFIELD_DIR' };
362
+ }
363
+ const baseName = norm.split('/').pop() || '';
364
+ if (baseName && String(userPrompt || '').includes(baseName)) {
365
+ return { detectorId: 'DET-06', triggered: false, decision: 'allow', exemptReason: 'USER_NAMED_FILE' };
366
+ }
367
+ if (Number(discoveryCallsCount) > 0) {
368
+ return { detectorId: 'DET-06', triggered: false, decision: 'allow' };
369
+ }
370
+
371
+ const reason = `[DET-06] Creating new module "${norm}" with 0 prior grep_search/find_by_name/list_dir calls; verify existing utilities first to prevent duplicate modules.`;
372
+ return {
373
+ detectorId: 'DET-06',
374
+ subType: 'BLIND_NEW_MODULE',
375
+ triggered: true,
376
+ decision: mode === 'AUTO_PILOT' ? 'ask' : 'allow',
377
+ reason,
378
+ hudAlert: reason
379
+ };
380
+ }
381
+
382
+ /**
383
+ * DET-07: Guard against unbounded reads of package-lock.json, pnpm-lock.yaml, and minified bundles.
384
+ * Strictly adheres to Active Source File Protection: active source files (.ts, .js, etc.) are never blocked.
385
+ */
386
+ export function evaluateDet07IgnorableFileReadGuard({
387
+ toolName = '',
388
+ targetPath = '',
389
+ startLine = null,
390
+ endLine = null,
391
+ limit = null,
392
+ flightMode = 'COACH'
393
+ } = {}) {
394
+ const name = String(toolName || '').toLowerCase();
395
+ if (!/^(view_file|read_file|read)$/i.test(name)) {
396
+ return { detectorId: 'DET-07', triggered: false, decision: 'allow' };
397
+ }
398
+ const norm = String(targetPath || '').replace(/\\/g, '/');
399
+ const isLockfileOrBundle =
400
+ /(?:^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|composer\.lock)$/i.test(norm) ||
401
+ /\.(?:min\.js|bundle\.min\.js|bundle\.js|min\.css|map)$/i.test(norm) ||
402
+ /(?:^|\/)(dist|build|\.next|out)\/.*\.(?:js|json|css)$/i.test(norm);
403
+
404
+ if (!isLockfileOrBundle) {
405
+ return { detectorId: 'DET-07', triggered: false, decision: 'allow' };
406
+ }
407
+
408
+ const isBounded =
409
+ (startLine != null && endLine != null && (Number(endLine) - Number(startLine)) <= 100) ||
410
+ (Number(limit) > 0 && Number(limit) <= 100);
411
+
412
+ if (isBounded) {
413
+ return { detectorId: 'DET-07', triggered: false, decision: 'allow' };
414
+ }
415
+
416
+ const mode = String(flightMode || 'COACH').toUpperCase();
417
+ const base = norm.split('/').pop() || 'lockfile';
418
+ const reason = `[DET-07] Unbounded read of lockfile or minified bundle ("${base}"). Dumping full lockfile/bundle wastes context. Inspect package.json or use StartLine/EndLine <= 100.`;
419
+ return {
420
+ detectorId: 'DET-07',
421
+ subType: 'LOCKFILE_OR_BUNDLE_READ_BLOCKED',
422
+ triggered: true,
423
+ decision: mode === 'AUTO_PILOT' ? 'deny' : 'allow',
424
+ reason,
425
+ hudAlert: reason
426
+ };
427
+ }
428
+
429
+ // ============================================================================
430
+ // Rank 5 (DET-04): 3-Strike Consecutive Tool Failure Breaker
431
+ // ============================================================================
432
+
433
+ export function normalizeToolTargetKey(toolName = '', toolArgs = {}) {
434
+ const name = String(toolName || '').toLowerCase().trim();
435
+ const args = toolArgs && typeof toolArgs === 'object' ? toolArgs : {};
436
+ const rawTarget = String(
437
+ args.CommandLine || args.command || args.cmd || args.Path || args.path || args.TargetFile || args.Query || args.Pattern || ''
438
+ )
439
+ .trim()
440
+ .replace(/\s+/g, () => ' ');
441
+ const prefix = rawTarget.slice(0, 48).toLowerCase();
442
+ return `${name}::${prefix || '*'}`;
443
+ }
444
+
445
+ export function evaluateDet04ConsecutiveFailureBreaker({
446
+ toolName = '',
447
+ toolArgs = {},
448
+ failureStreaks = {},
449
+ currentTurn = 1,
450
+ lastAlertTurnByKey = {},
451
+ cooldownTurns = 3,
452
+ flightMode = 'COACH'
453
+ } = {}) {
454
+ const key = normalizeToolTargetKey(toolName, toolArgs);
455
+ const streaks = failureStreaks && typeof failureStreaks === 'object' ? { ...failureStreaks } : {};
456
+ const alerts = lastAlertTurnByKey && typeof lastAlertTurnByKey === 'object' ? { ...lastAlertTurnByKey } : {};
457
+ const priorFailures = Number(streaks[key] || 0);
458
+
459
+ if (priorFailures < 3) {
460
+ return {
461
+ detectorId: 'DET-04',
462
+ triggered: false,
463
+ decision: 'allow',
464
+ key,
465
+ consecutiveFailures: priorFailures
466
+ };
467
+ }
468
+
469
+ const mode = String(flightMode || 'COACH').toUpperCase();
470
+ const reason = `[DET-04] ${priorFailures} consecutive failures on "${key}". State a root-cause hypothesis or inspect state before a 4th retry.`;
471
+ const lastTurn = alerts[key];
472
+ const inCooldown = typeof lastTurn === 'number' && (Number(currentTurn) - lastTurn) < Number(cooldownTurns);
473
+ if (!inCooldown) {
474
+ alerts[key] = Number(currentTurn);
475
+ }
476
+
477
+ return {
478
+ detectorId: 'DET-04',
479
+ triggered: true,
480
+ decision: mode === 'AUTO_PILOT' ? 'deny' : 'allow',
481
+ reason,
482
+ hudAlert: inCooldown ? null : reason,
483
+ inCooldown,
484
+ key,
485
+ consecutiveFailures: priorFailures,
486
+ lastAlertTurnByKey: alerts
487
+ };
488
+ }
489
+
490
+ export function recordToolOutcomeForDet04({
491
+ toolName = '',
492
+ toolArgs = {},
493
+ failed = false,
494
+ failureStreaks = {}
495
+ } = {}) {
496
+ const streaks = failureStreaks && typeof failureStreaks === 'object' ? { ...failureStreaks } : {};
497
+ const name = String(toolName || '').toLowerCase();
498
+
499
+ // Successful source edit resets command/test streaks so fixed code can be re-tested immediately
500
+ if (!failed && /^(write_to_file|write_file|replace_file_content|multi_replace_file_content|edit_file|edit)$/.test(name)) {
501
+ return {};
502
+ }
503
+
504
+ const key = normalizeToolTargetKey(toolName, toolArgs);
505
+ if (failed) {
506
+ streaks[key] = Number(streaks[key] || 0) + 1;
507
+ } else {
508
+ delete streaks[key];
509
+ }
510
+ return streaks;
511
+ }
512
+
513
+ // ============================================================================
514
+ // Rank 3 (DET-07): Exit-Safe CLI Output Noise Stripper & Head/Tail/Error Slicer
515
+ // ============================================================================
516
+
517
+ export const DET07_ERROR_LINE_RE =
518
+ /(?:Error|Exception|FAIL|FAILED|AssertionError|SyntaxError|error\[E|panic:|ERR!)/;
519
+
520
+ const PROGRESS_NOISE_LINE_RE =
521
+ /^(?:\s*(?:\[[\s=#>-]{4,}\]|\d{1,3}%\s*[|█▉▊▋▌▍▎▏-]+|(?:Downloading|Downloaded|Fetch|Fetching)\s+\S+\s*\.\.\.|npm\s+http\s+fetch|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏)\s*)$/i;
522
+
523
+ const PASSING_BOILERPLATE_LINE_RE =
524
+ /^\s*(?:✓|✔|PASS\s+\S+|ok\s+\d+\s+-\s+|\.\.\.\s*ok\s*$|test\s+\S+\s+\.\.\.\s+ok\s*$)/;
525
+
526
+ export function compressCliOutputPure(rawOutput = '', {
527
+ headCount = 30,
528
+ tailCount = 45,
529
+ archiveThresholdChars = 4096,
530
+ queryHint = 'node .agents/shims/ah_log_query.mjs "<term>"'
531
+ } = {}) {
532
+ const raw = String(rawOutput ?? '');
533
+ // 1. Strip ANSI CSI/OSC sequences
534
+ const noAnsi = raw.replace(
535
+ /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\].*?(?:\x07|\x1B\\))/g,
536
+ () => ''
537
+ );
538
+
539
+ // 2. Collapse \r spinner overwrites and filter pure progress/passing boilerplate
540
+ const rawLines = noAnsi.split(/\r?\n/);
541
+ const filteredLines = [];
542
+ for (const rawLine of rawLines) {
543
+ const collapsed = rawLine.includes('\r')
544
+ ? (rawLine.split('\r').filter((seg) => seg.length > 0).pop() || '')
545
+ : rawLine;
546
+ if (DET07_ERROR_LINE_RE.test(collapsed)) {
547
+ filteredLines.push(collapsed);
548
+ continue;
549
+ }
550
+ if (PROGRESS_NOISE_LINE_RE.test(collapsed) || PASSING_BOILERPLATE_LINE_RE.test(collapsed)) {
551
+ continue;
552
+ }
553
+ filteredLines.push(collapsed);
554
+ }
555
+
556
+ const exceedsThreshold = raw.length > archiveThresholdChars;
557
+ if (!exceedsThreshold && filteredLines.length <= headCount + tailCount) {
558
+ const joined = filteredLines.join('\n');
559
+ return {
560
+ detectorId: 'DET-07',
561
+ compressed: joined !== raw,
562
+ archived: false,
563
+ output: joined,
564
+ rawBytes: raw.length,
565
+ compressedBytes: joined.length,
566
+ bytesSaved: Math.max(0, raw.length - joined.length),
567
+ preservedErrorLineCount: filteredLines.filter((l) => DET07_ERROR_LINE_RE.test(l)).length
568
+ };
569
+ }
570
+
571
+ const head = filteredLines.slice(0, headCount);
572
+ const tailStartIdx = Math.max(headCount, filteredLines.length - tailCount);
573
+ const middle = filteredLines.slice(headCount, tailStartIdx);
574
+ const middleErrors = middle.filter((line) => DET07_ERROR_LINE_RE.test(line));
575
+ const tail = filteredLines.slice(tailStartIdx);
576
+
577
+ const omittedCount = Math.max(0, middle.length - middleErrors.length);
578
+ const outParts = [...head];
579
+ if (omittedCount > 0 || middleErrors.length > 0) {
580
+ outParts.push(`... [${omittedCount} noisy/passing line(s) elided; ${middleErrors.length} middle error line(s) preserved] ...`);
581
+ outParts.push(...middleErrors);
582
+ }
583
+ outParts.push(...tail);
584
+ if (exceedsThreshold && queryHint) {
585
+ outParts.push(`[DET-07 FTS5 Archive] Query full redacted log: ${queryHint}`);
586
+ }
587
+
588
+ const compressedText = outParts.join('\n');
589
+ const allErrorCount = outParts.filter((l) => DET07_ERROR_LINE_RE.test(l)).length;
590
+ return {
591
+ detectorId: 'DET-07',
592
+ compressed: true,
593
+ archived: exceedsThreshold,
594
+ output: compressedText,
595
+ rawBytes: raw.length,
596
+ compressedBytes: compressedText.length,
597
+ bytesSaved: Math.max(0, raw.length - compressedText.length),
598
+ preservedErrorLineCount: allErrorCount
599
+ };
600
+ }
601
+
602
+ // ============================================================================
603
+ // Rank 11 (DET-02): Zero-Token PreInvocation Secret & Mega-Dump Hold + Env Deny
604
+ // ============================================================================
605
+
606
+ const SENSITIVE_FILE_PATH_RE =
607
+ /(?:^|[\\/])(?:\.env(?:\.[A-Za-z0-9_.-]+)?|id_rsa|id_ed25519|id_ecdsa|authorized_keys|known_hosts)$|\.(?:pem|key|p12|pfx)$|(?:^|[\\/])\.ssh[\\/]/i;
608
+
609
+ const SAFE_ENV_TEMPLATE_RE = /\.(?:example|sample|template|dist|schema)$/i;
610
+
611
+ export function isSensitiveCredentialPath(resolvedPath = '') {
612
+ const norm = String(resolvedPath || '').replace(/\\/g, '/').trim();
613
+ if (!norm || SAFE_ENV_TEMPLATE_RE.test(norm)) return false;
614
+ return SENSITIVE_FILE_PATH_RE.test(norm);
615
+ }
616
+
617
+ export function evaluateDet02PreInvocationHold({
618
+ prompt = '',
619
+ invocationNum = 1,
620
+ flightMode = 'COACH',
621
+ megaDumpThresholdChars = 20000
622
+ } = {}) {
623
+ if (Number(invocationNum) > 1) {
624
+ return { detectorId: 'DET-02', triggered: false, fastExit: true, output: {} };
625
+ }
626
+
627
+ const text = String(prompt ?? '');
628
+ if (!text) {
629
+ return { detectorId: 'DET-02', triggered: false, fastExit: false, output: {} };
630
+ }
631
+
632
+ const allowSecret = text.includes('[ah:allow-secret]');
633
+ if (!allowSecret) {
634
+ const matchedLabels = [];
635
+ for (const def of LIVE_SECRET_DEFINITIONS) {
636
+ const re = new RegExp(def.re.source, def.re.flags);
637
+ let m;
638
+ while ((m = re.exec(text)) !== null) {
639
+ const token = m[0];
640
+ if (def.id === 'pem_private_key' || !isPlaceholderSecretValue(token)) {
641
+ matchedLabels.push(def.label);
642
+ break;
643
+ }
644
+ }
645
+ }
646
+
647
+ // High-entropy .env assignment check
648
+ const envLines = text.matchAll(/^\s*([A-Z][A-Z0-9_]{2,})\s*=\s*(['"]?)([^\s'"\r\n#]{20,})\2\s*$/gm);
649
+ for (const match of envLines) {
650
+ const key = match[1];
651
+ const val = match[3];
652
+ if (isPlaceholderSecretValue(val)) continue;
653
+ if (/^(?:PATH|HOME|PYTHONPATH|NODE_OPTIONS|DATABASE_URL)$/i.test(key) && !/:\/\/[^:]+:[^@]+@/.test(val)) {
654
+ continue;
655
+ }
656
+ if (computeShannonEntropy(val) >= 3.6) {
657
+ matchedLabels.push(`High-entropy .env assignment (${key})`);
658
+ break;
659
+ }
660
+ }
661
+
662
+ if (matchedLabels.length > 0) {
663
+ const userMessage = `[DET-02 Secret Hold] Blocked live credential paste (${matchedLabels[0]}) at 0 tokens. Store secrets in .env and reference variable names instead (or include [ah:allow-secret] for synthetic fixtures).`;
664
+ return {
665
+ detectorId: 'DET-02',
666
+ subType: 'LIVE_SECRET',
667
+ triggered: true,
668
+ blocked: true,
669
+ matchedLabels,
670
+ output: {
671
+ terminationBehavior: 'terminate',
672
+ errorMessage: { userMessage }
673
+ }
674
+ };
675
+ }
676
+ }
677
+
678
+ // Raw Mega-Dump check (>= 20,000 chars without @file or [ah:allow-paste])
679
+ const allowPaste = text.includes('[ah:allow-paste]');
680
+ const hasFileRef = /(?:^|\s)@[A-Za-z0-9_./\\-]+\.[A-Za-z0-9]+/.test(text);
681
+ if (!allowPaste && !hasFileRef && text.length >= megaDumpThresholdChars) {
682
+ const mode = String(flightMode || 'COACH').toUpperCase();
683
+ const msg = `[DET-02 Mega-Dump Hold] Raw paste is ${text.length.toLocaleString('en-US')} chars (>= ${megaDumpThresholdChars.toLocaleString('en-US')}). Save to a workspace file and reference via @file (or add [ah:allow-paste]).`;
684
+ if (mode === 'AUTO_PILOT') {
685
+ return {
686
+ detectorId: 'DET-02',
687
+ subType: 'MEGA_DUMP',
688
+ triggered: true,
689
+ blocked: true,
690
+ output: {
691
+ terminationBehavior: 'terminate',
692
+ errorMessage: { userMessage: msg }
693
+ }
694
+ };
695
+ }
696
+ return {
697
+ detectorId: 'DET-02',
698
+ subType: 'MEGA_DUMP',
699
+ triggered: true,
700
+ blocked: false,
701
+ hudHint: msg,
702
+ output: {}
703
+ };
704
+ }
705
+
706
+ return { detectorId: 'DET-02', triggered: false, fastExit: false, output: {} };
707
+ }
708
+
709
+ // ============================================================================
710
+ // Rank 10 (DET-13): Eager MCP Override & Startup Bloat Auditor
711
+ // ============================================================================
712
+
713
+ export function evaluateDet13EagerMcpAuditor({
714
+ servers = [],
715
+ eagerTokenThreshold = 15000,
716
+ bundledSkillsTokens = 0,
717
+ syncedSkillsTokens = 0,
718
+ mcpSchemaTokens = 0,
719
+ claudeMdTokens = 0,
720
+ turnsElapsed = 0,
721
+ mcpInvocations = 0
722
+ } = {}) {
723
+ const list = Array.isArray(servers) ? servers : [];
724
+ const eagerOverrides = [];
725
+ const unreachableServers = [];
726
+ let totalEagerTokens = 0;
727
+
728
+ for (const srv of list) {
729
+ if (!srv || typeof srv !== 'object') continue;
730
+ const name = String(srv.name || 'unnamed-mcp');
731
+ const isExplicitEager = srv.eager === true || srv.lazy === false || srv.loadingMode === 'eager';
732
+ const estTokens = Math.max(0, Number(srv.estimatedTokens ?? srv.tokenCount ?? (isExplicitEager ? 2500 : 0)));
733
+
734
+ if (isExplicitEager) {
735
+ eagerOverrides.push(name);
736
+ totalEagerTokens += estTokens;
737
+ } else if (Number(srv.eagerTokens) > 0) {
738
+ totalEagerTokens += Number(srv.eagerTokens);
739
+ }
740
+
741
+ if (srv.transport === 'stdio' && srv.commandReachable === false) {
742
+ unreachableServers.push(name);
743
+ }
744
+ }
745
+
746
+ const effectiveMcpTokens = Math.max(totalEagerTokens, Math.max(0, Number(mcpSchemaTokens || 0)));
747
+ const bTok = Math.max(0, Number(bundledSkillsTokens || 0));
748
+ const sTok = Math.max(0, Number(syncedSkillsTokens || 0));
749
+ const cTok = Math.max(0, Number(claudeMdTokens || 0));
750
+ const turn0StaticPrefillBreakdown = {
751
+ bundledSkillsTokens: bTok,
752
+ syncedSkillsTokens: sTok,
753
+ mcpSchemaTokens: effectiveMcpTokens,
754
+ claudeMdTokens: cTok,
755
+ totalStaticPrefillTokens: bTok + sTok + effectiveMcpTokens + cTok
756
+ };
757
+
758
+ const idleMcpHoarding5Turns =
759
+ effectiveMcpTokens >= eagerTokenThreshold &&
760
+ Number(turnsElapsed) >= 5 &&
761
+ Number(mcpInvocations) === 0;
762
+
763
+ const exceedsBudget = effectiveMcpTokens > eagerTokenThreshold;
764
+ const triggered =
765
+ eagerOverrides.length > 0 ||
766
+ unreachableServers.length > 0 ||
767
+ exceedsBudget ||
768
+ idleMcpHoarding5Turns;
769
+ const offendingServers = Array.from(new Set([...eagerOverrides, ...unreachableServers]));
770
+
771
+ const parts = [];
772
+ if (eagerOverrides.length > 0) {
773
+ parts.push(`explicit "eager": true override on [${eagerOverrides.join(', ')}]`);
774
+ }
775
+ if (unreachableServers.length > 0) {
776
+ parts.push(`unreachable/orphaned stdio binary on [${unreachableServers.join(', ')}]`);
777
+ }
778
+ if (exceedsBudget) {
779
+ parts.push(`eager schema overhead ${effectiveMcpTokens.toLocaleString('en-US')} tok exceeds ${eagerTokenThreshold.toLocaleString('en-US')} tok`);
780
+ }
781
+ if (idleMcpHoarding5Turns) {
782
+ parts.push(`0 MCP invocations across ${turnsElapsed} turns (set ENABLE_TOOL_SEARCH=auto:5 or lazy loading; Turn-0 static prefill = ${turn0StaticPrefillBreakdown.totalStaticPrefillTokens.toLocaleString('en-US')} tok)`);
783
+ }
784
+
785
+ return {
786
+ detectorId: 'DET-13',
787
+ subType: idleMcpHoarding5Turns ? 'IDLE_MCP_HOARDING_5_TURNS' : 'EAGER_MCP_AUDIT',
788
+ triggered,
789
+ eagerOverrides,
790
+ unreachableServers,
791
+ offendingServers,
792
+ totalEagerTokens: effectiveMcpTokens,
793
+ exceedsBudget,
794
+ idleMcpHoarding5Turns,
795
+ recommendedEnv: idleMcpHoarding5Turns ? 'ENABLE_TOOL_SEARCH=auto:5' : null,
796
+ turn0StaticPrefillBreakdown,
797
+ hudAlert: triggered
798
+ ? `[DET-13 MCP Audit] Antigravity 1.3.3+ defaults to lazy MCP loading, but detected ${parts.join('; ')}.`
799
+ : null
800
+ };
801
+ }
802
+
803
+ export const evaluateDet09McpSchemaTax = evaluateDet13EagerMcpAuditor;
804
+
805
+ // ============================================================================
806
+ // Rank 6 (DET-06B): Lean Flash Subagent Search Offloader
807
+ // ============================================================================
808
+
809
+ const SEARCH_OR_READ_TOOL_RE = /^(view_file|read_file|grep_search|find_by_name|list_dir|glob|grep)$/i;
810
+ const WRITE_OR_EDIT_TOOL_RE = /^(write_to_file|write_file|replace_file_content|multi_replace_file_content|edit_file|edit|multiedit)$/i;
811
+
812
+ export function evaluateDet06bFlashScoutOffloader({
813
+ toolName = '',
814
+ consecutiveReadSearchCount = 0,
815
+ activeModel = '',
816
+ cachedTokens = 0,
817
+ isSubagent = false,
818
+ flightMode = 'COACH'
819
+ } = {}) {
820
+ if (isSubagent) {
821
+ return { detectorId: 'DET-06B', triggered: false, decision: 'allow', nextCount: consecutiveReadSearchCount };
822
+ }
823
+ if (WRITE_OR_EDIT_TOOL_RE.test(toolName)) {
824
+ return { detectorId: 'DET-06B', triggered: false, decision: 'allow', nextCount: 0 };
825
+ }
826
+ if (!SEARCH_OR_READ_TOOL_RE.test(toolName)) {
827
+ return { detectorId: 'DET-06B', triggered: false, decision: 'allow', nextCount: consecutiveReadSearchCount };
828
+ }
829
+
830
+ const nextCount = Number(consecutiveReadSearchCount || 0) + 1;
831
+ const modelNorm = String(activeModel || '').toLowerCase();
832
+ const isWarmFrontier = (modelNorm.includes('gemini-4-carbon') || modelNorm.includes('gemini-4-argon'))
833
+ && Number(cachedTokens) > 3529;
834
+
835
+ if (!isWarmFrontier || nextCount < 7) {
836
+ return { detectorId: 'DET-06B', triggered: false, decision: 'allow', nextCount };
837
+ }
838
+
839
+ const mode = String(flightMode || 'COACH').toUpperCase();
840
+ const reason = `[DET-06B] Unedited read/search call #${nextCount} on warm ${activeModel} (${cachedTokens} cached tok). Delegate repository scouting to @ah-flash-scout (<200-tok File:Line summary) to protect main-thread KV cache.`;
841
+ return {
842
+ detectorId: 'DET-06B',
843
+ triggered: true,
844
+ decision: mode === 'AUTO_PILOT' ? 'deny' : 'allow',
845
+ reason,
846
+ hudAlert: reason,
847
+ nextCount
848
+ };
849
+ }
850
+
851
+ // ============================================================================
852
+ // Rank 7 (DET-08): KV-Cache Gravity & Between-Turn Effort Router
853
+ // ============================================================================
854
+
855
+ export const WARM_CACHE_GRAVITY_FLOOR_TOKENS = 3529;
856
+
857
+ export function resolveCarbonPricingForTimestamp(timestampUtc = '2026-11-10T00:00:00Z') {
858
+ const ts = Date.parse(String(timestampUtc || '2026-11-10T00:00:00Z'));
859
+ const stepTs = Date.parse('2026-12-01T00:00:00Z');
860
+ if (!Number.isNaN(ts) && ts >= stepTs) {
861
+ return { inputPer1M: 4.00, cachedReadPer1M: 0.20, outputPer1M: 20.00, window: 'post_2026_12_01' };
862
+ }
863
+ return { inputPer1M: 2.00, cachedReadPer1M: 0.10, outputPer1M: 10.00, window: 'pre_2026_12_01' };
864
+ }
865
+
866
+ export function evaluateDet08CacheGravityAndEffort({
867
+ turnCount = 0,
868
+ cachedTokens = 0,
869
+ activeModel = 'gemini-4-carbon',
870
+ activeEffort = 'high',
871
+ isSimpleTask = false,
872
+ recentTestFailures = 0,
873
+ det05Oscillation = false,
874
+ dismissalStrikes = 0,
875
+ timestampUtc = '2026-11-10T00:00:00Z'
876
+ } = {}) {
877
+ const cached = Math.max(0, Number(cachedTokens || 0));
878
+ const turn = Math.max(0, Number(turnCount || 0));
879
+ const modelNorm = String(activeModel || '').toLowerCase();
880
+ const isFrontier = modelNorm.includes('carbon') || modelNorm.includes('argon');
881
+ const carbonRates = resolveCarbonPricingForTimestamp(timestampUtc);
882
+ const flashColdInputPer1M = 0.75;
883
+
884
+ // Lane 1: Turn 0-2 (cachedTokens <= 3529) -> route simple single-file/typo tasks to gemini-3.8-flash
885
+ if (turn <= 2 && cached <= WARM_CACHE_GRAVITY_FLOOR_TOKENS) {
886
+ if (isFrontier && isSimpleTask) {
887
+ return {
888
+ detectorId: 'DET-08',
889
+ lane: 'TURN_0_2_COLD_FLASH_ROUTE',
890
+ triggered: true,
891
+ keepSameModel: false,
892
+ recommendedModel: 'gemini-3.8-flash',
893
+ recommendedEffort: 'low',
894
+ chipLabel: '[Route: gemini-3.8-flash (cold Turn 0-2 simple task)]',
895
+ carbonRates
896
+ };
897
+ }
898
+ return {
899
+ detectorId: 'DET-08',
900
+ lane: 'TURN_0_2_NOMINAL',
901
+ triggered: false,
902
+ keepSameModel: true,
903
+ recommendedModel: activeModel,
904
+ recommendedEffort: activeEffort,
905
+ carbonRates
906
+ };
907
+ }
908
+
909
+ // Lane 2: Mid-Session (cachedTokens > 3529) -> NEVER switch main-thread model ID to Flash!
910
+ const hysteresisLocked = Number(recentTestFailures) >= 2 || Boolean(det05Oscillation);
911
+ const mutedByStrikes = Number(dismissalStrikes) >= 3;
912
+ const coldFlashInputCostRatio = Number((flashColdInputPer1M / carbonRates.cachedReadPer1M).toFixed(2));
913
+ const canDownshiftEffort =
914
+ isFrontier &&
915
+ String(activeEffort || '').toLowerCase() !== 'low' &&
916
+ !hysteresisLocked &&
917
+ !mutedByStrikes &&
918
+ isSimpleTask;
919
+
920
+ return {
921
+ detectorId: 'DET-08',
922
+ lane: 'MID_SESSION_SAME_MODEL_EFFORT',
923
+ triggered: canDownshiftEffort,
924
+ keepSameModel: true,
925
+ forbidFlashModelSwitch: true,
926
+ coldFlashInputPenaltyMultiplier: coldFlashInputCostRatio,
927
+ hysteresisLocked,
928
+ mutedByStrikes,
929
+ recommendedModel: activeModel,
930
+ recommendedEffort: canDownshiftEffort ? 'low' : activeEffort,
931
+ outputBurnReductionPct: 68,
932
+ chipLabel: canDownshiftEffort
933
+ ? '[Downshift: /effort low (-68% output burn, keeps warm cache)]'
934
+ : null,
935
+ carbonRates
936
+ };
937
+ }
938
+
939
+ // ============================================================================
940
+ // Rank 12 (DET-16 & DET-20): 80% Hybrid Quota Fan-Out Throttle & Vision Quirk
941
+ // ============================================================================
942
+
943
+ export function evaluateDet16HybridQuotaThrottle({
944
+ baseQuotaUsedPct = 0,
945
+ activeSubagentsCount = 0,
946
+ requestedWorkers = 1,
947
+ subagentTokens = 0,
948
+ subagentTurns = 0,
949
+ maxSubagentTokens = 40000,
950
+ maxSubagentTurns = 12
951
+ } = {}) {
952
+ const usedPct = Math.max(0, Number(baseQuotaUsedPct || 0));
953
+
954
+ if (Number(subagentTokens) > maxSubagentTokens || Number(subagentTurns) > maxSubagentTurns) {
955
+ return {
956
+ detectorId: 'DET-16',
957
+ triggered: true,
958
+ subType: 'SUBAGENT_BUDGET_CAP',
959
+ decision: 'deny',
960
+ reason: `[DET-16] Subagent run exceeded per-worker budget (${subagentTokens}/${maxSubagentTokens} tok, ${subagentTurns}/${maxSubagentTurns} turns). Return compact summary now.`
961
+ };
962
+ }
963
+
964
+ if (usedPct >= 90) {
965
+ return {
966
+ detectorId: 'DET-16',
967
+ triggered: true,
968
+ subType: 'HYBRID_QUOTA_90_HARD_ASK',
969
+ decision: 'ask',
970
+ maxParallelWorkers: 1,
971
+ reason: `[DET-16] Base Quota is at ${usedPct}% (>=90%). Confirm before spawning subagents/swarms to avoid triggering a 4-to-7-day (168h) Hybrid Quota lockout.`
972
+ };
973
+ }
974
+
975
+ if (usedPct >= 80 && (Number(requestedWorkers) > 1 || Number(activeSubagentsCount) >= 1)) {
976
+ return {
977
+ detectorId: 'DET-16',
978
+ triggered: true,
979
+ subType: 'HYBRID_QUOTA_80_SINGLE_WORKER_CAP',
980
+ decision: 'deny',
981
+ maxParallelWorkers: 1,
982
+ reason: `[DET-16] Base Quota is at ${usedPct}% (>=80% throttle). Capped at 1 sequential subagent worker (requested ${requestedWorkers}, active ${activeSubagentsCount}) to prevent 168h lockout.`
983
+ };
984
+ }
985
+
986
+ return {
987
+ detectorId: 'DET-16',
988
+ triggered: false,
989
+ decision: 'allow',
990
+ maxParallelWorkers: usedPct >= 80 ? 1 : 4
991
+ };
992
+ }
993
+
994
+ export function evaluateDet20VisionOverageGuard({
995
+ quirkConfig = { enabled: true },
996
+ aiCreditOveragesActive = false,
997
+ hasImageAttachment = false,
998
+ consecutiveImageTurns = 0,
999
+ promptText = '',
1000
+ imageCount = 0,
1001
+ messages = [],
1002
+ contentBlocks = [],
1003
+ tokensPerImage = 1600
1004
+ } = {}) {
1005
+ // Inspect historical messages & contentBlocks for base64 / image blocks
1006
+ let base64ImageBlockCount = 0;
1007
+ let cumulativeVisionTaxTokens = 0;
1008
+ const msgList = Array.isArray(messages) ? messages : [];
1009
+ const totalMsgLen = msgList.length;
1010
+
1011
+ for (let i = 0; i < totalMsgLen; i++) {
1012
+ const msg = msgList[i];
1013
+ const blocks = Array.isArray(msg?.content) ? msg.content : [];
1014
+ let msgImages = 0;
1015
+ for (const b of blocks) {
1016
+ if (
1017
+ b &&
1018
+ (b.type === 'image' ||
1019
+ b.type === 'image_url' ||
1020
+ b?.source?.type === 'base64' ||
1021
+ String(b?.mime_type || b?.mimeType || '').startsWith('image/'))
1022
+ ) {
1023
+ base64ImageBlockCount += 1;
1024
+ msgImages += 1;
1025
+ }
1026
+ }
1027
+ if (msgImages > 0) {
1028
+ // Each historical image block is re-sent on every subsequent turn (`totalMsgLen - i` turns)
1029
+ const turnsResent = Math.max(1, Math.ceil((totalMsgLen - i) / 2));
1030
+ cumulativeVisionTaxTokens += msgImages * Number(tokensPerImage || 1600) * turnsResent;
1031
+ }
1032
+ }
1033
+
1034
+ if (Array.isArray(contentBlocks)) {
1035
+ for (const b of contentBlocks) {
1036
+ if (b && (b.type === 'image' || b?.source?.type === 'base64')) {
1037
+ base64ImageBlockCount += 1;
1038
+ cumulativeVisionTaxTokens += Number(tokensPerImage || 1600);
1039
+ }
1040
+ }
1041
+ }
1042
+
1043
+ const effectiveHasImage = Boolean(hasImageAttachment || base64ImageBlockCount > 0 || imageCount > 0);
1044
+ const effectiveImageCount = Math.max(Number(imageCount || 0), base64ImageBlockCount);
1045
+ if (cumulativeVisionTaxTokens === 0 && effectiveImageCount > 0) {
1046
+ const resendFactor = Math.max(1, Number(consecutiveImageTurns || 1));
1047
+ cumulativeVisionTaxTokens = effectiveImageCount * Number(tokensPerImage || 1600) * resendFactor;
1048
+ }
1049
+
1050
+ if (!quirkConfig?.enabled || !effectiveHasImage) {
1051
+ return {
1052
+ detectorId: 'DET-20',
1053
+ triggered: false,
1054
+ base64ImageBlockCount,
1055
+ cumulativeVisionTaxTokens: 0
1056
+ };
1057
+ }
1058
+
1059
+ // 1. Google HTTP 400 crash during credit overages
1060
+ if (aiCreditOveragesActive) {
1061
+ const message =
1062
+ quirkConfig.warningMessage ||
1063
+ '[DET-20 Vision Overage Quirk] AI Credit Overages are active and an image/screenshot is attached. Remove image attachments or switch to a text-only turn to avoid Google HTTP 400 Bad Request (Unable to process input image).';
1064
+ return {
1065
+ detectorId: 'DET-20',
1066
+ subType: 'VISION_OVERAGE_HTTP400',
1067
+ triggered: true,
1068
+ base64ImageBlockCount,
1069
+ cumulativeVisionTaxTokens,
1070
+ warningMessage: message,
1071
+ ephemeralMessage: message
1072
+ };
1073
+ }
1074
+
1075
+ // 2. Normal billing vision/screenshot abuse on text-based CSS/console errors or multi-turn Base64 accumulation
1076
+ const isTextDebuggablePrompt =
1077
+ /\b(TypeError|ReferenceError|SyntaxError|console\.error|stack\s*trace|padding|margin|z-index|flex|grid|css|align|overflow|dom|selector|button|headless|playwright|puppeteer)\b/i.test(
1078
+ promptText
1079
+ );
1080
+ if ((consecutiveImageTurns >= 2 || effectiveImageCount >= 2) && (isTextDebuggablePrompt || base64ImageBlockCount >= 2)) {
1081
+ const message = `[DET-20 Vision Token Drain Advisory] ${effectiveImageCount} screenshot/image blocks accumulated (~${cumulativeVisionTaxTokens.toLocaleString('en-US')} cumulative vision tokens) for text/DOM/CSS debugging. Paste console logs or DOM/CSS rules as text instead.`;
1082
+ return {
1083
+ detectorId: 'DET-20',
1084
+ subType: 'VISION_SCREENSHOT_ABUSE',
1085
+ triggered: true,
1086
+ base64ImageBlockCount,
1087
+ cumulativeVisionTaxTokens,
1088
+ warningMessage: message,
1089
+ ephemeralMessage: message
1090
+ };
1091
+ }
1092
+
1093
+ return {
1094
+ detectorId: 'DET-20',
1095
+ triggered: false,
1096
+ base64ImageBlockCount,
1097
+ cumulativeVisionTaxTokens
1098
+ };
1099
+ }
1100
+
1101
+ // ============================================================================
1102
+ // Rank 4 (DET-17) & Rank 8 (DET-10) & Rank 9 (RSI-01)
1103
+ // ============================================================================
1104
+
1105
+ export function evaluateDet17CascadeCheckpoints({
1106
+ currentTokens = 0,
1107
+ ceilingTokens = CASCADE_COMPACTION_CEILING_TOKENS,
1108
+ crossedBands = [],
1109
+ cacheHitRatio = 0
1110
+ } = {}) {
1111
+ const tok = Math.max(0, Number(currentTokens || 0));
1112
+ const crossed = new Set(Array.isArray(crossedBands) ? crossedBands : []);
1113
+ const newlyCrossed = [];
1114
+
1115
+ for (const band of CASCADE_CHECKPOINT_BANDS) {
1116
+ if (tok >= band.tokens && !crossed.has(band.label)) {
1117
+ newlyCrossed.push(band);
1118
+ crossed.add(band.label);
1119
+ }
1120
+ }
1121
+
1122
+ const suppressPrematureCompact = Number(cacheHitRatio) > 0.96 && tok < 50000;
1123
+ return {
1124
+ detectorId: 'DET-17',
1125
+ ceilingTokens,
1126
+ newlyCrossedBands: newlyCrossed,
1127
+ shouldWriteStateBaton: newlyCrossed.length > 0,
1128
+ crossedBands: Array.from(crossed),
1129
+ suppressPrematureCompact
1130
+ };
1131
+ }
1132
+
1133
+ export function evaluateDet10IdleCacheWatchdog({
1134
+ elapsedSeconds = 0,
1135
+ ttlWindowSeconds = 300,
1136
+ planDefaultTtlSeconds = null,
1137
+ aiCreditOveragesActive = false,
1138
+ isSubagent = false,
1139
+ billingMode = 'subscription',
1140
+ cachedTokens = 0,
1141
+ workspaceEditsOccurred = false
1142
+ } = {}) {
1143
+ const force5mDrop =
1144
+ Boolean(aiCreditOveragesActive) ||
1145
+ Boolean(isSubagent) ||
1146
+ String(billingMode || '').toLowerCase() === 'api';
1147
+ const effectiveTtlSeconds =
1148
+ planDefaultTtlSeconds != null
1149
+ ? (force5mDrop ? 300 : Math.max(60, Number(planDefaultTtlSeconds)))
1150
+ : Math.max(1, Number(ttlWindowSeconds ?? 300));
1151
+ const ttlDroppedTo5m =
1152
+ planDefaultTtlSeconds != null &&
1153
+ Number(planDefaultTtlSeconds) > 300 &&
1154
+ effectiveTtlSeconds === 300;
1155
+
1156
+ const elapsed = Math.max(0, Number(elapsedSeconds || 0));
1157
+ const cacheExpired = elapsed > effectiveTtlSeconds;
1158
+ const rem = Math.max(0, Number((effectiveTtlSeconds - elapsed).toFixed(1)));
1159
+ const mins = Math.floor(rem / 60);
1160
+ const secs = Math.floor(rem % 60);
1161
+ const tierPrefix = effectiveTtlSeconds >= 3600 ? 'Est. 1h Cache' : 'Est. 5m Implicit Cache';
1162
+ const label = `${tierPrefix}: ${mins}m ${String(secs).padStart(2, '0')}s`;
1163
+ const pulseAmber = rem > 0 && rem <= 45 && Number(cachedTokens) >= 25000 && Boolean(workspaceEditsOccurred);
1164
+
1165
+ return {
1166
+ detectorId: 'DET-10',
1167
+ subType: cacheExpired ? 'CACHE_TTL_EXPIRED' : (pulseAmber ? 'PRE_EXPIRY_PULSE' : 'NOMINAL'),
1168
+ effectiveTtlSeconds,
1169
+ ttlDroppedTo5m,
1170
+ cacheExpired,
1171
+ remainingSeconds: rem,
1172
+ label,
1173
+ pulseAmber,
1174
+ shouldFlushColdResumeBaton: pulseAmber || (cacheExpired && Number(cachedTokens) >= 25000)
1175
+ };
1176
+ }
1177
+
1178
+ /**
1179
+ * Pure zero-I/O evaluator for Silent Prefix Mutations (`Sim 01` & `Sim 16`):
1180
+ * - `LATE_MCP_CONNECT`: MCP server count or schema hash changing after Turn 1
1181
+ * - `MEMORY_MD_MID_THREAD_MUTATION`: Mid-thread `MEMORY.md` hash/byte change (up to 25KB)
1182
+ * - `IDE_STATE_PREFIX_MUTATION`: Dynamic IDE state (active tab, line selection, Problems tab) injected into system prefix instead of user-turn tail
1183
+ * - `LOOKBACK_WINDOW_DELETION`: Message deletion inside 20-block lookback window shifting cached suffix
1184
+ */
1185
+ export function evaluateSilentPrefixMutations({
1186
+ turnCount = 1,
1187
+ prevMcpServerCount = null,
1188
+ currMcpServerCount = null,
1189
+ prevMcpSchemaHash = null,
1190
+ currMcpSchemaHash = null,
1191
+ prevMemoryMdHash = null,
1192
+ currMemoryMdHash = null,
1193
+ prevMemoryMdBytes = null,
1194
+ currMemoryMdBytes = null,
1195
+ ideStateInSystemPrefix = false,
1196
+ prevIdePrefixHash = null,
1197
+ currIdePrefixHash = null,
1198
+ prevMessageIds = null,
1199
+ currMessageIds = null,
1200
+ tokensPerMessage = 5000,
1201
+ cachedTokens = 0
1202
+ } = {}) {
1203
+ const turn = Math.max(1, Number(turnCount || 1));
1204
+ const subTypes = [];
1205
+ const details = [];
1206
+ let shiftedSuffixTokens = 0;
1207
+
1208
+ if (turn > 1) {
1209
+ const mcpCountChanged =
1210
+ prevMcpServerCount != null &&
1211
+ currMcpServerCount != null &&
1212
+ Number(prevMcpServerCount) !== Number(currMcpServerCount);
1213
+ const mcpHashChanged =
1214
+ Boolean(prevMcpSchemaHash && currMcpSchemaHash) &&
1215
+ String(prevMcpSchemaHash) !== String(currMcpSchemaHash);
1216
+ if (mcpCountChanged || mcpHashChanged) {
1217
+ subTypes.push('LATE_MCP_CONNECT');
1218
+ details.push(
1219
+ `Mid-session MCP server/schema change at Turn ${turn} (${prevMcpServerCount ?? '?'} -> ${currMcpServerCount ?? '?'} servers)`
1220
+ );
1221
+ }
1222
+
1223
+ const memHashChanged =
1224
+ Boolean(prevMemoryMdHash && currMemoryMdHash) &&
1225
+ String(prevMemoryMdHash) !== String(currMemoryMdHash);
1226
+ const memBytesChanged =
1227
+ prevMemoryMdBytes != null &&
1228
+ currMemoryMdBytes != null &&
1229
+ Number(prevMemoryMdBytes) !== Number(currMemoryMdBytes);
1230
+ if (memHashChanged || memBytesChanged) {
1231
+ subTypes.push('MEMORY_MD_MID_THREAD_MUTATION');
1232
+ const kb = currMemoryMdBytes != null ? `${(Number(currMemoryMdBytes) / 1024).toFixed(1)}KB` : 'updated';
1233
+ details.push(`Mid-thread MEMORY.md mutation (${kb}) invalidated static system prefix`);
1234
+ }
1235
+
1236
+ const ideHashChanged =
1237
+ Boolean(prevIdePrefixHash && currIdePrefixHash) &&
1238
+ String(prevIdePrefixHash) !== String(currIdePrefixHash);
1239
+ if (Boolean(ideStateInSystemPrefix) || ideHashChanged) {
1240
+ subTypes.push('IDE_STATE_PREFIX_MUTATION');
1241
+ details.push(
1242
+ 'Dynamic IDE state (active tab / highlighted lines / Problems diagnostics) injected into system prefix instead of user-turn tail'
1243
+ );
1244
+ }
1245
+ }
1246
+
1247
+ if (Array.isArray(prevMessageIds) && Array.isArray(currMessageIds) && prevMessageIds.length > 0) {
1248
+ const currSet = new Set(currMessageIds);
1249
+ let firstDeletedIdx = -1;
1250
+ let deletedCount = 0;
1251
+ for (let i = 0; i < prevMessageIds.length; i++) {
1252
+ if (!currSet.has(prevMessageIds[i])) {
1253
+ if (firstDeletedIdx === -1) firstDeletedIdx = i;
1254
+ deletedCount += 1;
1255
+ }
1256
+ }
1257
+ if (firstDeletedIdx !== -1) {
1258
+ const remainingAfterDeletion = Math.max(0, prevMessageIds.length - firstDeletedIdx - deletedCount);
1259
+ const tokPerMsg = Array.isArray(tokensPerMessage)
1260
+ ? 0
1261
+ : Math.max(1, Number(tokensPerMessage || 5000));
1262
+ if (Array.isArray(tokensPerMessage)) {
1263
+ for (let j = firstDeletedIdx + deletedCount; j < prevMessageIds.length; j++) {
1264
+ shiftedSuffixTokens += Math.max(0, Number(tokensPerMessage[j] || 0));
1265
+ }
1266
+ } else {
1267
+ shiftedSuffixTokens = remainingAfterDeletion * tokPerMsg;
1268
+ }
1269
+ subTypes.push('LOOKBACK_WINDOW_DELETION');
1270
+ details.push(
1271
+ `Deleted ${deletedCount} historical message(s) starting at index ${firstDeletedIdx}, shifting ${shiftedSuffixTokens.toLocaleString('en-US')} suffix tokens outside 20-block lookback window`
1272
+ );
1273
+ }
1274
+ }
1275
+
1276
+ const triggered = subTypes.length > 0;
1277
+ const detectorId = subTypes.includes('LOOKBACK_WINDOW_DELETION')
1278
+ ? 'DET-26'
1279
+ : subTypes.includes('LATE_MCP_CONNECT')
1280
+ ? 'DET-25'
1281
+ : 'DET-09';
1282
+
1283
+ return {
1284
+ detectorId,
1285
+ triggered,
1286
+ subTypes,
1287
+ shiftedSuffixTokens: shiftedSuffixTokens || (triggered ? Math.max(0, Number(cachedTokens || 0)) : 0),
1288
+ details,
1289
+ reason: triggered ? `[${detectorId} Silent Prefix Mutation] ${details.join('; ')}.` : null
1290
+ };
1291
+ }
1292
+
1293
+ export function evaluateRsi01PrefixDietAndSkillFault({
1294
+ staticRulesTokens = 0,
1295
+ staticRulesOverheadCeiling = 8000,
1296
+ domainSections = [],
1297
+ lastExecutedSkill = null,
1298
+ userCorrectionText = '',
1299
+ validatedDomainInstinctsCount = 0
1300
+ } = {}) {
1301
+ const prefixBloatExceeded = Number(staticRulesTokens) > Number(staticRulesOverheadCeiling);
1302
+ const proposedExtractions = prefixBloatExceeded
1303
+ ? (Array.isArray(domainSections) ? domainSections : []).map((sec) => ({
1304
+ domain: String(sec.domain || sec).toLowerCase().replace(/[^a-z0-9-]+/g, () => '-'),
1305
+ targetSkillPath: `.agents/skills/${String(sec.domain || sec).toLowerCase().replace(/[^a-z0-9-]+/g, () => '-')}/SKILL.md`,
1306
+ estimatedTokensSaved: Number(sec.tokens || 1200)
1307
+ }))
1308
+ : [];
1309
+
1310
+ let routedDeltaTarget = null;
1311
+ if (userCorrectionText && String(userCorrectionText).trim()) {
1312
+ if (lastExecutedSkill) {
1313
+ const cleanSkill = String(lastExecutedSkill).replace(/[^a-zA-Z0-9_-]/g, () => '');
1314
+ routedDeltaTarget = `.agents/skills/${cleanSkill}/SKILL.md`;
1315
+ } else {
1316
+ routedDeltaTarget = 'INSTINCT_QUEUE';
1317
+ }
1318
+ }
1319
+
1320
+ const canSynthesizeNewSkillDraft = Number(validatedDomainInstinctsCount) >= 5;
1321
+ return {
1322
+ detectorId: 'RSI-01',
1323
+ prefixBloatExceeded,
1324
+ proposedExtractions,
1325
+ routedDeltaTarget,
1326
+ mutatesGlobalAgentsMdDirectly: false,
1327
+ canSynthesizeNewSkillDraft,
1328
+ recursiveSubagentCritiqueAllowed: false,
1329
+ requiresExplicitOneClickDiffApproval: true,
1330
+ gatedByTurnZeroGate: true
1331
+ };
1332
+ }
1333
+
1334
+ export { fnv1a64Hex, redactSecretsPure };
1335
+ export {
1336
+ RELAY_STATES,
1337
+ matchRelayHardNegativeFilter,
1338
+ countRefereeSyntaxMarkers,
1339
+ evaluateScopeBrake,
1340
+ evaluateRelayBreaker,
1341
+ evaluateTwoStageSightseeingIntercept
1342
+ } from './prompt_hygiene_governor.mjs';