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,578 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { canonicalizePath } from '../paths.mjs';
4
+ import { atomicWriteFileSync } from '../atomic_io.mjs';
5
+ import { recordHookDiagnostic } from '../hook_diagnostics.mjs';
6
+
7
+ /**
8
+ * Phase 4 / Ring 1 Hardening: Advisory Workspace Scope Registry & DET-20 Collision Alert
9
+ * (`src/core/telemetry/scope_lock_registry.mjs`)
10
+ *
11
+ * Maintains `.agents/locks/active_scopes.json` mapping active session/trajectory IDs
12
+ * to claimed relative file paths (derived from active `task.md` targets and dirty `git status` paths).
13
+ *
14
+ * Invariants:
15
+ * - Atomic Windows-safe writes via temp file rename with EPERM fallback.
16
+ * - Automatic eviction of stale leases where `Date.now() > expiresAtMs` (300s TTL)
17
+ * or where the owning `pid` is no longer alive (`!isPidAlive(pid)`).
18
+ * - DET-20 Collision Alert: Triggers when the current trajectory attempts to claim or edit
19
+ * a file held by another live trajectory ID, warning of 2x merge conflict risk and
20
+ * providing a 1-click `git worktree` command snippet.
21
+ */
22
+
23
+ export const SCOPE_LOCK_CONSTANTS = Object.freeze({
24
+ DEFAULT_TTL_SECONDS: 900,
25
+ DEFAULT_TTL_MS: 900_000,
26
+ LOCK_FILE_NAME: 'active_scopes.json',
27
+ DETECTOR_ID: 'DET-20',
28
+ VERSION: 1,
29
+ SCHEMA_VERSION: '2026.11.1'
30
+ });
31
+
32
+ /**
33
+ * Determines whether a process with the given PID is currently alive on the host.
34
+ */
35
+ export function isPidAlive(pid) {
36
+ if (!pid || typeof pid !== 'number' || pid <= 0) return false;
37
+ try {
38
+ process.kill(pid, 0);
39
+ return true;
40
+ } catch (err) {
41
+ return err.code !== 'ESRCH';
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Returns the path to `.agents/locks/active_scopes.json` (Antigravity's owned lockfile).
47
+ */
48
+ export function getLockFilePath(workspaceDir = process.cwd()) {
49
+ return path.join(workspaceDir, '.agents', 'locks', SCOPE_LOCK_CONSTANTS.LOCK_FILE_NAME);
50
+ }
51
+
52
+ /**
53
+ * Returns the path to `.claude/locks/active_scopes.json` (Claude Code cross-harness lockfile, read-only).
54
+ */
55
+ export function getClaudeLockFilePath(workspaceDir = process.cwd()) {
56
+ return path.join(workspaceDir, '.claude', 'locks', SCOPE_LOCK_CONSTANTS.LOCK_FILE_NAME);
57
+ }
58
+
59
+ /**
60
+ * Normalizes relative file paths or scope globs for cross-platform comparison.
61
+ */
62
+ export function normalizeClaimedPath(filePath = '') {
63
+ return String(filePath || '')
64
+ .trim()
65
+ .replace(/^["']|["']$/g, '')
66
+ .replace(/\\/g, '/')
67
+ .replace(/^\.\//, '')
68
+ .toLowerCase();
69
+ }
70
+
71
+ function compileScopeGlob(pattern) {
72
+ const norm = normalizeClaimedPath(pattern);
73
+ if (!norm) return null;
74
+ if (norm.endsWith('/') && !norm.includes('*') && !norm.includes('?')) {
75
+ const base = norm.slice(0, -1);
76
+ const escapedBase = base.replace(/[.+^${}()|[\]\\]/g, '\\$&');
77
+ return new RegExp(`^${escapedBase}(?:/.*)?$`, 'i');
78
+ }
79
+ let regexSrc = '^';
80
+ for (let i = 0; i < norm.length; i++) {
81
+ const ch = norm[i];
82
+ if (ch === '*') {
83
+ if (norm[i + 1] === '*') {
84
+ if (norm[i + 2] === '/') {
85
+ regexSrc += '(?:.+/)?';
86
+ i += 2;
87
+ } else {
88
+ regexSrc += '.*';
89
+ i += 1;
90
+ }
91
+ } else {
92
+ regexSrc += '[^/]*';
93
+ }
94
+ } else if (ch === '?') {
95
+ regexSrc += '[^/]';
96
+ } else {
97
+ regexSrc += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
98
+ }
99
+ }
100
+ regexSrc += '$';
101
+ return new RegExp(regexSrc, 'i');
102
+ }
103
+
104
+ /**
105
+ * Returns true if two normalized paths or glob patterns overlap (exact match, directory prefix, or glob).
106
+ */
107
+ export function scopesOverlap(scopeA, scopeB) {
108
+ const a = normalizeClaimedPath(scopeA);
109
+ const b = normalizeClaimedPath(scopeB);
110
+ if (!a || !b) return false;
111
+ if (a === b) return true;
112
+
113
+ const aHasGlob = a.includes('*') || a.includes('?') || a.endsWith('/');
114
+ const bHasGlob = b.includes('*') || b.includes('?') || b.endsWith('/');
115
+ if (!aHasGlob && !bHasGlob) return false;
116
+
117
+ if (aHasGlob) {
118
+ const reA = compileScopeGlob(a);
119
+ if (reA && reA.test(b)) return true;
120
+ }
121
+ if (bHasGlob) {
122
+ const reB = compileScopeGlob(b);
123
+ if (reB && reB.test(a)) return true;
124
+ }
125
+ if (aHasGlob && bHasGlob) {
126
+ const prefixA = a.split(/[*?]/)[0].replace(/\/+$/, '');
127
+ const prefixB = b.split(/[*?]/)[0].replace(/\/+$/, '');
128
+ if (!prefixA || !prefixB) return true;
129
+ if (prefixA === prefixB || prefixA.startsWith(`${prefixB}/`) || prefixB.startsWith(`${prefixA}/`)) {
130
+ return true;
131
+ }
132
+ }
133
+ return false;
134
+ }
135
+
136
+ /**
137
+ * Normalizes either an Antigravity `leases[]` item or a Claude Code `locks[]` item
138
+ * into a unified cross-edition lease record.
139
+ */
140
+ export function normalizeScopeLeaseEntry(rawEntry = {}, {
141
+ source = 'local',
142
+ defaultTool = 'antigravity',
143
+ now = Date.now()
144
+ } = {}) {
145
+ if (!rawEntry || typeof rawEntry !== 'object') return null;
146
+ const trajectoryId = String(
147
+ rawEntry.trajectoryId ||
148
+ rawEntry.ownerId ||
149
+ rawEntry.agent_id ||
150
+ rawEntry.session_id ||
151
+ ''
152
+ ).trim();
153
+ if (!trajectoryId) return null;
154
+
155
+ const rawPaths = Array.isArray(rawEntry.claimedPaths)
156
+ ? rawEntry.claimedPaths
157
+ : (Array.isArray(rawEntry.scopes)
158
+ ? rawEntry.scopes
159
+ : (Array.isArray(rawEntry.files_locked) ? rawEntry.files_locked : []));
160
+ const claimedPaths = Array.from(
161
+ new Set(rawPaths.map((p) => String(p || '').trim()).filter(Boolean))
162
+ );
163
+
164
+ const parsedAcquired = typeof rawEntry.acquiredAt === 'number' && Number.isFinite(rawEntry.acquiredAt)
165
+ ? rawEntry.acquiredAt
166
+ : Date.parse(rawEntry.acquired_at || rawEntry.updatedAtIso || '');
167
+ const acquiredAtMs = Number.isFinite(parsedAcquired) ? parsedAcquired : now;
168
+
169
+ let expiresAtMs = null;
170
+ if (typeof rawEntry.expiresAtMs === 'number' && Number.isFinite(rawEntry.expiresAtMs)) {
171
+ expiresAtMs = rawEntry.expiresAtMs;
172
+ } else if (typeof rawEntry.expiresAt === 'number' && Number.isFinite(rawEntry.expiresAt)) {
173
+ expiresAtMs = rawEntry.expiresAt;
174
+ } else if (typeof rawEntry.expiresAt === 'string' && rawEntry.expiresAt.trim()) {
175
+ const parsedExp = Date.parse(rawEntry.expiresAt);
176
+ if (Number.isFinite(parsedExp)) expiresAtMs = parsedExp;
177
+ } else if (typeof rawEntry.expires_at === 'string' && rawEntry.expires_at.trim()) {
178
+ const parsedExp = Date.parse(rawEntry.expires_at);
179
+ if (Number.isFinite(parsedExp)) expiresAtMs = parsedExp;
180
+ }
181
+ if (!Number.isFinite(expiresAtMs)) {
182
+ const ttlMs = Number(rawEntry.ttl_ms) > 0
183
+ ? Number(rawEntry.ttl_ms)
184
+ : SCOPE_LOCK_CONSTANTS.DEFAULT_TTL_MS;
185
+ expiresAtMs = acquiredAtMs + ttlMs;
186
+ }
187
+
188
+ const ttlMs = Number(rawEntry.ttl_ms) > 0
189
+ ? Number(rawEntry.ttl_ms)
190
+ : Math.max(1000, expiresAtMs - acquiredAtMs);
191
+ const pid = typeof rawEntry.pid === 'number' && Number.isFinite(rawEntry.pid) ? rawEntry.pid : undefined;
192
+ const tool = String(rawEntry.tool || (source === 'cross_harness' ? 'claude-code' : defaultTool));
193
+
194
+ return {
195
+ trajectoryId,
196
+ ownerId: rawEntry.ownerId || trajectoryId,
197
+ agent_id: rawEntry.agent_id || trajectoryId,
198
+ session_id: rawEntry.session_id || trajectoryId,
199
+ ...(pid !== undefined ? { pid } : {}),
200
+ tool,
201
+ claimedPaths,
202
+ files_locked: claimedPaths,
203
+ scopes: claimedPaths,
204
+ acquiredAt: acquiredAtMs,
205
+ acquired_at: new Date(acquiredAtMs).toISOString(),
206
+ updatedAtIso: rawEntry.updatedAtIso || new Date(acquiredAtMs).toISOString(),
207
+ expiresAt: expiresAtMs,
208
+ expiresAtMs,
209
+ expires_at: new Date(expiresAtMs).toISOString(),
210
+ ttl_ms: ttlMs,
211
+ source
212
+ };
213
+ }
214
+
215
+ function readLockFileEntriesSafe(lockFilePath, { source, defaultTool, now }) {
216
+ if (!lockFilePath || !fs.existsSync(lockFilePath)) return [];
217
+ try {
218
+ const raw = fs.readFileSync(lockFilePath, 'utf8');
219
+ const data = JSON.parse(raw);
220
+ const combinedRaw = [
221
+ ...(Array.isArray(data?.leases) ? data.leases : []),
222
+ ...(Array.isArray(data?.locks) ? data.locks : [])
223
+ ];
224
+ const dedupedByOwner = new Map();
225
+ for (const item of combinedRaw) {
226
+ const normalized = normalizeScopeLeaseEntry(item, { source, defaultTool, now });
227
+ if (!normalized) continue;
228
+ const isExpired = typeof normalized.expiresAtMs === 'number' && now > normalized.expiresAtMs;
229
+ const pidAlive = typeof normalized.pid === 'number' ? isPidAlive(normalized.pid) : true;
230
+ if (!isExpired && pidAlive) {
231
+ dedupedByOwner.set(normalized.trajectoryId, normalized);
232
+ }
233
+ }
234
+ return Array.from(dedupedByOwner.values());
235
+ } catch (err) {
236
+ recordHookDiagnostic('scope_lock_registry', 'readLockFileEntriesSafe', err, {
237
+ ignoreCodes: ['ENOENT'],
238
+ persist: false
239
+ });
240
+ return [];
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Loads the active scope registry from BOTH `.agents/locks/active_scopes.json` (local)
246
+ * and `.claude/locks/active_scopes.json` (read-only cross-harness visibility),
247
+ * automatically pruning expired or dead-PID leases.
248
+ */
249
+ export function loadRegistry(workspaceDir = process.cwd(), options = {}) {
250
+ const now = typeof options.now === 'number' ? options.now : Date.now();
251
+ const includeCrossHarness = options.includeCrossHarness !== false;
252
+
253
+ const localEntries = readLockFileEntriesSafe(getLockFilePath(workspaceDir), {
254
+ source: 'local',
255
+ defaultTool: 'antigravity',
256
+ now
257
+ });
258
+ const crossEntries = includeCrossHarness
259
+ ? readLockFileEntriesSafe(getClaudeLockFilePath(workspaceDir), {
260
+ source: 'cross_harness',
261
+ defaultTool: 'claude-code',
262
+ now
263
+ })
264
+ : [];
265
+
266
+ const mergedByKey = new Map();
267
+ for (const entry of localEntries) {
268
+ mergedByKey.set(`local::${entry.trajectoryId}`, entry);
269
+ }
270
+ for (const entry of crossEntries) {
271
+ if (!localEntries.some((l) => l.trajectoryId === entry.trajectoryId)) {
272
+ mergedByKey.set(`cross::${entry.trajectoryId}`, entry);
273
+ }
274
+ }
275
+
276
+ const validLeases = Array.from(mergedByKey.values());
277
+ const locks = validLeases.map((l) => ({
278
+ ownerId: l.ownerId || l.trajectoryId,
279
+ ...(l.pid !== undefined ? { pid: l.pid } : {}),
280
+ tool: l.tool,
281
+ scopes: l.scopes || l.claimedPaths,
282
+ acquiredAt: l.acquiredAt,
283
+ expiresAt: l.expiresAtMs,
284
+ source: l.source
285
+ }));
286
+
287
+ return {
288
+ version: SCOPE_LOCK_CONSTANTS.VERSION,
289
+ schemaVersion: SCOPE_LOCK_CONSTANTS.SCHEMA_VERSION,
290
+ updatedAt: new Date(now).toISOString(),
291
+ leases: validLeases,
292
+ locks
293
+ };
294
+ }
295
+
296
+ export const loadScopeLockRegistry = loadRegistry;
297
+
298
+ /**
299
+ * Saves Antigravity's local registry atomically to `.agents/locks/active_scopes.json`
300
+ * (emitting both `leases[]` and `locks[]` for cross-edition interoperability while never
301
+ * modifying `.claude/locks/active_scopes.json`).
302
+ */
303
+ export function saveRegistry(workspaceDir = process.cwd(), registry = { version: 1, leases: [] }) {
304
+ const now = Date.now();
305
+ const lockFile = getLockFilePath(workspaceDir);
306
+ const rawItems = Array.isArray(registry?.leases)
307
+ ? registry.leases
308
+ : (Array.isArray(registry?.locks) ? registry.locks : []);
309
+
310
+ const localLeases = [];
311
+ const seenOwners = new Set();
312
+ for (const item of rawItems) {
313
+ if (item?.source === 'cross_harness') continue;
314
+ const norm = normalizeScopeLeaseEntry(item, { source: 'local', defaultTool: 'antigravity', now });
315
+ if (!norm || seenOwners.has(norm.trajectoryId)) continue;
316
+ seenOwners.add(norm.trajectoryId);
317
+ localLeases.push(norm);
318
+ }
319
+
320
+ const locks = localLeases.map((l) => ({
321
+ ownerId: l.ownerId || l.trajectoryId,
322
+ ...(l.pid !== undefined ? { pid: l.pid } : {}),
323
+ tool: l.tool,
324
+ scopes: l.claimedPaths,
325
+ acquiredAt: l.acquiredAt,
326
+ expiresAt: l.expiresAtMs
327
+ }));
328
+
329
+ const payload = JSON.stringify({
330
+ version: registry?.version || SCOPE_LOCK_CONSTANTS.VERSION,
331
+ schemaVersion: SCOPE_LOCK_CONSTANTS.SCHEMA_VERSION,
332
+ updatedAt: new Date(now).toISOString(),
333
+ leases: localLeases,
334
+ locks
335
+ }, null, 2);
336
+ atomicWriteFileSync(lockFile, payload, { encoding: 'utf8' });
337
+ return true;
338
+ }
339
+
340
+ /**
341
+ * Checks for file-scope collisions (exact path, directory prefix, or glob) across other active leases/locks.
342
+ */
343
+ export function detectScopeCollision(currentTrajectoryId, claimedPaths = [], activeLeases = [], options = {}) {
344
+ const normalizedCurrent = Array.from(
345
+ new Set((Array.isArray(claimedPaths) ? claimedPaths : []).map(normalizeClaimedPath).filter(Boolean))
346
+ );
347
+ if (normalizedCurrent.length === 0) return null;
348
+
349
+ const now = typeof options.now === 'number' && Number.isFinite(options.now) ? options.now : Date.now();
350
+
351
+ for (const lease of Array.isArray(activeLeases) ? activeLeases : []) {
352
+ if (!lease || typeof lease !== 'object') continue;
353
+ const ownerId = lease.trajectoryId || lease.ownerId || lease.agent_id || lease.session_id;
354
+ if (!ownerId || ownerId === currentTrajectoryId) continue;
355
+
356
+ let expMs = null;
357
+ if (typeof lease.expiresAtMs === 'number' && Number.isFinite(lease.expiresAtMs)) {
358
+ expMs = lease.expiresAtMs;
359
+ } else if (typeof lease.expiresAt === 'number' && Number.isFinite(lease.expiresAt)) {
360
+ expMs = lease.expiresAt;
361
+ } else if (typeof lease.expiresAt === 'string' && lease.expiresAt.trim()) {
362
+ const parsed = Date.parse(lease.expiresAt);
363
+ if (Number.isFinite(parsed)) expMs = parsed;
364
+ } else if (typeof lease.expires_at === 'string' && lease.expires_at.trim()) {
365
+ const parsed = Date.parse(lease.expires_at);
366
+ if (Number.isFinite(parsed)) expMs = parsed;
367
+ }
368
+ if (Number.isFinite(expMs) && now > expMs) continue;
369
+
370
+ const rawLeasePaths = lease.claimedPaths || lease.scopes || lease.files_locked || [];
371
+ const leasePaths = rawLeasePaths.map(normalizeClaimedPath).filter(Boolean);
372
+ const overlapping = normalizedCurrent.filter((cp) =>
373
+ leasePaths.some((lp) => scopesOverlap(cp, lp))
374
+ );
375
+
376
+ if (overlapping.length > 0) {
377
+ return {
378
+ trajectoryId: ownerId,
379
+ ownerId,
380
+ pid: lease.pid,
381
+ tool: lease.tool || 'antigravity',
382
+ source: lease.source || 'local',
383
+ overlappingPaths: overlapping
384
+ };
385
+ }
386
+ }
387
+
388
+ return null;
389
+ }
390
+
391
+ /**
392
+ * Derives file paths touched or claimed in the current session from task.md and git status.
393
+ */
394
+ export function deriveSessionClaimedPaths({
395
+ workspaceDir = process.cwd(),
396
+ taskMdContent = null,
397
+ gitStatusOutput = null
398
+ } = {}) {
399
+ const paths = new Set();
400
+
401
+ // 1. From task.md
402
+ let resolvedTask = taskMdContent;
403
+ if (resolvedTask === null) {
404
+ const taskPath = path.join(workspaceDir, 'task.md');
405
+ if (fs.existsSync(taskPath)) {
406
+ try {
407
+ resolvedTask = fs.readFileSync(taskPath, 'utf8');
408
+ } catch (err) {
409
+ recordHookDiagnostic('scope_lock_registry', 'deriveSessionClaimedPaths_readTaskMd', err, {
410
+ ignoreCodes: ['ENOENT'],
411
+ persist: false
412
+ });
413
+ }
414
+ }
415
+ }
416
+
417
+ if (resolvedTask) {
418
+ const taskLines = String(resolvedTask).split(/\r?\n/);
419
+ const hasChecklistItems = taskLines.some((l) => /^\s*[-*+]\s*\[[ xX\/]\]/.test(l));
420
+ const validFilePathRe = /([\\/]|^\.[a-zA-Z0-9_-]+|\.(mjs|cjs|js|ts|tsx|jsx|json|jsonl|md|html|css|scss|py|go|rs|java|rb|sh|ps1|yml|yaml|toml|sql|sqlite|db|proto|xml|txt|env|lock|gitignore|eslintrc|prettierrc)$)/i;
421
+ const versionOrMetricRe = /^v?\d+(\.\d+)+[a-zA-Z0-9_-]*$/i;
422
+
423
+ for (const line of taskLines) {
424
+ const trimmedLine = line.trim();
425
+ if (!trimmedLine) continue;
426
+ // Ignore completed checklist items (- [x] or - [X])
427
+ if (/^[-*+]\s*\[[xX]\]/.test(trimmedLine)) continue;
428
+ // When task.md uses checklist items, only claim paths from active/pending items (- [ ] or - [/])
429
+ if (hasChecklistItems && !/^[-*+]\s*\[[ \/]\]/.test(trimmedLine)) continue;
430
+
431
+ const matches = trimmedLine.match(/`([^`]+)`/g) || [];
432
+ for (const m of matches) {
433
+ const clean = m
434
+ .replace(/`/g, '')
435
+ .trim()
436
+ .replace(/:\d+(?:-\d+)?$/, '');
437
+ if (!clean || clean.includes(' ')) continue;
438
+ if (/^(https?:|file:|node:)/i.test(clean)) continue;
439
+ if (versionOrMetricRe.test(clean)) continue;
440
+ if (validFilePathRe.test(clean)) {
441
+ paths.add(clean.replace(/\\/g, '/'));
442
+ }
443
+ }
444
+ }
445
+ }
446
+
447
+ // 2. From git status output
448
+ if (gitStatusOutput) {
449
+ const lines = String(gitStatusOutput).split(/\r?\n/);
450
+ for (const line of lines) {
451
+ const trimmed = line.trim();
452
+ if (!trimmed) continue;
453
+ // Porcelain format: " M path", "?? path", or "R old -> new"
454
+ const parts = trimmed.split(/\s+/);
455
+ if (parts.length >= 2) {
456
+ let filePath = parts.slice(1).join(' ').trim();
457
+ if (filePath.includes(' -> ')) {
458
+ filePath = filePath.split(' -> ').pop().trim();
459
+ }
460
+ const norm = filePath.replace(/\\/g, '/');
461
+ if (
462
+ norm &&
463
+ norm !== '.' &&
464
+ norm !== '..' &&
465
+ !/^\.agents\/(scope-locks\.json|cache(\/|$))/i.test(norm)
466
+ ) {
467
+ paths.add(norm);
468
+ }
469
+ }
470
+ }
471
+ }
472
+
473
+ return Array.from(paths).sort();
474
+ }
475
+
476
+ /**
477
+ * ScopeLockRegistry class providing lease acquisition, renewal, release, and DET-20 collision alerts.
478
+ */
479
+ export class ScopeLockRegistry {
480
+ constructor(options = {}) {
481
+ this.workspaceDir = options.workspaceDir || process.cwd();
482
+ this.pid = options.pid || process.pid;
483
+ this.tool = options.tool || 'antigravity';
484
+ }
485
+
486
+ /**
487
+ * Acquires or renews a scope lease for a trajectory.
488
+ * If an active lease owned by another trajectory claims any of the same paths, triggers DET-20.
489
+ */
490
+ acquireOrRenewLease({
491
+ trajectoryId = 'default-trajectory',
492
+ claimedPaths = [],
493
+ ttlSeconds = SCOPE_LOCK_CONSTANTS.DEFAULT_TTL_SECONDS
494
+ } = {}) {
495
+ const registry = loadRegistry(this.workspaceDir);
496
+ const normClaimed = Array.isArray(claimedPaths) ? claimedPaths.filter(Boolean) : [];
497
+
498
+ // Check for collision with another live trajectory
499
+ const collision = detectScopeCollision(trajectoryId, normClaimed, registry.leases);
500
+ if (collision) {
501
+ const worktreeBranch = `feature-parallel-${String(trajectoryId).slice(0, 8)}`;
502
+ const worktreeCmd = `git worktree add ../${path.basename(this.workspaceDir)}-worktree-${String(trajectoryId).slice(0, 8)} -b ${worktreeBranch}`;
503
+
504
+ return {
505
+ ok: false,
506
+ collisionDetected: true,
507
+ detectorId: SCOPE_LOCK_CONSTANTS.DETECTOR_ID,
508
+ conflictingTrajectoryId: collision.trajectoryId,
509
+ conflictingPid: collision.pid,
510
+ conflictingTool: collision.tool,
511
+ overlappingPaths: collision.overlappingPaths,
512
+ worktreeCommand: worktreeCmd,
513
+ warning: `[HORIZON DET-20] Concurrent file-scope collision: file(s) [${collision.overlappingPaths.join(', ')}] are currently leased by trajectory "${collision.trajectoryId}" (PID ${collision.pid}). Run in isolated worktree to prevent merge conflicts.`,
514
+ activeLeases: registry.leases
515
+ };
516
+ }
517
+
518
+ const now = Date.now();
519
+ const expiresAtMs = now + ttlSeconds * 1000;
520
+
521
+ // Upsert current local lease (preserving read-only visibility of cross-harness locks without copying them)
522
+ const crossHarnessCount = registry.leases.filter((l) => l.source === 'cross_harness').length;
523
+ const updatedLocalLeases = registry.leases.filter(
524
+ (l) => l.source !== 'cross_harness' && l.trajectoryId !== trajectoryId
525
+ );
526
+ const newLease = normalizeScopeLeaseEntry({
527
+ trajectoryId,
528
+ ownerId: trajectoryId,
529
+ agent_id: trajectoryId,
530
+ session_id: trajectoryId,
531
+ pid: this.pid,
532
+ tool: this.tool,
533
+ claimedPaths: normClaimed,
534
+ acquiredAt: now,
535
+ updatedAtIso: new Date(now).toISOString(),
536
+ expiresAtMs,
537
+ ttl_ms: ttlSeconds * 1000
538
+ }, { source: 'local', defaultTool: this.tool, now });
539
+ updatedLocalLeases.push(newLease);
540
+
541
+ saveRegistry(this.workspaceDir, {
542
+ version: SCOPE_LOCK_CONSTANTS.VERSION,
543
+ leases: updatedLocalLeases
544
+ });
545
+
546
+ return {
547
+ ok: true,
548
+ collisionDetected: false,
549
+ lease: newLease,
550
+ activeLeaseCount: updatedLocalLeases.length + crossHarnessCount
551
+ };
552
+ }
553
+
554
+ /**
555
+ * Releases a trajectory lease.
556
+ */
557
+ releaseLease(trajectoryId) {
558
+ const registry = loadRegistry(this.workspaceDir);
559
+ const crossHarnessCount = registry.leases.filter((l) => l.source === 'cross_harness').length;
560
+ const updatedLocalLeases = registry.leases.filter(
561
+ (l) => l.source !== 'cross_harness' && l.trajectoryId !== trajectoryId
562
+ );
563
+ saveRegistry(this.workspaceDir, {
564
+ version: SCOPE_LOCK_CONSTANTS.VERSION,
565
+ leases: updatedLocalLeases
566
+ });
567
+ return { ok: true, remainingCount: updatedLocalLeases.length + crossHarnessCount };
568
+ }
569
+
570
+ /**
571
+ * Returns all active non-expired leases for the workspace.
572
+ */
573
+ getActiveLeases() {
574
+ return loadRegistry(this.workspaceDir).leases;
575
+ }
576
+ }
577
+
578
+ export default ScopeLockRegistry;