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,423 @@
1
+ /**
2
+ * @file src/core/rsl_clash_auditor.mjs
3
+ * Deterministic Dual-Platform Rule Clash & Polarity Auditor + Spec Consolidation Helper.
4
+ *
5
+ * Scans `AGENTS.md`, `CLAUDE.md`, `.agents/rules/*.md`, and `.claude/rules/*.md` read-only
6
+ * (strictly excluding `packages/airlock/`) to catch opposite-polarity imperatives sharing an
7
+ * overlapping scope and identical technical anchor before conflicting RSL rules activate.
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { execFileSync } from 'node:child_process';
13
+ import { isExcludedFromRslScan } from './rsl_triage.mjs';
14
+
15
+ const NEG_POLARITY_RE =
16
+ /\b(?:never|do\s+not|don't|must\s+not|must\s+never|forbid(?:den)?|prohibit(?:ed)?|avoid)\b/i;
17
+ const POS_POLARITY_RE = /\b(?:always|must|require(?:d|s)?|enforce|mandate|prefer)\b/i;
18
+ const BACKTICK_TOKEN_RE = /`([^`\n]{2,80})`/g;
19
+ const PATH_TOKEN_RE = /(?:@([A-Za-z0-9_./\\-]{3,80})|\b([A-Za-z0-9_.-]+\.(?:[cm]?[jt]sx?|py|go|rs|json|ya?ml|md|db|sqlite|env|sh))\b)/gi;
20
+ const ENV_UNIT_RE = /\bunit(?:\s+tests?)?\b/i;
21
+ const ENV_INT_RE = /\b(?:integration|e2e|end-to-end)\b/i;
22
+ const ENV_PROD_RE = /\bprod(?:uction)?\b/i;
23
+ const ENV_DEV_RE = /\b(?:dev(?:elopment)?|local|staging|mock(?:ed)?\s+tests?)\b/i;
24
+ const STOP_ANCHORS = new Set(['true', 'false', 'null', 'undefined', 'json', 'utf8', 'utf-8', 'yes', 'no', 'on', 'off', 'read', 'write', 'file', 'code']);
25
+
26
+ function readFileReadOnlyUtf8(filePath) {
27
+ let fd;
28
+ try {
29
+ const stat = fs.statSync(filePath);
30
+ if (!stat.isFile() || stat.size > 256 * 1024) return '';
31
+ fd = fs.openSync(filePath, 'r');
32
+ const buf = Buffer.allocUnsafe(stat.size);
33
+ let offset = 0;
34
+ while (offset < stat.size) {
35
+ const n = fs.readSync(fd, buf, offset, stat.size - offset, offset);
36
+ if (n === 0) break;
37
+ offset += n;
38
+ }
39
+ return buf.subarray(0, offset).toString('utf8');
40
+ } catch {
41
+ return '';
42
+ } finally {
43
+ if (fd !== undefined) {
44
+ try {
45
+ fs.closeSync(fd);
46
+ } catch {
47
+ // Ignore close error
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ function parseRuleFrontmatter(markdown = '') {
54
+ const normalized = String(markdown || '').replace(/\r\n/g, '\n');
55
+ const fmMatch = normalized.match(/^---\n([\s\S]*?)\n---\n?/);
56
+ if (!fmMatch) {
57
+ return { trigger: '', globs: [], paths: [], description: '', body: normalized };
58
+ }
59
+ const fmBlock = fmMatch[1];
60
+ const body = normalized.slice(fmMatch[0].length);
61
+ const trigger = (fmBlock.match(/^trigger:\s*([^\n]+)/im)?.[1] || '').trim().replace(/^["']|["']$/g, '').toLowerCase();
62
+ const description = (fmBlock.match(/^description:\s*([^\n]+)/im)?.[1] || '').trim().replace(/^["']|["']$/g, '');
63
+ const globsRaw = (fmBlock.match(/^globs:\s*([^\n]+)/im)?.[1] || '').trim().replace(/^["']|["']$/g, '');
64
+ const globs = globsRaw ? globsRaw.split(',').map((g) => g.trim().replace(/^["']|["']$/g, '')).filter(Boolean) : [];
65
+
66
+ const paths = [];
67
+ const inlinePaths = fmBlock.match(/^paths:\s*\[([^\]]*)\]/im)?.[1];
68
+ if (inlinePaths) {
69
+ for (const part of inlinePaths.split(',')) {
70
+ const clean = part.trim().replace(/^["']|["']$/g, '');
71
+ if (clean) paths.push(clean);
72
+ }
73
+ } else {
74
+ const pathsBlock = fmBlock.match(/^paths:\s*\n((?:\s+-\s+[^\n]+\n?)+)/im)?.[1] || '';
75
+ for (const line of pathsBlock.split('\n')) {
76
+ const item = line.replace(/^\s*-\s*/, '').trim().replace(/^["']|["']$/g, '');
77
+ if (item) paths.push(item);
78
+ }
79
+ }
80
+ return { trigger, globs, paths, description, body };
81
+ }
82
+
83
+ function extractEnvQualifiers(text = '') {
84
+ const envs = new Set();
85
+ if (ENV_UNIT_RE.test(text)) envs.add('unit');
86
+ if (ENV_INT_RE.test(text)) envs.add('integration');
87
+ if (ENV_PROD_RE.test(text)) envs.add('prod');
88
+ if (ENV_DEV_RE.test(text)) envs.add('dev');
89
+ return envs;
90
+ }
91
+
92
+ function areEnvsDisjoint(envsA, envsB) {
93
+ if (!envsA || !envsB || envsA.size === 0 || envsB.size === 0) return false;
94
+ for (const tag of envsA) {
95
+ if (envsB.has(tag)) return false;
96
+ }
97
+ return true;
98
+ }
99
+
100
+ function extractAnchors(clause = '') {
101
+ const anchors = new Set();
102
+ for (const m of clause.matchAll(BACKTICK_TOKEN_RE)) {
103
+ const raw = m[1].trim().replace(/^@/, '').toLowerCase();
104
+ if (raw.length >= 2 && !STOP_ANCHORS.has(raw)) anchors.add(raw);
105
+ }
106
+ for (const m of clause.matchAll(PATH_TOKEN_RE)) {
107
+ const tok = (m[1] || m[2] || '').trim().replace(/\\/g, '/').toLowerCase();
108
+ if (tok.length >= 3 && !STOP_ANCHORS.has(tok)) anchors.add(tok);
109
+ }
110
+ for (const m of clause.matchAll(/\b([A-Z][A-Z0-9_]{4,})\b/g)) {
111
+ anchors.add(m[1].toLowerCase());
112
+ }
113
+ if (/\b(?:mock|stub|spy)\b[^.!?;]{0,24}\b(?:database|db|sqlite)\b/i.test(clause)) {
114
+ anchors.add('mock:database');
115
+ }
116
+ if (/\b(?:mock|stub|spy)\b[^.!?;]{0,24}\b(?:external|network|http|i\/o|io)\b/i.test(clause)) {
117
+ anchors.add('mock:external-io');
118
+ }
119
+ if (/\bdefault\s+exports?\b/i.test(clause)) anchors.add('export:default');
120
+ if (/\bfull\s+files?\b|\bentire\s+files?\b/i.test(clause)) anchors.add('read:full-file');
121
+ return Array.from(anchors);
122
+ }
123
+
124
+ /**
125
+ * Extracts imperative polarity directives with concrete technical anchors and environment tags.
126
+ * @param {string} markdown
127
+ * @param {object} [meta={}]
128
+ */
129
+ export function extractRuleDirectives(markdown = '', meta = {}) {
130
+ const parsed = parseRuleFrontmatter(markdown);
131
+ const scopePatterns = (parsed.globs.length > 0 ? parsed.globs : parsed.paths).length > 0
132
+ ? (parsed.globs.length > 0 ? parsed.globs : parsed.paths)
133
+ : (Array.isArray(meta.globs) ? meta.globs : []);
134
+ const scopeType =
135
+ meta.scopeType ||
136
+ (parsed.trigger === 'always_on' || scopePatterns.includes('**')
137
+ ? 'always_on'
138
+ : scopePatterns.length > 0
139
+ ? 'glob'
140
+ : parsed.trigger || (meta.source?.startsWith('.claude/rules/') ? 'always_on' : 'model_decision'));
141
+
142
+ const lines = parsed.body.split('\n');
143
+ const directives = [];
144
+ let inCodeFence = false;
145
+
146
+ const inspectText = (text) => {
147
+ const clauses = String(text || '').split(/[;]+|(?<=\.)\s+/).map((s) => s.trim()).filter(Boolean);
148
+ for (const clause of clauses) {
149
+ const isNeg = NEG_POLARITY_RE.test(clause);
150
+ const isPos = !isNeg && POS_POLARITY_RE.test(clause);
151
+ if (!isNeg && !isPos) continue;
152
+ const anchors = extractAnchors(clause);
153
+ if (anchors.length === 0) continue;
154
+ directives.push({
155
+ source: meta.source || 'inline',
156
+ slug: meta.slug || 'rule',
157
+ scopeType,
158
+ globs: scopePatterns.map((g) => g.toLowerCase()),
159
+ polarity: isNeg ? 'NEGATIVE' : 'POSITIVE',
160
+ anchors,
161
+ envs: Array.from(extractEnvQualifiers(clause)),
162
+ excerpt: clause.replace(/^[-*+\s#]+/, '').slice(0, 160)
163
+ });
164
+ }
165
+ };
166
+
167
+ for (const rawLine of lines) {
168
+ const trimmed = rawLine.trim();
169
+ if (trimmed.startsWith('```')) {
170
+ inCodeFence = !inCodeFence;
171
+ continue;
172
+ }
173
+ if (inCodeFence || !trimmed || trimmed.startsWith('<!--')) continue;
174
+ inspectText(trimmed);
175
+ }
176
+ if (directives.length === 0 && parsed.description) {
177
+ inspectText(parsed.description);
178
+ }
179
+ return directives;
180
+ }
181
+
182
+ function getGlobExtension(glob = '') {
183
+ const m = String(glob || '').toLowerCase().match(/\*\.([a-z0-9]+)$/);
184
+ return m ? m[1] : '';
185
+ }
186
+
187
+ function getGlobDirPrefix(glob = '') {
188
+ return String(glob || '')
189
+ .toLowerCase()
190
+ .replace(/\\/g, '/')
191
+ .replace(/^\.\//, '')
192
+ .replace(/\/?\*\*.*$/, '')
193
+ .replace(/\/?\*[^/]*$/, '')
194
+ .replace(/\/+$/, '');
195
+ }
196
+
197
+ function doGlobPairOverlap(g1 = '', g2 = '') {
198
+ const a = String(g1 || '').trim().toLowerCase().replace(/\\/g, '/').replace(/^\.\//, '');
199
+ const b = String(g2 || '').trim().toLowerCase().replace(/\\/g, '/').replace(/^\.\//, '');
200
+ if (!a || !b || a === b || a === '**' || b === '**' || a === '*' || b === '*') return true;
201
+ const extA = getGlobExtension(a);
202
+ const extB = getGlobExtension(b);
203
+ if (extA && extB && extA !== extB) return false;
204
+ const dirA = getGlobDirPrefix(a);
205
+ const dirB = getGlobDirPrefix(b);
206
+ if (dirA && dirB && dirA !== dirB && !dirA.startsWith(`${dirB}/`) && !dirB.startsWith(`${dirA}/`)) {
207
+ return false;
208
+ }
209
+ return true;
210
+ }
211
+
212
+ /**
213
+ * Checks whether two rule scopes can fire on the same file or turn.
214
+ * @param {object} ruleA
215
+ * @param {object} ruleB
216
+ * @returns {boolean}
217
+ */
218
+ export function doRuleScopesOverlap(ruleA = {}, ruleB = {}) {
219
+ if (ruleA.scopeType === 'always_on' || ruleB.scopeType === 'always_on') return true;
220
+ const globsA = Array.isArray(ruleA.globs) ? ruleA.globs : [];
221
+ const globsB = Array.isArray(ruleB.globs) ? ruleB.globs : [];
222
+ if (globsA.length === 0 || globsB.length === 0) return true;
223
+ return globsA.some((ga) => globsB.some((gb) => doGlobPairOverlap(ga, gb)));
224
+ }
225
+
226
+ /**
227
+ * Detects opposite-polarity imperative rule conflicts across parsed rule documents.
228
+ * @param {Array<object>} ruleDocs
229
+ */
230
+ export function detectRuleClashes(ruleDocs = []) {
231
+ const allDirectives = [];
232
+ for (const doc of ruleDocs) {
233
+ if (!doc || !doc.content) continue;
234
+ allDirectives.push(...extractRuleDirectives(doc.content, doc));
235
+ }
236
+
237
+ const clashes = [];
238
+ const seenKeys = new Set();
239
+ for (let i = 0; i < allDirectives.length; i++) {
240
+ const a = allDirectives[i];
241
+ for (let j = i + 1; j < allDirectives.length; j++) {
242
+ const b = allDirectives[j];
243
+ if (a.slug === b.slug || a.source === b.source || a.polarity === b.polarity) continue;
244
+ if (!doRuleScopesOverlap(a, b)) continue;
245
+ if (areEnvsDisjoint(new Set(a.envs), new Set(b.envs))) continue;
246
+ const sharedAnchor = a.anchors.find((anc) => b.anchors.includes(anc));
247
+ if (!sharedAnchor) continue;
248
+ const pairKey = [a.slug, b.slug].sort().join('::') + `::${sharedAnchor}`;
249
+ if (seenKeys.has(pairKey)) continue;
250
+ seenKeys.add(pairKey);
251
+ clashes.push({
252
+ id: `RULE_CONFLICT:${pairKey}`,
253
+ code: 'RULE_CONFLICT',
254
+ sourceA: a.source,
255
+ sourceB: b.source,
256
+ slugA: a.slug,
257
+ slugB: b.slug,
258
+ polarityA: a.polarity,
259
+ polarityB: b.polarity,
260
+ anchor: sharedAnchor,
261
+ excerptA: a.excerpt,
262
+ excerptB: b.excerpt,
263
+ reason: `[RULE_CONFLICT] "${a.source}" (${a.polarity}) and "${b.source}" (${b.polarity}) clash on \`${sharedAnchor}\`.`
264
+ });
265
+ }
266
+ }
267
+ return clashes;
268
+ }
269
+
270
+ /**
271
+ * Scans workspace rule files (strictly excluding `packages/airlock/`) and checks optional candidate RSL item.
272
+ * @param {string} [workspaceRoot=process.cwd()]
273
+ * @param {object|null} [candidateItem=null]
274
+ */
275
+ export function auditWorkspaceRuleClashes(workspaceRoot = process.cwd(), candidateItem = null) {
276
+ const baseRoot = path.resolve(workspaceRoot || process.cwd());
277
+ const docs = [];
278
+ const loadedRslSlugs = new Set();
279
+
280
+ for (const topFile of ['AGENTS.md', 'CLAUDE.md']) {
281
+ if (isExcludedFromRslScan(topFile)) continue;
282
+ const abs = path.join(baseRoot, topFile);
283
+ const content = readFileReadOnlyUtf8(abs);
284
+ if (content) {
285
+ docs.push({
286
+ source: topFile,
287
+ slug: topFile.toLowerCase().replace(/\./g, '-'),
288
+ scopeType: 'always_on',
289
+ globs: ['**'],
290
+ content
291
+ });
292
+ }
293
+ }
294
+
295
+ for (const relDir of ['.agents/rules', '.claude/rules']) {
296
+ const absDir = path.join(baseRoot, relDir);
297
+ if (!fs.existsSync(absDir)) continue;
298
+ try {
299
+ for (const ent of fs.readdirSync(absDir, { withFileTypes: true }).sort((x, y) => x.name.localeCompare(y.name))) {
300
+ if (!ent.isFile() || !ent.name.endsWith('.md')) continue;
301
+ const relPath = `${relDir}/${ent.name}`;
302
+ if (isExcludedFromRslScan(relPath)) continue;
303
+ const isRsl = ent.name.startsWith('rsl-');
304
+ const slug = (isRsl ? ent.name.slice(4) : ent.name).replace(/\.md$/i, '').toLowerCase();
305
+ // Skip dual-compiled `.claude/rules/rsl-*` copy when `.agents/rules/rsl-*` is present so same slug never self-compares
306
+ if (relDir === '.claude/rules' && isRsl && loadedRslSlugs.has(slug)) continue;
307
+ if (isRsl) loadedRslSlugs.add(slug);
308
+ const content = readFileReadOnlyUtf8(path.join(absDir, ent.name));
309
+ if (content) docs.push({ source: relPath, slug, content });
310
+ }
311
+ } catch {
312
+ // Ignore unreadable rule dir
313
+ }
314
+ }
315
+
316
+ let candidateSlug = null;
317
+ if (candidateItem && candidateItem.carrier !== 'skill_workflow') {
318
+ candidateSlug = String(candidateItem.slug || 'candidate-rule').toLowerCase();
319
+ const candidateGlobs = Array.isArray(candidateItem.paths) && candidateItem.paths.length > 0
320
+ ? candidateItem.paths
321
+ : String(candidateItem.globs || '').split(',').map((g) => g.trim()).filter(Boolean);
322
+ const body = [
323
+ candidateGlobs.length > 0 ? `---\ntrigger: glob\nglobs: "${candidateGlobs.join(', ')}"\n---` : '---\ntrigger: model_decision\n---',
324
+ candidateItem.when_condition || '',
325
+ candidateItem.then_guidance || candidateItem.description || ''
326
+ ].filter(Boolean).join('\n');
327
+ const filteredDocs = docs.filter((d) => d.slug !== candidateSlug);
328
+ const allClashes = detectRuleClashes([
329
+ ...filteredDocs,
330
+ { source: `candidate:rsl-${candidateSlug}`, slug: candidateSlug, globs: candidateGlobs, content: body }
331
+ ]);
332
+ const candidateClashes = allClashes.filter((c) => c.slugA === candidateSlug || c.slugB === candidateSlug);
333
+ return { clashCount: allClashes.length, clashes: allClashes, candidateClashes };
334
+ }
335
+
336
+ const clashes = detectRuleClashes(docs);
337
+ return { clashCount: clashes.length, clashes, candidateClashes: [] };
338
+ }
339
+
340
+ /**
341
+ * Builds a concise Consolidated Requirements Contract merging Turn-1 goal, recorded sharded constraints,
342
+ * and `git diff --stat` (excluding `packages/airlock/`).
343
+ *
344
+ * @param {string} [workspaceRoot=process.cwd()]
345
+ * @param {object} [options={}]
346
+ */
347
+ export function buildConsolidatedSpecMarkdown(workspaceRoot = process.cwd(), options = {}) {
348
+ const baseRoot = path.resolve(workspaceRoot || process.cwd());
349
+ const telemetryDir = path.join(baseRoot, '.agents', 'telemetry');
350
+ let initialGoal = String(options.initialGoal || '').trim();
351
+ let shards = Array.isArray(options.specShards) ? options.specShards : [];
352
+
353
+ if (shards.length === 0 && fs.existsSync(telemetryDir)) {
354
+ try {
355
+ const files = fs.readdirSync(telemetryDir)
356
+ .filter((n) => n.startsWith('prompt_state.') && n.endsWith('.json'))
357
+ .map((n) => ({ name: n, full: path.join(telemetryDir, n), mtime: fs.statSync(path.join(telemetryDir, n)).mtimeMs }))
358
+ .sort((a, b) => b.mtime - a.mtime);
359
+ const target = options.sessionId
360
+ ? files.find((f) => f.name.includes(String(options.sessionId))) || files[0]
361
+ : files[0];
362
+ if (target) {
363
+ const parsed = JSON.parse(readFileReadOnlyUtf8(target.full) || '{}');
364
+ initialGoal = initialGoal || String(parsed.initialGoal || '').trim();
365
+ shards = Array.isArray(parsed.specShards) ? parsed.specShards : [];
366
+ }
367
+ } catch {
368
+ // Ignore missing telemetry
369
+ }
370
+ }
371
+
372
+ let changedFiles = [];
373
+ if (options.includeGitDiff !== false) {
374
+ try {
375
+ const rawDiff = execFileSync('git', ['diff', '--stat', '--name-only'], {
376
+ cwd: baseRoot,
377
+ encoding: 'utf8',
378
+ stdio: ['ignore', 'pipe', 'ignore'],
379
+ timeout: 1500
380
+ });
381
+ changedFiles = rawDiff
382
+ .split(/\r?\n/)
383
+ .map((l) => l.trim().replace(/\\/g, '/'))
384
+ .filter((l) => l && !isExcludedFromRslScan(l))
385
+ .slice(0, 15);
386
+ } catch {
387
+ // Not a git repo or git unavailable
388
+ }
389
+ }
390
+
391
+ const lines = [
392
+ '# Consolidated Requirements Contract',
393
+ '',
394
+ '## Objective',
395
+ initialGoal || '(No initial Turn-1 goal recorded; summarize target objective before editing.)',
396
+ '',
397
+ '## Consolidated Constraint Shards'
398
+ ];
399
+ if (shards.length === 0) {
400
+ lines.push('- (No incremental requirement shards recorded yet.)');
401
+ } else {
402
+ for (const s of shards) {
403
+ lines.push(`- Turn ${s.turn || '?'}: ${String(s.excerpt || '').trim()}`);
404
+ }
405
+ }
406
+ lines.push('', '## Touched Files');
407
+ if (changedFiles.length === 0) {
408
+ lines.push('- (Clean working tree / no uncommitted files)');
409
+ } else {
410
+ for (const f of changedFiles) lines.push(`- \`${f}\``);
411
+ }
412
+ lines.push('', '## Verification Gate', '- Run targeted tests and `node bin/ctxtop.mjs verify --json` before stopping.', '');
413
+
414
+ return {
415
+ ok: true,
416
+ workspaceRoot: baseRoot,
417
+ initialGoal,
418
+ shardCount: shards.length,
419
+ specShards: shards,
420
+ changedFiles,
421
+ consolidatedMarkdown: lines.join('\n')
422
+ };
423
+ }