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,399 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { canonicalizePath } from './path_canonicalizer.mjs';
5
+ import { fingerprintErrorLoop } from './session_forensics.mjs';
6
+ import { resolveModelCeiling } from './constants.mjs';
7
+
8
+ /**
9
+ * Sensor 1: detectDirtySnapshots (DIRTY_SNAP)
10
+ * Flags files modified on disk by external processes after agent last touched them.
11
+ */
12
+ export function detectDirtySnapshots(stepEvents = [], workspacePath = '') {
13
+ const lastTouchMap = new Map();
14
+ const fileTools = new Set([
15
+ 'view_file', 'read_file',
16
+ 'write_to_file', 'write_file',
17
+ 'replace_file_content', 'edit_file'
18
+ ]);
19
+
20
+ for (const ev of stepEvents) {
21
+ if (ev.targetPath && (fileTools.has(ev.toolName) || ev.type === 'FILE_ACCESS')) {
22
+ const ts = Number(ev.timestampMs || (ev.createdAt ? Date.parse(ev.createdAt) : 0));
23
+ if (!Number.isFinite(ts) || ts <= 0) continue;
24
+ const canonical = canonicalizePath(ev.targetPath);
25
+ const prev = lastTouchMap.get(canonical) || 0;
26
+ lastTouchMap.set(canonical, Math.max(prev, ts));
27
+ }
28
+ }
29
+
30
+ const dirtySnapshotPaths = [];
31
+ for (const [filePath, lastTouchMs] of lastTouchMap.entries()) {
32
+ if (!Number.isFinite(lastTouchMs) || lastTouchMs <= 0) continue;
33
+ try {
34
+ if (fs.existsSync(filePath)) {
35
+ const stat = fs.statSync(filePath);
36
+ if (stat.mtimeMs > lastTouchMs + 500) {
37
+ dirtySnapshotPaths.push(filePath);
38
+ }
39
+ }
40
+ } catch {}
41
+ }
42
+
43
+ return dirtySnapshotPaths;
44
+ }
45
+
46
+ /**
47
+ * Sensor 2: auditSchemaAndPayloads (SCHEMA_TAX)
48
+ * Audits Turn 0 schema cost and oversized tool payloads (>25k tokens).
49
+ */
50
+ export function auditSchemaAndPayloads(stepEvents = [], toolUsageLedger = {}, config = {}) {
51
+ let schemaTokens = 0;
52
+ for (const ev of stepEvents) {
53
+ if (ev.stepIndex === 0 && (ev.type === 'SCHEMA' || ev.type === 'ANCHOR_SCHEMA')) {
54
+ schemaTokens += ev.tokenEstimate || 0;
55
+ }
56
+ }
57
+
58
+ const resolvedDynamicCeiling = resolveModelCeiling(
59
+ config.activeModel || config.modelId || config.model || 'default',
60
+ config.context_window || config.contextWindow || null,
61
+ { useLegacyDefault: true, config }
62
+ );
63
+ const baseCeiling = config.max_tokens || config.maxTokens || config.nativeCeilingTokens || resolvedDynamicCeiling;
64
+ const schemaTaxPct = Number(((schemaTokens / baseCeiling) * 100).toFixed(1));
65
+ const unusedMcpServers = [];
66
+
67
+ if (schemaTaxPct > 15 && toolUsageLedger && toolUsageLedger.servers) {
68
+ for (const [serverName, meta] of Object.entries(toolUsageLedger.servers)) {
69
+ const calls = meta.invocationsLast15Sessions ?? meta.invocations ?? 0;
70
+ if (calls === 0) {
71
+ unusedMcpServers.push(serverName);
72
+ }
73
+ }
74
+ }
75
+
76
+ const maxPayloadTokens = config.max_tool_payload_tokens || 25000;
77
+ let oversizedPayloadDetected = false;
78
+
79
+ // Check last turn tool outputs
80
+ for (let i = stepEvents.length - 1; i >= 0; i--) {
81
+ const ev = stepEvents[i];
82
+ if (ev.role === 'user') break; // stop at boundary of last turn
83
+ if ((ev.role === 'tool' || ev.type === 'TOOL_RESULT') && (ev.tokenEstimate || 0) > maxPayloadTokens) {
84
+ oversizedPayloadDetected = true;
85
+ break;
86
+ }
87
+ }
88
+
89
+ return { schemaTaxPct, unusedMcpServers, oversizedPayloadDetected };
90
+ }
91
+
92
+ /**
93
+ * Sensor 3: detectUnseenCallers (UNSEEN_CALLERS)
94
+ * Identifies workspace files importing target files that are NOT in ACTIVE_SET.
95
+ */
96
+ let cachedReverseMap = null;
97
+ let cachedWorkspace = '';
98
+ let cachedScanTime = 0;
99
+
100
+ export function buildReverseImportMap(workspacePath) {
101
+ const now = Date.now();
102
+ if (cachedReverseMap && cachedWorkspace === workspacePath && (now - cachedScanTime) < 15000) {
103
+ return cachedReverseMap;
104
+ }
105
+
106
+ const importMap = new Map(); // targetBaseName -> Set of canonical importer paths
107
+ if (!workspacePath || !fs.existsSync(workspacePath)) {
108
+ return importMap;
109
+ }
110
+
111
+ const fileExtensions = new Set(['.js', '.mjs', '.ts', '.tsx', '.py']);
112
+ const skipDirs = new Set(['node_modules', '.git', 'dist', 'build', '.gemini', 'out']);
113
+
114
+ function scanDir(dir, depth = 0) {
115
+ if (depth > 4) return;
116
+ let entries = [];
117
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
118
+
119
+ for (const entry of entries) {
120
+ const full = path.join(dir, entry.name);
121
+ if (entry.isDirectory()) {
122
+ if (!skipDirs.has(entry.name)) scanDir(full, depth + 1);
123
+ } else if (entry.isFile()) {
124
+ const ext = path.extname(entry.name).toLowerCase();
125
+ if (fileExtensions.has(ext)) {
126
+ try {
127
+ const content = fs.readFileSync(full, 'utf8');
128
+ const canonicalImporter = canonicalizePath(full);
129
+ // JS/TS imports
130
+ const jsMatches = content.matchAll(/(?:import|require|from)\s*\(?['"]([^'"]+)['"]/g);
131
+ const importerDir = path.dirname(full);
132
+ for (const m of jsMatches) {
133
+ const rawSpec = m[1];
134
+ const noExtSpec = rawSpec.replace(/\.[^/.]+$/, '');
135
+ const base = path.basename(noExtSpec).toLowerCase();
136
+ if (rawSpec.startsWith('.')) {
137
+ const resolvedNoExt = canonicalizePath(path.resolve(importerDir, noExtSpec));
138
+ if (!importMap.has(resolvedNoExt)) importMap.set(resolvedNoExt, new Set());
139
+ importMap.get(resolvedNoExt).add(canonicalImporter);
140
+ }
141
+ const dirBase = path.posix.join(path.basename(path.dirname(noExtSpec)).toLowerCase(), base);
142
+ if (dirBase && dirBase !== `.` && !dirBase.startsWith('./')) {
143
+ if (!importMap.has(dirBase)) importMap.set(dirBase, new Set());
144
+ importMap.get(dirBase).add(canonicalImporter);
145
+ }
146
+ if (base && base !== 'index') {
147
+ if (!importMap.has(base)) importMap.set(base, new Set());
148
+ importMap.get(base).add(canonicalImporter);
149
+ }
150
+ }
151
+ // Python imports
152
+ const pyMatches = content.matchAll(/(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))/g);
153
+ for (const m of pyMatches) {
154
+ const mod = (m[1] || m[2] || '').split('.').pop()?.toLowerCase();
155
+ if (mod) {
156
+ if (!importMap.has(mod)) importMap.set(mod, new Set());
157
+ importMap.get(mod).add(canonicalImporter);
158
+ }
159
+ }
160
+ } catch {}
161
+ }
162
+ }
163
+ }
164
+ }
165
+
166
+ scanDir(workspacePath, 0);
167
+ cachedReverseMap = importMap;
168
+ cachedWorkspace = workspacePath;
169
+ cachedScanTime = now;
170
+ return importMap;
171
+ }
172
+
173
+ export function detectUnseenCallers(targetFiles = [], activeSetPaths = [], workspacePath = '') {
174
+ const unseen = new Set();
175
+ const activeSet = new Set(activeSetPaths.map(p => canonicalizePath(p)));
176
+ const reverseMap = buildReverseImportMap(workspacePath);
177
+
178
+ for (const target of targetFiles) {
179
+ const canonicalTarget = canonicalizePath(target);
180
+ const targetNoExt = canonicalTarget.replace(/\.[^/.]+$/, '');
181
+ const baseName = path.basename(target).replace(/\.[^/.]+$/, '').toLowerCase();
182
+ const dirBase = path.posix.join(path.basename(path.dirname(canonicalTarget)).toLowerCase(), baseName);
183
+ const candidateSets = [
184
+ reverseMap.get(targetNoExt),
185
+ reverseMap.get(dirBase),
186
+ baseName !== 'index' ? reverseMap.get(baseName) : null
187
+ ];
188
+
189
+ for (const callers of candidateSets) {
190
+ if (callers) {
191
+ for (const caller of callers) {
192
+ if (!activeSet.has(caller) && caller !== canonicalTarget) {
193
+ unseen.add(caller);
194
+ }
195
+ }
196
+ }
197
+ }
198
+ }
199
+
200
+ return Array.from(unseen);
201
+ }
202
+
203
+ /**
204
+ * Sensor 4: detectLegacyPoison (LEGACY_POISON)
205
+ * Detects deprecated legacy code loaded into attention context.
206
+ */
207
+ export function detectLegacyPoison(stepEvents = [], config = {}) {
208
+ const deprecatedGlobs = config.deprecated_paths || ['**/legacy/**', '**/deprecated/**', '**/v1/**'];
209
+ const legacyPoison = new Set();
210
+
211
+ for (const ev of stepEvents) {
212
+ if (!ev.targetPath) continue;
213
+ const canon = canonicalizePath(ev.targetPath);
214
+ const hasDeprecatedTag = Boolean(ev.isDeprecatedContent) ||
215
+ /@deprecated/i.test(String(ev.content || '').split(/\r?\n/).slice(0, 30).join('\n'));
216
+ if (hasDeprecatedTag) {
217
+ legacyPoison.add(canon);
218
+ } else {
219
+ const isDeprecated = deprecatedGlobs.some(g => canon.includes(g.replace(/\*/g, '').toLowerCase()));
220
+ if (isDeprecated) {
221
+ legacyPoison.add(canon);
222
+ }
223
+ }
224
+ }
225
+
226
+ return Array.from(legacyPoison);
227
+ }
228
+
229
+ /**
230
+ * Sensor 5: evaluateQuotaAndStreamShield (QUOTA_AND_STREAM_SHIELD)
231
+ * Guards 10% rolling quota floor and flags >600-line rewrite stream cutoff risk.
232
+ */
233
+ export function evaluateQuotaAndStreamShield(sidecarState = {}, targetFiles = [], promptText = '', config = {}) {
234
+ const remainingFraction = sidecarState.telemetry?.quota?.remaining_fraction ?? 1.0;
235
+ const quotaFloor = config.quota_floor_fraction ?? 0.10;
236
+ const quotaFloorBreached = remainingFraction < quotaFloor;
237
+
238
+ const inPlan = Boolean(sidecarState.sessionMeta?.inPlanMode);
239
+ const activeModel = String(sidecarState.sessionMeta?.activeModel || '');
240
+ const isFlash = activeModel.includes('flash');
241
+ const tokens = sidecarState.telemetry?.totalInputTokens || 0;
242
+ const planToFlashHandoffNeeded = inPlan && isFlash && tokens > 40000;
243
+
244
+ const maxLines = config.max_single_write_lines || 600;
245
+ const streamCutoffRiskFiles = [];
246
+
247
+ for (const tf of targetFiles) {
248
+ try {
249
+ if (fs.existsSync(tf)) {
250
+ const text = fs.readFileSync(tf, 'utf8');
251
+ const lines = text.split(/\r?\n/).length;
252
+ if (lines > maxLines) {
253
+ const isFullRewrite = /(rewrite|regenerate|replace whole|re-implement|create entire)/i.test(promptText) ||
254
+ !/(lines?|slice|chunk|diff|function|method|surgical)/i.test(promptText);
255
+ if (isFullRewrite) {
256
+ streamCutoffRiskFiles.push(canonicalizePath(tf));
257
+ }
258
+ }
259
+ }
260
+ } catch {}
261
+ }
262
+
263
+ return {
264
+ quotaFloorBreached,
265
+ planToFlashHandoffNeeded,
266
+ streamCutoffRiskFiles
267
+ };
268
+ }
269
+
270
+ /**
271
+ * Sensor 6: evaluateLoopAndGitGuard (LOOP_AND_GIT_GUARD)
272
+ * Detects 3-strike error loops and uncheckpointed git code drift.
273
+ */
274
+ let cachedGitResult = { dirtyGitFileCount: 0, uncheckpointedGitDrift: false, timestampMs: 0, workspace: '' };
275
+
276
+ export function evaluateLoopAndGitGuard(stepEvents = [], sidecarState = {}, workspacePath = '', config = {}) {
277
+ const limit = config.consecutive_error_strike_limit || 3;
278
+ let trailingErrorStreak = 0;
279
+
280
+ for (let i = stepEvents.length - 1; i >= 0; i--) {
281
+ const ev = stepEvents[i];
282
+ if (ev.exitCode !== null && ev.exitCode !== 0) {
283
+ trailingErrorStreak++;
284
+ } else if (ev.exitCode === 0) {
285
+ break;
286
+ }
287
+ }
288
+
289
+ const loopFp = fingerprintErrorLoop(stepEvents);
290
+ const threeStrikeLoop = trailingErrorStreak >= limit || Boolean(sidecarState.brainSignals?.errorLoop?.loop) || loopFp.loop;
291
+ const loopFingerprint = loopFp.fingerprint || sidecarState.brainSignals?.errorLoop?.fingerprint || null;
292
+ const turnsSincePassing = sidecarState.sessionMeta?.turnsSinceLastPassingTest || 0;
293
+ const fileLimit = config.uncheckpointed_dirty_file_limit || 4;
294
+
295
+ const editTools = new Set(['write_to_file', 'write_file', 'replace_file_content', 'multi_replace_file_content', 'edit_file']);
296
+ const sessionEditedPaths = new Set();
297
+ for (const ev of stepEvents) {
298
+ if (ev?.targetPath && (editTools.has(String(ev.toolName || '').toLowerCase()) || ev.type === 'FILE_WRITE')) {
299
+ sessionEditedPaths.add(canonicalizePath(ev.targetPath));
300
+ }
301
+ }
302
+ const sessionHasEdits = sessionEditedPaths.size > 0 || Boolean(sidecarState.brainSignals?.activeSignal?.sessionHasWorkspaceEdits);
303
+
304
+ // If passing tests are recent (<3 turns) or session made 0 workspace edits, git drift is false by definition
305
+ if (turnsSincePassing < 3 || !workspacePath || !sessionHasEdits) {
306
+ return { threeStrikeLoop, loopFingerprint, uncheckpointedGitDrift: false, dirtyGitFileCount: 0 };
307
+ }
308
+
309
+ const now = Date.now();
310
+ if (cachedGitResult.workspace === workspacePath && (now - cachedGitResult.timestampMs) < 3000) {
311
+ return {
312
+ threeStrikeLoop,
313
+ loopFingerprint,
314
+ uncheckpointedGitDrift: cachedGitResult.uncheckpointedGitDrift,
315
+ dirtyGitFileCount: cachedGitResult.dirtyGitFileCount
316
+ };
317
+ }
318
+
319
+ let dirtyGitFileCount = 0;
320
+ let uncheckpointedGitDrift = false;
321
+
322
+ // Only spawn git if .git directory exists in workspace
323
+ const gitDir = path.join(workspacePath, '.git');
324
+ if (fs.existsSync(gitDir)) {
325
+ try {
326
+ const stdout = execFileSync('git', ['status', '--porcelain'], {
327
+ cwd: workspacePath,
328
+ timeout: 200,
329
+ encoding: 'utf8',
330
+ stdio: ['ignore', 'pipe', 'ignore']
331
+ });
332
+ const lines = stdout.split(/\r?\n/).filter(l => l.trim().length > 0);
333
+ if (sessionEditedPaths.size > 0) {
334
+ const matched = lines.filter(rawLine => {
335
+ const rel = rawLine.slice(3).trim().replace(/^"(.*)"$/, '$1');
336
+ const abs = canonicalizePath(path.isAbsolute(rel) ? rel : path.join(workspacePath, rel));
337
+ return sessionEditedPaths.has(abs);
338
+ });
339
+ dirtyGitFileCount = matched.length;
340
+ } else {
341
+ dirtyGitFileCount = lines.length;
342
+ }
343
+
344
+ if (dirtyGitFileCount >= fileLimit && turnsSincePassing >= 3) {
345
+ uncheckpointedGitDrift = true;
346
+ }
347
+ } catch {
348
+ // Git unavailable or timeout, skip gracefully
349
+ }
350
+ }
351
+
352
+ cachedGitResult = {
353
+ dirtyGitFileCount,
354
+ uncheckpointedGitDrift,
355
+ timestampMs: now,
356
+ workspace: workspacePath
357
+ };
358
+
359
+ return { threeStrikeLoop, loopFingerprint, uncheckpointedGitDrift, dirtyGitFileCount };
360
+ }
361
+
362
+ /**
363
+ * Aggregator: runs all 6 sensors in under 15ms.
364
+ */
365
+ export function runAllBlindspotSensors(params = {}) {
366
+ const {
367
+ stepEvents = [],
368
+ sidecarState = {},
369
+ workspacePath = '',
370
+ targetFiles = [],
371
+ activeSetPaths = [],
372
+ toolUsageLedger = {},
373
+ promptText = '',
374
+ config = {}
375
+ } = params;
376
+
377
+ const dirtySnapshotPaths = detectDirtySnapshots(stepEvents, workspacePath);
378
+ const { schemaTaxPct, unusedMcpServers, oversizedPayloadDetected } = auditSchemaAndPayloads(stepEvents, toolUsageLedger, config);
379
+ const unseenCallers = detectUnseenCallers(targetFiles, activeSetPaths, workspacePath);
380
+ const legacyPoisonPaths = detectLegacyPoison(stepEvents, config);
381
+ const { quotaFloorBreached, planToFlashHandoffNeeded, streamCutoffRiskFiles } = evaluateQuotaAndStreamShield(sidecarState, targetFiles, promptText, config);
382
+ const { threeStrikeLoop, loopFingerprint, uncheckpointedGitDrift, dirtyGitFileCount } = evaluateLoopAndGitGuard(stepEvents, sidecarState, workspacePath, config);
383
+
384
+ return {
385
+ dirtySnapshotPaths,
386
+ schemaTaxPct,
387
+ unusedMcpServers,
388
+ oversizedPayloadDetected,
389
+ unseenCallers,
390
+ legacyPoisonPaths,
391
+ quotaFloorBreached,
392
+ planToFlashHandoffNeeded,
393
+ streamCutoffRiskFiles,
394
+ threeStrikeLoop,
395
+ loopFingerprint,
396
+ uncheckpointedGitDrift,
397
+ dirtyGitFileCount
398
+ };
399
+ }