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,376 @@
1
+ /**
2
+ * @file src/engine-node/sensors/blindspots.mjs
3
+ * Local filesystem & AST repository blindspot forensic sensors.
4
+ *
5
+ * Implements the 4 core repository sensors:
6
+ * 1. DIRTY_SNAP (DET-28): Detects files modified externally after last touch.
7
+ * 2. UNSEEN_CALLERS (DET-27): Reverses workspace AST import graph to identify unmonitored callers.
8
+ * 3. LEGACY_POISON (DET-26): Detects deprecated / v1 code or @deprecated headers in context.
9
+ * 4. FOREIGN_BLEED (DET-25 / DET-23): Detects foreign knowledge:// items or cross-workspace bleed.
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+
15
+ /**
16
+ * Normalizes a path for consistent case-insensitive slash-independent comparisons.
17
+ * @param {string} p
18
+ * @returns {string}
19
+ */
20
+ export function canonicalizePath(p = '') {
21
+ const norm = String(p || '').replace(/\\/g, '/').trim();
22
+ // On Windows, drive letters should be normalized
23
+ return norm.toLowerCase();
24
+ }
25
+
26
+ /**
27
+ * Sensor 1: detectDirtySnapshots (DIRTY_SNAP - DET-28)
28
+ * Flags files modified on disk by external processes after agent last touched them.
29
+ *
30
+ * @param {Array<object>} stepEvents
31
+ * @param {string} [workspacePath='']
32
+ * @returns {string[]} List of dirty file paths
33
+ */
34
+ export function detectDirtySnapshots(stepEvents = [], workspacePath = '') {
35
+ if (!Array.isArray(stepEvents)) return [];
36
+ const lastTouchMap = new Map();
37
+ const fileTools = new Set([
38
+ 'view_file', 'read_file', 'read', 'view',
39
+ 'write_to_file', 'write_file', 'write',
40
+ 'replace_file_content', 'edit_file', 'edit'
41
+ ]);
42
+
43
+ for (const ev of stepEvents) {
44
+ if (!ev || typeof ev !== 'object') continue;
45
+ const tool = String(ev.toolName || ev.tool || '').toLowerCase();
46
+ const target = ev.targetPath || ev.filePath || ev.path;
47
+ if (target && (fileTools.has(tool) || ev.type === 'FILE_ACCESS' || ev.type === 'FILE_READ' || ev.type === 'FILE_WRITE')) {
48
+ const ts = Number(ev.timestampMs || (ev.createdAt ? Date.parse(ev.createdAt) : 0) || ev.timestamp || 0);
49
+ if (!Number.isFinite(ts) || ts <= 0) continue;
50
+ const canonical = canonicalizePath(target);
51
+ const prev = lastTouchMap.get(canonical);
52
+ const nextTs = prev ? Math.max(prev.ts, ts) : ts;
53
+ lastTouchMap.set(canonical, { ts: nextTs, rawPath: String(target).trim(), canonical });
54
+ }
55
+ }
56
+
57
+ const dirtySnapshotPaths = [];
58
+ for (const [canonical, entry] of lastTouchMap.entries()) {
59
+ const lastTouchMs = entry.ts;
60
+ if (!Number.isFinite(lastTouchMs) || lastTouchMs <= 0) continue;
61
+ try {
62
+ const candidatePath = fs.existsSync(entry.rawPath)
63
+ ? entry.rawPath
64
+ : (workspacePath && fs.existsSync(path.resolve(workspacePath, entry.rawPath))
65
+ ? path.resolve(workspacePath, entry.rawPath)
66
+ : canonical);
67
+ if (fs.existsSync(candidatePath)) {
68
+ const stat = fs.statSync(candidatePath);
69
+ if (stat.mtimeMs > lastTouchMs + 500) {
70
+ dirtySnapshotPaths.push(canonical);
71
+ }
72
+ }
73
+ } catch {
74
+ // Ignore file access errors
75
+ }
76
+ }
77
+
78
+ return dirtySnapshotPaths;
79
+ }
80
+
81
+ let cachedReverseMap = null;
82
+ let cachedWorkspace = null;
83
+ let cachedScanTime = 0;
84
+
85
+ /**
86
+ * Builds or retrieves cached reverse import map for workspace (<15s TTL).
87
+ * Bounded to max depth 4, max 250 files to guarantee <8ms execution.
88
+ *
89
+ * @param {string} workspacePath
90
+ * @returns {Map<string, Set<string>>}
91
+ */
92
+ export function buildReverseImportMap(workspacePath) {
93
+ const now = Date.now();
94
+ if (cachedReverseMap && cachedWorkspace === workspacePath && (now - cachedScanTime) < 15000) {
95
+ return cachedReverseMap;
96
+ }
97
+
98
+ const importMap = new Map();
99
+ if (!workspacePath || !fs.existsSync(workspacePath)) {
100
+ return importMap;
101
+ }
102
+
103
+ const fileExtensions = new Set(['.js', '.mjs', '.ts', '.tsx', '.py']);
104
+ const skipDirs = new Set(['node_modules', '.git', 'dist', 'build', '.gemini', 'out', '.agents']);
105
+ let scannedCount = 0;
106
+
107
+ function scanDir(dir, depth = 0) {
108
+ if (depth > 4 || scannedCount >= 250) return;
109
+ let entries = [];
110
+ try {
111
+ entries = fs.readdirSync(dir, { withFileTypes: true });
112
+ } catch {
113
+ return;
114
+ }
115
+
116
+ for (const entry of entries) {
117
+ if (scannedCount >= 250) break;
118
+ const full = path.join(dir, entry.name);
119
+ if (entry.isDirectory()) {
120
+ if (!skipDirs.has(entry.name)) scanDir(full, depth + 1);
121
+ } else if (entry.isFile()) {
122
+ const ext = path.extname(entry.name).toLowerCase();
123
+ if (fileExtensions.has(ext)) {
124
+ scannedCount++;
125
+ try {
126
+ const content = fs.readFileSync(full, 'utf8');
127
+ const canonicalImporter = canonicalizePath(full);
128
+ const importerDir = path.dirname(full);
129
+
130
+ // JS/TS imports and requires
131
+ const jsMatches = content.matchAll(/(?:import|require|from)\s*\(?['"]([^'"]+)['"]/g);
132
+ for (const m of jsMatches) {
133
+ const rawSpec = m[1];
134
+ const noExtSpec = rawSpec.replace(/\.[^/.]+$/, '');
135
+ const base = path.basename(noExtSpec).toLowerCase();
136
+
137
+ if (rawSpec.startsWith('.')) {
138
+ const resolvedNoExt = canonicalizePath(path.resolve(importerDir, noExtSpec));
139
+ if (!importMap.has(resolvedNoExt)) importMap.set(resolvedNoExt, new Set());
140
+ importMap.get(resolvedNoExt).add(canonicalImporter);
141
+ }
142
+
143
+ const dirBase = path.posix.join(path.basename(path.dirname(noExtSpec)).toLowerCase(), base);
144
+ if (dirBase && dirBase !== '.' && !dirBase.startsWith('./')) {
145
+ if (!importMap.has(dirBase)) importMap.set(dirBase, new Set());
146
+ importMap.get(dirBase).add(canonicalImporter);
147
+ }
148
+
149
+ if (base && base !== 'index') {
150
+ if (!importMap.has(base)) importMap.set(base, new Set());
151
+ importMap.get(base).add(canonicalImporter);
152
+ }
153
+ }
154
+
155
+ // Python imports
156
+ const pyMatches = content.matchAll(/(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))/g);
157
+ for (const m of pyMatches) {
158
+ const mod = (m[1] || m[2] || '').split('.').pop()?.toLowerCase();
159
+ if (mod) {
160
+ if (!importMap.has(mod)) importMap.set(mod, new Set());
161
+ importMap.get(mod).add(canonicalImporter);
162
+ }
163
+ }
164
+ } catch {
165
+ // Ignore individual file read errors
166
+ }
167
+ }
168
+ }
169
+ }
170
+ }
171
+
172
+ scanDir(workspacePath, 0);
173
+ cachedReverseMap = importMap;
174
+ cachedWorkspace = workspacePath;
175
+ cachedScanTime = now;
176
+ return importMap;
177
+ }
178
+
179
+ /**
180
+ * Sensor 2: detectUnseenCallers (UNSEEN_CALLERS - DET-27)
181
+ * Identifies workspace files importing the targets that are not in the activeSet.
182
+ *
183
+ * @param {string[]} targetFiles
184
+ * @param {string[]} activeSetPaths
185
+ * @param {string} [workspacePath='']
186
+ * @returns {string[]} List of unseen caller file paths
187
+ */
188
+ export function detectUnseenCallers(targetFiles = [], activeSetPaths = [], workspacePath = '') {
189
+ const unseen = new Set();
190
+ const safeActivePaths = Array.isArray(activeSetPaths) ? activeSetPaths : [];
191
+ const safeTargets = Array.isArray(targetFiles) ? targetFiles : [];
192
+ const activeSet = new Set(safeActivePaths.filter(Boolean).map(p => canonicalizePath(p)));
193
+ const reverseMap = buildReverseImportMap(workspacePath);
194
+
195
+ for (const target of safeTargets) {
196
+ if (!target) continue;
197
+ const canonicalTarget = canonicalizePath(target);
198
+ const targetNoExt = canonicalTarget.replace(/\.[^/.]+$/, '');
199
+ const baseName = path.basename(target).replace(/\.[^/.]+$/, '').toLowerCase();
200
+ const dirBase = path.posix.join(path.basename(path.dirname(canonicalTarget)).toLowerCase(), baseName);
201
+ const candidateSets = [
202
+ reverseMap.get(targetNoExt),
203
+ reverseMap.get(dirBase),
204
+ baseName !== 'index' ? reverseMap.get(baseName) : null
205
+ ];
206
+
207
+ for (const callers of candidateSets) {
208
+ if (callers) {
209
+ for (const caller of callers) {
210
+ if (!activeSet.has(caller) && caller !== canonicalTarget) {
211
+ unseen.add(caller);
212
+ }
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ return Array.from(unseen);
219
+ }
220
+
221
+ /**
222
+ * Sensor 3: detectLegacyPoison (LEGACY_POISON - DET-26)
223
+ * Detects deprecated legacy code loaded into attention context.
224
+ *
225
+ * @param {Array<object>} stepEvents
226
+ * @param {object} [config={}]
227
+ * @returns {string[]} List of legacy poison file paths
228
+ */
229
+ export function detectLegacyPoison(stepEvents = [], config = {}) {
230
+ if (!Array.isArray(stepEvents)) return [];
231
+ const cfg = (config && typeof config === 'object') ? config : {};
232
+ const deprecatedGlobs = cfg.deprecated_paths || ['**/legacy/**', '**/deprecated/**', '**/v1/**'];
233
+ const legacyPoison = new Set();
234
+
235
+ for (const ev of stepEvents) {
236
+ if (!ev || typeof ev !== 'object') continue;
237
+ const target = ev.targetPath || ev.filePath || ev.path;
238
+ if (!target) continue;
239
+ const canon = canonicalizePath(target);
240
+ const hasDeprecatedTag = Boolean(ev.isDeprecatedContent) ||
241
+ /@deprecated/i.test(String(ev.content || '').split(/\r?\n/).slice(0, 30).join('\n'));
242
+
243
+ if (hasDeprecatedTag) {
244
+ legacyPoison.add(canon);
245
+ } else {
246
+ const isDeprecated = deprecatedGlobs.some(g => canon.includes(g.replace(/\*/g, '').toLowerCase()));
247
+ if (isDeprecated) {
248
+ legacyPoison.add(canon);
249
+ }
250
+ }
251
+ }
252
+
253
+ return Array.from(legacyPoison);
254
+ }
255
+
256
+ /**
257
+ * Sensor 4: detectForeignBleed (FOREIGN_BLEED - DET-25 / DET-23)
258
+ * Evaluates knowledge URIs (knowledge://) and cross-workspace path references.
259
+ *
260
+ * @param {Array<object>} stepEvents
261
+ * @param {string[]} [canonicalWorkspaces=[]]
262
+ * @param {object} [options={}]
263
+ * @returns {Array<object>} List of foreign bleed items
264
+ */
265
+ export function detectForeignBleed(stepEvents = [], canonicalWorkspaces = [], options = {}) {
266
+ if (!Array.isArray(stepEvents)) return [];
267
+ const safeWorkspaces = Array.isArray(canonicalWorkspaces) ? canonicalWorkspaces : [];
268
+ const allowedWorkspaces = safeWorkspaces
269
+ .map(w => canonicalizePath(w))
270
+ .filter(Boolean);
271
+
272
+ const bleedItems = [];
273
+ const seenUris = new Set();
274
+
275
+ for (const ev of stepEvents) {
276
+ if (!ev || typeof ev !== 'object') continue;
277
+ // 1. Check knowledge:// references
278
+ const text = [
279
+ ev.content,
280
+ ev.targetPath,
281
+ ev.filePath,
282
+ ev.uri,
283
+ ev.description
284
+ ].filter(Boolean).join(' ');
285
+
286
+ const knowledgeMatches = text.match(/knowledge:\/\/([a-zA-Z0-9_.-]+)/gi);
287
+ if (knowledgeMatches) {
288
+ for (const km of knowledgeMatches) {
289
+ if (!seenUris.has(km)) {
290
+ seenUris.add(km);
291
+ // If knowledge item points to metadata or workspace references outside allowedWorkspaces
292
+ const isBleed = Boolean(ev.isForeignBleed || ev.isBleed);
293
+ if (isBleed || allowedWorkspaces.length > 0) {
294
+ bleedItems.push({
295
+ uri: km,
296
+ type: 'KNOWLEDGE_BLEED',
297
+ source: ev.targetPath || ev.toolName || 'prompt',
298
+ reason: `Foreign knowledge item reference: ${km}`
299
+ });
300
+ }
301
+ }
302
+ }
303
+ }
304
+
305
+ // 2. Check cross-workspace path bleed
306
+ const targetPath = ev.targetPath || ev.filePath;
307
+ if (targetPath && allowedWorkspaces.length > 0) {
308
+ const canon = canonicalizePath(targetPath);
309
+ // Skip system or temporary tool output paths
310
+ if (!canon.includes('/tmp/') && !canon.includes('/temp/') && !canon.startsWith('node:')) {
311
+ const matchesAnyWorkspace = allowedWorkspaces.some(w => canon.startsWith(w));
312
+ if (!matchesAnyWorkspace && !seenUris.has(canon)) {
313
+ seenUris.add(canon);
314
+ bleedItems.push({
315
+ uri: canon,
316
+ type: 'WORKSPACE_BLEED',
317
+ source: targetPath,
318
+ reason: `Cross-workspace path reference outside active workspace roots: ${targetPath}`
319
+ });
320
+ }
321
+ }
322
+ }
323
+ }
324
+
325
+ return bleedItems;
326
+ }
327
+
328
+ /**
329
+ * Aggregator: runs all 4 blindspot sensors in <12ms.
330
+ *
331
+ * @param {object} params
332
+ * @param {Array<object>} [params.stepEvents=[]]
333
+ * @param {string[]} [params.targetFiles=[]]
334
+ * @param {string[]} [params.activeSetPaths=[]]
335
+ * @param {string} [params.workspacePath='']
336
+ * @param {string[]} [params.canonicalWorkspaces=[]]
337
+ * @param {object} [params.config={}]
338
+ * @returns {object} Aggregate blindspot forensic report
339
+ */
340
+ export function runBlindspotSensors(params = {}) {
341
+ const start = performance.now();
342
+ const safeParams = (params && typeof params === 'object') ? params : {};
343
+ const stepEvents = Array.isArray(safeParams.stepEvents) ? safeParams.stepEvents : [];
344
+ const targetFiles = Array.isArray(safeParams.targetFiles) ? safeParams.targetFiles : [];
345
+ const activeSetPaths = Array.isArray(safeParams.activeSetPaths) ? safeParams.activeSetPaths : [];
346
+ const workspacePath = safeParams.workspacePath || '';
347
+ const canonicalWorkspaces = Array.isArray(safeParams.canonicalWorkspaces)
348
+ ? safeParams.canonicalWorkspaces
349
+ : (workspacePath ? [workspacePath] : []);
350
+ const config = (safeParams.config && typeof safeParams.config === 'object') ? safeParams.config : {};
351
+
352
+ const dirtySnapshotPaths = detectDirtySnapshots(stepEvents, workspacePath);
353
+ const unseenCallers = detectUnseenCallers(targetFiles, activeSetPaths, workspacePath);
354
+ const legacyPoisonPaths = detectLegacyPoison(stepEvents, config);
355
+ const foreignBleedItems = detectForeignBleed(stepEvents, canonicalWorkspaces, params);
356
+
357
+ const durationMs = Number((performance.now() - start).toFixed(3));
358
+
359
+ return {
360
+ dirtySnapshotPaths,
361
+ unseenCallers,
362
+ legacyPoisonPaths,
363
+ foreignBleedItems,
364
+ durationMs
365
+ };
366
+ }
367
+
368
+ export default {
369
+ canonicalizePath,
370
+ detectDirtySnapshots,
371
+ buildReverseImportMap,
372
+ detectUnseenCallers,
373
+ detectLegacyPoison,
374
+ detectForeignBleed,
375
+ runBlindspotSensors
376
+ };
@@ -0,0 +1,223 @@
1
+ /**
2
+ * @file src/engine-node/sensors/git_merge_tree.mjs
3
+ * Non-destructive DET-31 Cross-Worktree Git Merge Conflict Sensor.
4
+ *
5
+ * Runs `git merge-tree --write-tree` with 0 working-tree or index mutations,
6
+ * and caches clean/conflict results per (workspaceDir, baseCommit, targetCommit, .git/index mtime, .git/HEAD mtime)
7
+ * so polling loops on win32 run in <0.05ms without repeated 35ms subprocess spawns.
8
+ */
9
+
10
+ import { execFileSync } from 'node:child_process';
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+
14
+ const MERGE_TREE_CACHE = new Map();
15
+ const MAX_CACHE_ENTRIES = 128;
16
+
17
+ function resolveGitStateStamp(cwd) {
18
+ try {
19
+ const gitDir = path.join(cwd, '.git');
20
+ const stGit = fs.statSync(gitDir);
21
+ if (!stGit.isDirectory() && !stGit.isFile()) return null;
22
+ let indexMtime = 0;
23
+ let headMtime = 0;
24
+ let refsMtime = 0;
25
+ try { indexMtime = fs.statSync(path.join(gitDir, 'index')).mtimeMs; } catch {}
26
+ try { headMtime = fs.statSync(path.join(gitDir, 'HEAD')).mtimeMs; } catch {}
27
+ try { refsMtime = fs.statSync(path.join(gitDir, 'refs', 'heads')).mtimeMs; } catch {}
28
+ return `${indexMtime}:${headMtime}:${refsMtime}`;
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+
34
+ export function clearGitMergeTreeCache() {
35
+ MERGE_TREE_CACHE.clear();
36
+ }
37
+
38
+ /**
39
+ * Parses conflict files and messages from git merge-tree output.
40
+ *
41
+ * @param {string} output
42
+ * @returns {{ conflictFiles: string[], conflictMessages: string[] }}
43
+ */
44
+ export function parseMergeTreeOutput(output = '') {
45
+ const lines = output.split(/\r?\n/);
46
+ const conflictFiles = new Set();
47
+ const conflictMessages = [];
48
+
49
+ for (const line of lines) {
50
+ const trimmed = line.trim();
51
+ if (!trimmed) continue;
52
+
53
+ // Line format: CONFLICT (content): Merge conflict in path/to/file.js
54
+ const conflictMatch = trimmed.match(/^CONFLICT\s*\(([^)]+)\):\s*(.+)$/i);
55
+ if (conflictMatch) {
56
+ conflictMessages.push(trimmed);
57
+ const detail = conflictMatch[2];
58
+ const fileMatch = detail.match(/(?:in|of)\s+([^\s]+)$/i);
59
+ if (fileMatch) {
60
+ conflictFiles.add(fileMatch[1].trim());
61
+ }
62
+ continue;
63
+ }
64
+
65
+ // Git merge-tree unmerged stage entry: 100644 <hash> <stage> <file>
66
+ const stageMatch = trimmed.match(/^\d{6}\s+[0-9a-f]{40,64}\s+[123]\s+(.+)$/i);
67
+ if (stageMatch) {
68
+ conflictFiles.add(stageMatch[1].trim());
69
+ }
70
+ }
71
+
72
+ return {
73
+ conflictFiles: Array.from(conflictFiles),
74
+ conflictMessages
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Probes for merge conflicts between two commits or branch heads non-destructively.
80
+ *
81
+ * @param {string} baseCommit - Commit or ref (e.g. 'HEAD', 'main')
82
+ * @param {string} targetCommit - Commit or ref (e.g. 'feature-branch', worktree commit)
83
+ * @param {object} [options={}]
84
+ * @param {string} [options.workspaceDir] - Repository working directory
85
+ * @param {boolean} [options.nameOnly=false] - Only report conflicting file names
86
+ * @param {number} [options.timeoutMs=5000] - Process execution timeout
87
+ * @param {boolean} [options.bypassCache=false] - Force fresh git subprocess execution
88
+ * @returns {{
89
+ * clean: boolean,
90
+ * hasConflict: boolean,
91
+ * treeHash: string | null,
92
+ * conflictFiles: string[],
93
+ * conflictMessages: string[],
94
+ * latencyMs: number,
95
+ * cached?: boolean,
96
+ * error?: string,
97
+ * degraded?: boolean
98
+ * }}
99
+ */
100
+ export function probeGitMergeTree(baseCommit, targetCommit, options = {}) {
101
+ const start = performance.now();
102
+ if (!baseCommit || !targetCommit) {
103
+ return {
104
+ clean: false,
105
+ hasConflict: false,
106
+ treeHash: null,
107
+ conflictFiles: [],
108
+ conflictMessages: [],
109
+ latencyMs: 0,
110
+ error: 'Both baseCommit and targetCommit must be provided'
111
+ };
112
+ }
113
+
114
+ const cwd = options.workspaceDir || process.cwd();
115
+ const gitStamp = !options.bypassCache ? resolveGitStateStamp(cwd) : null;
116
+ const cacheKey = gitStamp
117
+ ? `${cwd}|${baseCommit}|${targetCommit}|${Boolean(options.nameOnly)}|${gitStamp}`
118
+ : null;
119
+
120
+ if (cacheKey && MERGE_TREE_CACHE.has(cacheKey)) {
121
+ const cachedEntry = MERGE_TREE_CACHE.get(cacheKey);
122
+ const latencyMs = Number((performance.now() - start).toFixed(4));
123
+ return {
124
+ ...cachedEntry,
125
+ conflictFiles: [...cachedEntry.conflictFiles],
126
+ conflictMessages: [...cachedEntry.conflictMessages],
127
+ latencyMs,
128
+ cached: true
129
+ };
130
+ }
131
+
132
+ const args = ['merge-tree', '--write-tree'];
133
+ if (options.nameOnly) {
134
+ args.push('--name-only');
135
+ }
136
+ args.push('--', String(baseCommit), String(targetCommit));
137
+
138
+ try {
139
+ const stdout = execFileSync('git', args, {
140
+ cwd,
141
+ encoding: 'utf8',
142
+ timeout: options.timeoutMs || 5000,
143
+ stdio: ['ignore', 'pipe', 'pipe']
144
+ });
145
+
146
+ const latencyMs = Number((performance.now() - start).toFixed(3));
147
+ const lines = stdout.trim().split(/\r?\n/);
148
+ const treeHash = lines[0] ? lines[0].trim() : null;
149
+
150
+ const result = {
151
+ clean: true,
152
+ hasConflict: false,
153
+ treeHash,
154
+ conflictFiles: [],
155
+ conflictMessages: [],
156
+ latencyMs
157
+ };
158
+ if (cacheKey) {
159
+ if (MERGE_TREE_CACHE.size >= MAX_CACHE_ENTRIES) {
160
+ const oldestKey = MERGE_TREE_CACHE.keys().next().value;
161
+ MERGE_TREE_CACHE.delete(oldestKey);
162
+ }
163
+ MERGE_TREE_CACHE.set(cacheKey, result);
164
+ }
165
+ return result;
166
+ } catch (err) {
167
+ const latencyMs = Number((performance.now() - start).toFixed(3));
168
+
169
+ // Exit status 1 signals a merge conflict in git merge-tree --write-tree
170
+ if (err && err.status === 1) {
171
+ const stderr = err.stderr ? String(err.stderr) : '';
172
+ if (/not something we can merge|fatal:|unknown option/i.test(stderr)) {
173
+ return {
174
+ clean: false,
175
+ hasConflict: false,
176
+ treeHash: null,
177
+ conflictFiles: [],
178
+ conflictMessages: [],
179
+ latencyMs,
180
+ error: stderr.trim() || 'Invalid commit or git error',
181
+ degraded: true
182
+ };
183
+ }
184
+
185
+ const out = (err.stdout ? String(err.stdout) : '') + '\n' + stderr;
186
+ const parsed = parseMergeTreeOutput(out);
187
+ const lines = (err.stdout ? String(err.stdout) : '').trim().split(/\r?\n/);
188
+ const treeHash = lines[0] && /^[0-9a-f]{40,64}$/i.test(lines[0].trim()) ? lines[0].trim() : null;
189
+ const hasRealConflict = parsed.conflictFiles.length > 0 || parsed.conflictMessages.length > 0;
190
+
191
+ const conflictResult = {
192
+ clean: false,
193
+ hasConflict: hasRealConflict,
194
+ treeHash,
195
+ conflictFiles: parsed.conflictFiles,
196
+ conflictMessages: parsed.conflictMessages,
197
+ latencyMs,
198
+ ...(hasRealConflict ? {} : { error: stderr.trim() || 'Merge probe failed', degraded: true })
199
+ };
200
+ if (cacheKey && hasRealConflict) {
201
+ MERGE_TREE_CACHE.set(cacheKey, conflictResult);
202
+ }
203
+ return conflictResult;
204
+ }
205
+
206
+ // Any other error (e.g. invalid git ref, git not found, git version < 2.38) degrades gracefully
207
+ return {
208
+ clean: false,
209
+ hasConflict: false,
210
+ treeHash: null,
211
+ conflictFiles: [],
212
+ conflictMessages: [],
213
+ latencyMs,
214
+ error: err ? err.message || String(err) : 'Unknown git merge-tree error',
215
+ degraded: true
216
+ };
217
+ }
218
+ }
219
+
220
+ export default {
221
+ probeGitMergeTree,
222
+ clearGitMergeTreeCache
223
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @file src/engine-node/sensors/index.mjs
3
+ * Repository blindspot sensors and git merge-tree conflict probe.
4
+ */
5
+
6
+ export * from './blindspots.mjs';
7
+ export * from './git_merge_tree.mjs';