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,574 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { atomicWriteFileSync } from '../atomic_io.mjs';
5
+
6
+ /**
7
+ * Phase 4.1: Turn-0 Workspace Hygiene & MCP Profile Gate (`src/core/coach/turn_zero_gate.mjs`)
8
+ *
9
+ * Enforces Invariant 1 (Zero Mid-Session Prefix Mutation):
10
+ * - Never modifies `AGENTS.md`, `.agents/CONTEXT.md`, or active MCP server schemas while a
11
+ * session KV cache is warm (`cachedTokens >= 15000` and `ttlRemainingSeconds > 0`).
12
+ * - Queues all system-prefix hygiene changes in `TurnZeroGate` until Turn 0 (cold session) or `/handoff`.
13
+ * - Scans `AGENTS.md` and `.agents/CONTEXT.md` for U-shaped attention placement, moving
14
+ * `NEVER`, `MUST`, `NON-NEGOTIABLE` rules out of the 30%–70% middle trough into the
15
+ * top 25% Primacy and bottom 20% Recency bands.
16
+ * - Provides 1-click Pre-Session MCP Profiles (`Lean Code`, `UI/Frontend`, `Full Stack`)
17
+ * to dampen unused MCP JSON schemas before Turn 1 warms the cache.
18
+ */
19
+
20
+ export const TURN_ZERO_GATE_CONSTANTS = Object.freeze({
21
+ WARM_CACHE_LOCK_TOKENS: 15000,
22
+ PRIMACY_BAND_END: 0.25,
23
+ MIDDLE_TROUGH_START: 0.30,
24
+ MIDDLE_TROUGH_END: 0.70,
25
+ RECENCY_BAND_START: 0.80,
26
+ CRITICAL_RULE_REGEX: /\b(NEVER|MUST|NON-NEGOTIABLE)\b/i,
27
+ FENCED_BLOCK_TTL_MS: 48 * 60 * 60 * 1000,
28
+ MAX_RECOMMENDED_RULE_LINES: 200
29
+ });
30
+
31
+ export const MCP_PROFILES = Object.freeze({
32
+ 'Lean Code': Object.freeze({
33
+ id: 'lean_code',
34
+ label: 'Lean Code',
35
+ description: 'Core filesystem & terminal only; dampens browser, design, and cloud MCP schemas.',
36
+ enabledServers: ['filesystem', 'git'],
37
+ dampenedServers: ['chrome-devtools', 'figma', 'shadcn-ui', 'notebooklm', 'playwright'],
38
+ estimatedSavedTokens: 14800
39
+ }),
40
+ 'UI/Frontend': Object.freeze({
41
+ id: 'ui_frontend',
42
+ label: 'UI/Frontend',
43
+ description: 'Enables Chrome DevTools, Figma, and shadcn-ui; dampens backend/database MCP schemas.',
44
+ enabledServers: ['chrome-devtools', 'figma', 'shadcn-ui'],
45
+ dampenedServers: ['notebooklm', 'postgres', 'databricks', 'looker'],
46
+ estimatedSavedTokens: 8400
47
+ }),
48
+ 'Full Stack': Object.freeze({
49
+ id: 'full_stack',
50
+ label: 'Full Stack',
51
+ description: 'Enables full frontend, browser, and knowledge MCP servers for cross-stack debugging.',
52
+ enabledServers: ['chrome-devtools', 'figma', 'shadcn-ui', 'google-developer-knowledge', 'notebooklm'],
53
+ dampenedServers: [],
54
+ estimatedSavedTokens: 0
55
+ })
56
+ });
57
+
58
+ export function isCriticalDirective(line = '') {
59
+ const trimmed = String(line || '').trim();
60
+ if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('```')) return false;
61
+ return TURN_ZERO_GATE_CONSTANTS.CRITICAL_RULE_REGEX.test(trimmed);
62
+ }
63
+
64
+ /**
65
+ * Scans rule file content (`AGENTS.md` or `.agents/CONTEXT.md`) and relocates critical
66
+ * `NEVER`, `MUST`, `NON-NEGOTIABLE` rules out of the 30%–70% middle trough into the
67
+ * top 25% Primacy and bottom 20% Recency bands.
68
+ */
69
+ export function optimizeUShapedRulePlacement(rawContent = '') {
70
+ const startMs = performance.now();
71
+ const lines = String(rawContent || '').split(/\r?\n/);
72
+ const totalLines = lines.length;
73
+ if (totalLines < 4) {
74
+ return {
75
+ reordered: false,
76
+ strandedCount: 0,
77
+ strandedRules: [],
78
+ primacyInsertedCount: 0,
79
+ recencyInsertedCount: 0,
80
+ optimizedContent: String(rawContent || ''),
81
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
82
+ };
83
+ }
84
+
85
+ const troughStartIdx = Math.floor(totalLines * TURN_ZERO_GATE_CONSTANTS.MIDDLE_TROUGH_START);
86
+ const troughEndIdx = Math.ceil(totalLines * TURN_ZERO_GATE_CONSTANTS.MIDDLE_TROUGH_END);
87
+
88
+ const strandedRules = [];
89
+ const keptLines = [];
90
+
91
+ for (let i = 0; i < totalLines; i++) {
92
+ const line = lines[i];
93
+ const inTrough = i >= troughStartIdx && i <= troughEndIdx;
94
+ if (inTrough && isCriticalDirective(line)) {
95
+ strandedRules.push({
96
+ originalLineNumber: i + 1,
97
+ positionRatio: Number((i / Math.max(1, totalLines - 1)).toFixed(3)),
98
+ text: line
99
+ });
100
+ } else {
101
+ keptLines.push(line);
102
+ }
103
+ }
104
+
105
+ if (strandedRules.length === 0) {
106
+ return {
107
+ reordered: false,
108
+ strandedCount: 0,
109
+ strandedRules: [],
110
+ primacyInsertedCount: 0,
111
+ recencyInsertedCount: 0,
112
+ optimizedContent: String(rawContent || ''),
113
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
114
+ };
115
+ }
116
+
117
+ // Split rescued rules between Top 25% Primacy band and Bottom 20% Recency band
118
+ const half = Math.ceil(strandedRules.length / 2);
119
+ const primacyBatch = strandedRules.slice(0, half).map((r) => r.text);
120
+ const recencyBatch = strandedRules.slice(half).map((r) => r.text);
121
+
122
+ // Find insertion index inside Top 25% Primacy (right after first heading if present)
123
+ let primacyInsertIdx = 0;
124
+ const maxPrimacyIdx = Math.max(1, Math.floor(keptLines.length * TURN_ZERO_GATE_CONSTANTS.PRIMACY_BAND_END));
125
+ for (let i = 0; i < Math.min(keptLines.length, maxPrimacyIdx); i++) {
126
+ if (keptLines[i].trim().startsWith('#')) {
127
+ primacyInsertIdx = i + 1;
128
+ break;
129
+ }
130
+ }
131
+
132
+ const reorderedLines = [
133
+ ...keptLines.slice(0, primacyInsertIdx),
134
+ ...primacyBatch,
135
+ ...keptLines.slice(primacyInsertIdx),
136
+ ...recencyBatch
137
+ ];
138
+
139
+ return {
140
+ reordered: true,
141
+ strandedCount: strandedRules.length,
142
+ strandedRules,
143
+ primacyInsertedCount: primacyBatch.length,
144
+ recencyInsertedCount: recencyBatch.length,
145
+ optimizedContent: reorderedLines.join('\n'),
146
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Feature #17: Inserts or updates a 48-hour TTL fenced managed coach block
152
+ * (`COACH` or `MODEL_ROUTING`) using deterministic, timestamp-free markers so
153
+ * identical directives produce byte-for-byte identical prefix content across turns.
154
+ */
155
+ export function upsertFencedCoachBlock(
156
+ rawContent = '',
157
+ {
158
+ blockType = 'COACH',
159
+ bodyText = '',
160
+ nowMs = Date.now(),
161
+ ttlMs = TURN_ZERO_GATE_CONSTANTS.FENCED_BLOCK_TTL_MS
162
+ } = {}
163
+ ) {
164
+ const cleanType = String(blockType || 'COACH').toUpperCase().replace(/[^A-Z0-9_]/g, '');
165
+ const createdIso = new Date(nowMs).toISOString();
166
+ const expiresIso = new Date(nowMs + ttlMs).toISOString();
167
+ const startMarker = `<!-- HORIZON:${cleanType}:START -->`;
168
+ const endMarker = `<!-- HORIZON:${cleanType}:END -->`;
169
+ const blockContent = `${startMarker}\n${String(bodyText || '').trim()}\n${endMarker}`;
170
+
171
+ const existingRegex = new RegExp(
172
+ `<!--\\s*HORIZON:${cleanType}:START\\b[^>]*-->[\\s\\S]*?<!--\\s*HORIZON:${cleanType}:END\\s*-->`,
173
+ 'g'
174
+ );
175
+
176
+ const base = String(rawContent || '');
177
+ let updatedContent;
178
+ if (existingRegex.test(base)) {
179
+ updatedContent = base.replace(existingRegex, () => blockContent);
180
+ } else {
181
+ updatedContent = base.trim() ? `${base.trimEnd()}\n\n${blockContent}\n` : `${blockContent}\n`;
182
+ }
183
+
184
+ return {
185
+ blockType: cleanType,
186
+ timestamp: createdIso,
187
+ expiresAt: expiresIso,
188
+ createdAtMs: nowMs,
189
+ expiresAtMs: nowMs + ttlMs,
190
+ blockContent,
191
+ updatedContent
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Feature #17: Scans rule content for `<!-- HORIZON:<TYPE>:START ... -->` blocks and
197
+ * removes any block whose external `blockMeta` TTL (or legacy inline `expires_at`) has elapsed.
198
+ */
199
+ export function pruneExpiredFencedBlocks(
200
+ rawContent = '',
201
+ {
202
+ nowMs = Date.now(),
203
+ ttlMs = TURN_ZERO_GATE_CONSTANTS.FENCED_BLOCK_TTL_MS,
204
+ blockMeta = null
205
+ } = {}
206
+ ) {
207
+ const base = String(rawContent || '');
208
+ const blockRegex =
209
+ /<!--\s*HORIZON:([A-Z0-9_]+):START\b([^>]*)-->([\s\S]*?)<!--\s*HORIZON:\1:END\s*-->\n?/g;
210
+
211
+ const prunedBlockTypes = [];
212
+ const cleanedContent = base.replace(blockRegex, (fullMatch, typeName, attrStr) => {
213
+ let expiresAtMs = NaN;
214
+
215
+ const metaEntry = blockMeta && typeof blockMeta === 'object' ? blockMeta[typeName] : null;
216
+ if (metaEntry) {
217
+ if (Number.isFinite(metaEntry.expiresAtMs)) {
218
+ expiresAtMs = metaEntry.expiresAtMs;
219
+ } else if (typeof metaEntry.expiresAt === 'string') {
220
+ expiresAtMs = Date.parse(metaEntry.expiresAt);
221
+ } else if (Number.isFinite(metaEntry.createdAtMs)) {
222
+ expiresAtMs = metaEntry.createdAtMs + ttlMs;
223
+ }
224
+ }
225
+
226
+ if (!Number.isFinite(expiresAtMs)) {
227
+ const expiresMatch = attrStr.match(/(?:expires_at|expires)="([^"]+)"/i);
228
+ const timestampMatch = attrStr.match(/(?:timestamp|created)="([^"]+)"/i);
229
+ if (expiresMatch) {
230
+ expiresAtMs = Date.parse(expiresMatch[1]);
231
+ } else if (timestampMatch) {
232
+ const tsMs = Date.parse(timestampMatch[1]);
233
+ if (Number.isFinite(tsMs)) expiresAtMs = tsMs + ttlMs;
234
+ }
235
+ }
236
+
237
+ if (Number.isFinite(expiresAtMs) && nowMs >= expiresAtMs) {
238
+ prunedBlockTypes.push(typeName);
239
+ return '';
240
+ }
241
+ return fullMatch;
242
+ });
243
+
244
+ const normalizedCleaned = cleanedContent.replace(/\n{3,}/g, '\n\n');
245
+
246
+ return {
247
+ pruned: prunedBlockTypes.length > 0,
248
+ prunedCount: prunedBlockTypes.length,
249
+ prunedBlockTypes,
250
+ cleanedContent: normalizedCleaned
251
+ };
252
+ }
253
+
254
+ /**
255
+ * DET-27: Audits rule file length against the 200-line ceiling (`MEMORY.md` / `AGENTS.md`).
256
+ */
257
+ export function auditRuleLineCountHygiene(
258
+ rawContent = '',
259
+ { maxLines = TURN_ZERO_GATE_CONSTANTS.MAX_RECOMMENDED_RULE_LINES } = {}
260
+ ) {
261
+ const text = String(rawContent || '');
262
+ const lineCount = text ? text.split(/\r?\n/).length : 0;
263
+ const excessLines = Math.max(0, lineCount - maxLines);
264
+ return {
265
+ exceedsCap: lineCount > maxLines,
266
+ lineCount,
267
+ maxLines,
268
+ excessLines,
269
+ detectorId: 'DET-27'
270
+ };
271
+ }
272
+
273
+ export class TurnZeroGate {
274
+ constructor(options = {}) {
275
+ this.warmCacheLockTokens = Number(
276
+ options.warmCacheLockTokens ?? TURN_ZERO_GATE_CONSTANTS.WARM_CACHE_LOCK_TOKENS
277
+ );
278
+ this.workspaceDir = options.workspaceDir || process.cwd();
279
+ this.metaPath =
280
+ options.metaPath ||
281
+ path.join(this.workspaceDir, '.agents', 'horizon', 'turn_zero_meta.json');
282
+ this.queuedMutations = [];
283
+ this.activeMcpProfile = options.activeMcpProfile || 'Full Stack';
284
+ }
285
+
286
+ _normalizeMetaKey(targetPath) {
287
+ return path.resolve(String(targetPath || '')).replace(/\\/g, '/').toLowerCase();
288
+ }
289
+
290
+ _readMetaStore() {
291
+ if (!fs.existsSync(this.metaPath)) return { version: 1, files: {} };
292
+ try {
293
+ const parsed = JSON.parse(fs.readFileSync(this.metaPath, 'utf8'));
294
+ if (!parsed || typeof parsed !== 'object') return { version: 1, files: {} };
295
+ if (!parsed.files || typeof parsed.files !== 'object') parsed.files = {};
296
+ return parsed;
297
+ } catch {
298
+ return { version: 1, files: {} };
299
+ }
300
+ }
301
+
302
+ _writeMetaStore(store) {
303
+ atomicWriteFileSync(this.metaPath, JSON.stringify(store, null, 2) + '\n', { encoding: 'utf8' });
304
+ }
305
+
306
+ _recordBlockMeta(targetPath, blockType, { createdAtMs, expiresAtMs, timestamp, expiresAt }) {
307
+ const store = this._readMetaStore();
308
+ const key = this._normalizeMetaKey(targetPath);
309
+ if (!store.files[key]) store.files[key] = {};
310
+ store.files[key][blockType] = {
311
+ createdAtMs,
312
+ expiresAtMs,
313
+ createdAt: timestamp,
314
+ expiresAt
315
+ };
316
+ this._writeMetaStore(store);
317
+ }
318
+
319
+ _getBlockMetaForFile(targetPath) {
320
+ const store = this._readMetaStore();
321
+ const key = this._normalizeMetaKey(targetPath);
322
+ return store.files[key] || null;
323
+ }
324
+
325
+ _removeBlockMetaTypes(targetPath, prunedTypes = []) {
326
+ if (!Array.isArray(prunedTypes) || prunedTypes.length === 0) return;
327
+ const store = this._readMetaStore();
328
+ const key = this._normalizeMetaKey(targetPath);
329
+ if (!store.files[key]) return;
330
+ for (const t of prunedTypes) {
331
+ delete store.files[key][t];
332
+ }
333
+ this._writeMetaStore(store);
334
+ }
335
+
336
+ /**
337
+ * Invariant 1 check: returns true if session KV cache is warm (`cachedTokens >= 15000 && ttlRemainingSeconds > 0`).
338
+ */
339
+ isWarmPrefixLocked(session = {}) {
340
+ const cachedTokens = Number(session.cachedTokens ?? session.cacheReadTokens ?? 0);
341
+ const ttlRemainingSeconds = Number(session.ttlRemainingSeconds ?? session.cacheTtlSeconds ?? 0);
342
+ const isHandoff = Boolean(session.isHandoff || session.onHandoff);
343
+ const isTurnZero = Number(session.turnCount ?? -1) === 0 && cachedTokens < this.warmCacheLockTokens;
344
+
345
+ if (isHandoff || isTurnZero) return false;
346
+ return cachedTokens >= this.warmCacheLockTokens && ttlRemainingSeconds > 0;
347
+ }
348
+
349
+ /**
350
+ * Queues or applies a mutation to `AGENTS.md`, `.agents/CONTEXT.md`, or MCP config.
351
+ * Never mutates disk while `isWarmPrefixLocked(session)` is true.
352
+ */
353
+ queueOrApplyHygieneMutation(mutation = {}, session = {}) {
354
+ if (this.isWarmPrefixLocked(session)) {
355
+ const queuedItem = {
356
+ id: `tzg-${Date.now()}-${this.queuedMutations.length + 1}`,
357
+ ...mutation,
358
+ queuedAt: new Date().toISOString()
359
+ };
360
+ this.queuedMutations.push(queuedItem);
361
+ return {
362
+ applied: false,
363
+ queued: true,
364
+ lockedByInvariant1: true,
365
+ queueLength: this.queuedMutations.length,
366
+ item: queuedItem
367
+ };
368
+ }
369
+
370
+ return this._applyMutationNow(mutation);
371
+ }
372
+
373
+ _applyMutationNow(mutation = {}) {
374
+ if (mutation.type === 'MCP_PROFILE') {
375
+ const profile = MCP_PROFILES[mutation.profileName] || MCP_PROFILES['Lean Code'];
376
+ this.activeMcpProfile = profile.label;
377
+ if (mutation.mcpConfigPath && fs.existsSync(path.dirname(mutation.mcpConfigPath))) {
378
+ const payload = {
379
+ activeProfile: profile.id,
380
+ enabledServers: profile.enabledServers,
381
+ dampenedServers: profile.dampenedServers
382
+ };
383
+ atomicWriteFileSync(mutation.mcpConfigPath, JSON.stringify(payload, null, 2) + '\n', { encoding: 'utf8' });
384
+ }
385
+ return {
386
+ applied: true,
387
+ queued: false,
388
+ lockedByInvariant1: false,
389
+ profile
390
+ };
391
+ }
392
+
393
+ if (mutation.targetPath && mutation.newContent !== undefined) {
394
+ atomicWriteFileSync(mutation.targetPath, String(mutation.newContent), { encoding: 'utf8' });
395
+ if (mutation.type === 'FENCED_COACH_BLOCK_PRUNE' && Array.isArray(mutation.prunedBlockTypes)) {
396
+ this._removeBlockMetaTypes(mutation.targetPath, mutation.prunedBlockTypes);
397
+ }
398
+ return {
399
+ applied: true,
400
+ queued: false,
401
+ lockedByInvariant1: false,
402
+ targetPath: mutation.targetPath
403
+ };
404
+ }
405
+
406
+ return {
407
+ applied: true,
408
+ queued: false,
409
+ lockedByInvariant1: false
410
+ };
411
+ }
412
+
413
+ /**
414
+ * Scans workspace `AGENTS.md` and `.agents/CONTEXT.md` for U-shaped attention placement
415
+ * and either applies (at Turn 0 / `/handoff`) or queues (when warm cache locked).
416
+ */
417
+ auditAndOptimizeWorkspaceRules(session = {}, { workspaceDir = this.workspaceDir, writeChanges = false, nowMs = Date.now() } = {}) {
418
+ const candidates = [
419
+ path.join(workspaceDir, 'AGENTS.md'),
420
+ path.join(workspaceDir, '.agents', 'CONTEXT.md'),
421
+ path.join(workspaceDir, 'MEMORY.md')
422
+ ];
423
+
424
+ const fileReports = [];
425
+ for (const filePath of candidates) {
426
+ if (!fs.existsSync(filePath)) continue;
427
+ const raw = fs.readFileSync(filePath, 'utf8');
428
+ const pruneAudit = pruneExpiredFencedBlocks(raw, {
429
+ nowMs,
430
+ blockMeta: this._getBlockMetaForFile(filePath)
431
+ });
432
+ const analysis = optimizeUShapedRulePlacement(pruneAudit.cleanedContent);
433
+ const lineCapAudit = auditRuleLineCountHygiene(analysis.optimizedContent);
434
+ let mutationStatus = null;
435
+
436
+ if (writeChanges && (analysis.reordered || pruneAudit.pruned)) {
437
+ mutationStatus = this.queueOrApplyHygieneMutation(
438
+ {
439
+ type: 'U_SHAPED_REORDER',
440
+ targetPath: filePath,
441
+ newContent: analysis.optimizedContent,
442
+ prunedBlockTypes: pruneAudit.prunedBlockTypes
443
+ },
444
+ session
445
+ );
446
+ }
447
+
448
+ fileReports.push({
449
+ filePath,
450
+ ...analysis,
451
+ prunedExpiredBlocks: pruneAudit.prunedCount,
452
+ prunedBlockTypes: pruneAudit.prunedBlockTypes,
453
+ lineCapAudit,
454
+ mutationStatus
455
+ });
456
+ }
457
+
458
+ return {
459
+ lockedByInvariant1: this.isWarmPrefixLocked(session),
460
+ queuedCount: this.queuedMutations.length,
461
+ availableMcpProfiles: Object.values(MCP_PROFILES),
462
+ activeMcpProfile: this.activeMcpProfile,
463
+ files: fileReports
464
+ };
465
+ }
466
+
467
+ /**
468
+ * Feature #17: Upserts a 48-hour TTL fenced block (`COACH` or `MODEL_ROUTING`) into `targetPath`,
469
+ * strictly gated by Invariant 1 (queued if KV cache is warm, written immediately if cold / Turn 0).
470
+ */
471
+ stageOrApplyFencedBlock(
472
+ {
473
+ targetPath,
474
+ blockType = 'COACH',
475
+ bodyText = '',
476
+ nowMs = Date.now(),
477
+ ttlMs = TURN_ZERO_GATE_CONSTANTS.FENCED_BLOCK_TTL_MS
478
+ } = {},
479
+ session = {}
480
+ ) {
481
+ if (!targetPath) {
482
+ throw new Error('TurnZeroGate.stageOrApplyFencedBlock: targetPath is required');
483
+ }
484
+ const existing = fs.existsSync(targetPath) ? fs.readFileSync(targetPath, 'utf8') : '';
485
+ const upserted = upsertFencedCoachBlock(existing, { blockType, bodyText, nowMs, ttlMs });
486
+ this._recordBlockMeta(targetPath, upserted.blockType, upserted);
487
+ return {
488
+ ...upserted,
489
+ mutation: this.queueOrApplyHygieneMutation(
490
+ {
491
+ type: 'FENCED_COACH_BLOCK_UPSERT',
492
+ blockType: upserted.blockType,
493
+ targetPath,
494
+ newContent: upserted.updatedContent
495
+ },
496
+ session
497
+ )
498
+ };
499
+ }
500
+
501
+ /**
502
+ * Feature #17: Prunes expired 48-hour TTL fenced blocks from `targetPath` strictly
503
+ * when the KV cache is cold (or queues the prune if the cache is currently warm).
504
+ */
505
+ pruneExpiredFencedBlocksOnColdCache(
506
+ targetPath,
507
+ session = {},
508
+ { nowMs = Date.now(), ttlMs = TURN_ZERO_GATE_CONSTANTS.FENCED_BLOCK_TTL_MS } = {}
509
+ ) {
510
+ if (!targetPath || !fs.existsSync(targetPath)) {
511
+ return { pruned: false, prunedCount: 0, mutation: null };
512
+ }
513
+ const existing = fs.readFileSync(targetPath, 'utf8');
514
+ const res = pruneExpiredFencedBlocks(existing, {
515
+ nowMs,
516
+ ttlMs,
517
+ blockMeta: this._getBlockMetaForFile(targetPath)
518
+ });
519
+ if (!res.pruned) {
520
+ return { ...res, mutation: null };
521
+ }
522
+ const mutation = this.queueOrApplyHygieneMutation(
523
+ {
524
+ type: 'FENCED_COACH_BLOCK_PRUNE',
525
+ targetPath,
526
+ newContent: res.cleanedContent,
527
+ prunedBlockTypes: res.prunedBlockTypes
528
+ },
529
+ session
530
+ );
531
+ return {
532
+ ...res,
533
+ mutation
534
+ };
535
+ }
536
+
537
+ /**
538
+ * Selects a 1-click Pre-Session MCP Profile (`Lean Code`, `UI/Frontend`, `Full Stack`).
539
+ */
540
+ selectMcpProfile(profileName = 'Lean Code', session = {}, options = {}) {
541
+ return this.queueOrApplyHygieneMutation(
542
+ {
543
+ type: 'MCP_PROFILE',
544
+ profileName,
545
+ mcpConfigPath: options.mcpConfigPath || null
546
+ },
547
+ session
548
+ );
549
+ }
550
+
551
+ /**
552
+ * Flushes all queued hygiene mutations at Turn 0 or during `/handoff`.
553
+ */
554
+ flushQueuedMutations(session = { turnCount: 0, cachedTokens: 0, ttlRemainingSeconds: 0, isHandoff: true }) {
555
+ if (this.isWarmPrefixLocked(session)) {
556
+ return {
557
+ flushed: false,
558
+ flushedCount: 0,
559
+ remainingCount: this.queuedMutations.length
560
+ };
561
+ }
562
+
563
+ const pending = this.queuedMutations.splice(0, this.queuedMutations.length);
564
+ const applied = pending.map((m) => this._applyMutationNow(m));
565
+ return {
566
+ flushed: applied.length > 0,
567
+ flushedCount: applied.length,
568
+ remainingCount: 0,
569
+ applied
570
+ };
571
+ }
572
+ }
573
+
574
+ export default TurnZeroGate;