thumbgate 0.9.9

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 (369) hide show
  1. package/.claude-plugin/README.md +134 -0
  2. package/.claude-plugin/bundle/icon.png +0 -0
  3. package/.claude-plugin/bundle/icon.svg +18 -0
  4. package/.claude-plugin/bundle/server/index.js +24 -0
  5. package/.claude-plugin/marketplace.json +36 -0
  6. package/.claude-plugin/plugin.json +21 -0
  7. package/.well-known/mcp/server-card.json +231 -0
  8. package/LICENSE +21 -0
  9. package/README.md +375 -0
  10. package/adapters/README.md +9 -0
  11. package/adapters/amp/skills/rlhf-feedback/SKILL.md +22 -0
  12. package/adapters/chatgpt/INSTALL.md +83 -0
  13. package/adapters/chatgpt/openapi.yaml +1281 -0
  14. package/adapters/claude/.mcp.json +14 -0
  15. package/adapters/codex/config.toml +9 -0
  16. package/adapters/gemini/function-declarations.json +224 -0
  17. package/adapters/mcp/server-stdio.js +788 -0
  18. package/adapters/opencode/opencode.json +15 -0
  19. package/bin/cli.js +1483 -0
  20. package/bin/memory.sh +64 -0
  21. package/bin/obsidian-sync.sh +20 -0
  22. package/bin/postinstall.js +37 -0
  23. package/config/build-metadata.json +4 -0
  24. package/config/e2e-critical-flows.json +45 -0
  25. package/config/gate-templates.json +77 -0
  26. package/config/gates/claim-verification.json +29 -0
  27. package/config/gates/computer-use.json +39 -0
  28. package/config/gates/default.json +117 -0
  29. package/config/github-about.json +25 -0
  30. package/config/mcp-allowlists.json +135 -0
  31. package/config/model-tiers.json +33 -0
  32. package/config/partner-routing.json +132 -0
  33. package/config/policy-bundles/constrained-v1.json +64 -0
  34. package/config/policy-bundles/default-v1.json +91 -0
  35. package/config/rubrics/default-v1.json +52 -0
  36. package/config/skill-packs/react-testing.json +23 -0
  37. package/config/skill-packs/stripe-integration/references/api-spec.json +1 -0
  38. package/config/skill-packs/stripe-integration/references/webhook-guide.md +3 -0
  39. package/config/skill-specs/pr-reviewer.json +9 -0
  40. package/config/skill-specs/release-status.json +9 -0
  41. package/config/skill-specs/ticket-triage.json +9 -0
  42. package/config/subagent-profiles.json +32 -0
  43. package/config/tessl-tiles.json +29 -0
  44. package/config/thumbgate-settings.managed.json +12 -0
  45. package/openapi/openapi.yaml +1281 -0
  46. package/package.json +286 -0
  47. package/plugins/amp-skill/INSTALL.md +52 -0
  48. package/plugins/amp-skill/SKILL.md +64 -0
  49. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +22 -0
  50. package/plugins/claude-codex-bridge/.mcp.json +12 -0
  51. package/plugins/claude-codex-bridge/INSTALL.md +43 -0
  52. package/plugins/claude-codex-bridge/README.md +46 -0
  53. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +288 -0
  54. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +24 -0
  55. package/plugins/claude-codex-bridge/skills/result/SKILL.md +22 -0
  56. package/plugins/claude-codex-bridge/skills/review/SKILL.md +28 -0
  57. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +27 -0
  58. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +21 -0
  59. package/plugins/claude-codex-bridge/skills/status/SKILL.md +19 -0
  60. package/plugins/claude-skill/INSTALL.md +55 -0
  61. package/plugins/claude-skill/SKILL.md +46 -0
  62. package/plugins/codex-profile/.codex-plugin/plugin.json +43 -0
  63. package/plugins/codex-profile/.mcp.json +12 -0
  64. package/plugins/codex-profile/AGENTS.md +20 -0
  65. package/plugins/codex-profile/INSTALL.md +66 -0
  66. package/plugins/codex-profile/README.md +37 -0
  67. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +23 -0
  68. package/plugins/cursor-marketplace/CHANGELOG.md +30 -0
  69. package/plugins/cursor-marketplace/LICENSE +21 -0
  70. package/plugins/cursor-marketplace/README.md +124 -0
  71. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +31 -0
  72. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  73. package/plugins/cursor-marketplace/commands/capture-feedback.md +33 -0
  74. package/plugins/cursor-marketplace/commands/check-gates.md +25 -0
  75. package/plugins/cursor-marketplace/commands/show-lessons.md +27 -0
  76. package/plugins/cursor-marketplace/hooks/hooks.json +10 -0
  77. package/plugins/cursor-marketplace/mcp.json +12 -0
  78. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +34 -0
  79. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +30 -0
  80. package/plugins/cursor-marketplace/rules/session-continuity.mdc +28 -0
  81. package/plugins/cursor-marketplace/scripts/gate-check.sh +11 -0
  82. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +47 -0
  83. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +31 -0
  84. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +30 -0
  85. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +33 -0
  86. package/plugins/gemini-extension/INSTALL.md +92 -0
  87. package/plugins/gemini-extension/gemini_prompt.txt +14 -0
  88. package/plugins/gemini-extension/tool_contract.json +45 -0
  89. package/plugins/opencode-profile/INSTALL.md +57 -0
  90. package/public/assets/instagram-card.png +0 -0
  91. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  92. package/public/blog.html +400 -0
  93. package/public/dashboard.html +1093 -0
  94. package/public/guide.html +317 -0
  95. package/public/index.html +1195 -0
  96. package/public/learn/agent-harness-pattern.html +180 -0
  97. package/public/learn/ai-agent-persistent-memory.html +202 -0
  98. package/public/learn/learn.css +45 -0
  99. package/public/learn/mcp-pre-action-gates-explained.html +172 -0
  100. package/public/learn/stop-ai-agent-force-push.html +134 -0
  101. package/public/learn/vibe-coding-safety-net.html +142 -0
  102. package/public/learn.html +213 -0
  103. package/public/lessons.html +650 -0
  104. package/public/vercel.json +8 -0
  105. package/scripts/__pycache__/train_from_feedback.cpython-314.pyc +0 -0
  106. package/scripts/a2ui-engine.js +73 -0
  107. package/scripts/access-anomaly-detector.js +12 -0
  108. package/scripts/adk-consolidator.js +266 -0
  109. package/scripts/agent-readiness.js +220 -0
  110. package/scripts/agent-security-hardening.js +227 -0
  111. package/scripts/agentic-data-pipeline.js +847 -0
  112. package/scripts/analytics-report.js +328 -0
  113. package/scripts/analytics-window.js +158 -0
  114. package/scripts/async-job-runner.js +1001 -0
  115. package/scripts/audit-trail.js +398 -0
  116. package/scripts/auto-promote-gates.js +293 -0
  117. package/scripts/auto-wire-hooks.js +316 -0
  118. package/scripts/autonomous-sales-agent.js +39 -0
  119. package/scripts/autoresearch-runner.js +216 -0
  120. package/scripts/background-agent-governance.js +237 -0
  121. package/scripts/behavioral-extraction.js +93 -0
  122. package/scripts/belief-update.js +84 -0
  123. package/scripts/billing.js +2438 -0
  124. package/scripts/bot-detector.js +50 -0
  125. package/scripts/budget-guard.js +173 -0
  126. package/scripts/build-claude-mcpb.js +189 -0
  127. package/scripts/build-metadata.js +97 -0
  128. package/scripts/check-congruence.js +322 -0
  129. package/scripts/cli-feedback.js +135 -0
  130. package/scripts/cli-telemetry.js +87 -0
  131. package/scripts/cloudflare-dynamic-sandbox.js +315 -0
  132. package/scripts/code-reasoning.js +350 -0
  133. package/scripts/codegraph-context.js +466 -0
  134. package/scripts/commercial-offer.js +56 -0
  135. package/scripts/computer-use-firewall.js +250 -0
  136. package/scripts/context-engine.js +694 -0
  137. package/scripts/contextfs.js +1287 -0
  138. package/scripts/conversation-context.js +119 -0
  139. package/scripts/creator-campaigns.js +239 -0
  140. package/scripts/daemon-manager.js +108 -0
  141. package/scripts/daily-digest.js +11 -0
  142. package/scripts/dashboard-render-spec.js +395 -0
  143. package/scripts/dashboard.js +1058 -0
  144. package/scripts/data-governance.js +173 -0
  145. package/scripts/delegation-runtime.js +900 -0
  146. package/scripts/deploy-gcp.sh +44 -0
  147. package/scripts/deploy-policy.js +231 -0
  148. package/scripts/disagreement-mining.js +315 -0
  149. package/scripts/dispatch-brief.js +159 -0
  150. package/scripts/distribution-surfaces.js +44 -0
  151. package/scripts/dpo-optimizer.js +206 -0
  152. package/scripts/ensure-repo-bootstrap.js +129 -0
  153. package/scripts/ephemeral-agent-store.js +219 -0
  154. package/scripts/eval-harness.js +56 -0
  155. package/scripts/evolution-state.js +241 -0
  156. package/scripts/experiment-tracker.js +267 -0
  157. package/scripts/export-databricks-bundle.js +242 -0
  158. package/scripts/export-dpo-pairs.js +344 -0
  159. package/scripts/export-kto-pairs.js +309 -0
  160. package/scripts/export-training.js +450 -0
  161. package/scripts/failure-diagnostics.js +558 -0
  162. package/scripts/feedback-attribution.js +313 -0
  163. package/scripts/feedback-fallback.js +110 -0
  164. package/scripts/feedback-history-distiller.js +391 -0
  165. package/scripts/feedback-inbox-read.js +162 -0
  166. package/scripts/feedback-loop.js +1887 -0
  167. package/scripts/feedback-paths.js +145 -0
  168. package/scripts/feedback-quality.js +139 -0
  169. package/scripts/feedback-root-consolidator.js +238 -0
  170. package/scripts/feedback-schema.js +426 -0
  171. package/scripts/feedback-session.js +286 -0
  172. package/scripts/feedback-to-memory.js +185 -0
  173. package/scripts/feedback-to-rules.js +164 -0
  174. package/scripts/filesystem-search.js +405 -0
  175. package/scripts/funnel-analytics.js +35 -0
  176. package/scripts/gate-satisfy.js +42 -0
  177. package/scripts/gate-stats.js +116 -0
  178. package/scripts/gate-templates.js +70 -0
  179. package/scripts/gates-engine.js +816 -0
  180. package/scripts/generate-paperbanana-diagrams.sh +99 -0
  181. package/scripts/generate-pretool-hook.sh +40 -0
  182. package/scripts/github-about.js +350 -0
  183. package/scripts/github-outreach.js +65 -0
  184. package/scripts/gtm-revenue-loop.js +520 -0
  185. package/scripts/hallucination-detector.js +226 -0
  186. package/scripts/hf-papers.js +317 -0
  187. package/scripts/history-distiller.js +200 -0
  188. package/scripts/hook-auto-capture.sh +100 -0
  189. package/scripts/hook-stop-pr-thread-check.sh +68 -0
  190. package/scripts/hook-stop-self-score.sh +51 -0
  191. package/scripts/hook-stop-verify-deploy.sh +31 -0
  192. package/scripts/hook-thumbgate-cache-updater.js +48 -0
  193. package/scripts/hook-verify-before-done.sh +20 -0
  194. package/scripts/hosted-config.js +156 -0
  195. package/scripts/hybrid-feedback-context.js +675 -0
  196. package/scripts/install-mcp.js +159 -0
  197. package/scripts/intent-router.js +392 -0
  198. package/scripts/internal-agent-bootstrap.js +490 -0
  199. package/scripts/jsonl-watcher.js +155 -0
  200. package/scripts/lesson-db.js +613 -0
  201. package/scripts/lesson-inference.js +310 -0
  202. package/scripts/lesson-retrieval.js +95 -0
  203. package/scripts/lesson-rotation.js +137 -0
  204. package/scripts/lesson-search.js +644 -0
  205. package/scripts/lesson-synthesis.js +196 -0
  206. package/scripts/license.js +50 -0
  207. package/scripts/local-model-profile.js +384 -0
  208. package/scripts/markdown-escape.js +12 -0
  209. package/scripts/marketing-experiment.js +671 -0
  210. package/scripts/mcp-config.js +149 -0
  211. package/scripts/mcp-policy.js +99 -0
  212. package/scripts/memalign-recall.js +111 -0
  213. package/scripts/memory-firewall.js +222 -0
  214. package/scripts/memory-migration.js +296 -0
  215. package/scripts/meta-policy.js +190 -0
  216. package/scripts/metered-billing.js +16 -0
  217. package/scripts/model-tier-router.js +301 -0
  218. package/scripts/money-watcher.js +71 -0
  219. package/scripts/multi-hop-recall.js +240 -0
  220. package/scripts/natural-language-harness.js +330 -0
  221. package/scripts/obsidian-export.js +713 -0
  222. package/scripts/operational-dashboard.js +103 -0
  223. package/scripts/operational-summary.js +93 -0
  224. package/scripts/optimize-context.js +17 -0
  225. package/scripts/org-dashboard.js +201 -0
  226. package/scripts/partner-orchestration.js +146 -0
  227. package/scripts/per-step-scoring.js +165 -0
  228. package/scripts/perplexity-marketing.js +466 -0
  229. package/scripts/pii-scanner.js +153 -0
  230. package/scripts/plan-gate.js +154 -0
  231. package/scripts/post-everywhere.js +308 -0
  232. package/scripts/post-to-x-retry.sh +22 -0
  233. package/scripts/post-to-x.js +369 -0
  234. package/scripts/pr-manager.js +236 -0
  235. package/scripts/predictive-insights.js +356 -0
  236. package/scripts/principle-extractor.js +162 -0
  237. package/scripts/pro-features.js +40 -0
  238. package/scripts/pro-local-dashboard.js +174 -0
  239. package/scripts/problem-detail.js +53 -0
  240. package/scripts/product-feedback.js +134 -0
  241. package/scripts/profile-router.js +245 -0
  242. package/scripts/prompt-dlp.js +221 -0
  243. package/scripts/prompt-guard.js +83 -0
  244. package/scripts/prove-adapters.js +863 -0
  245. package/scripts/prove-attribution.js +365 -0
  246. package/scripts/prove-automation.js +653 -0
  247. package/scripts/prove-autoresearch.js +304 -0
  248. package/scripts/prove-claim-verification.js +277 -0
  249. package/scripts/prove-cloudflare-sandbox.js +163 -0
  250. package/scripts/prove-data-pipeline.js +410 -0
  251. package/scripts/prove-data-quality.js +227 -0
  252. package/scripts/prove-evolution.js +352 -0
  253. package/scripts/prove-harnesses.js +287 -0
  254. package/scripts/prove-intelligence.js +259 -0
  255. package/scripts/prove-lancedb.js +371 -0
  256. package/scripts/prove-local-intelligence.js +342 -0
  257. package/scripts/prove-loop-closure.js +263 -0
  258. package/scripts/prove-predictive-insights.js +357 -0
  259. package/scripts/prove-runtime.js +350 -0
  260. package/scripts/prove-seo-gsd.js +234 -0
  261. package/scripts/prove-settings.js +279 -0
  262. package/scripts/prove-subway-upgrades.js +277 -0
  263. package/scripts/prove-tessl.js +229 -0
  264. package/scripts/prove-training-export.js +327 -0
  265. package/scripts/prove-workflow-contract.js +116 -0
  266. package/scripts/prove-xmemory.js +332 -0
  267. package/scripts/publish-decision.js +133 -0
  268. package/scripts/pulse.js +80 -0
  269. package/scripts/rate-limiter.js +125 -0
  270. package/scripts/reddit-dm-outreach.js +182 -0
  271. package/scripts/reddit-monitor-cron.sh +26 -0
  272. package/scripts/reflector-agent.js +221 -0
  273. package/scripts/reminder-engine.js +132 -0
  274. package/scripts/revenue-status.js +472 -0
  275. package/scripts/risk-scorer.js +459 -0
  276. package/scripts/rlaif-self-audit.js +129 -0
  277. package/scripts/rlhf_session_start.sh +32 -0
  278. package/scripts/rubric-engine.js +230 -0
  279. package/scripts/schedule-manager.js +251 -0
  280. package/scripts/secret-scanner.js +414 -0
  281. package/scripts/self-heal.js +147 -0
  282. package/scripts/self-healing-check.js +188 -0
  283. package/scripts/semantic-layer.js +98 -0
  284. package/scripts/seo-gsd.js +1153 -0
  285. package/scripts/settings-hierarchy.js +214 -0
  286. package/scripts/shieldcortex-memory-firewall-runner.mjs +53 -0
  287. package/scripts/skill-exporter.js +262 -0
  288. package/scripts/skill-generator.js +446 -0
  289. package/scripts/skill-materializer.js +134 -0
  290. package/scripts/skill-packs.js +136 -0
  291. package/scripts/skill-proposer.js +99 -0
  292. package/scripts/skill-quality-tracker.js +282 -0
  293. package/scripts/slo-alert-engine.js +14 -0
  294. package/scripts/slow-loop.js +72 -0
  295. package/scripts/social-analytics/db/schema.sql +32 -0
  296. package/scripts/social-analytics/db/social-analytics.db +0 -0
  297. package/scripts/social-analytics/digest.js +256 -0
  298. package/scripts/social-analytics/generate-instagram-card.js +97 -0
  299. package/scripts/social-analytics/instagram-thumbgate-post.js +107 -0
  300. package/scripts/social-analytics/load-env.js +46 -0
  301. package/scripts/social-analytics/mcp-server.js +289 -0
  302. package/scripts/social-analytics/normalizer.js +580 -0
  303. package/scripts/social-analytics/notify.js +162 -0
  304. package/scripts/social-analytics/poll-all.js +92 -0
  305. package/scripts/social-analytics/pollers/github.js +195 -0
  306. package/scripts/social-analytics/pollers/instagram.js +253 -0
  307. package/scripts/social-analytics/pollers/linkedin.js +330 -0
  308. package/scripts/social-analytics/pollers/plausible.js +247 -0
  309. package/scripts/social-analytics/pollers/reddit.js +306 -0
  310. package/scripts/social-analytics/pollers/threads.js +233 -0
  311. package/scripts/social-analytics/pollers/tiktok.js +203 -0
  312. package/scripts/social-analytics/pollers/x.js +227 -0
  313. package/scripts/social-analytics/pollers/youtube.js +304 -0
  314. package/scripts/social-analytics/pollers/zernio.js +183 -0
  315. package/scripts/social-analytics/publish-instagram-thumbgate.js +98 -0
  316. package/scripts/social-analytics/publish-thumbgate-launch.js +316 -0
  317. package/scripts/social-analytics/publishers/devto.js +122 -0
  318. package/scripts/social-analytics/publishers/instagram.js +317 -0
  319. package/scripts/social-analytics/publishers/linkedin.js +294 -0
  320. package/scripts/social-analytics/publishers/reddit.js +390 -0
  321. package/scripts/social-analytics/publishers/threads.js +275 -0
  322. package/scripts/social-analytics/publishers/tiktok.js +217 -0
  323. package/scripts/social-analytics/publishers/x.js +259 -0
  324. package/scripts/social-analytics/publishers/youtube.js +223 -0
  325. package/scripts/social-analytics/publishers/zernio.js +378 -0
  326. package/scripts/social-analytics/run-digest.js +34 -0
  327. package/scripts/social-analytics/store.js +257 -0
  328. package/scripts/social-analytics/utm.js +143 -0
  329. package/scripts/social-pipeline.js +2628 -0
  330. package/scripts/social-quality-gate.js +18 -0
  331. package/scripts/social-reply-monitor.js +445 -0
  332. package/scripts/status-dashboard.js +155 -0
  333. package/scripts/statusline-lesson.js +16 -0
  334. package/scripts/statusline-tower.js +8 -0
  335. package/scripts/statusline.sh +116 -0
  336. package/scripts/stripe-live-status.js +115 -0
  337. package/scripts/subagent-profiles.js +79 -0
  338. package/scripts/sync-gh-secrets-from-env.sh +70 -0
  339. package/scripts/sync-github-about.js +52 -0
  340. package/scripts/sync-version.js +447 -0
  341. package/scripts/synthetic-dpo.js +234 -0
  342. package/scripts/telemetry-analytics.js +821 -0
  343. package/scripts/tessl-export.js +371 -0
  344. package/scripts/test-coverage.js +120 -0
  345. package/scripts/thompson-sampling.js +417 -0
  346. package/scripts/thumbgate-search.js +189 -0
  347. package/scripts/tool-kpi-tracker.js +12 -0
  348. package/scripts/tool-registry.js +811 -0
  349. package/scripts/train_from_feedback.py +933 -0
  350. package/scripts/user-profile.js +78 -0
  351. package/scripts/validate-feedback.js +581 -0
  352. package/scripts/validate-workflow-contract.js +287 -0
  353. package/scripts/vector-store.js +197 -0
  354. package/scripts/verification-loop.js +291 -0
  355. package/scripts/verify-obsidian-setup.sh +269 -0
  356. package/scripts/verify-run.js +269 -0
  357. package/scripts/webhook-delivery.js +62 -0
  358. package/scripts/weekly-auto-post.js +124 -0
  359. package/scripts/workflow-runs.js +154 -0
  360. package/scripts/workflow-sprint-intake.js +475 -0
  361. package/scripts/workspace-evolver.js +374 -0
  362. package/scripts/x-autonomous-marketing.js +139 -0
  363. package/scripts/xmemory-lite.js +405 -0
  364. package/skills/agent-memory/SKILL.md +97 -0
  365. package/skills/rlhf-feedback/SKILL.md +49 -0
  366. package/skills/solve-architecture-autonomy/SKILL.md +17 -0
  367. package/skills/solve-architecture-autonomy/tool.js +33 -0
  368. package/skills/thumbgate/SKILL.md +114 -0
  369. package/src/api/server.js +4206 -0
@@ -0,0 +1,694 @@
1
+ /**
2
+ * Context Engine
3
+ *
4
+ * Inspired by Dropbox Dash's architecture for intelligent context retrieval.
5
+ * Pre-computes knowledge bundles from project docs, routes queries to relevant
6
+ * context, scores retrieval quality, and manages prompt templates.
7
+ *
8
+ * Key insight: instead of agents reading 100+ docs at runtime, pre-compute
9
+ * topical bundles and route queries to the most relevant subset. This reduces
10
+ * MCP tool calls and context window consumption.
11
+ *
12
+ * Ported from Subway_RN_Demo/scripts/context-engine.js for thumbgate.
13
+ * PATH: PROJECT_ROOT = path.join(__dirname, '..') — 1 level up from scripts/
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const crypto = require('crypto');
21
+ const { constructContextPack } = require('./contextfs');
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Default paths
25
+ // ---------------------------------------------------------------------------
26
+
27
+ const PROJECT_ROOT = path.join(__dirname, '..');
28
+ const DEFAULT_DOCS_DIR = path.join(PROJECT_ROOT, 'docs');
29
+ const CONTEXT_ENGINE_DIR = path.join(PROJECT_ROOT, '.claude', 'context-engine');
30
+ const DEFAULT_INDEX_PATH = path.join(CONTEXT_ENGINE_DIR, 'knowledge-index.json');
31
+ const DEFAULT_QUALITY_LOG_PATH = path.join(CONTEXT_ENGINE_DIR, 'quality-log.json');
32
+ const DEFAULT_REGISTRY_PATH = path.join(CONTEXT_ENGINE_DIR, 'prompt-registry.json');
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Category detection rules (from filename patterns)
36
+ // ---------------------------------------------------------------------------
37
+
38
+ // Order: specific domain rules first, broader categories last.
39
+ // This prevents "ANDROID_BUILD" matching BUILD→ci-cd before ANDROID→mobile-dev.
40
+ const CATEGORY_RULES = [
41
+ { category: 'mobile-dev', pattern: /ANDROID|IOS|EXPO|TURBOMODULE|DEVICE|METRO|MMKV/i },
42
+ { category: 'mcp-ai', pattern: /MCP|CONTEXT7|CLAUDE|AGENTIC|AGENT|(?:^|_)AI(?:_|\.)|MEMORY/i },
43
+ { category: 'security', pattern: /SECURITY|CVE|CODEQL|INJECTION|AUDIT|PERMISSION/i },
44
+ { category: 'testing', pattern: /TEST|COVERAGE|REASSURE|RNTL|MAESTRO|PERF/i },
45
+ { category: 'ado-git', pattern: /(?:^|_)ADO(?:_|\.)|AZURE|PR_|SQUASH|BRANCH|GITFLOW|GIT_/i },
46
+ { category: 'architecture', pattern: /ARCHITECTURE|FEATURE|PROJECT_STRUCTURE|PLUGIN|REDUX|CART/i },
47
+ { category: 'ci-cd', pattern: /(?:^|_)CI(?:_|\.)|(?:^|_)CD(?:_|\.)|BUILD|WORKFLOW|PIPELINE|FIREBASE|(?:^|_)ACT(?:_|\.)/i },
48
+ ];
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // MCP Consolidation Manifest
52
+ // ---------------------------------------------------------------------------
53
+
54
+ const TOOL_CONSOLIDATION = {
55
+ 'context:retrieve': {
56
+ sources: ['context7', 'knowledge-index'],
57
+ description: 'Unified context retrieval',
58
+ },
59
+ 'memory:query': {
60
+ sources: ['jsonl-memory', 'lancedb-vectors'],
61
+ description: 'Unified memory access',
62
+ },
63
+ 'quality:check': {
64
+ sources: ['sonarqube', 'eslint', 'jest'],
65
+ description: 'Unified quality gate',
66
+ },
67
+ 'docs:lookup': {
68
+ sources: ['context7', 'knowledge-bundles'],
69
+ description: 'Documentation lookup',
70
+ },
71
+ };
72
+
73
+ // ---------------------------------------------------------------------------
74
+ // Utility: ensure directory exists
75
+ // ---------------------------------------------------------------------------
76
+
77
+ function ensureDir(dirPath) {
78
+ if (!fs.existsSync(dirPath)) {
79
+ fs.mkdirSync(dirPath, { recursive: true });
80
+ }
81
+ }
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // Knowledge Bundle Builder
85
+ // ---------------------------------------------------------------------------
86
+
87
+ /**
88
+ * Determine the category for a doc file based on its filename.
89
+ *
90
+ * @param {string} filename - The filename (e.g., "CI_FIXES.md")
91
+ * @returns {string} Category string (e.g., "ci-cd", "testing", "general")
92
+ */
93
+ function categorizeDoc(filename) {
94
+ for (const rule of CATEGORY_RULES) {
95
+ if (rule.pattern.test(filename)) {
96
+ return rule.category;
97
+ }
98
+ }
99
+ return 'general';
100
+ }
101
+
102
+ /**
103
+ * Extract a summary from a markdown file: title + first 3 non-empty lines after it.
104
+ *
105
+ * @param {string} filePath - Absolute path to the markdown file
106
+ * @returns {{ title: string, summary: string }} Extracted title and summary
107
+ */
108
+ function extractDocSummary(filePath) {
109
+ let content;
110
+ try {
111
+ content = fs.readFileSync(filePath, 'utf-8');
112
+ } catch {
113
+ return { title: path.basename(filePath, '.md'), summary: '' };
114
+ }
115
+
116
+ const lines = content.split('\n');
117
+ let title = path.basename(filePath, '.md');
118
+ let titleLineIndex = -1;
119
+
120
+ // Find first heading line
121
+ for (let i = 0; i < lines.length; i++) {
122
+ const trimmed = lines[i].trim();
123
+ if (trimmed.startsWith('#')) {
124
+ title = trimmed.replace(/^#+\s*/, '');
125
+ titleLineIndex = i;
126
+ break;
127
+ }
128
+ }
129
+
130
+ // Collect first 3 non-empty lines after the title
131
+ const summaryLines = [];
132
+ const startIdx = titleLineIndex + 1;
133
+ for (let i = startIdx; i < lines.length && summaryLines.length < 3; i++) {
134
+ const trimmed = lines[i].trim();
135
+ if (trimmed && !trimmed.startsWith('#')) {
136
+ summaryLines.push(trimmed);
137
+ }
138
+ }
139
+
140
+ return { title, summary: summaryLines.join(' ') };
141
+ }
142
+
143
+ /**
144
+ * Scan a docs directory and build a pre-computed knowledge index.
145
+ *
146
+ * Groups markdown files into topical bundles by category, extracts titles
147
+ * and summaries, and writes the index to disk for fast runtime lookup.
148
+ *
149
+ * @param {string} [docsDir] - Path to the docs directory (default: project docs/)
150
+ * @param {string} [outputPath] - Path to write the index JSON (default: .claude/context-engine/knowledge-index.json)
151
+ * @returns {{ bundles: object, totalDocs: number, generatedAt: string }} The generated index
152
+ */
153
+ function buildKnowledgeIndex(docsDir, outputPath) {
154
+ const docs = docsDir || DEFAULT_DOCS_DIR;
155
+ const output = outputPath || DEFAULT_INDEX_PATH;
156
+ const bundles = {};
157
+
158
+ // Scan for .md files
159
+ let files;
160
+ try {
161
+ files = fs.readdirSync(docs).filter((f) => f.endsWith('.md'));
162
+ } catch {
163
+ files = [];
164
+ }
165
+
166
+ for (const file of files) {
167
+ const filePath = path.join(docs, file);
168
+ const category = categorizeDoc(file);
169
+ const { title, summary } = extractDocSummary(filePath);
170
+
171
+ if (!bundles[category]) {
172
+ bundles[category] = {
173
+ category,
174
+ docs: [],
175
+ keywords: [],
176
+ };
177
+ }
178
+
179
+ const doc = {
180
+ filename: file,
181
+ title,
182
+ summary,
183
+ };
184
+
185
+ bundles[category].docs.push(doc);
186
+
187
+ // Extract keywords from title and filename
188
+ const words = `${title} ${file.replace(/[._-]/g, ' ')}`
189
+ .toLowerCase()
190
+ .split(/\s+/)
191
+ .filter((w) => w.length > 2 && w !== 'md');
192
+
193
+ for (const word of words) {
194
+ if (!bundles[category].keywords.includes(word)) {
195
+ bundles[category].keywords.push(word);
196
+ }
197
+ }
198
+ }
199
+
200
+ const index = {
201
+ bundles,
202
+ metadata: {
203
+ builtAt: new Date().toISOString(),
204
+ docCount: files.length,
205
+ version: '1.0.0',
206
+ checksum: crypto
207
+ .createHash('sha256')
208
+ .update(JSON.stringify(bundles))
209
+ .digest('hex')
210
+ .slice(0, 12),
211
+ },
212
+ };
213
+
214
+ // Persist to disk
215
+ try {
216
+ ensureDir(path.dirname(output));
217
+ fs.writeFileSync(output, JSON.stringify(index, null, 2));
218
+ } catch {
219
+ // Non-critical — index still returned in memory
220
+ }
221
+
222
+ return index;
223
+ }
224
+
225
+ // ---------------------------------------------------------------------------
226
+ // Context Router
227
+ // ---------------------------------------------------------------------------
228
+
229
+ /**
230
+ * Score a single bundle against a set of query tokens.
231
+ *
232
+ * Counts how many query tokens match the bundle's keywords, then normalizes
233
+ * by bundle size to avoid large bundles always winning.
234
+ *
235
+ * @param {string[]} queryTokens - Lowercased query words
236
+ * @param {{ keywords: string[], docs: object[] }} bundle - A knowledge bundle
237
+ * @returns {number} Relevance score (higher is better)
238
+ */
239
+ function scoreBundle(queryTokens, bundle) {
240
+ if (!bundle.keywords.length || !queryTokens.length) return 0;
241
+
242
+ let matches = 0;
243
+ for (const token of queryTokens) {
244
+ for (const keyword of bundle.keywords) {
245
+ if (keyword.includes(token) || token.includes(keyword)) {
246
+ matches++;
247
+ break; // Count each token at most once
248
+ }
249
+ }
250
+ }
251
+
252
+ // Normalize: raw matches / sqrt(bundle size) to balance precision vs. recall
253
+ const bundleSize = bundle.docs.length || 1;
254
+ return matches / Math.sqrt(bundleSize);
255
+ }
256
+
257
+ /**
258
+ * Route a natural-language query to the most relevant knowledge bundles.
259
+ *
260
+ * Replaces multiple MCP tool calls with a single pre-computed lookup.
261
+ *
262
+ * @param {string} query - Natural-language query (e.g., "How do I fix Android build errors?")
263
+ * @param {string} [indexPath] - Path to the knowledge index JSON
264
+ * @param {number} [topN=3] - Number of top bundles to return
265
+ * @returns {{ query: string, results: object[] }} Top-N bundles with scores and doc references
266
+ */
267
+ /**
268
+ * Base routing logic for bundles.
269
+ */
270
+ function baseRouteQuery(query, index, topN) {
271
+ const queryTokens = query
272
+ .toLowerCase()
273
+ .split(/\s+/)
274
+ .filter((w) => w.length > 2);
275
+
276
+ const scored = Object.entries(index.bundles)
277
+ .map(([category, bundle]) => ({
278
+ category,
279
+ score: scoreBundle(queryTokens, bundle),
280
+ docs: bundle.docs,
281
+ }))
282
+ .filter((entry) => entry.score > 0)
283
+ .sort((a, b) => b.score - a.score)
284
+ .slice(0, topN);
285
+
286
+ return scored;
287
+ }
288
+
289
+ /**
290
+ * Adaptive Retrieval Loop (Agentic RAG)
291
+ *
292
+ * Step 1: Analyze query to expand tokens or identify intent.
293
+ * Step 2: Perform retrieval with boosted weights for intent-matching categories.
294
+ */
295
+ function routeQuery(query, indexPath, topN) {
296
+ const idxPath = indexPath || DEFAULT_INDEX_PATH;
297
+ const n = topN || 3;
298
+
299
+ // Load index
300
+ let index;
301
+ try {
302
+ index = JSON.parse(fs.readFileSync(idxPath, 'utf-8'));
303
+ } catch {
304
+ index = buildKnowledgeIndex(undefined, idxPath);
305
+ }
306
+
307
+ // Step 1: Intent Detection (Simple heuristic for now, can be LLM-backed)
308
+ const lowerQuery = query.toLowerCase();
309
+ let intentBoost = null;
310
+ if (lowerQuery.includes('test') || lowerQuery.includes('jest')) intentBoost = 'testing';
311
+ if (lowerQuery.includes('build') || lowerQuery.includes('ci')) intentBoost = 'ci-cd';
312
+ if (lowerQuery.includes('security') || lowerQuery.includes('audit')) intentBoost = 'security';
313
+ if (lowerQuery.includes('mobile') || lowerQuery.includes('android')) intentBoost = 'mobile-dev';
314
+ if (lowerQuery.includes('memory') || lowerQuery.includes('rlhf')) intentBoost = 'mcp-ai';
315
+
316
+ // Step 2: Contextual Ranking
317
+ const queryTokens = query
318
+ .toLowerCase()
319
+ .split(/\s+/)
320
+ .filter((w) => w.length > 2);
321
+
322
+ const scored = Object.entries(index.bundles)
323
+ .map(([category, bundle]) => {
324
+ let score = scoreBundle(queryTokens, bundle);
325
+
326
+ // Boost score if intent matches category
327
+ if (intentBoost && category === intentBoost) {
328
+ score *= 1.5;
329
+ }
330
+
331
+ return {
332
+ category,
333
+ score,
334
+ docs: bundle.docs,
335
+ };
336
+ })
337
+ .filter((entry) => entry.score > 0)
338
+ .sort((a, b) => b.score - a.score)
339
+ .slice(0, n);
340
+
341
+ // Recursive Retrieval (EvoSkill Hardening)
342
+ // Drill down to get high-density structured state documents
343
+ let denseContext = null;
344
+ if (scored.length > 0) {
345
+ try {
346
+ denseContext = constructContextPack({
347
+ query,
348
+ maxItems: 3,
349
+ namespaces: ['rules', 'memoryLearning', 'memoryError']
350
+ });
351
+ } catch (err) {
352
+ // Graceful fallback if contextfs is unavailable
353
+ }
354
+ }
355
+
356
+ return {
357
+ query,
358
+ intent: intentBoost,
359
+ results: scored,
360
+ denseContext: denseContext ? denseContext.items : [],
361
+ indexAge: index.metadata && index.metadata.builtAt,
362
+ retrievalType: intentBoost ? 'adaptive' : 'base',
363
+ };
364
+ }
365
+
366
+ // ---------------------------------------------------------------------------
367
+ // Quality Scorer
368
+ // ---------------------------------------------------------------------------
369
+
370
+ /**
371
+ * Score retrieval quality by comparing retrieved docs against expected topics.
372
+ *
373
+ * Uses a precision/recall-style metric:
374
+ * - Precision: what fraction of retrieved docs are relevant to expected topics?
375
+ * - Recall: what fraction of expected topics are covered by retrieved docs?
376
+ *
377
+ * @param {string} query - The original query
378
+ * @param {string[]} retrievedDocs - Filenames of retrieved docs
379
+ * @param {string[]} expectedTopics - Expected topic keywords to match against
380
+ * @param {string} [logPath] - Optional path for the quality log
381
+ * @returns {{ precision: number, recall: number, f1: number, query: string, timestamp: string }}
382
+ */
383
+ function scoreRetrievalQuality(query, retrievedDocs, expectedTopics, logPath) {
384
+ if (!retrievedDocs.length || !expectedTopics.length) {
385
+ const result = {
386
+ query,
387
+ precision: 0,
388
+ recall: 0,
389
+ f1: 0,
390
+ retrievedCount: retrievedDocs.length,
391
+ expectedCount: expectedTopics.length,
392
+ timestamp: new Date().toISOString(),
393
+ };
394
+ logQualityResult(result, logPath);
395
+ return result;
396
+ }
397
+
398
+ const normalizedDocs = retrievedDocs.map((d) => d.toLowerCase());
399
+ const normalizedTopics = expectedTopics.map((t) => t.toLowerCase());
400
+
401
+ // Precision: how many retrieved docs match at least one expected topic?
402
+ let relevantRetrieved = 0;
403
+ for (const doc of normalizedDocs) {
404
+ for (const topic of normalizedTopics) {
405
+ if (doc.includes(topic) || topic.includes(doc.replace('.md', ''))) {
406
+ relevantRetrieved++;
407
+ break;
408
+ }
409
+ }
410
+ }
411
+ const precision = relevantRetrieved / normalizedDocs.length;
412
+
413
+ // Recall: how many expected topics are covered by at least one retrieved doc?
414
+ let topicsCovered = 0;
415
+ for (const topic of normalizedTopics) {
416
+ for (const doc of normalizedDocs) {
417
+ if (doc.includes(topic) || topic.includes(doc.replace('.md', ''))) {
418
+ topicsCovered++;
419
+ break;
420
+ }
421
+ }
422
+ }
423
+ const recall = topicsCovered / normalizedTopics.length;
424
+
425
+ // F1 harmonic mean
426
+ const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0;
427
+
428
+ const result = {
429
+ query,
430
+ precision: Math.round(precision * 1000) / 1000,
431
+ recall: Math.round(recall * 1000) / 1000,
432
+ f1: Math.round(f1 * 1000) / 1000,
433
+ retrievedCount: retrievedDocs.length,
434
+ expectedCount: expectedTopics.length,
435
+ timestamp: new Date().toISOString(),
436
+ };
437
+
438
+ logQualityResult(result, logPath);
439
+ return result;
440
+ }
441
+
442
+ /**
443
+ * Append a quality result to the JSONL quality log.
444
+ *
445
+ * @param {object} result - Quality score result object
446
+ * @param {string} [logPath] - Path to the quality log file
447
+ */
448
+ function logQualityResult(result, logPath) {
449
+ const log = logPath || DEFAULT_QUALITY_LOG_PATH;
450
+ const entry = { ...result };
451
+
452
+ // Ensure timestamp is always present
453
+ if (!entry.timestamp) {
454
+ entry.timestamp = new Date().toISOString();
455
+ }
456
+
457
+ try {
458
+ ensureDir(path.dirname(log));
459
+ fs.appendFileSync(log, JSON.stringify(entry) + '\n');
460
+ } catch {
461
+ // Non-critical — scoring still works without persistence
462
+ }
463
+ }
464
+
465
+ // ---------------------------------------------------------------------------
466
+ // Prompt Registry
467
+ // ---------------------------------------------------------------------------
468
+
469
+ /**
470
+ * Load the prompt registry from disk.
471
+ *
472
+ * @param {string} [registryPath] - Path to the registry JSON
473
+ * @returns {object} Map of prompt name → { template, metadata }
474
+ */
475
+ function loadRegistry(registryPath) {
476
+ const reg = registryPath || DEFAULT_REGISTRY_PATH;
477
+ try {
478
+ if (fs.existsSync(reg)) {
479
+ return JSON.parse(fs.readFileSync(reg, 'utf-8'));
480
+ }
481
+ } catch {
482
+ // Corrupted file — start fresh
483
+ }
484
+ return {};
485
+ }
486
+
487
+ /**
488
+ * Save the prompt registry to disk.
489
+ *
490
+ * @param {object} registry - The full registry object
491
+ * @param {string} [registryPath] - Path to the registry JSON
492
+ */
493
+ function saveRegistry(registry, registryPath) {
494
+ const reg = registryPath || DEFAULT_REGISTRY_PATH;
495
+ try {
496
+ ensureDir(path.dirname(reg));
497
+ fs.writeFileSync(reg, JSON.stringify(registry, null, 2));
498
+ } catch {
499
+ // Non-critical — registry still works in memory
500
+ }
501
+ }
502
+
503
+ /**
504
+ * Register a prompt template with version and model compatibility metadata.
505
+ *
506
+ * @param {string} name - Unique prompt name (e.g., "code-review-system")
507
+ * @param {string} template - The prompt template string
508
+ * @param {{ version: string, models: string[], category: string }} metadata - Prompt metadata
509
+ * @param {string} [registryPath] - Path to the registry JSON
510
+ * @returns {{ name: string, registered: boolean }} Registration result
511
+ */
512
+ function registerPrompt(name, template, metadata, registryPath) {
513
+ const registry = loadRegistry(registryPath);
514
+
515
+ // Support both metadata.models (array) and metadata.model (single string)
516
+ let models = [];
517
+ if (metadata && metadata.models) {
518
+ models = metadata.models;
519
+ } else if (metadata && metadata.model) {
520
+ models = [metadata.model];
521
+ }
522
+
523
+ registry[name] = {
524
+ template,
525
+ metadata: {
526
+ version: (metadata && metadata.version) || '1.0.0',
527
+ models,
528
+ category: (metadata && metadata.category) || 'general',
529
+ lastUpdated: new Date().toISOString(),
530
+ },
531
+ };
532
+
533
+ saveRegistry(registry, registryPath);
534
+ return { name, registered: true };
535
+ }
536
+
537
+ /**
538
+ * Retrieve a registered prompt, optionally filtering by model compatibility.
539
+ *
540
+ * @param {string} name - Prompt name to look up
541
+ * @param {string} [modelId] - Optional model ID to check compatibility
542
+ * @param {string} [registryPath] - Path to the registry JSON
543
+ * @returns {{ name: string, template: string, metadata: object, compatible: boolean }|null}
544
+ */
545
+ function getPrompt(name, modelId, registryPath) {
546
+ const registry = loadRegistry(registryPath);
547
+ const entry = registry[name];
548
+
549
+ if (!entry) return null;
550
+
551
+ const compatible =
552
+ !modelId || !entry.metadata.models.length || entry.metadata.models.includes(modelId);
553
+
554
+ // If a specific model was requested and it's not compatible, return null
555
+ if (modelId && entry.metadata.models.length > 0 && !entry.metadata.models.includes(modelId)) {
556
+ return null;
557
+ }
558
+
559
+ return {
560
+ name,
561
+ template: entry.template,
562
+ metadata: entry.metadata,
563
+ compatible,
564
+ };
565
+ }
566
+
567
+ /**
568
+ * List all registered prompts with their metadata.
569
+ *
570
+ * @param {string} [registryPath] - Path to the registry JSON
571
+ * @returns {{ name: string, metadata: object }[]} Array of prompt entries
572
+ */
573
+ function listPrompts(registryPath) {
574
+ const registry = loadRegistry(registryPath);
575
+
576
+ return Object.entries(registry).map(([name, entry]) => ({
577
+ name,
578
+ metadata: entry.metadata,
579
+ }));
580
+ }
581
+
582
+ // ---------------------------------------------------------------------------
583
+ // Adaptive Context Compaction (OpenDev 5-stage algorithm)
584
+ // ---------------------------------------------------------------------------
585
+
586
+ /**
587
+ * Compact a set of feedback entries using a 5-stage progressive algorithm.
588
+ *
589
+ * Stage 1: Group by signal type, keep top 10 per group
590
+ * Stage 2: Truncate large text fields to perEntryMaxChars
591
+ * Stage 3: Drop entries missing both context and whatWentWrong
592
+ * Stage 4: Window to most recent windowSize (anchors preserved)
593
+ * Stage 5: Deduplicate entries with identical whatWentWrong
594
+ *
595
+ * @param {object[]} entries - Feedback log entries
596
+ * @param {object[]} [anchors=[]] - Anchor entries to always preserve
597
+ * @param {{ windowSize?: number, perEntryMaxChars?: number }} [opts={}]
598
+ * @returns {{ entries: object[], stage: number, removedCount: number, compacted: boolean }}
599
+ */
600
+ function compactContext(entries, anchors, opts) {
601
+ const anchorIds = new Set((anchors || []).map((a) => a.id));
602
+ const options = opts || {};
603
+ const windowSize = typeof options.windowSize === 'number' ? options.windowSize : 30;
604
+ const perEntryMaxChars = typeof options.perEntryMaxChars === 'number' ? options.perEntryMaxChars : 512;
605
+
606
+ const anchorEntries = entries.filter((e) => anchorIds.has(e.id));
607
+ let working = entries.filter((e) => !anchorIds.has(e.id));
608
+ const initial = working.length;
609
+
610
+ // Stage 1: Group by signal, keep most recent 10 per signal type
611
+ const bySignal = {};
612
+ for (const entry of working) {
613
+ const sig = entry.signal || 'unknown';
614
+ if (!bySignal[sig]) bySignal[sig] = [];
615
+ bySignal[sig].push(entry);
616
+ }
617
+ working = Object.values(bySignal).flatMap((group) => group.slice(-10));
618
+
619
+ // Stage 2: Truncate large text fields
620
+ working = working.map((entry) => {
621
+ const truncated = { ...entry };
622
+ if (truncated.context && truncated.context.length > perEntryMaxChars) {
623
+ truncated.context = truncated.context.slice(0, perEntryMaxChars);
624
+ }
625
+ if (truncated.whatWentWrong && truncated.whatWentWrong.length > perEntryMaxChars) {
626
+ truncated.whatWentWrong = truncated.whatWentWrong.slice(0, perEntryMaxChars);
627
+ }
628
+ return truncated;
629
+ });
630
+
631
+ // Stage 3: Drop low-information entries (empty context AND empty whatWentWrong)
632
+ working = working.filter(
633
+ (e) => (e.context && e.context.trim()) || (e.whatWentWrong && e.whatWentWrong.trim()),
634
+ );
635
+
636
+ // Stage 4: Window to most recent N
637
+ if (working.length > windowSize) {
638
+ working = working.slice(-windowSize);
639
+ }
640
+
641
+ // Stage 5: Deduplicate by whatWentWrong fingerprint
642
+ const seen = new Set();
643
+ working = working.filter((e) => {
644
+ const key = e.whatWentWrong ? e.whatWentWrong.trim().toLowerCase() : null;
645
+ if (!key) return true;
646
+ if (seen.has(key)) return false;
647
+ seen.add(key);
648
+ return true;
649
+ });
650
+
651
+ const removedCount = initial - working.length;
652
+ return {
653
+ entries: [...anchorEntries, ...working],
654
+ stage: 5,
655
+ removedCount,
656
+ compacted: removedCount > 0,
657
+ };
658
+ }
659
+
660
+ // ---------------------------------------------------------------------------
661
+ // Exports
662
+ // ---------------------------------------------------------------------------
663
+
664
+ module.exports = {
665
+ // Knowledge Bundle Builder
666
+ buildKnowledgeIndex,
667
+ categorizeDoc,
668
+ extractDocSummary,
669
+
670
+ // Context Router
671
+ routeQuery,
672
+ scoreBundle,
673
+
674
+ // Quality Scorer
675
+ scoreRetrievalQuality,
676
+ logQualityResult,
677
+
678
+ // Prompt Registry
679
+ registerPrompt,
680
+ getPrompt,
681
+ listPrompts,
682
+
683
+ // Adaptive Context Compaction
684
+ compactContext,
685
+
686
+ // MCP Consolidation Manifest
687
+ TOOL_CONSOLIDATION,
688
+
689
+ // Constants (for testing / external use)
690
+ CATEGORY_RULES,
691
+ DEFAULT_INDEX_PATH,
692
+ DEFAULT_QUALITY_LOG_PATH,
693
+ DEFAULT_REGISTRY_PATH,
694
+ };