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,442 @@
1
+ /**
2
+ * @file src/core-isomorphic/guards/bucketBGamma.mjs
3
+ * Pure Isomorphic Evaluators for Bucket B Sub-Wave B-Gamma:
4
+ * - `#5` `SUBAGENT_TEAM_GOVERNOR` (Read-only scout model right-sizing, brief cap & safe idle check)
5
+ * - `#13` `VAGUE_PROMPT_ANCHOR` (Zero-spawn `<6`-word ambiguous failure cry classifier)
6
+ * - `#16` `MCP_CLI_ROUTER` (Heavy MCP -> verified authenticated local CLI router)
7
+ * - `#17` `LSP_SYMBOL_ROUTER` (Verified active-LSP symbol lookup hint)
8
+ * - `#20` `PROSE_TO_HOOK_COMPILER` (Unconditional `NEVER`/`DO NOT` prose -> candidate hook preview)
9
+ *
10
+ * Mod Law 4 Compliant: Zero `node:*` imports, zero `process.cwd`/`exit`, zero global mutable state.
11
+ */
12
+
13
+ // ============================================================================
14
+ // #5 SUBAGENT_TEAM_GOVERNOR
15
+ // ============================================================================
16
+
17
+ const WRITE_CAPABLE_TOOL_RE =
18
+ /^(?:Edit|MultiEdit|Write|NotebookEdit|Bash|PowerShell|run_command|write_file|edit_file|delete_file|apply_patch)$/i;
19
+
20
+ const WRITE_ACTION_PROMPT_RE =
21
+ /\b(?:implement|edit|modify|write|refactor|fix|patch|create\s+file|update\s+code|commit|merge|delete)\b/i;
22
+
23
+ const READ_ONLY_SCOUT_PROMPT_RE =
24
+ /\b(?:scout|search|find|locate|summarize|explore|survey|grep|read-only|list\s+files|inspect\s+where)\b/i;
25
+
26
+ const EXEMPT_FRONTIER_ROLE_RE =
27
+ /\b(?:cold\s+critic|spec\s+relay|adversarial\s+critic|security\s+auditor|architecture\s+review|verifier|judge)\b/i;
28
+
29
+ const FRONTIER_MODEL_RE =
30
+ /^(?:opus|claude-(?:opus|sonnet)(?:-[a-z0-9.]+)*|sonnet|pro|gemini-[a-z0-9.-]*(?:pro|carbon|argon)|inherit)$/i;
31
+
32
+ /**
33
+ * Evaluates subagent/team spawn parameters for read-only model right-sizing, brief bloat,
34
+ * and safe idle-teammate governance (`0` misclassified write workers, `0` premature verifier kills).
35
+ *
36
+ * @param {object} input
37
+ * @param {string} [input.typeName=''] - e.g. `'research'`, `'Explore'`, `'self'`, `'general-purpose'`
38
+ * @param {string} [input.role='']
39
+ * @param {string} [input.prompt='']
40
+ * @param {string} [input.model='inherit']
41
+ * @param {boolean} [input.enableWriteTools]
42
+ * @param {string[]} [input.allowedTools]
43
+ * @param {string} [input.workspace='inherit'] - `'inherit' | 'branch' | 'share' | 'worktree'`
44
+ * @param {number} [input.idleMinutes=0]
45
+ * @param {number} [input.pendingPeerCommits=0]
46
+ * @param {boolean} [input.coordinatorWaiting=false]
47
+ * @param {number} [input.maxBriefTokens=2500]
48
+ */
49
+ export function evaluateSubagentGovernor(input = {}) {
50
+ const typeName = String(input.typeName || '').trim();
51
+ const role = String(input.role || '').trim();
52
+ const prompt = String(input.prompt || '').trim();
53
+ const model = String(input.model || 'inherit').trim();
54
+ const workspace = String(input.workspace || 'inherit').trim().toLowerCase();
55
+ const maxBriefTokens = Number(input.maxBriefTokens) || 2500;
56
+
57
+ // 1. Check idle teammate termination governance (if evaluating a live idle teammate)
58
+ const idleMinutes = Number(input.idleMinutes) || 0;
59
+ if (idleMinutes >= 5) {
60
+ const pendingPeerCommits = Number(input.pendingPeerCommits) || 0;
61
+ const coordinatorWaiting = Boolean(input.coordinatorWaiting);
62
+ if (pendingPeerCommits > 0 || coordinatorWaiting || EXEMPT_FRONTIER_ROLE_RE.test(`${role} ${prompt}`)) {
63
+ return {
64
+ triggered: false,
65
+ decision: 'allow',
66
+ exemptReason: 'verifier_or_pending_peer_work',
67
+ isReadOnlyScout: false,
68
+ tokensSavedEst: 0
69
+ };
70
+ }
71
+ return {
72
+ triggered: true,
73
+ decision: 'warn',
74
+ code: 'SUBAGENT_IDLE_DRAIN',
75
+ action: 'recommend_retire_idle_worker',
76
+ isReadOnlyScout: false,
77
+ tokensSavedEst: 3200,
78
+ reason: `[Quota Shield] Teammate \`${role || typeName || 'worker'}\` has been idle for ${idleMinutes}m with 0 pending peer commits and no coordinator wait.`
79
+ };
80
+ }
81
+
82
+ // 2. Exempt Cold Critic / Spec Relay / Architecture Verifier roles from model downgrades
83
+ if (EXEMPT_FRONTIER_ROLE_RE.test(`${typeName} ${role} ${prompt}`)) {
84
+ return {
85
+ triggered: false,
86
+ decision: 'allow',
87
+ exemptReason: 'frontier_critic_or_verifier',
88
+ isReadOnlyScout: false,
89
+ tokensSavedEst: 0
90
+ };
91
+ }
92
+
93
+ // 3. Determine strict read-only scout status (NEVER misclassify write-capable workers!)
94
+ const hasExplicitWriteFlag = input.enableWriteTools === true;
95
+ const hasIsolatedWriteWorkspace =
96
+ workspace === 'branch' || workspace === 'share' || workspace === 'worktree';
97
+ const tools = Array.isArray(input.allowedTools) ? input.allowedTools : null;
98
+ const hasWriteToolGrant = tools ? tools.some((t) => WRITE_CAPABLE_TOOL_RE.test(String(t))) : false;
99
+ const isKnownReadOnlyType = /^(?:research|explore|ah-flash-scout|scout)$/i.test(typeName);
100
+ const hasWriteIntentInPrompt = WRITE_ACTION_PROMPT_RE.test(prompt);
101
+
102
+ const isReadOnlyScout =
103
+ !hasExplicitWriteFlag &&
104
+ !hasIsolatedWriteWorkspace &&
105
+ !hasWriteToolGrant &&
106
+ !hasWriteIntentInPrompt &&
107
+ (isKnownReadOnlyType ||
108
+ (input.enableWriteTools === false && READ_ONLY_SCOUT_PROMPT_RE.test(`${role} ${prompt}`)) ||
109
+ (tools !== null && tools.length > 0 && READ_ONLY_SCOUT_PROMPT_RE.test(`${role} ${prompt}`)));
110
+
111
+ const briefTokens = Math.ceil(prompt.length / 4);
112
+ const bloatedBrief = briefTokens > maxBriefTokens;
113
+ const frontierOnScout = isReadOnlyScout && FRONTIER_MODEL_RE.test(model);
114
+
115
+ if (!frontierOnScout && !bloatedBrief) {
116
+ return {
117
+ triggered: false,
118
+ decision: 'allow',
119
+ isReadOnlyScout,
120
+ briefTokens,
121
+ tokensSavedEst: 0
122
+ };
123
+ }
124
+
125
+ const reasons = [];
126
+ let saved = 0;
127
+ if (frontierOnScout) {
128
+ reasons.push(
129
+ `read-only scout \`${role || typeName}\` requested \`${model}\` -> prefer \`haiku\`/\`flash\` to save ~4x–10x subagent quota`
130
+ );
131
+ saved += 4500;
132
+ }
133
+ if (bloatedBrief) {
134
+ reasons.push(`spawn brief is ~${briefTokens} tokens (>${maxBriefTokens} cap)`);
135
+ saved += Math.max(500, briefTokens - maxBriefTokens);
136
+ }
137
+
138
+ return {
139
+ triggered: true,
140
+ decision: 'warn',
141
+ code: 'SUBAGENT_TEAM_GOVERNOR',
142
+ isReadOnlyScout,
143
+ recommendedModel: frontierOnScout ? 'flash_or_haiku' : model,
144
+ briefTokens,
145
+ tokensSavedEst: saved,
146
+ reason: `[Quota Shield] Subagent optimization: ${reasons.join('; ')}.`
147
+ };
148
+ }
149
+
150
+ // ============================================================================
151
+ // #13 VAGUE_PROMPT_ANCHOR
152
+ // ============================================================================
153
+
154
+ const CRISP_CONFIRMATION_OR_SELECTION_RE =
155
+ /^(?:go|yes|yep|yeah|ok|okay|sure|proceed|continue|ship\s+it|do\s+it|lgtm|approved?|looks\s+good|sounds\s+good|thanks|thank\s+you|stop|cancel|skip|done|next|(?:proceed|go|do|pick|use|option|step|choice)\s+(?:with\s+)?(?:#?\d+|[a-c]|both|all))[\s.!]*$/i;
156
+
157
+ const EXPLICIT_SHORT_COMMAND_RE =
158
+ /^(?:git\s+\S+|npm\s+\S+|pnpm\s+\S+|node\s+\S+|run\s+(?:the\s+)?(?:tests?|lint|build|verify|bench\S*)|commit(?:\s+and\s+push|\s+now)?|push(?:\s+now|\s+to\s+\S+)?|sync\s+mirrors|build\s+(?:release|bundles|assets|all|prod|dev|pkg)|revert\s+that|show\s+diff|check\s+status)[\s.!]*$/i;
159
+
160
+ const QUESTION_OR_EXPLAIN_RE =
161
+ /\?$|^(?:why|what|where|how|when|who|which|explain|describe|summarize|show\s+me|list|compare)\b/i;
162
+
163
+ const AMBIGUOUS_FAILURE_CRY_RE =
164
+ /^(?:fix\s+(?:it|this|that)(?:\s+please)?|still\s+(?:broken|failing|fails|buggy|wrong|crashing|errors?)|same\s+(?:error|issue|bug|crash|problem)|(?:it\s+|that\s+)?(?:didnt|didn't|doesnt|doesn't|isnt|isn't)\s+work(?:ing)?|not\s+working|broken\s+again|try\s+again|still\s+doesnt\s+work|still\s+doesn't\s+work|it\s+(?:failed|fails|crashed|broke)|wrong\s+output|test\s+still\s+fails|tests\s+still\s+fail|build\s+broken|fix\s+the\s+error)[\s.!]*$/i;
165
+
166
+ const EXPLICIT_ANCHOR_TOKEN_RE =
167
+ /(?:[A-Za-z0-9_-]+\.[a-z]{1,5}\b|\/[A-Za-z0-9_.-]+|`[^`]+`|\bDET-\d+\b|\bISS-\d+\b|#[0-9]+\b|\bline\s+\d+\b)/i;
168
+
169
+ /**
170
+ * Classifies `<8`-word user prompts with `0ms` subprocess overhead:
171
+ * - Returns `triggered: true` ONLY on ambiguous failure cries (`"fix it"`, `"still broken"`, `"same error"`)
172
+ * lacking any file/symbol/issue anchor when pre-cached `dirtyFiles` or `lastFailingLocation` exist.
173
+ * - Guarantees `0%` false-injection on slash commands, confirmations (`"proceed with 1"`), CLI verbs (`"git push"`), or Q&A.
174
+ *
175
+ * @param {object} input
176
+ * @param {string} [input.prompt='']
177
+ * @param {string[]} [input.cachedDirtyFiles=[]]
178
+ * @param {string} [input.lastFailingLocation='']
179
+ */
180
+ export function evaluateVaguePromptAnchor(input = {}) {
181
+ const raw = String(input.prompt || '').trim();
182
+ if (!raw || raw.startsWith('/')) {
183
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
184
+ }
185
+
186
+ const words = raw.split(/\s+/).filter(Boolean);
187
+ if (words.length === 0 || words.length > 7) {
188
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
189
+ }
190
+
191
+ if (
192
+ CRISP_CONFIRMATION_OR_SELECTION_RE.test(raw) ||
193
+ EXPLICIT_SHORT_COMMAND_RE.test(raw) ||
194
+ QUESTION_OR_EXPLAIN_RE.test(raw) ||
195
+ EXPLICIT_ANCHOR_TOKEN_RE.test(raw)
196
+ ) {
197
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
198
+ }
199
+
200
+ if (!AMBIGUOUS_FAILURE_CRY_RE.test(raw)) {
201
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
202
+ }
203
+
204
+ const dirty = Array.isArray(input.cachedDirtyFiles) ? input.cachedDirtyFiles.slice(0, 5) : [];
205
+ const lastFail = String(input.lastFailingLocation || '').trim();
206
+ if (dirty.length === 0 && !lastFail) {
207
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
208
+ }
209
+
210
+ const anchorParts = [];
211
+ if (lastFail) anchorParts.push(`last failure: ${lastFail}`);
212
+ if (dirty.length > 0) anchorParts.push(`modified: ${dirty.join(', ')}`);
213
+
214
+ return {
215
+ triggered: true,
216
+ decision: 'warn',
217
+ code: 'VAGUE_PROMPT_ANCHOR',
218
+ anchorContext: `[CTX_ANCHOR] ${anchorParts.join(' | ')}`,
219
+ tokensSavedEst: 1900,
220
+ reason: `[Quota Shield] Short unanchored debug prompt anchored to cached workspace state (${anchorParts.join(' | ')}) to prevent blind exploratory grep sweeps.`
221
+ };
222
+ }
223
+
224
+ // ============================================================================
225
+ // #16 MCP_CLI_ROUTER
226
+ // ============================================================================
227
+
228
+ const HEAVY_MCP_SERVER_TO_CLI = Object.freeze({
229
+ github: { cli: 'gh', example: 'gh pr / gh issue / gh api' },
230
+ gh: { cli: 'gh', example: 'gh pr / gh issue / gh api' },
231
+ aws: { cli: 'aws', example: 'aws <service> describe-* --output json' },
232
+ gcloud: { cli: 'gcloud', example: 'gcloud <group> list --format=json' },
233
+ sentry: { cli: 'sentry-cli', example: 'sentry-cli issues list' },
234
+ kubectl: { cli: 'kubectl', example: 'kubectl get <resource> -o json' },
235
+ kubernetes: { cli: 'kubectl', example: 'kubectl get <resource> -o json' }
236
+ });
237
+
238
+ const READ_LIKE_MCP_ACTION_RE = /(?:^|_|-)(?:list|get|read|search|query|fetch|view|describe|status|inspect)(?:$|_|-)/i;
239
+
240
+ /**
241
+ * Suggests lightweight authenticated CLI calls over heavy MCP JSON-schema/payload calls
242
+ * ONLY when BOTH the local CLI binary AND non-expired local auth state are verified.
243
+ *
244
+ * @param {object} input
245
+ * @param {string} [input.toolName=''] - e.g. `'mcp__github__list_pull_requests'`
246
+ * @param {Record<string, { installed?: boolean, authValid?: boolean, authExpired?: boolean }>} [input.cliCapabilities={}]
247
+ */
248
+ export function evaluateMcpCliRouter(input = {}) {
249
+ const toolName = String(input.toolName || '').trim();
250
+ const match = toolName.match(/^mcp__([a-z0-9_-]+)__([a-z0-9_-]+)$/i);
251
+ if (!match) {
252
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
253
+ }
254
+
255
+ const serverKey = match[1].toLowerCase();
256
+ const actionName = match[2];
257
+ const mapping = HEAVY_MCP_SERVER_TO_CLI[serverKey];
258
+ if (!mapping || !READ_LIKE_MCP_ACTION_RE.test(actionName)) {
259
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
260
+ }
261
+
262
+ const caps = (input.cliCapabilities || {})[mapping.cli] || null;
263
+ if (!caps || caps.installed !== true || caps.authValid !== true || caps.authExpired === true) {
264
+ return {
265
+ triggered: false,
266
+ decision: 'allow',
267
+ exemptReason: 'cli_missing_or_unauthenticated',
268
+ tokensSavedEst: 0
269
+ };
270
+ }
271
+
272
+ return {
273
+ triggered: true,
274
+ decision: 'warn',
275
+ code: 'MCP_CLI_ROUTER',
276
+ recommendedCli: mapping.cli,
277
+ tokensSavedEst: 3400,
278
+ reason: `[CTX_HINT] Verified authenticated \`${mapping.cli}\` CLI is available locally (${mapping.example}) and avoids ~3k–15k MCP schema/JSON envelope tokens.`
279
+ };
280
+ }
281
+
282
+ // ============================================================================
283
+ // #17 LSP_SYMBOL_ROUTER
284
+ // ============================================================================
285
+
286
+ /**
287
+ * Emits a `<20`-token `[CTX_HINT]` recommending native `LSP` definition/reference navigation
288
+ * on repeated symbol `Grep`/`Read` hops STRICTLY when `lspToolEnabled === true` AND an active
289
+ * language server covers the target file extension (`0` hints when LSP is absent).
290
+ *
291
+ * @param {object} input
292
+ * @param {string} [input.symbol='']
293
+ * @param {string} [input.filePath='']
294
+ * @param {number} [input.symbolLookupCount=0]
295
+ * @param {boolean} [input.lspToolEnabled=false]
296
+ * @param {Iterable<string>} [input.activeExtensions=[]] - e.g. `['.ts', '.tsx', '.py', '.go', '.rs']`
297
+ */
298
+ export function evaluateLspSymbolRouter(input = {}) {
299
+ const symbol = String(input.symbol || '').trim();
300
+ const filePath = String(input.filePath || '').trim();
301
+ const lookupCount = Number(input.symbolLookupCount) || 0;
302
+
303
+ if (!input.lspToolEnabled || lookupCount < 3 || !/^[A-Za-z_$][A-Za-z0-9_$]{2,}$/.test(symbol)) {
304
+ return { triggered: false, decision: 'allow', tokensSavedEst: 0 };
305
+ }
306
+
307
+ const dotIdx = filePath.lastIndexOf('.');
308
+ const ext = dotIdx >= 0 ? filePath.slice(dotIdx).toLowerCase() : '';
309
+ const activeSet = new Set(
310
+ Array.from(input.activeExtensions || [], (e) =>
311
+ (String(e).startsWith('.') ? String(e) : `.${e}`).toLowerCase()
312
+ )
313
+ );
314
+
315
+ if (!ext || !activeSet.has(ext)) {
316
+ return {
317
+ triggered: false,
318
+ decision: 'allow',
319
+ exemptReason: 'no_active_lsp_for_extension',
320
+ tokensSavedEst: 0
321
+ };
322
+ }
323
+
324
+ return {
325
+ triggered: true,
326
+ decision: 'warn',
327
+ code: 'LSP_SYMBOL_ROUTER',
328
+ hint: `[CTX_HINT] Prefer native LSP goToDefinition/findReferences for \`${symbol}\` (${ext}).`,
329
+ tokensSavedEst: 1200,
330
+ reason: `[CTX_HINT] Prefer native LSP goToDefinition/findReferences for \`${symbol}\` (${ext}).`
331
+ };
332
+ }
333
+
334
+ // ============================================================================
335
+ // #20 PROSE_TO_HOOK_COMPILER
336
+ // ============================================================================
337
+
338
+ const IMPERATIVE_PROHIBITION_LINE_RE =
339
+ /^\s*(?:[-*+]|\d+\.)\s*(?:\*\*)?(?:NEVER|DO\s+NOT|DON'T|MUST\s+NEVER|STRICTLY\s+NEVER)(?:\*\*)?\b/i;
340
+
341
+ const CONDITIONAL_QUALIFIER_RE =
342
+ /\b(?:unless|except|if|when|whenever|until|before|after|while|otherwise|instead\s+of|rather\s+than|only\s+when|only\s+if|in\s+case|provided\s+that|except\s+when)\b/i;
343
+
344
+ const FILE_ACTION_VERB_RE =
345
+ /\b(?:read|edit|modify|write|touch|stage|index|grep|delete|overwrite|access)\b/i;
346
+
347
+ const SHELL_EXEC_VERB_RE = /\b(?:run|execute|invoke|spawn|call)\b/i;
348
+
349
+ function looksLikePathOrGlobToken(tok = '') {
350
+ const t = tok.trim();
351
+ if (!t || t.includes(' ') || t.length < 3) return false;
352
+ if (/^(?:true|false|null|undefined|stdout|stderr|json|utf8)$/i.test(t)) return false;
353
+ return (
354
+ t.includes('/') ||
355
+ t.includes('\\') ||
356
+ t.startsWith('~/.') ||
357
+ t.startsWith('.') ||
358
+ /\.(?:json|ya?ml|md|mjs|cjs|js|ts|tsx|py|toml|lock|env|db|sqlite|sql|sh|sha256|sum|pem|key|crt|cfg|ini|conf|xml|csv|txt)$/i.test(
359
+ t
360
+ )
361
+ );
362
+ }
363
+
364
+ function looksLikeShellCommandToken(tok = '') {
365
+ const t = tok.trim();
366
+ if (!t || !t.includes(' ')) return false;
367
+ return /^(?:git|npm|pnpm|yarn|npx|node|rm|del|curl|wget|docker|kubectl|claude|gemini|agy)\s+\S+/i.test(
368
+ t
369
+ );
370
+ }
371
+
372
+ /**
373
+ * Scans `AGENTS.md` / `CLAUDE.md` Markdown text for unconditional imperative `NEVER` / `DO NOT`
374
+ * rules containing explicit backticked globs, paths, or commands, compiling them into candidate
375
+ * `PreToolUse` hook previews for `ctxtop doctor` (rejecting all conditional rules).
376
+ *
377
+ * @param {string} markdown
378
+ * @param {object} [options={}]
379
+ * @param {string} [options.sourceFile='AGENTS.md']
380
+ */
381
+ export function compileProseRulesToHooks(markdown = '', options = {}) {
382
+ const sourceFile = String(options.sourceFile || 'AGENTS.md');
383
+ const lines = String(markdown || '').split(/\r?\n/);
384
+ const candidates = [];
385
+ const skippedConditional = [];
386
+
387
+ for (let idx = 0; idx < lines.length; idx++) {
388
+ const rawLine = lines[idx];
389
+ if (!IMPERATIVE_PROHIBITION_LINE_RE.test(rawLine)) continue;
390
+
391
+ // Strip backticked spans before checking conditional prose words so identifiers like `if` inside code don't skew,
392
+ // AND also check full prose outside backticks for any conditional/temporal qualifier!
393
+ const proseOutsideBackticks = rawLine.replace(/`[^`]*`/g, ' ');
394
+ if (CONDITIONAL_QUALIFIER_RE.test(proseOutsideBackticks)) {
395
+ skippedConditional.push({
396
+ line: idx + 1,
397
+ sourceFile,
398
+ reason: 'conditional_or_temporal_clause',
399
+ excerpt: rawLine.trim().slice(0, 140)
400
+ });
401
+ continue;
402
+ }
403
+
404
+ const backtickTokens = [...rawLine.matchAll(/`([^`\n]+)`/g)].map((m) => m[1].trim());
405
+ if (backtickTokens.length === 0) continue;
406
+
407
+ const pathGlobs = backtickTokens.filter(looksLikePathOrGlobToken);
408
+ const shellCommands = backtickTokens.filter(looksLikeShellCommandToken);
409
+
410
+ if (pathGlobs.length > 0 && FILE_ACTION_VERB_RE.test(proseOutsideBackticks)) {
411
+ candidates.push({
412
+ line: idx + 1,
413
+ sourceFile,
414
+ hookEvent: 'PreToolUse',
415
+ matcher: 'Read|Edit|MultiEdit|Write|Grep|Glob',
416
+ kind: 'PATH_DENY_RULE',
417
+ patterns: pathGlobs,
418
+ previewOnly: true,
419
+ sourceExcerpt: rawLine.trim().slice(0, 160)
420
+ });
421
+ } else if (shellCommands.length > 0 && SHELL_EXEC_VERB_RE.test(proseOutsideBackticks)) {
422
+ candidates.push({
423
+ line: idx + 1,
424
+ sourceFile,
425
+ hookEvent: 'PreToolUse',
426
+ matcher: 'Bash|PowerShell',
427
+ kind: 'COMMAND_DENY_RULE',
428
+ patterns: shellCommands,
429
+ previewOnly: true,
430
+ sourceExcerpt: rawLine.trim().slice(0, 160)
431
+ });
432
+ }
433
+ }
434
+
435
+ return {
436
+ triggered: candidates.length > 0,
437
+ decision: 'allow',
438
+ candidates,
439
+ skippedConditional,
440
+ tokensSavedEst: candidates.length * 400
441
+ };
442
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @file src/core-isomorphic/guards/bucketBHeuristics.mjs
3
+ * Unified Pure Isomorphic Barrel for all 12 Bucket B Heuristic Guardrails (`#2`, `#3b`, `#4`,
4
+ * `#5`, `#6`, `#8`, `#9`, `#13`, `#16`, `#17`, `#19`, `#20`).
5
+ *
6
+ * Mod Law 4 Compliant: Zero `node:*` imports.
7
+ */
8
+
9
+ export {
10
+ POPULAR_ECOSYSTEM_PACKAGES,
11
+ KNOWN_LLM_CONFLATIONS,
12
+ damerauLevenshteinMax1,
13
+ normalizePackageSpec,
14
+ parsePackageInstallCommands,
15
+ evaluateSlopsquatCommand
16
+ } from './slopsquatGate.mjs';
17
+
18
+ export {
19
+ isBucketBForbiddenSkuPath,
20
+ evaluateGrepGlobFirewall,
21
+ distillHtmlWebPayload,
22
+ evaluateBlastRadiusBreaker,
23
+ fnv1a64Hex,
24
+ normalizeLinesForShingling,
25
+ computeFileShingles,
26
+ detectDuplicateClones,
27
+ evaluateHardcodedOracle,
28
+ evaluateOverengineeringDiffGate
29
+ } from './bucketBAlphaBeta.mjs';
30
+
31
+ export {
32
+ evaluateSubagentGovernor,
33
+ evaluateVaguePromptAnchor,
34
+ evaluateMcpCliRouter,
35
+ evaluateLspSymbolRouter,
36
+ compileProseRulesToHooks
37
+ } from './bucketBGamma.mjs';