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,622 @@
1
+ /**
2
+ * @file src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs
3
+ * Prompt Hygiene Governor (v4.1 Phase 1): Scope Brake ('vague-prompt-rubric')
4
+ * and Relay Breaker ('relay-breaker').
5
+ *
6
+ * Strictly zero `node:*` imports (Claude Code Mod Law 4 compliant).
7
+ * Runs in memory in < 1 ms using Highbeam's local sidecar/breaker ledger
8
+ * with zero background LLM calls and zero synchronous `git status` spawns.
9
+ */
10
+
11
+ export const RELAY_STATES = Object.freeze({
12
+ IDLE: 'Idle',
13
+ CANDIDATE: 'Candidate',
14
+ ARMED: 'Armed',
15
+ FINAL_PASS: 'Final Pass',
16
+ LOCKED: 'Locked'
17
+ });
18
+
19
+ const AFFIRMATIVE_OR_CONTINUATION_RE =
20
+ /^(?:yes|y|yep|yeah|ok|okay|sure|ship\s+it|go\s+ahead|proceed|continue|approved|approve|lgtm|do\s+it|sounds\s+good|looks\s+good|run\s+it|commit(?:\s+it)?|push(?:\s+it)?|next|thanks|thank\s+you)[.!?\s]*$/i;
21
+
22
+ const AUTONOMOUS_PROVENANCE_RE =
23
+ /^(?:scheduled|cron|loop|subagent|agent_callback|callback|auto|autonomous|background|system|hook|task_notification|wake)$/i;
24
+
25
+ const VAGUE_UNANCHORED_IMPERATIVE_RE =
26
+ /\b(?:make\s+(?:it|this)\s+(?:better|faster|cleaner|nicer|work)|optimize\s+(?:it|this)|clean\s+(?:this|it)\s+up|speed\s+(?:this|it)\s+up|(?:still\s+)?(?:broken|not\s+working|failing|buggy)|fix\s+(?:it|this|bugs|errors|everything)|improve\s+(?:it|this|performance|code)|refactor\s+(?:it|this)|polish\s+(?:it|this)|update\s+(?:it|this))\b/i;
27
+
28
+ const CONCRETE_FILE_OR_PATH_RE =
29
+ /(?:^|\s)@[A-Za-z0-9_./\\-]+|\b[A-Za-z0-9_.-]+\.(?:mjs|cjs|js|ts|tsx|jsx|py|go|rs|rb|java|kt|cs|cpp|c|h|css|scss|html|json|ya?ml|toml|md|sql|sh|ps1)\b|(?:^|[\s'"`(])(?:src|test|tests|lib|app|packages|hooks|scripts|sidecars|bin|config|docs)[\\/][A-Za-z0-9_./\\-]+/i;
30
+
31
+ const CONCRETE_SYMBOL_OR_METRIC_RE =
32
+ /`[^`]{2,}`|\b[a-z][a-zA-Z0-9]+_[a-zA-Z0-9_]+\b|\b[a-z][a-z0-9]*[A-Z][A-Za-z0-9]+\b|\b[A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*\b|\b[a-zA-Z_]\w*\s*\([^)]*\)|\b(?:line|ln)\s+\d+\b|\b\d+(?:\.\d+)?\s*(?:ms|s|sec|mb|kb|gb|%|tok|tokens|fps|rps|qps)\b|\b(?:DET|ISS|RSI|SIM)-\d+\b|\b(?:TypeError|ReferenceError|SyntaxError|RangeError|ENOENT|EACCES|ECONNREFUSED|ERR_[A-Z0-9_]+|HTTP\s+[45]\d\d)\b|\b(?:[Uu][Ii]\s+alignment|alignment|margin|padding|z-index|flexbox|grid\s+layout|tooltip|dropdown|sidebar|navbar|modal|button|input|form|card|table|header|footer|panel|drawer|badge|icon|color|font|border|layout|style|css|html|test|tests|spec|build|lint|typecheck|commit|branch|merge|hook|daemon|server|client|router|cache|token|prompt|rule|config|package|readme|console)\b/;
33
+
34
+ // Hard negative filters for Relay Breaker (3.1.4): stack traces, compiler errors, unified diffs, log timestamps, SQL, JSON/CSV payloads
35
+ const HARD_NEGATIVE_STACK_TRACE_RE =
36
+ /(?:^\s*at\s+[^\r\n]+\([^\r\n]+:\d+:\d+\)|Traceback\s+\(most\s+recent\s+call\s+last\):|^\s*File\s+"[^"]+",\s+line\s+\d+|panic:\s+runtime\s+error)/m;
37
+
38
+ const HARD_NEGATIVE_COMPILER_ERROR_RE =
39
+ /(?:\berror\s+TS\d{3,5}:|\b(?:SyntaxError|TypeError|ReferenceError|RangeError|AssertionError):|^\s*error\[E\d{4}\]:|\bFAIL\s+[^\r\n]+\.(?:test|spec)\.)/m;
40
+
41
+ const HARD_NEGATIVE_UNIFIED_DIFF_RE =
42
+ /(?:^diff\s+--git\s+a\/|^---\s+a\/|^\+\+\+\s+b\/|^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@)/m;
43
+
44
+ const HARD_NEGATIVE_LOG_TIMESTAMP_RE =
45
+ /(?:^\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\s+(?:\[?(?:INFO|WARN|ERROR|DEBUG|TRACE|FATAL)\]?))/m;
46
+
47
+ const HARD_NEGATIVE_SQL_RE =
48
+ /\b(?:SELECT\s+[\s\S]{1,120}\s+FROM\s+[A-Za-z0-9_."`]+|INSERT\s+INTO\s+[A-Za-z0-9_."`]+|CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[A-Za-z0-9_."`]+|ALTER\s+TABLE\s+[A-Za-z0-9_."`]+)/i;
49
+
50
+ const REFEREE_SYNTAX_PATTERNS = Object.freeze([
51
+ /\bwhat\s+i\s+confirmed\b/i,
52
+ /\bcould(?:n't|\s+not)\s+confirm\b/i,
53
+ /\bwhat\s+holds\s+up\b/i,
54
+ /\bwhere\s+(?:it|the\s+(?:spec|review|critique|reviewer|author))\s+(?:overreaches|falls\s+short|is\s+right|is\s+wrong|misses)\b/i,
55
+ /\b(?:verdict|overall\s+assessment|blind\s+spots?|my\s+rebuttal|point-by-point|counter-?argument|reviewer(?:'s)?\s+(?:claim|critique|feedback))\b/i,
56
+ /\b\d+(?:\.\d+)?\s*\/\s*(?:10|100)\b/,
57
+ /\b(?:S0|S1|S2)\s*[:—-]\s*(?:Blocker|Major|Minor|Nit)\b/i,
58
+ /\b(?:concede|push\s+back|disagree\s+with\s+point|agree\s+with\s+point|round\s+[234]\s+rebuttal)\b/i
59
+ ]);
60
+
61
+ function isJsonOrCsvPayload(text = '') {
62
+ const trimmed = String(text || '').trim();
63
+ if (!trimmed) return false;
64
+ if ((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']'))) {
65
+ try {
66
+ JSON.parse(trimmed);
67
+ return true;
68
+ } catch {
69
+ // Not pure JSON; check if >60% of lines look like JSON key-value pairs
70
+ const lines = trimmed.split(/\r?\n/);
71
+ if (lines.length >= 6) {
72
+ const jsonLikeLines = lines.filter((l) => /^\s*"[^"]+"\s*:/.test(l)).length;
73
+ if (jsonLikeLines / lines.length >= 0.6) return true;
74
+ }
75
+ }
76
+ }
77
+ const lines = trimmed.split(/\r?\n/).filter((l) => l.trim().length > 0);
78
+ if (lines.length >= 4) {
79
+ const commaCounts = lines.slice(0, 6).map((l) => (l.match(/,/g) || []).length);
80
+ if (commaCounts[0] >= 3 && commaCounts.every((c) => c === commaCounts[0])) {
81
+ return true;
82
+ }
83
+ }
84
+ return false;
85
+ }
86
+
87
+ /**
88
+ * Checks whether a prompt matches any of the Relay Breaker hard negative filters (Section 3.1.4).
89
+ *
90
+ * @param {string} promptText
91
+ * @returns {{ matched: boolean, filter: string | null }}
92
+ */
93
+ export function matchRelayHardNegativeFilter(promptText = '') {
94
+ const text = String(promptText || '');
95
+ if (!text) return { matched: false, filter: null };
96
+ if (HARD_NEGATIVE_STACK_TRACE_RE.test(text)) return { matched: true, filter: 'STACK_TRACE' };
97
+ if (HARD_NEGATIVE_COMPILER_ERROR_RE.test(text)) return { matched: true, filter: 'COMPILER_OR_TEST_ERROR' };
98
+ if (HARD_NEGATIVE_UNIFIED_DIFF_RE.test(text)) return { matched: true, filter: 'UNIFIED_DIFF' };
99
+ if (HARD_NEGATIVE_LOG_TIMESTAMP_RE.test(text)) return { matched: true, filter: 'LOG_TIMESTAMPS' };
100
+ if (HARD_NEGATIVE_SQL_RE.test(text)) return { matched: true, filter: 'SQL_PAYLOAD' };
101
+ if (isJsonOrCsvPayload(text)) return { matched: true, filter: 'JSON_OR_CSV_PAYLOAD' };
102
+ return { matched: false, filter: null };
103
+ }
104
+
105
+ /**
106
+ * Counts how many distinct referee/critique markers appear in `promptText`.
107
+ *
108
+ * @param {string} promptText
109
+ * @returns {{ count: number, matchedMarkers: string[] }}
110
+ */
111
+ export function countRefereeSyntaxMarkers(promptText = '') {
112
+ const text = String(promptText || '');
113
+ const matchedMarkers = [];
114
+ for (const re of REFEREE_SYNTAX_PATTERNS) {
115
+ const m = text.match(re);
116
+ if (m) {
117
+ matchedMarkers.push(m[0]);
118
+ }
119
+ }
120
+ return {
121
+ count: matchedMarkers.length,
122
+ matchedMarkers
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Pure zero-I/O Scope Brake classifier (Section 3.2 & 5.1).
128
+ * Consolidated into `'vague-prompt-rubric'` (`DET-26` on Antigravity, `DET-14` on Claude Code).
129
+ *
130
+ * @param {object} [params={}]
131
+ * @returns {{
132
+ * detectorId: string,
133
+ * slug: string,
134
+ * triggered: boolean,
135
+ * subType: string | null,
136
+ * decision: 'allow' | 'steer' | 'block',
137
+ * mode: string,
138
+ * bypassReason: string | null,
139
+ * wordCount: number,
140
+ * candidateFiles: string[],
141
+ * steerContext: string | null,
142
+ * blockReason: string | null,
143
+ * unanchoredTurnFlag: boolean
144
+ * }}
145
+ */
146
+ export function evaluateScopeBrake({
147
+ prompt = '',
148
+ provenance = 'user',
149
+ isAutonomousTurn = false,
150
+ isSubagent = false,
151
+ isScheduledTask = false,
152
+ isLoopIteration = false,
153
+ priorTurnEditedFilesCount = 0,
154
+ priorTurnSingleFileTarget = null,
155
+ priorTurnHadToolOrTestFailure = false,
156
+ priorTurnAssistantAskedQuestion = false,
157
+ activeSetPaths = [],
158
+ modifiedFiles = [],
159
+ recentlyViewedFiles = [],
160
+ overrideMode = 'default',
161
+ flightMode = 'COACH',
162
+ detectorId = 'DET-26'
163
+ } = {}) {
164
+ const raw = String(prompt || '').trim();
165
+ const cleaned = raw.replace(/#check\b/gi, '').trim();
166
+ const words = cleaned ? cleaned.split(/\s+/).filter(Boolean) : [];
167
+ const wordCount = words.length;
168
+
169
+ const normOverride = String(overrideMode || 'default').toLowerCase();
170
+ if (normOverride === 'off' || String(flightMode || '').toUpperCase() === 'OFF') {
171
+ return {
172
+ detectorId,
173
+ slug: 'vague-prompt-rubric',
174
+ triggered: false,
175
+ subType: null,
176
+ decision: 'allow',
177
+ mode: 'off',
178
+ bypassReason: 'DISABLED_BY_CONFIG',
179
+ wordCount,
180
+ candidateFiles: [],
181
+ steerContext: null,
182
+ blockReason: null,
183
+ unanchoredTurnFlag: false
184
+ };
185
+ }
186
+
187
+ // 1. Autonomous turn & affirmative reply bypass (< 1 ms)
188
+ if (
189
+ Boolean(isAutonomousTurn) ||
190
+ Boolean(isSubagent) ||
191
+ Boolean(isScheduledTask) ||
192
+ Boolean(isLoopIteration) ||
193
+ AUTONOMOUS_PROVENANCE_RE.test(String(provenance || '')) ||
194
+ cleaned.startsWith('/') ||
195
+ AFFIRMATIVE_OR_CONTINUATION_RE.test(cleaned)
196
+ ) {
197
+ return {
198
+ detectorId,
199
+ slug: 'vague-prompt-rubric',
200
+ triggered: false,
201
+ subType: null,
202
+ decision: 'allow',
203
+ mode: normOverride,
204
+ bypassReason: 'AUTONOMOUS_OR_AFFIRMATIVE_BYPASS',
205
+ wordCount,
206
+ candidateFiles: [],
207
+ steerContext: null,
208
+ blockReason: null,
209
+ unanchoredTurnFlag: false
210
+ };
211
+ }
212
+
213
+ // 2. Trailing context anchor suppression (single-file edit, tool/test failure, or assistant question)
214
+ const effectiveSingleFileEdit =
215
+ Number(priorTurnEditedFilesCount) === 1 || Boolean(priorTurnSingleFileTarget);
216
+ if (
217
+ effectiveSingleFileEdit ||
218
+ Boolean(priorTurnHadToolOrTestFailure) ||
219
+ Boolean(priorTurnAssistantAskedQuestion)
220
+ ) {
221
+ return {
222
+ detectorId,
223
+ slug: 'vague-prompt-rubric',
224
+ triggered: false,
225
+ subType: null,
226
+ decision: 'allow',
227
+ mode: normOverride,
228
+ bypassReason: 'TRAILING_CONTEXT_ANCHOR',
229
+ wordCount,
230
+ candidateFiles: [],
231
+ steerContext: null,
232
+ blockReason: null,
233
+ unanchoredTurnFlag: false
234
+ };
235
+ }
236
+
237
+ // 3. Lexical trigger: < 12 words built around bare imperatives / vague comparatives lacking file/symbol/metric/error
238
+ const hasConcreteAnchor =
239
+ CONCRETE_FILE_OR_PATH_RE.test(cleaned) || CONCRETE_SYMBOL_OR_METRIC_RE.test(cleaned);
240
+ const isUnder12Words = wordCount > 0 && wordCount < 12;
241
+ const matchesVagueDirective = VAGUE_UNANCHORED_IMPERATIVE_RE.test(cleaned);
242
+
243
+ if (!isUnder12Words || hasConcreteAnchor || !matchesVagueDirective) {
244
+ return {
245
+ detectorId,
246
+ slug: 'vague-prompt-rubric',
247
+ triggered: false,
248
+ subType: null,
249
+ decision: 'allow',
250
+ mode: normOverride,
251
+ bypassReason: null,
252
+ wordCount,
253
+ candidateFiles: [],
254
+ steerContext: null,
255
+ blockReason: null,
256
+ unanchoredTurnFlag: false
257
+ };
258
+ }
259
+
260
+ // Gather top 5 candidate paths from sidecar activeSetPaths / modifiedFiles / recentlyViewedFiles (zero git spawn)
261
+ const seen = new Set();
262
+ const candidates = [];
263
+ for (const list of [modifiedFiles, activeSetPaths, recentlyViewedFiles]) {
264
+ if (!Array.isArray(list)) continue;
265
+ for (const item of list) {
266
+ const p = String(item || '').trim().replace(/\\/g, '/');
267
+ if (!p || seen.has(p)) continue;
268
+ seen.add(p);
269
+ candidates.push(p);
270
+ if (candidates.length >= 5) break;
271
+ }
272
+ if (candidates.length >= 5) break;
273
+ }
274
+
275
+ const candidateDisplay =
276
+ candidates.length > 0 ? candidates.slice(0, 5).join(', ') : '<target-file>';
277
+ const recentTwoDisplay =
278
+ candidates.length > 0 ? candidates.slice(0, 2).join(' or ') : '@<target-file>';
279
+
280
+ const isBlockMode =
281
+ normOverride === 'block' ||
282
+ (normOverride === 'default' && String(flightMode || '').toUpperCase() === 'AUTO_PILOT');
283
+
284
+ const steerContext =
285
+ `[${detectorId} Scope Brake] Unanchored directive ("${cleaned}") with no target file, symbol, or error anchor. ` +
286
+ `Candidate active files: [${candidateDisplay}]. ` +
287
+ `Single-turn boundary: Do NOT call repository-wide search, directory-listing, or multi-file edit tools on this turn; ask 1 concise scoping question naming candidate target files (${recentTwoDisplay}) and the specific optimization axis (latency, memory allocation, error handling, or readability).`;
288
+
289
+ const blockReason =
290
+ `[${detectorId} Scope Brake] Unanchored directive ("${cleaned}"). ` +
291
+ `Re-send with a concrete target (e.g., "In ${recentTwoDisplay}, ${cleaned} focusing on latency/readability").`;
292
+
293
+ return {
294
+ detectorId,
295
+ slug: 'vague-prompt-rubric',
296
+ triggered: true,
297
+ subType: 'UNANCHORED_SCOPE_BRAKE',
298
+ decision: isBlockMode ? 'block' : 'steer',
299
+ mode: isBlockMode ? 'block' : 'steer',
300
+ bypassReason: null,
301
+ wordCount,
302
+ candidateFiles: candidates,
303
+ steerContext,
304
+ blockReason,
305
+ unanchoredTurnFlag: true
306
+ };
307
+ }
308
+
309
+ /**
310
+ * Pure zero-I/O Relay Breaker classifier & 5-state machine (Section 3.1, 4 & 5.2):
311
+ * `Idle -> Candidate -> Armed -> Final Pass -> Locked`.
312
+ * Any edit to source code outside the bound Markdown specification resets Relay Breaker back to `Idle`.
313
+ *
314
+ * @param {object} [params={}]
315
+ * @returns {{
316
+ * detectorId: string,
317
+ * slug: string,
318
+ * triggered: boolean,
319
+ * subType: string | null,
320
+ * prevState: string,
321
+ * nextState: string,
322
+ * decision: 'allow' | 'steer' | 'block',
323
+ * refereeMarkerCount: number,
324
+ * matchedMarkers: string[],
325
+ * hardNegativeFilter: string | null,
326
+ * pasteChars: number,
327
+ * tailInjection: string | null,
328
+ * hudBadge: string | null,
329
+ * relayStateSnapshot: object
330
+ * }}
331
+ */
332
+ export function evaluateRelayBreaker({
333
+ prompt = '',
334
+ relayState = null,
335
+ sourceCodeEditsInSession = 0,
336
+ sourceCodeEditedSinceLastRelay = false,
337
+ priorTurnWebSearches = 0,
338
+ zeroEditSessionTokens = 0,
339
+ boundSpecPath = null,
340
+ overrideMode = 'default',
341
+ flightMode = 'COACH',
342
+ detectorId = 'DET-26'
343
+ } = {}) {
344
+ const prevSnap = relayState && typeof relayState === 'object' ? relayState : {};
345
+ const prevState = Object.values(RELAY_STATES).includes(prevSnap.state)
346
+ ? prevSnap.state
347
+ : RELAY_STATES.IDLE;
348
+ const prevCritiquePastes = Math.max(0, Number(prevSnap.critiquePastes || 0));
349
+ const activeSpecPath = boundSpecPath || prevSnap.boundSpecPath || 'SPEC.md';
350
+
351
+ const normOverride = String(overrideMode || 'default').toLowerCase();
352
+ if (normOverride === 'off' || String(flightMode || '').toUpperCase() === 'OFF') {
353
+ return {
354
+ detectorId,
355
+ slug: 'relay-breaker',
356
+ triggered: false,
357
+ subType: null,
358
+ prevState,
359
+ nextState: prevState,
360
+ decision: 'allow',
361
+ refereeMarkerCount: 0,
362
+ matchedMarkers: [],
363
+ hardNegativeFilter: null,
364
+ pasteChars: String(prompt || '').length,
365
+ tailInjection: null,
366
+ hudBadge: null,
367
+ relayStateSnapshot: {
368
+ state: prevState,
369
+ critiquePastes: prevCritiquePastes,
370
+ boundSpecPath: activeSpecPath
371
+ }
372
+ };
373
+ }
374
+
375
+ // Any source-code edit outside the bound Markdown spec resets Relay Breaker to Idle
376
+ if (Boolean(sourceCodeEditedSinceLastRelay) || Number(sourceCodeEditsInSession) > 0) {
377
+ return {
378
+ detectorId,
379
+ slug: 'relay-breaker',
380
+ triggered: false,
381
+ subType: null,
382
+ prevState,
383
+ nextState: RELAY_STATES.IDLE,
384
+ decision: 'allow',
385
+ refereeMarkerCount: 0,
386
+ matchedMarkers: [],
387
+ hardNegativeFilter: null,
388
+ pasteChars: String(prompt || '').length,
389
+ tailInjection: null,
390
+ hudBadge: null,
391
+ relayStateSnapshot: {
392
+ state: RELAY_STATES.IDLE,
393
+ critiquePastes: 0,
394
+ boundSpecPath: activeSpecPath
395
+ }
396
+ };
397
+ }
398
+
399
+ const text = String(prompt || '');
400
+ const pasteChars = text.length;
401
+
402
+ // 4. Hard negative filters abort scoring immediately
403
+ const neg = matchRelayHardNegativeFilter(text);
404
+ if (neg.matched) {
405
+ return {
406
+ detectorId,
407
+ slug: 'relay-breaker',
408
+ triggered: false,
409
+ subType: null,
410
+ prevState,
411
+ nextState: prevState,
412
+ decision: 'allow',
413
+ refereeMarkerCount: 0,
414
+ matchedMarkers: [],
415
+ hardNegativeFilter: neg.filter,
416
+ pasteChars,
417
+ tailInjection: null,
418
+ hudBadge: null,
419
+ relayStateSnapshot: {
420
+ state: prevState,
421
+ critiquePastes: prevCritiquePastes,
422
+ boundSpecPath: activeSpecPath
423
+ }
424
+ };
425
+ }
426
+
427
+ const { count: refereeMarkerCount, matchedMarkers } = countRefereeSyntaxMarkers(text);
428
+ const isCritiquePaste = pasteChars > 1500 && refereeMarkerCount >= 2;
429
+ const hasVerificationSprawl =
430
+ Number(priorTurnWebSearches) >= 3 || Number(zeroEditSessionTokens) > 35000;
431
+
432
+ if (!isCritiquePaste) {
433
+ return {
434
+ detectorId,
435
+ slug: 'relay-breaker',
436
+ triggered: false,
437
+ subType: null,
438
+ prevState,
439
+ nextState: prevState,
440
+ decision: 'allow',
441
+ refereeMarkerCount,
442
+ matchedMarkers,
443
+ hardNegativeFilter: null,
444
+ pasteChars,
445
+ tailInjection: null,
446
+ hudBadge: prevState === RELAY_STATES.IDLE ? null : `Relay: ${prevState}`,
447
+ relayStateSnapshot: {
448
+ state: prevState,
449
+ critiquePastes: prevCritiquePastes,
450
+ boundSpecPath: activeSpecPath
451
+ }
452
+ };
453
+ }
454
+
455
+ const nextCritiquePastes = prevCritiquePastes + 1;
456
+ let nextState = prevState;
457
+
458
+ if (prevState === RELAY_STATES.IDLE) {
459
+ nextState = hasVerificationSprawl && nextCritiquePastes >= 2
460
+ ? RELAY_STATES.ARMED
461
+ : RELAY_STATES.CANDIDATE;
462
+ } else if (prevState === RELAY_STATES.CANDIDATE) {
463
+ nextState = hasVerificationSprawl || nextCritiquePastes >= 2
464
+ ? RELAY_STATES.ARMED
465
+ : RELAY_STATES.CANDIDATE;
466
+ } else if (prevState === RELAY_STATES.ARMED) {
467
+ nextState = RELAY_STATES.FINAL_PASS;
468
+ } else if (prevState === RELAY_STATES.FINAL_PASS || prevState === RELAY_STATES.LOCKED) {
469
+ nextState = RELAY_STATES.LOCKED;
470
+ }
471
+
472
+ const isBlockMode =
473
+ normOverride === 'block' ||
474
+ (normOverride === 'default' && String(flightMode || '').toUpperCase() === 'AUTO_PILOT' && nextState === RELAY_STATES.LOCKED);
475
+
476
+ let tailInjection = null;
477
+ let hudBadge = null;
478
+ let subType = null;
479
+
480
+ if (nextState === RELAY_STATES.CANDIDATE) {
481
+ hudBadge = 'Spec Churn Candidate (Round 1)';
482
+ subType = 'RELAY_CANDIDATE';
483
+ } else if (nextState === RELAY_STATES.ARMED) {
484
+ hudBadge = 'Relay Mode Armed (Owner Protocol)';
485
+ subType = 'RELAY_ARMED';
486
+ tailInjection =
487
+ `[${detectorId} Relay Breaker — Armed (Owner Protocol)] Cross-model spec relay detected (${pasteChars.toLocaleString('en-US')} chars, ${refereeMarkerCount} critique markers, 0 code edits). ` +
488
+ `Act as the stateful Spec Owner: (1) Commit accepted spec changes directly to "${activeSpecPath}" instead of printing full prose recaps; ` +
489
+ `(2) Do NOT run exploratory web searches on uncited peer claims; ` +
490
+ `(3) Triage feedback into Blocker (S0), Major flaw (S1), or Testable runtime question (T) and defer style nits.`;
491
+ } else if (nextState === RELAY_STATES.FINAL_PASS) {
492
+ hudBadge = 'Relay Round 2 of 2 (Final Pass)';
493
+ subType = 'RELAY_FINAL_PASS';
494
+ tailInjection =
495
+ `[${detectorId} Relay Breaker — Round 2 of 2 Cap] Final critique pass for "${activeSpecPath}". Resolve remaining S0/S1 items on disk and convert unresolved runtime debates into a local verification test.`;
496
+ } else if (nextState === RELAY_STATES.LOCKED) {
497
+ hudBadge = 'Relay Locked (Round 3+ Cap Reached)';
498
+ subType = 'RELAY_LOCKED';
499
+ tailInjection =
500
+ `[${detectorId} Relay Breaker — LOCKED (Round ${nextCritiquePastes})] Spec relay cap reached with 0 source-code edits. Stop cross-model prose relays; freeze "${activeSpecPath}" and write a local verification script or begin implementation.`;
501
+ }
502
+
503
+ const triggered =
504
+ nextState === RELAY_STATES.ARMED ||
505
+ nextState === RELAY_STATES.FINAL_PASS ||
506
+ nextState === RELAY_STATES.LOCKED;
507
+
508
+ return {
509
+ detectorId,
510
+ slug: 'relay-breaker',
511
+ triggered,
512
+ subType,
513
+ prevState,
514
+ nextState,
515
+ decision: triggered ? (isBlockMode ? 'block' : 'steer') : 'allow',
516
+ refereeMarkerCount,
517
+ matchedMarkers,
518
+ hardNegativeFilter: null,
519
+ pasteChars,
520
+ tailInjection,
521
+ hudBadge,
522
+ relayStateSnapshot: {
523
+ state: nextState,
524
+ critiquePastes: nextCritiquePastes,
525
+ boundSpecPath: activeSpecPath
526
+ }
527
+ };
528
+ }
529
+
530
+ /**
531
+ * Two-Stage `PreToolUse` Sightseeing-Tool Interception Fallback (Section 4).
532
+ * When `unanchoredTurnFlag` or `relayState === 'Locked'` (or `'Armed'` web search) was recorded
533
+ * at prompt submission, intercepts the model's first exploratory repository scan or web search.
534
+ *
535
+ * @param {object} [params={}]
536
+ * @returns {{
537
+ * intercepted: boolean,
538
+ * detectorId: string | null,
539
+ * subType: string | null,
540
+ * decision: 'allow' | 'deny',
541
+ * reason: string | null,
542
+ * consumeFlag: boolean
543
+ * }}
544
+ */
545
+ export function evaluateTwoStageSightseeingIntercept({
546
+ toolName = '',
547
+ toolArgs = {},
548
+ unanchoredTurnFlag = false,
549
+ candidateFiles = [],
550
+ relayState = null,
551
+ overrideMode = 'default',
552
+ flightMode = 'COACH',
553
+ detectorId = 'DET-26'
554
+ } = {}) {
555
+ const name = String(toolName || '').trim();
556
+ const isExploratorySearchOrList =
557
+ /^(?:Grep|Glob|grep_search|find_by_name|list_dir|WebFetch|web_search|search_web)$/i.test(name);
558
+ const isWebSearchTool = /^(?:WebFetch|web_search|search_web)$/i.test(name);
559
+ const isUnscopedRead =
560
+ /^(?:Read|read_file|view_file)$/i.test(name) &&
561
+ candidateFiles.length > 0 &&
562
+ !candidateFiles.some((cf) => {
563
+ const target = String(
564
+ toolArgs?.file_path || toolArgs?.Path || toolArgs?.TargetFile || toolArgs?.path || ''
565
+ ).replace(/\\/g, '/');
566
+ return target && (target.endsWith(cf) || cf.endsWith(target));
567
+ });
568
+
569
+ // 1. Scope Brake Two-Stage Gate: intercept first exploratory search/list/unscoped read on unanchored turn
570
+ if (Boolean(unanchoredTurnFlag) && (isExploratorySearchOrList || isUnscopedRead)) {
571
+ const candidateHint =
572
+ Array.isArray(candidateFiles) && candidateFiles.length > 0
573
+ ? candidateFiles.slice(0, 3).join(', ')
574
+ : '@<target-file>';
575
+ const normOverride = String(overrideMode || 'default').toLowerCase();
576
+ const shouldDeny =
577
+ normOverride === 'block' ||
578
+ normOverride === 'warn' ||
579
+ String(flightMode || '').toUpperCase() === 'AUTO_PILOT';
580
+
581
+ return {
582
+ intercepted: true,
583
+ detectorId,
584
+ subType: 'TWO_STAGE_SCOPE_BRAKE_INTERCEPT',
585
+ decision: shouldDeny ? 'deny' : 'allow',
586
+ reason:
587
+ `[${detectorId} Scope Brake Two-Stage Gate] Exploratory tool "${name}" intercepted on unanchored turn. ` +
588
+ `Stop scanning the repository and ask 1 concrete scoping question naming candidate files (${candidateHint}) and the optimization axis.`,
589
+ consumeFlag: true
590
+ };
591
+ }
592
+
593
+ // 2. Relay Breaker Two-Stage Gate: intercept exploratory WebFetch/web_search during Armed/Final Pass/Locked spec relay
594
+ const currentRelayState =
595
+ typeof relayState === 'string' ? relayState : relayState?.state || RELAY_STATES.IDLE;
596
+ if (
597
+ isWebSearchTool &&
598
+ (currentRelayState === RELAY_STATES.ARMED ||
599
+ currentRelayState === RELAY_STATES.FINAL_PASS ||
600
+ currentRelayState === RELAY_STATES.LOCKED)
601
+ ) {
602
+ return {
603
+ intercepted: true,
604
+ detectorId,
605
+ subType: 'TWO_STAGE_RELAY_WEB_SEARCH_INTERCEPT',
606
+ decision: 'deny',
607
+ reason:
608
+ `[${detectorId} Relay Breaker Two-Stage Gate] Exploratory web fetch ("${name}") blocked during ${currentRelayState} spec relay. ` +
609
+ `Do not scrape uncited external pages during critique relays; verify claims via local code or ask the user for primary source citations.`,
610
+ consumeFlag: false
611
+ };
612
+ }
613
+
614
+ return {
615
+ intercepted: false,
616
+ detectorId: null,
617
+ subType: null,
618
+ decision: 'allow',
619
+ reason: null,
620
+ consumeFlag: false
621
+ };
622
+ }