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,505 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { canonicalizePath } from '../paths.mjs';
6
+ import { SESSION_RISK_THRESHOLDS } from '../constants.mjs';
7
+ import { auditRuleContradictions } from './contradiction_auditor.mjs';
8
+ import { atomicWriteFileSync } from '../atomic_io.mjs';
9
+ import {
10
+ PREFIX_CACHE_SHIELD_CONSTANTS,
11
+ isProtectedPrefixFile,
12
+ isWarmCacheState
13
+ } from '../prefix_cache_shield.mjs';
14
+
15
+ /**
16
+ * Phase 2.2: "Teachable Moments" Reflector Queue & Project-Scoped Hash Isolation (`DET-29`)
17
+ * (`src/core/coach/reflector_queue.mjs`)
18
+ */
19
+
20
+ export const REFLECTOR_CONSTANTS = Object.freeze({
21
+ WARM_CACHE_LOCK_TOKENS: SESSION_RISK_THRESHOLDS.WARM_CACHE_LOCK_TOKENS,
22
+ PROTECTED_FILE_REGEX: PREFIX_CACHE_SHIELD_CONSTANTS.PROTECTED_FILE_REGEX,
23
+ GLOBAL_PROMOTION_MIN_CONFIDENCE: 0.80,
24
+ GLOBAL_PROMOTION_MIN_REPOS: 2,
25
+ SKILL_CLUSTER_MIN_COUNT: 3
26
+ });
27
+
28
+ export function isReflectorProtectedFile(filePath = '') {
29
+ return isProtectedPrefixFile(filePath);
30
+ }
31
+
32
+ function tryGetGitRemoteOrigin(workspaceDir) {
33
+ if (!workspaceDir || !fs.existsSync(workspaceDir)) return '';
34
+ try {
35
+ return execFileSync('git', ['config', '--get', 'remote.origin.url'], {
36
+ cwd: workspaceDir,
37
+ encoding: 'utf8',
38
+ stdio: ['ignore', 'pipe', 'ignore'],
39
+ timeout: 2000
40
+ }).trim();
41
+ } catch {
42
+ return '';
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Computes a deterministic 12-character SHA-256 hex identity hash for a repository
48
+ * to keep learned rules isolated locally until cross-project promotion.
49
+ */
50
+ export function computeProjectScopeHash(workspaceDir = process.cwd(), { gitRemoteUrl = '' } = {}) {
51
+ const remote = String(gitRemoteUrl || tryGetGitRemoteOrigin(workspaceDir) || '')
52
+ .trim()
53
+ .toLowerCase()
54
+ .replace(/\.git$/, '');
55
+ const seed = remote || canonicalizePath(String(workspaceDir || process.cwd()));
56
+ return crypto.createHash('sha256').update(seed, 'utf8').digest('hex').slice(0, 12);
57
+ }
58
+
59
+ /**
60
+ * Evaluates which instincts across projects meet the Global Promotion Pipeline
61
+ * threshold (`confidence >= 0.80` across `>= minDistinctRepos` / `minReposForGlobalPromotion`,
62
+ * defaulting to 2 distinct `project_hash` values, or 1 when `userConfirmed: true`).
63
+ */
64
+ export function evaluateGlobalPromotionEligibility(
65
+ instinctRows = [],
66
+ {
67
+ minConfidence = REFLECTOR_CONSTANTS.GLOBAL_PROMOTION_MIN_CONFIDENCE,
68
+ minDistinctRepos = REFLECTOR_CONSTANTS.GLOBAL_PROMOTION_MIN_REPOS,
69
+ minReposForGlobalPromotion,
70
+ userConfirmed = false
71
+ } = {}
72
+ ) {
73
+ const effectiveMinRepos = Math.max(
74
+ 1,
75
+ Number(minReposForGlobalPromotion ?? minDistinctRepos ?? REFLECTOR_CONSTANTS.GLOBAL_PROMOTION_MIN_REPOS)
76
+ );
77
+ const groups = new Map();
78
+
79
+ for (const row of Array.isArray(instinctRows) ? instinctRows : []) {
80
+ if (!row || row.status === 'quarantined' || row.status === 'contradiction_blocked') continue;
81
+ const conf = Number(row.confidence ?? 0);
82
+ if (conf < minConfidence) continue;
83
+
84
+ const domain = String(row.domain || 'general').toLowerCase().trim();
85
+ const directive = String(row.directive_action || '').trim();
86
+ if (!directive) continue;
87
+
88
+ const key = `${domain}::${directive.toLowerCase().replace(/\s+/g, ' ')}`;
89
+ const projHash = String(row.project_hash || row.projectHash || 'local');
90
+
91
+ if (!groups.has(key)) {
92
+ groups.set(key, {
93
+ domain,
94
+ directive_action: directive,
95
+ trigger_condition: String(row.trigger_condition || 'When executing matching domain tasks'),
96
+ projectHashes: new Set(),
97
+ confidences: [],
98
+ instinctIds: [],
99
+ userConfirmed: Boolean(userConfirmed)
100
+ });
101
+ }
102
+
103
+ const entry = groups.get(key);
104
+ entry.projectHashes.add(projHash);
105
+ entry.confidences.push(conf);
106
+ if (row.id) entry.instinctIds.push(row.id);
107
+ if (row.userConfirmed || row.user_confirmed) {
108
+ entry.userConfirmed = true;
109
+ }
110
+ }
111
+
112
+ const eligible = [];
113
+ for (const entry of groups.values()) {
114
+ const repoCount = entry.projectHashes.size;
115
+ const requiredRepos = entry.userConfirmed ? 1 : effectiveMinRepos;
116
+ if (repoCount >= requiredRepos) {
117
+ const avgConf =
118
+ entry.confidences.reduce((a, b) => a + b, 0) / Math.max(1, entry.confidences.length);
119
+ eligible.push({
120
+ domain: entry.domain,
121
+ directive_action: entry.directive_action,
122
+ trigger_condition: entry.trigger_condition,
123
+ distinctRepoCount: repoCount,
124
+ projectHashes: Array.from(entry.projectHashes),
125
+ avgConfidence: Number(avgConf.toFixed(4)),
126
+ instinctIds: entry.instinctIds,
127
+ eligibleForGlobal: true,
128
+ promotedViaUserConfirmation: Boolean(entry.userConfirmed && repoCount < effectiveMinRepos)
129
+ });
130
+ }
131
+ }
132
+
133
+ return eligible;
134
+ }
135
+
136
+ export function isCorruptedDirective(text = '') {
137
+ const s = String(text || '').trim();
138
+ if (!s) return true;
139
+ if (/<\/?(system_context_prefix|ADDITIONAL_METADATA|USER_SETTINGS_CHANGE|CONTEXT_SUMMARY|SYSTEM_MESSAGE)\b/i.test(s)) {
140
+ return true;
141
+ }
142
+ if (/^#+\s*ROLE\b/im.test(s) || /\bYou are the Principal Systems Architect\b/i.test(s)) {
143
+ return true;
144
+ }
145
+ return false;
146
+ }
147
+
148
+ export class ReflectorQueue {
149
+ constructor(options = {}) {
150
+ this.workspaceDir = options.workspaceDir || process.cwd();
151
+ this._hasCustomQueuePath = Boolean(options.queuePath);
152
+ this._hasCustomProjectHash = Boolean(options.projectHash);
153
+ this._hasCustomSkillsBaseDir = Boolean(options.skillsBaseDir);
154
+ this.projectHash =
155
+ options.projectHash ||
156
+ computeProjectScopeHash(this.workspaceDir, { gitRemoteUrl: options.gitRemoteUrl });
157
+ this.queuePath =
158
+ options.queuePath ||
159
+ path.join(this.workspaceDir, '.agents', 'cache', 'learnings-queue.json');
160
+ this.skillsBaseDir =
161
+ options.skillsBaseDir ||
162
+ path.join(this.workspaceDir, '.agents', 'skills');
163
+ this.prefixShield = options.prefixShield || null;
164
+ this.nowFn = typeof options.nowFn === 'function' ? options.nowFn : () => Date.now();
165
+ }
166
+
167
+ setWorkspaceDir(workspaceDir) {
168
+ if (!workspaceDir || typeof workspaceDir !== 'string') return this;
169
+ const resolved = path.resolve(workspaceDir);
170
+ // Never bind project learnings queue to the internal horizon-daemon sidecar directory
171
+ if (/sidecars[\\/]horizon-daemon$/i.test(resolved)) return this;
172
+ if (resolved === path.resolve(this.workspaceDir)) return this;
173
+ this.workspaceDir = resolved;
174
+ if (!this._hasCustomProjectHash) {
175
+ this.projectHash = computeProjectScopeHash(this.workspaceDir);
176
+ }
177
+ if (!this._hasCustomQueuePath) {
178
+ this.queuePath = path.join(this.workspaceDir, '.agents', 'cache', 'learnings-queue.json');
179
+ }
180
+ if (!this._hasCustomSkillsBaseDir) {
181
+ this.skillsBaseDir = path.join(this.workspaceDir, '.agents', 'skills');
182
+ }
183
+ return this;
184
+ }
185
+
186
+ attachPrefixCacheShield(prefixShield) {
187
+ this.prefixShield = prefixShield || null;
188
+ return this;
189
+ }
190
+
191
+ _readQueueData() {
192
+ if (!fs.existsSync(this.queuePath)) {
193
+ return {
194
+ version: 1,
195
+ project_hash: this.projectHash,
196
+ updated_at: new Date(this.nowFn()).toISOString(),
197
+ items: []
198
+ };
199
+ }
200
+ try {
201
+ const parsed = JSON.parse(fs.readFileSync(this.queuePath, 'utf8'));
202
+ if (!Array.isArray(parsed.items)) parsed.items = [];
203
+ return parsed;
204
+ } catch {
205
+ return {
206
+ version: 1,
207
+ project_hash: this.projectHash,
208
+ updated_at: new Date(this.nowFn()).toISOString(),
209
+ items: []
210
+ };
211
+ }
212
+ }
213
+
214
+ _writeQueueData(data) {
215
+ data.updated_at = new Date(this.nowFn()).toISOString();
216
+ atomicWriteFileSync(this.queuePath, JSON.stringify(data, null, 2) + '\n', { encoding: 'utf8' });
217
+ }
218
+
219
+ /**
220
+ * Stages a candidate learning ("Teachable Moment") in `learnings-queue.json`
221
+ * after running `auditRuleContradictions` against existing workspace rules and queued items.
222
+ */
223
+ enqueue(learning = {}, { existingRulesText = '' } = {}) {
224
+ const data = this._readQueueData();
225
+ const rawDirective = String(learning.directive_action || learning.ruleText || '').trim();
226
+ if (!rawDirective) {
227
+ throw new Error('ReflectorQueue.enqueue: directive_action is required');
228
+ }
229
+ const directive = rawDirective
230
+ .replace(/<\/?(?:USER_REQUEST|system_context_prefix)[^>]*>/gi, '')
231
+ .trim();
232
+ if (!directive || isCorruptedDirective(directive)) {
233
+ return {
234
+ enqueued: false,
235
+ reinforced: false,
236
+ blockedByContradiction: false,
237
+ rejectedCorruptedDirective: true,
238
+ item: null,
239
+ contradictionAudit: { hasContradiction: false, conflicts: [] }
240
+ };
241
+ }
242
+
243
+ const domain = String(learning.domain || 'general').toLowerCase().trim();
244
+ const trigger = String(learning.trigger_condition || 'When working in this project').trim();
245
+ const projHash = String(learning.project_hash || learning.projectHash || this.projectHash);
246
+ const confidence = Number.isFinite(learning.confidence) ? Number(learning.confidence) : 0.30;
247
+
248
+ // Combine existing workspace rules + active staged/approved items in the same project for contradiction checking
249
+ const activeProjectDirectives = data.items
250
+ .filter((it) => it.project_hash === projHash && it.status !== 'dismissed' && it.status !== 'contradiction_blocked')
251
+ .map((it) => it.directive_action);
252
+
253
+ const combinedExisting = [
254
+ ...String(existingRulesText || '').split(/\r?\n/),
255
+ ...activeProjectDirectives
256
+ ];
257
+
258
+ const audit = auditRuleContradictions(directive, combinedExisting);
259
+ const nowIso = new Date(this.nowFn()).toISOString();
260
+
261
+ // Check if identical item already exists for this projectHash
262
+ const existingItem = data.items.find(
263
+ (it) =>
264
+ it.project_hash === projHash &&
265
+ it.domain === domain &&
266
+ it.directive_action.toLowerCase().replace(/\s+/g, ' ') === directive.toLowerCase().replace(/\s+/g, ' ')
267
+ );
268
+
269
+ if (existingItem) {
270
+ existingItem.confidence = Math.min(0.95, Number((existingItem.confidence + 0.12).toFixed(4)));
271
+ existingItem.updated_at = nowIso;
272
+ if (audit.hasContradiction) {
273
+ existingItem.status = 'contradiction_blocked';
274
+ existingItem.contradictions = audit.conflicts;
275
+ }
276
+ this._writeQueueData(data);
277
+ return {
278
+ enqueued: false,
279
+ reinforced: true,
280
+ blockedByContradiction: audit.hasContradiction,
281
+ item: existingItem,
282
+ contradictionAudit: audit
283
+ };
284
+ }
285
+
286
+ const item = {
287
+ id: learning.id || `learn-${crypto.randomBytes(6).toString('hex')}`,
288
+ detectorId: 'DET-29',
289
+ project_hash: projHash,
290
+ scope: learning.scope === 'global' ? 'global' : 'project',
291
+ domain,
292
+ trigger_condition: trigger,
293
+ directive_action: directive,
294
+ confidence,
295
+ status: audit.hasContradiction ? 'contradiction_blocked' : (learning.status || 'staged'),
296
+ contradictions: audit.conflicts,
297
+ source: learning.source || 'teachable_moment',
298
+ session_id: learning.sessionId || 'default-session',
299
+ created_at: nowIso,
300
+ updated_at: nowIso
301
+ };
302
+
303
+ data.items.push(item);
304
+ this._writeQueueData(data);
305
+
306
+ return {
307
+ enqueued: !audit.hasContradiction,
308
+ reinforced: false,
309
+ blockedByContradiction: audit.hasContradiction,
310
+ item,
311
+ contradictionAudit: audit
312
+ };
313
+ }
314
+
315
+ approve(id) {
316
+ const data = this._readQueueData();
317
+ const item = data.items.find((it) => it.id === id);
318
+ if (!item) return null;
319
+ if (item.status === 'contradiction_blocked') {
320
+ return { approved: false, reason: 'CONTRADICTION_BLOCKED', item };
321
+ }
322
+ item.status = 'approved';
323
+ item.updated_at = new Date(this.nowFn()).toISOString();
324
+ this._writeQueueData(data);
325
+ return { approved: true, item };
326
+ }
327
+
328
+ dismiss(id) {
329
+ const data = this._readQueueData();
330
+ const item = data.items.find((it) => it.id === id);
331
+ if (!item) return null;
332
+ item.status = 'dismissed';
333
+ item.updated_at = new Date(this.nowFn()).toISOString();
334
+ this._writeQueueData(data);
335
+ return { dismissed: true, item };
336
+ }
337
+
338
+ listItems(filter = {}) {
339
+ const data = this._readQueueData();
340
+ const targetHash = filter.projectHash || (filter.currentProjectOnly !== false ? this.projectHash : null);
341
+ return data.items.filter((it) => {
342
+ if (isCorruptedDirective(it?.directive_action)) return false;
343
+ if (targetHash && it.project_hash !== targetHash) return false;
344
+ if (filter.status && it.status !== filter.status) return false;
345
+ if (filter.domain && it.domain !== filter.domain) return false;
346
+ return true;
347
+ });
348
+ }
349
+
350
+ /**
351
+ * Routes approved or staged high-confidence learnings for a domain into
352
+ * `.agents/skills/<domain>/SKILL.md` ONLY when the session KV cache is cold
353
+ * (`cachedTokens < 15000` or `ttlRemainingSeconds === 0`).
354
+ */
355
+ routeDomainToSkill(domain, { session = {}, minCount = REFLECTOR_CONSTANTS.SKILL_CLUSTER_MIN_COUNT } = {}) {
356
+ const cachedTokens = Number(session.cachedTokens ?? 0);
357
+ const ttlRemainingSeconds = Number(session.ttlRemainingSeconds ?? session.cacheTtlSeconds ?? 0);
358
+ const cacheWarm = isWarmCacheState(
359
+ { ...session, cachedTokens, cacheTtlSeconds: ttlRemainingSeconds },
360
+ REFLECTOR_CONSTANTS.WARM_CACHE_LOCK_TOKENS
361
+ );
362
+
363
+ if (cacheWarm) {
364
+ return {
365
+ routed: false,
366
+ deferredByWarmCache: true,
367
+ reason: `Warm KV cache lock active (${cachedTokens} tokens, ${ttlRemainingSeconds}s TTL remaining)`
368
+ };
369
+ }
370
+
371
+ const cleanDomain = String(domain || 'general').toLowerCase().trim();
372
+ const data = this._readQueueData();
373
+ const eligible = data.items.filter(
374
+ (it) =>
375
+ it.project_hash === this.projectHash &&
376
+ it.domain === cleanDomain &&
377
+ (it.status === 'approved' || it.status === 'staged')
378
+ );
379
+
380
+ if (eligible.length < minCount) {
381
+ return {
382
+ routed: false,
383
+ deferredByWarmCache: false,
384
+ reason: `Domain "${cleanDomain}" has ${eligible.length}/${minCount} learnings required for skill synthesis`
385
+ };
386
+ }
387
+
388
+ const skillSlug = `${cleanDomain.replace(/[^a-z0-9-]+/g, '-')}-project-instincts`;
389
+ const skillPath = path.join(this.skillsBaseDir, skillSlug, 'SKILL.md');
390
+
391
+ const lines = [
392
+ '---',
393
+ `name: ${skillSlug}`,
394
+ `description: Project-scoped (${this.projectHash}) evolved instincts for ${cleanDomain} (${eligible.length} verified rules).`,
395
+ '---',
396
+ '',
397
+ `# ${skillSlug} (\`${cleanDomain}\` | Repo \`${this.projectHash}\`)`,
398
+ '',
399
+ '## Project Directives',
400
+ '',
401
+ ...eligible.map(
402
+ (it, i) =>
403
+ `${i + 1}. **${it.directive_action}** *(when: ${it.trigger_condition}; confidence: ${Number(it.confidence).toFixed(2)})*`
404
+ ),
405
+ ''
406
+ ];
407
+
408
+ atomicWriteFileSync(skillPath, lines.join('\n'), { encoding: 'utf8' });
409
+
410
+ for (const it of eligible) {
411
+ it.status = 'promoted_to_skill';
412
+ it.updated_at = new Date(this.nowFn()).toISOString();
413
+ }
414
+ this._writeQueueData(data);
415
+
416
+ return {
417
+ routed: true,
418
+ deferredByWarmCache: false,
419
+ domain: cleanDomain,
420
+ skillSlug,
421
+ skillPath,
422
+ promotedCount: eligible.length,
423
+ projectHash: this.projectHash
424
+ };
425
+ }
426
+
427
+ /**
428
+ * Lists instincts eligible for global promotion using `.attention-horizon.json`
429
+ * `minReposForGlobalPromotion` (default 2, or 1 when userConfirmed).
430
+ */
431
+ getGlobalPromotionCandidates(options = {}) {
432
+ let configMinRepos;
433
+ try {
434
+ const cfgPath = path.join(this.workspaceDir, '.attention-horizon.json');
435
+ if (fs.existsSync(cfgPath)) {
436
+ const parsedCfg = JSON.parse(fs.readFileSync(cfgPath, 'utf8'));
437
+ if (Number.isFinite(Number(parsedCfg?.minReposForGlobalPromotion))) {
438
+ configMinRepos = Number(parsedCfg.minReposForGlobalPromotion);
439
+ }
440
+ }
441
+ } catch (err) {
442
+ void err;
443
+ }
444
+ const data = this._readQueueData();
445
+ return evaluateGlobalPromotionEligibility(data.items, {
446
+ ...options,
447
+ minReposForGlobalPromotion: options.minReposForGlobalPromotion ?? configMinRepos
448
+ });
449
+ }
450
+
451
+ /**
452
+ * Flushes approved learnings into `AGENTS.md` (or target rule file) strictly when
453
+ * the prompt cache is cold / `PostCompact`.
454
+ */
455
+ flushApprovedWhenCold(options = {}) {
456
+ const session = options.session || options;
457
+ const cacheWarm = !options.bypassShield && isWarmCacheState(session, REFLECTOR_CONSTANTS.WARM_CACHE_LOCK_TOKENS);
458
+ if (cacheWarm) {
459
+ return {
460
+ flushed: false,
461
+ deferredByWarmCache: true,
462
+ flushedCount: 0,
463
+ flushedItems: []
464
+ };
465
+ }
466
+
467
+ const data = this._readQueueData();
468
+ const approved = data.items.filter(
469
+ (it) => it.project_hash === this.projectHash && it.status === 'approved'
470
+ );
471
+ if (approved.length === 0) {
472
+ return {
473
+ flushed: true,
474
+ deferredByWarmCache: false,
475
+ flushedCount: 0,
476
+ flushedItems: []
477
+ };
478
+ }
479
+
480
+ const targetPath = options.targetPath || path.join(this.workspaceDir, 'AGENTS.md');
481
+ let content = fs.existsSync(targetPath) ? fs.readFileSync(targetPath, 'utf8') : '# Agent Directives\n';
482
+ const flushedItems = [];
483
+ for (const it of approved) {
484
+ const bullet = `- ${it.directive_action}`;
485
+ if (!content.includes(it.directive_action)) {
486
+ content = `${content.replace(/\s+$/, '')}\n${bullet}\n`;
487
+ }
488
+ it.status = 'flushed';
489
+ it.updated_at = new Date(this.nowFn()).toISOString();
490
+ flushedItems.push({ ...it, targetPath });
491
+ }
492
+ atomicWriteFileSync(targetPath, content, { encoding: 'utf8' });
493
+ this._writeQueueData(data);
494
+
495
+ return {
496
+ flushed: true,
497
+ deferredByWarmCache: false,
498
+ flushedCount: flushedItems.length,
499
+ targetPath,
500
+ flushedItems
501
+ };
502
+ }
503
+ }
504
+
505
+ export default ReflectorQueue;