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,386 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { getHomeDir, canonicalizePath } from './paths.mjs';
5
+ import { SESSION_RISK_THRESHOLDS } from './constants.mjs';
6
+ import { atomicWriteFileSync } from './atomic_io.mjs';
7
+ import { SavedQuotaReceiptLedger, SAVINGS_EVENT_TYPES } from './coach/saved_quota_ledger.mjs';
8
+ import { evaluateSilentPrefixMutations } from './shared/detectors.mjs';
9
+
10
+ export { evaluateSilentPrefixMutations };
11
+
12
+ /**
13
+ * Phase 0: PrefixCacheShield Transaction Manager
14
+ *
15
+ * Prevents self-inflicted KV prefix-cache busting by intercepting writes to:
16
+ * - ~/.gemini/GEMINI.md and .gemini/GEMINI.md / .gemini/rules/**\/*.md
17
+ * - workspace GEMINI.md / AGENTS.md / .antigravityignore / mcp_config.json
18
+ * - .agents/CONTEXT.md / .agents/rules/**\/*.md / .agents/skills/**\/SKILL.md
19
+ * - ~/.gemini/antigravity/skills/<skill>/SKILL.md (and antigravity-cli/skills)
20
+ *
21
+ * Strictly excludes CLAUDE.md, .claude/, and .cursorrules per ISS-021.
22
+ */
23
+
24
+ const FOREIGN_NON_ANTIGRAVITY_RULE_RE = /(^|[\\/])(CLAUDE\.md|\.cursorrules)$|(^|[\\/])\.claude([\\/]|$)/i;
25
+
26
+ export const PREFIX_CACHE_SHIELD_CONSTANTS = Object.freeze({
27
+ WARM_CACHE_TOKEN_THRESHOLD: SESSION_RISK_THRESHOLDS?.WARM_CACHE_LOCK_TOKENS || 50000,
28
+ PROTECTED_FILE_REGEX:
29
+ /(^|[\\/])(GEMINI\.md|AGENTS\.md|SKILL\.md|\.antigravityignore|mcp_config\.json)$|(^|[\\/])\.gemini[\\/](GEMINI\.md|rules[\\/].+\.md)$|(^|[\\/])\.agents[\\/](CONTEXT\.md|rules[\\/].+\.md|skills[\\/].+[\\/]SKILL\.md)$/i
30
+ });
31
+
32
+ export function getDefaultPendingDeltasPath(homeDir = getHomeDir()) {
33
+ return path.join(homeDir, '.gemini', 'antigravity', 'agy-horizon', 'pending_rule_deltas.json');
34
+ }
35
+
36
+ export function isProtectedPrefixFile(filePath = '') {
37
+ if (!filePath || typeof filePath !== 'string') return false;
38
+ const trimmed = filePath.trim();
39
+ if (!trimmed) return false;
40
+ if (FOREIGN_NON_ANTIGRAVITY_RULE_RE.test(trimmed)) return false;
41
+ return PREFIX_CACHE_SHIELD_CONSTANTS.PROTECTED_FILE_REGEX.test(trimmed);
42
+ }
43
+
44
+ export function isWarmCacheState(session = {}, warmThreshold = PREFIX_CACHE_SHIELD_CONSTANTS.WARM_CACHE_TOKEN_THRESHOLD) {
45
+ if (!session || typeof session !== 'object') return false;
46
+ if (
47
+ session.forceColdBust === true ||
48
+ session.forceHotCache === true ||
49
+ session.postCompact === true ||
50
+ session.isPostCompact === true
51
+ ) {
52
+ return false;
53
+ }
54
+ if (session.isPreTurn1 === true || (Number(session.turnCount) === 0 && session.forcePreTurn1 === true)) {
55
+ return false;
56
+ }
57
+ const stateStr = String(session.cacheState || '').trim().toUpperCase();
58
+ if (stateStr === 'COLD' || stateStr === 'POST_COMPACT') {
59
+ return false;
60
+ }
61
+ if (session.cacheWarm === true || stateStr === 'WARM' || stateStr === 'WARM_5M' || stateStr === 'WARM_1H') {
62
+ return true;
63
+ }
64
+ const cachedTokens = Number(session.cachedTokens ?? session.cacheReadTokens ?? 0);
65
+ const cacheTtlSeconds = Number(session.cacheTtlSeconds ?? session.ttlRemainingSec ?? session.ttlRemainingSeconds ?? 0);
66
+ return cachedTokens >= warmThreshold && cacheTtlSeconds > 0;
67
+ }
68
+
69
+ export function formatStagedBadge(stagedCount = 0) {
70
+ const n = Math.max(0, Number(stagedCount) || 0);
71
+ if (n === 0) return '';
72
+ if (n === 1) {
73
+ return '⏳ 1 Rule Update Staged (Waiting for Cache TTL expiry to prevent Prefix Bust)';
74
+ }
75
+ return `⏳ ${n} Rule Updates Staged (Waiting for Cache TTL expiry to prevent Prefix Bust)`;
76
+ }
77
+
78
+ function writeAtomicSync(targetPath, contentStr) {
79
+ atomicWriteFileSync(targetPath, contentStr, { encoding: 'utf8' });
80
+ }
81
+
82
+ /**
83
+ * Applies a single delta operation ('ADD' | 'MODIFY' | 'REMOVE' | 'REPLACE' | 'REORDER')
84
+ * to the existing text content of a rule or skill file.
85
+ */
86
+ export function applyRuleDeltaToContent(existingText = '', delta = {}) {
87
+ const op = String(delta.operation || delta.op || 'ADD').toUpperCase();
88
+ const base = String(existingText || '');
89
+
90
+ if (op === 'REPLACE' || op === 'REORDER') {
91
+ return String(delta.newContent ?? delta.content ?? base);
92
+ }
93
+
94
+ if (op === 'REMOVE') {
95
+ const targetStr = String(delta.targetText || delta.ruleText || delta.content || '').trim();
96
+ if (!targetStr) return base;
97
+ const lines = base.split(/\r?\n/);
98
+ const filtered = lines.filter(line => line.trim() !== targetStr && !line.includes(targetStr));
99
+ return filtered.join('\n');
100
+ }
101
+
102
+ if (op === 'MODIFY') {
103
+ const targetStr = String(delta.targetText ?? delta.target ?? '').trim();
104
+ const replacementStr = String(delta.replacementText ?? delta.ruleText ?? delta.content ?? delta.newContent ?? '').trim();
105
+ if (targetStr && base.includes(targetStr)) {
106
+ return base.replace(targetStr, () => replacementStr);
107
+ }
108
+ return base ? `${base.replace(/\s+$/, '')}\n${replacementStr}\n` : `${replacementStr}\n`;
109
+ }
110
+
111
+ // Default: 'ADD'
112
+ const addition = String(delta.ruleText ?? delta.content ?? delta.newContent ?? '').trim();
113
+ if (!addition) return base;
114
+ if (base.includes(addition)) return base;
115
+
116
+ if (!base.trim()) {
117
+ return `${addition}\n`;
118
+ }
119
+ return `${base.replace(/\s+$/, '')}\n${addition}\n`;
120
+ }
121
+
122
+ export class PrefixCacheShield {
123
+ constructor(options = {}) {
124
+ this.homeDir = options.homeDir || getHomeDir();
125
+ this.queuePath = options.queuePath || getDefaultPendingDeltasPath(this.homeDir);
126
+ this.warmCacheThreshold = Number.isFinite(options.warmCacheThreshold)
127
+ ? options.warmCacheThreshold
128
+ : PREFIX_CACHE_SHIELD_CONSTANTS.WARM_CACHE_TOKEN_THRESHOLD;
129
+ this.reflectorQueue = options.reflectorQueue || null;
130
+ this._memoryQueue = null;
131
+ }
132
+
133
+ attachReflectorQueue(reflectorQueue) {
134
+ this.reflectorQueue = reflectorQueue || null;
135
+ return this;
136
+ }
137
+
138
+ _loadQueue() {
139
+ if (Array.isArray(this._memoryQueue) && fs.existsSync(this.queuePath)) {
140
+ try {
141
+ const parsed = JSON.parse(fs.readFileSync(this.queuePath, 'utf8'));
142
+ if (Array.isArray(parsed.deltas)) {
143
+ this._memoryQueue = parsed.deltas;
144
+ return this._memoryQueue;
145
+ }
146
+ } catch {}
147
+ }
148
+ if (fs.existsSync(this.queuePath)) {
149
+ try {
150
+ const parsed = JSON.parse(fs.readFileSync(this.queuePath, 'utf8'));
151
+ this._memoryQueue = Array.isArray(parsed?.deltas) ? parsed.deltas : [];
152
+ return this._memoryQueue;
153
+ } catch {}
154
+ }
155
+ this._memoryQueue = [];
156
+ return this._memoryQueue;
157
+ }
158
+
159
+ _saveQueue(deltas = []) {
160
+ this._memoryQueue = Array.isArray(deltas) ? deltas : [];
161
+ const payload = {
162
+ schemaVersion: 1,
163
+ updatedAt: new Date().toISOString(),
164
+ stagedCount: this._memoryQueue.length,
165
+ badge: formatStagedBadge(this._memoryQueue.length),
166
+ deltas: this._memoryQueue
167
+ };
168
+ writeAtomicSync(this.queuePath, JSON.stringify(payload, null, 2) + '\n');
169
+ }
170
+
171
+ /**
172
+ * Determines whether the session's prefix cache is currently warm and locked.
173
+ */
174
+ isPrefixLocked(session = {}) {
175
+ return isWarmCacheState(session, this.warmCacheThreshold);
176
+ }
177
+
178
+ /**
179
+ * Returns current queue status and UI badge metadata.
180
+ */
181
+ getStatus(session = {}) {
182
+ const deltas = this._loadQueue();
183
+ const reflectorApproved = this.reflectorQueue?.listItems
184
+ ? this.reflectorQueue.listItems({ status: 'approved' }).length
185
+ : 0;
186
+ const totalStaged = deltas.length + reflectorApproved;
187
+ const locked = this.isPrefixLocked(session);
188
+ return {
189
+ locked,
190
+ stagedCount: totalStaged,
191
+ pendingDeltasCount: deltas.length,
192
+ reflectorApprovedCount: reflectorApproved,
193
+ badge: formatStagedBadge(totalStaged),
194
+ queuePath: this.queuePath,
195
+ deltas: [...deltas]
196
+ };
197
+ }
198
+
199
+ /**
200
+ * Stages or immediately applies a rule/skill file mutation depending on prefix cache warmth.
201
+ */
202
+ stageOrApplyDelta(deltaRequest = {}, session = {}) {
203
+ const targetPath = path.resolve(String(deltaRequest.targetPath || ''));
204
+ if (!targetPath) {
205
+ throw new Error('PrefixCacheShield: targetPath is required');
206
+ }
207
+
208
+ const deltaRecord = {
209
+ id: deltaRequest.id || `delta-${crypto.randomBytes(6).toString('hex')}`,
210
+ targetPath,
211
+ canonicalTargetPath: canonicalizePath(targetPath),
212
+ operation: String(deltaRequest.operation || 'ADD').toUpperCase(),
213
+ ruleText: deltaRequest.ruleText ?? null,
214
+ targetText: deltaRequest.targetText ?? deltaRequest.target ?? null,
215
+ replacementText: deltaRequest.replacementText ?? null,
216
+ newContent: deltaRequest.newContent ?? deltaRequest.content ?? null,
217
+ source: String(deltaRequest.source || 'coach'),
218
+ metadata: deltaRequest.metadata || {},
219
+ createdAt: deltaRequest.createdAt || new Date().toISOString()
220
+ };
221
+
222
+ const existingQueue = this._loadQueue();
223
+ const cacheTtlSeconds = Number(session?.cacheTtlSeconds ?? session?.ttlRemainingSec ?? session?.ttlRemainingSeconds ?? 0);
224
+ const forceColdBust = Boolean(session?.forceColdBust === true || session?.forceHotCache === true);
225
+ const isPreTurn1 = Boolean(
226
+ session?.isPreTurn1 === true || (Number(session?.turnCount) === 0 && session?.forcePreTurn1 === true)
227
+ );
228
+ const locked =
229
+ !forceColdBust &&
230
+ (this.isPrefixLocked(session) || (existingQueue.length > 0 && cacheTtlSeconds > 0 && !isPreTurn1));
231
+
232
+ if (locked) {
233
+ existingQueue.push(deltaRecord);
234
+ this._saveQueue(existingQueue);
235
+ const protectedTokens = Math.max(0, Math.round(Number(session?.cachedTokens || 0)));
236
+ if (protectedTokens > 0) {
237
+ try {
238
+ const ledgerDbPath = path.join(path.dirname(this.queuePath), 'saved_quota_ledger.sqlite');
239
+ const ledger = new SavedQuotaReceiptLedger({ homeDir: this.homeDir, dbPath: ledgerDbPath });
240
+ ledger.recordSaving({
241
+ sessionId: String(session?.sessionId || session?.conversationId || 'default-session'),
242
+ eventType: SAVINGS_EVENT_TYPES.COLD_PREFILL_AVOIDED,
243
+ tokensSaved: protectedTokens,
244
+ dedupeKey: `shield:${deltaRecord.id}`,
245
+ detail: `Staged ${path.basename(targetPath)} edit during warm ${Math.round(protectedTokens / 1000)}k prefix cache`
246
+ });
247
+ } catch (err) {
248
+ void err;
249
+ }
250
+ }
251
+ return {
252
+ staged: true,
253
+ flushed: false,
254
+ deferred: true,
255
+ locked: true,
256
+ reason: 'CACHE_WARM_FENCE',
257
+ delta: deltaRecord,
258
+ stagedCount: existingQueue.length,
259
+ badge: formatStagedBadge(existingQueue.length),
260
+ queuePath: this.queuePath
261
+ };
262
+ }
263
+
264
+ if (existingQueue.length > 0 && (cacheTtlSeconds <= 0 || isPreTurn1 || forceColdBust)) {
265
+ existingQueue.push(deltaRecord);
266
+ this._saveQueue(existingQueue);
267
+ const flushResult = this._flushAllNow(forceColdBust ? 'FORCE_COLD_BUST' : 'COLD_OR_PRE_TURN_1');
268
+ return {
269
+ staged: false,
270
+ flushed: true,
271
+ deferred: false,
272
+ locked: false,
273
+ delta: deltaRecord,
274
+ flushedCount: flushResult.flushedCount,
275
+ modifiedFiles: flushResult.modifiedFiles,
276
+ stagedCount: 0,
277
+ badge: ''
278
+ };
279
+ }
280
+
281
+ const existingText = fs.existsSync(targetPath) ? fs.readFileSync(targetPath, 'utf8') : '';
282
+ const nextContent = applyRuleDeltaToContent(existingText, deltaRecord);
283
+ writeAtomicSync(targetPath, nextContent);
284
+ return {
285
+ staged: false,
286
+ flushed: true,
287
+ deferred: false,
288
+ locked: false,
289
+ delta: deltaRecord,
290
+ flushedCount: 1,
291
+ modifiedFiles: [targetPath],
292
+ stagedCount: existingQueue.length,
293
+ badge: formatStagedBadge(existingQueue.length)
294
+ };
295
+ }
296
+
297
+ /**
298
+ * Flushes staged deltas only if the prefix lock has expired (`cacheTtlSeconds === 0`,
299
+ * `cacheState === 'COLD'`, `postCompact === true`, or `force === true`).
300
+ */
301
+ flushIfEligible(session = {}) {
302
+ const forceFlush = Boolean(session?.force === true || session?.forceColdBust === true);
303
+ const postCompact = Boolean(session?.postCompact === true || session?.isPostCompact === true);
304
+ const cacheTtlSeconds = Number(session?.cacheTtlSeconds ?? session?.ttlRemainingSec ?? session?.ttlRemainingSeconds ?? 0);
305
+ const isPreTurn1 = Boolean(
306
+ session?.isPreTurn1 === true || (Number(session?.turnCount) === 0 && session?.forcePreTurn1 === true)
307
+ );
308
+
309
+ if (!forceFlush && !postCompact && (this.isPrefixLocked(session) || (cacheTtlSeconds > 0 && !isPreTurn1))) {
310
+ const status = this.getStatus(session);
311
+ return {
312
+ flushed: false,
313
+ deferred: true,
314
+ reason: 'CACHE_WARM_FENCE',
315
+ stagedCount: status.stagedCount,
316
+ queuedCount: status.stagedCount,
317
+ badge: status.badge,
318
+ modifiedFiles: []
319
+ };
320
+ }
321
+ return this._flushAllNow(forceFlush ? 'FORCE_FLUSH' : (postCompact ? 'POST_COMPACT' : 'TTL_EXPIRED_OR_ELIGIBLE'));
322
+ }
323
+
324
+ /**
325
+ * Explicitly flushes all queued rule/skill deltas during a `/handoff` baton pass
326
+ * or `PostCompact` lifecycle boundary.
327
+ */
328
+ flushOnHandoff() {
329
+ return this._flushAllNow('EXPLICIT_HANDOFF');
330
+ }
331
+
332
+ flushOnPostCompact() {
333
+ return this._flushAllNow('POST_COMPACT');
334
+ }
335
+
336
+ _flushAllNow(reason = 'MANUAL') {
337
+ const queue = this._loadQueue();
338
+ const modifiedFilesSet = new Set();
339
+ let flushedCount = 0;
340
+
341
+ for (const delta of queue) {
342
+ const filePath = delta.targetPath;
343
+ if (!filePath) continue;
344
+ const existing = fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf8') : '';
345
+ const nextContent = applyRuleDeltaToContent(existing, delta);
346
+ writeAtomicSync(filePath, nextContent);
347
+ modifiedFilesSet.add(filePath);
348
+ flushedCount++;
349
+ }
350
+
351
+ if (queue.length > 0) {
352
+ this._saveQueue([]);
353
+ }
354
+
355
+ // Bridge: flush approved ReflectorQueue items together when cold / PostCompact / handoff
356
+ if (this.reflectorQueue && typeof this.reflectorQueue.flushApprovedWhenCold === 'function') {
357
+ try {
358
+ const rqRes = this.reflectorQueue.flushApprovedWhenCold({
359
+ isCacheWarm: false,
360
+ cacheTtlSeconds: 0,
361
+ cachedTokens: 0,
362
+ bypassShield: true
363
+ });
364
+ if (rqRes && rqRes.flushedCount > 0) {
365
+ flushedCount += rqRes.flushedCount;
366
+ for (const f of rqRes.flushedItems || []) {
367
+ if (f?.targetPath) modifiedFilesSet.add(f.targetPath);
368
+ }
369
+ }
370
+ } catch {}
371
+ }
372
+
373
+ return {
374
+ flushed: true,
375
+ deferred: false,
376
+ reason,
377
+ flushedCount,
378
+ stagedCount: 0,
379
+ queuedCount: 0,
380
+ badge: '',
381
+ modifiedFiles: Array.from(modifiedFilesSet)
382
+ };
383
+ }
384
+ }
385
+
386
+ export default PrefixCacheShield;