thumbgate 0.9.10

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 (364) 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/thumbgate-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 +1484 -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 +283 -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 +1014 -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-312.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 +299 -0
  117. package/scripts/auto-wire-hooks.js +312 -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 +97 -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 +263 -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 +209 -0
  152. package/scripts/ephemeral-agent-store.js +219 -0
  153. package/scripts/eval-harness.js +56 -0
  154. package/scripts/evolution-state.js +241 -0
  155. package/scripts/experiment-tracker.js +267 -0
  156. package/scripts/export-databricks-bundle.js +242 -0
  157. package/scripts/export-dpo-pairs.js +345 -0
  158. package/scripts/export-kto-pairs.js +310 -0
  159. package/scripts/export-training.js +448 -0
  160. package/scripts/failure-diagnostics.js +558 -0
  161. package/scripts/feedback-attribution.js +313 -0
  162. package/scripts/feedback-fallback.js +111 -0
  163. package/scripts/feedback-history-distiller.js +391 -0
  164. package/scripts/feedback-inbox-read.js +162 -0
  165. package/scripts/feedback-loop.js +1887 -0
  166. package/scripts/feedback-paths.js +145 -0
  167. package/scripts/feedback-quality.js +139 -0
  168. package/scripts/feedback-root-consolidator.js +238 -0
  169. package/scripts/feedback-schema.js +426 -0
  170. package/scripts/feedback-session.js +286 -0
  171. package/scripts/feedback-to-memory.js +185 -0
  172. package/scripts/feedback-to-rules.js +163 -0
  173. package/scripts/filesystem-search.js +404 -0
  174. package/scripts/funnel-analytics.js +35 -0
  175. package/scripts/gate-satisfy.js +42 -0
  176. package/scripts/gate-stats.js +116 -0
  177. package/scripts/gate-templates.js +70 -0
  178. package/scripts/gates-engine.js +816 -0
  179. package/scripts/generate-paperbanana-diagrams.sh +99 -0
  180. package/scripts/generate-pretool-hook.sh +40 -0
  181. package/scripts/github-about.js +350 -0
  182. package/scripts/github-outreach.js +65 -0
  183. package/scripts/gtm-revenue-loop.js +520 -0
  184. package/scripts/hallucination-detector.js +226 -0
  185. package/scripts/hf-papers.js +317 -0
  186. package/scripts/history-distiller.js +200 -0
  187. package/scripts/hook-auto-capture.sh +95 -0
  188. package/scripts/hook-stop-pr-thread-check.sh +68 -0
  189. package/scripts/hook-stop-self-score.sh +51 -0
  190. package/scripts/hook-stop-verify-deploy.sh +31 -0
  191. package/scripts/hook-thumbgate-cache-updater.js +48 -0
  192. package/scripts/hook-verify-before-done.sh +20 -0
  193. package/scripts/hosted-config.js +170 -0
  194. package/scripts/hybrid-feedback-context.js +676 -0
  195. package/scripts/install-mcp.js +159 -0
  196. package/scripts/intent-router.js +392 -0
  197. package/scripts/internal-agent-bootstrap.js +490 -0
  198. package/scripts/jsonl-watcher.js +155 -0
  199. package/scripts/lesson-db.js +613 -0
  200. package/scripts/lesson-inference.js +315 -0
  201. package/scripts/lesson-retrieval.js +95 -0
  202. package/scripts/lesson-rotation.js +137 -0
  203. package/scripts/lesson-search.js +644 -0
  204. package/scripts/lesson-synthesis.js +196 -0
  205. package/scripts/license.js +50 -0
  206. package/scripts/local-model-profile.js +383 -0
  207. package/scripts/markdown-escape.js +12 -0
  208. package/scripts/marketing-experiment.js +671 -0
  209. package/scripts/mcp-config.js +149 -0
  210. package/scripts/mcp-policy.js +99 -0
  211. package/scripts/memalign-recall.js +111 -0
  212. package/scripts/memory-firewall.js +222 -0
  213. package/scripts/memory-migration.js +296 -0
  214. package/scripts/meta-policy.js +194 -0
  215. package/scripts/metered-billing.js +16 -0
  216. package/scripts/model-tier-router.js +301 -0
  217. package/scripts/money-watcher.js +71 -0
  218. package/scripts/multi-hop-recall.js +240 -0
  219. package/scripts/natural-language-harness.js +330 -0
  220. package/scripts/obsidian-export.js +712 -0
  221. package/scripts/operational-dashboard.js +103 -0
  222. package/scripts/operational-summary.js +93 -0
  223. package/scripts/optimize-context.js +17 -0
  224. package/scripts/org-dashboard.js +201 -0
  225. package/scripts/partner-orchestration.js +146 -0
  226. package/scripts/per-step-scoring.js +165 -0
  227. package/scripts/perplexity-marketing.js +466 -0
  228. package/scripts/pii-scanner.js +153 -0
  229. package/scripts/plan-gate.js +154 -0
  230. package/scripts/post-everywhere.js +308 -0
  231. package/scripts/post-to-x-retry.sh +22 -0
  232. package/scripts/post-to-x.js +369 -0
  233. package/scripts/pr-manager.js +236 -0
  234. package/scripts/predictive-insights.js +356 -0
  235. package/scripts/principle-extractor.js +162 -0
  236. package/scripts/pro-features.js +40 -0
  237. package/scripts/pro-local-dashboard.js +174 -0
  238. package/scripts/problem-detail.js +53 -0
  239. package/scripts/product-feedback.js +134 -0
  240. package/scripts/profile-router.js +245 -0
  241. package/scripts/prompt-dlp.js +221 -0
  242. package/scripts/prompt-guard.js +83 -0
  243. package/scripts/prove-adapters.js +863 -0
  244. package/scripts/prove-attribution.js +365 -0
  245. package/scripts/prove-automation.js +653 -0
  246. package/scripts/prove-autoresearch.js +304 -0
  247. package/scripts/prove-claim-verification.js +277 -0
  248. package/scripts/prove-cloudflare-sandbox.js +163 -0
  249. package/scripts/prove-data-pipeline.js +410 -0
  250. package/scripts/prove-data-quality.js +227 -0
  251. package/scripts/prove-evolution.js +352 -0
  252. package/scripts/prove-harnesses.js +287 -0
  253. package/scripts/prove-intelligence.js +259 -0
  254. package/scripts/prove-lancedb.js +371 -0
  255. package/scripts/prove-local-intelligence.js +342 -0
  256. package/scripts/prove-loop-closure.js +263 -0
  257. package/scripts/prove-predictive-insights.js +357 -0
  258. package/scripts/prove-runtime.js +350 -0
  259. package/scripts/prove-seo-gsd.js +234 -0
  260. package/scripts/prove-settings.js +279 -0
  261. package/scripts/prove-subway-upgrades.js +277 -0
  262. package/scripts/prove-tessl.js +229 -0
  263. package/scripts/prove-training-export.js +327 -0
  264. package/scripts/prove-workflow-contract.js +116 -0
  265. package/scripts/prove-xmemory.js +332 -0
  266. package/scripts/publish-decision.js +133 -0
  267. package/scripts/pulse.js +80 -0
  268. package/scripts/rate-limiter.js +125 -0
  269. package/scripts/reddit-dm-outreach.js +182 -0
  270. package/scripts/reddit-monitor-cron.sh +26 -0
  271. package/scripts/reflector-agent.js +221 -0
  272. package/scripts/reminder-engine.js +132 -0
  273. package/scripts/revenue-status.js +472 -0
  274. package/scripts/risk-scorer.js +458 -0
  275. package/scripts/rlaif-self-audit.js +129 -0
  276. package/scripts/rubric-engine.js +230 -0
  277. package/scripts/schedule-manager.js +251 -0
  278. package/scripts/secret-scanner.js +414 -0
  279. package/scripts/self-heal.js +147 -0
  280. package/scripts/self-healing-check.js +188 -0
  281. package/scripts/semantic-layer.js +98 -0
  282. package/scripts/seo-gsd.js +1153 -0
  283. package/scripts/settings-hierarchy.js +214 -0
  284. package/scripts/shieldcortex-memory-firewall-runner.mjs +53 -0
  285. package/scripts/skill-exporter.js +262 -0
  286. package/scripts/skill-generator.js +446 -0
  287. package/scripts/skill-materializer.js +134 -0
  288. package/scripts/skill-packs.js +136 -0
  289. package/scripts/skill-proposer.js +99 -0
  290. package/scripts/skill-quality-tracker.js +284 -0
  291. package/scripts/slo-alert-engine.js +14 -0
  292. package/scripts/slow-loop.js +72 -0
  293. package/scripts/social-analytics/db/schema.sql +32 -0
  294. package/scripts/social-analytics/digest.js +256 -0
  295. package/scripts/social-analytics/generate-instagram-card.js +97 -0
  296. package/scripts/social-analytics/instagram-thumbgate-post.js +73 -0
  297. package/scripts/social-analytics/mcp-server.js +289 -0
  298. package/scripts/social-analytics/normalizer.js +580 -0
  299. package/scripts/social-analytics/notify.js +162 -0
  300. package/scripts/social-analytics/poll-all.js +107 -0
  301. package/scripts/social-analytics/pollers/github.js +195 -0
  302. package/scripts/social-analytics/pollers/instagram.js +253 -0
  303. package/scripts/social-analytics/pollers/linkedin.js +330 -0
  304. package/scripts/social-analytics/pollers/plausible.js +247 -0
  305. package/scripts/social-analytics/pollers/reddit.js +306 -0
  306. package/scripts/social-analytics/pollers/threads.js +233 -0
  307. package/scripts/social-analytics/pollers/tiktok.js +203 -0
  308. package/scripts/social-analytics/pollers/x.js +227 -0
  309. package/scripts/social-analytics/pollers/youtube.js +304 -0
  310. package/scripts/social-analytics/pollers/zernio.js +180 -0
  311. package/scripts/social-analytics/publish-instagram-thumbgate.js +85 -0
  312. package/scripts/social-analytics/publishers/devto.js +122 -0
  313. package/scripts/social-analytics/publishers/instagram.js +317 -0
  314. package/scripts/social-analytics/publishers/linkedin.js +294 -0
  315. package/scripts/social-analytics/publishers/reddit.js +390 -0
  316. package/scripts/social-analytics/publishers/threads.js +275 -0
  317. package/scripts/social-analytics/publishers/tiktok.js +217 -0
  318. package/scripts/social-analytics/publishers/x.js +259 -0
  319. package/scripts/social-analytics/publishers/youtube.js +223 -0
  320. package/scripts/social-analytics/publishers/zernio.js +209 -0
  321. package/scripts/social-analytics/run-digest.js +34 -0
  322. package/scripts/social-analytics/store.js +257 -0
  323. package/scripts/social-analytics/utm.js +143 -0
  324. package/scripts/social-pipeline.js +2628 -0
  325. package/scripts/social-quality-gate.js +18 -0
  326. package/scripts/social-reply-monitor.js +445 -0
  327. package/scripts/status-dashboard.js +155 -0
  328. package/scripts/statusline-lesson.js +16 -0
  329. package/scripts/statusline-tower.js +8 -0
  330. package/scripts/statusline.sh +116 -0
  331. package/scripts/stripe-live-status.js +115 -0
  332. package/scripts/subagent-profiles.js +79 -0
  333. package/scripts/sync-gh-secrets-from-env.sh +70 -0
  334. package/scripts/sync-github-about.js +52 -0
  335. package/scripts/sync-version.js +451 -0
  336. package/scripts/synthetic-dpo.js +234 -0
  337. package/scripts/telemetry-analytics.js +821 -0
  338. package/scripts/tessl-export.js +371 -0
  339. package/scripts/test-coverage.js +120 -0
  340. package/scripts/thompson-sampling.js +417 -0
  341. package/scripts/thumbgate-search.js +189 -0
  342. package/scripts/tool-kpi-tracker.js +12 -0
  343. package/scripts/tool-registry.js +811 -0
  344. package/scripts/train_from_feedback.py +910 -0
  345. package/scripts/user-profile.js +78 -0
  346. package/scripts/validate-feedback.js +580 -0
  347. package/scripts/validate-workflow-contract.js +287 -0
  348. package/scripts/vector-store.js +198 -0
  349. package/scripts/verification-loop.js +291 -0
  350. package/scripts/verify-obsidian-setup.sh +269 -0
  351. package/scripts/verify-run.js +269 -0
  352. package/scripts/webhook-delivery.js +62 -0
  353. package/scripts/weekly-auto-post.js +124 -0
  354. package/scripts/workflow-runs.js +154 -0
  355. package/scripts/workflow-sprint-intake.js +475 -0
  356. package/scripts/workspace-evolver.js +374 -0
  357. package/scripts/x-autonomous-marketing.js +139 -0
  358. package/scripts/xmemory-lite.js +405 -0
  359. package/skills/agent-memory/SKILL.md +97 -0
  360. package/skills/solve-architecture-autonomy/SKILL.md +17 -0
  361. package/skills/solve-architecture-autonomy/tool.js +33 -0
  362. package/skills/thumbgate/SKILL.md +114 -0
  363. package/skills/thumbgate-feedback/SKILL.md +49 -0
  364. package/src/api/server.js +4208 -0
@@ -0,0 +1,644 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+ const { readJSONL, getFeedbackPaths } = require('./feedback-loop');
5
+
6
+ const HIGH_RISK_TAGS = new Set([
7
+ 'billing',
8
+ 'data-loss',
9
+ 'deployment',
10
+ 'git',
11
+ 'production',
12
+ 'release',
13
+ 'security',
14
+ 'verification',
15
+ ]);
16
+
17
+ const PRIORITY_WEIGHT = {
18
+ critical: 4,
19
+ high: 3,
20
+ medium: 2,
21
+ low: 1,
22
+ };
23
+
24
+ function tokenize(text) {
25
+ return String(text || '')
26
+ .toLowerCase()
27
+ .split(/[^a-z0-9]+/)
28
+ .filter(Boolean);
29
+ }
30
+
31
+ function unique(values) {
32
+ return [...new Set((values || []).filter(Boolean))];
33
+ }
34
+
35
+ function jaccardSimilarity(tokensA, tokensB) {
36
+ const setA = new Set(unique(tokensA));
37
+ const setB = new Set(unique(tokensB));
38
+ if (setA.size === 0 && setB.size === 0) return 1;
39
+ if (setA.size === 0 || setB.size === 0) return 0;
40
+ let intersection = 0;
41
+ for (const token of setA) {
42
+ if (setB.has(token)) intersection++;
43
+ }
44
+ const union = setA.size + setB.size - intersection;
45
+ return union === 0 ? 0 : intersection / union;
46
+ }
47
+
48
+ function substringBoost(queryText, recordText) {
49
+ const query = String(queryText || '').toLowerCase().trim();
50
+ const haystack = String(recordText || '').toLowerCase();
51
+ if (!query) return 0;
52
+ if (haystack.includes(query)) return 0.35;
53
+ const words = query.split(/\s+/).filter((word) => word.length > 2);
54
+ if (words.length === 0) return 0;
55
+ const matched = words.filter((word) => haystack.includes(word)).length;
56
+ return (matched / words.length) * 0.25;
57
+ }
58
+
59
+ function recencyScore(timestamp) {
60
+ if (!timestamp) return 0;
61
+ const parsed = new Date(timestamp).getTime();
62
+ if (!Number.isFinite(parsed)) return 0;
63
+ const ageHours = (Date.now() - parsed) / (1000 * 60 * 60);
64
+ if (ageHours <= 24) return 0.15;
65
+ if (ageHours <= 24 * 7) return 0.1;
66
+ if (ageHours <= 24 * 30) return 0.05;
67
+ return 0;
68
+ }
69
+
70
+ function parseLessonContent(content = '') {
71
+ const lines = String(content || '')
72
+ .split('\n')
73
+ .map((line) => line.trim())
74
+ .filter(Boolean);
75
+
76
+ const parsed = {
77
+ summary: '',
78
+ whatWentWrong: null,
79
+ whatWorked: null,
80
+ approach: null,
81
+ howToAvoid: null,
82
+ actionNeeded: null,
83
+ reasoning: null,
84
+ visualEvidence: null,
85
+ rubric: [],
86
+ };
87
+
88
+ for (const line of lines) {
89
+ if (/^What went wrong:\s*/i.test(line)) {
90
+ parsed.whatWentWrong = line.replace(/^What went wrong:\s*/i, '');
91
+ continue;
92
+ }
93
+ if (/^What worked:\s*/i.test(line)) {
94
+ parsed.whatWorked = line.replace(/^What worked:\s*/i, '');
95
+ continue;
96
+ }
97
+ if (/^Approach:\s*/i.test(line)) {
98
+ parsed.approach = line.replace(/^Approach:\s*/i, '');
99
+ continue;
100
+ }
101
+ if (/^How to avoid:\s*/i.test(line)) {
102
+ parsed.howToAvoid = line.replace(/^How to avoid:\s*/i, '');
103
+ continue;
104
+ }
105
+ if (/^Action needed:\s*/i.test(line)) {
106
+ parsed.actionNeeded = line.replace(/^Action needed:\s*/i, '');
107
+ continue;
108
+ }
109
+ if (/^Reasoning:\s*/i.test(line)) {
110
+ parsed.reasoning = line.replace(/^Reasoning:\s*/i, '');
111
+ continue;
112
+ }
113
+ if (/^Visual Evidence:\s*/i.test(line)) {
114
+ parsed.visualEvidence = line.replace(/^Visual Evidence:\s*/i, '');
115
+ continue;
116
+ }
117
+ if (/^Rubric /i.test(line) || /^Guardrails failed:/i.test(line) || /^Judge disagreement/i.test(line)) {
118
+ parsed.rubric.push(line);
119
+ }
120
+ }
121
+
122
+ parsed.summary = parsed.whatWentWrong
123
+ || parsed.whatWorked
124
+ || parsed.approach
125
+ || parsed.howToAvoid
126
+ || parsed.actionNeeded
127
+ || lines[0]
128
+ || '';
129
+
130
+ return parsed;
131
+ }
132
+
133
+ function buildLessonQuery(memory, parsed, sourceFeedback) {
134
+ return [
135
+ memory.title,
136
+ parsed.whatWentWrong,
137
+ parsed.whatWorked,
138
+ parsed.approach,
139
+ parsed.howToAvoid,
140
+ parsed.actionNeeded,
141
+ parsed.reasoning,
142
+ sourceFeedback && sourceFeedback.context,
143
+ Array.isArray(memory.tags) ? memory.tags.join(' ') : '',
144
+ ].filter(Boolean).join(' ');
145
+ }
146
+
147
+ function resolveLessonPaths(options = {}) {
148
+ if (options.feedbackDir) {
149
+ const feedbackDir = path.resolve(String(options.feedbackDir));
150
+ return {
151
+ FEEDBACK_DIR: feedbackDir,
152
+ FEEDBACK_LOG_PATH: path.join(feedbackDir, 'feedback-log.jsonl'),
153
+ MEMORY_LOG_PATH: path.join(feedbackDir, 'memory-log.jsonl'),
154
+ PREVENTION_RULES_PATH: path.join(feedbackDir, 'prevention-rules.md'),
155
+ AUTO_GATES_PATH: path.join(feedbackDir, 'auto-promoted-gates.json'),
156
+ };
157
+ }
158
+
159
+ const paths = getFeedbackPaths();
160
+ return {
161
+ ...paths,
162
+ PREVENTION_RULES_PATH: path.join(paths.FEEDBACK_DIR, 'prevention-rules.md'),
163
+ AUTO_GATES_PATH: path.join(paths.FEEDBACK_DIR, 'auto-promoted-gates.json'),
164
+ };
165
+ }
166
+
167
+ function readPreventionRuleMatches(queryText, limit = 3, options = {}) {
168
+ const { PREVENTION_RULES_PATH } = resolveLessonPaths(options);
169
+ if (!PREVENTION_RULES_PATH) return [];
170
+ let content = '';
171
+ try {
172
+ content = require('node:fs').readFileSync(PREVENTION_RULES_PATH, 'utf-8');
173
+ } catch {
174
+ return [];
175
+ }
176
+
177
+ const blocks = content.split(/^#{1,3}\s+/m).filter(Boolean);
178
+ const queryTokens = tokenize(queryText);
179
+
180
+ return blocks
181
+ .map((block) => {
182
+ const lines = block.trim().split('\n');
183
+ const title = lines[0] || '';
184
+ const body = lines.slice(1).join('\n').trim();
185
+ const text = `${title} ${body}`;
186
+ const score = jaccardSimilarity(queryTokens, tokenize(text)) + substringBoost(queryText, text);
187
+ return { title, body, score };
188
+ })
189
+ .filter((rule) => rule.score > 0)
190
+ .sort((a, b) => b.score - a.score)
191
+ .slice(0, limit)
192
+ .map((rule) => ({
193
+ title: rule.title,
194
+ summary: String(rule.body || '').split('\n')[0] || '',
195
+ score: Number((rule.score || 0).toFixed(4)),
196
+ }));
197
+ }
198
+
199
+ function readAutoGates(options = {}) {
200
+ const { AUTO_GATES_PATH } = resolveLessonPaths(options);
201
+ try {
202
+ return JSON.parse(require('node:fs').readFileSync(AUTO_GATES_PATH, 'utf-8'));
203
+ } catch {
204
+ return { version: 1, gates: [], promotionLog: [] };
205
+ }
206
+ }
207
+
208
+ function scoreGateMatch(gate, queryText, tags = [], diagnosis = null) {
209
+ const gateText = [
210
+ gate.id,
211
+ gate.pattern,
212
+ gate.message,
213
+ gate.trigger,
214
+ gate.action,
215
+ gate.severity,
216
+ ].filter(Boolean).join(' ');
217
+ const score = jaccardSimilarity(tokenize(queryText), tokenize(gateText))
218
+ + substringBoost(queryText, gateText);
219
+ const tagScore = tags.some((tag) => String(gate.pattern || '').toLowerCase().includes(String(tag).toLowerCase()))
220
+ ? 0.2
221
+ : 0;
222
+ const diagnosisScore = diagnosis && diagnosis.rootCauseCategory
223
+ && String(gate.pattern || '').toLowerCase().includes(String(diagnosis.rootCauseCategory).toLowerCase())
224
+ ? 0.2
225
+ : 0;
226
+ return score + tagScore + diagnosisScore;
227
+ }
228
+
229
+ function buildGateMatches(memory, parsed, limit = 3, options = {}) {
230
+ const autoGates = readAutoGates(options);
231
+ const lessonQuery = buildLessonQuery(memory, parsed, null);
232
+ return (autoGates.gates || [])
233
+ .map((gate) => ({
234
+ gate,
235
+ score: scoreGateMatch(gate, lessonQuery, memory.tags || [], memory.diagnosis || null),
236
+ }))
237
+ .filter((entry) => entry.score > 0)
238
+ .sort((a, b) => b.score - a.score)
239
+ .slice(0, limit)
240
+ .map(({ gate, score }) => ({
241
+ id: gate.id,
242
+ action: gate.action,
243
+ pattern: gate.pattern,
244
+ message: gate.message,
245
+ occurrences: gate.occurrences,
246
+ promotedAt: gate.promotedAt,
247
+ score: Number(score.toFixed(4)),
248
+ }));
249
+ }
250
+
251
+ function inferPriority(memory, tags = []) {
252
+ if (String(memory.importance || '').toLowerCase() === 'critical') return 'critical';
253
+ if (String(memory.importance || '').toLowerCase() === 'high') return 'high';
254
+ if ((tags || []).some((tag) => HIGH_RISK_TAGS.has(String(tag).toLowerCase()))) return 'high';
255
+ return 'medium';
256
+ }
257
+
258
+ function inferVerificationState(parsed, memory, sourceFeedback, ruleMatches, gateMatches) {
259
+ const lessonText = [
260
+ memory.title,
261
+ parsed.whatWentWrong,
262
+ parsed.howToAvoid,
263
+ parsed.actionNeeded,
264
+ parsed.whatWorked,
265
+ parsed.reasoning,
266
+ sourceFeedback && sourceFeedback.context,
267
+ ].filter(Boolean).join(' ');
268
+ const verificationPattern = /\b(attach|check|proof|review|rollback|test|validate|verification|verify)\b/i;
269
+ const ruleText = ruleMatches.map((rule) => `${rule.title} ${rule.summary}`).join(' ');
270
+ const gateText = gateMatches.map((gate) => `${gate.id} ${gate.pattern} ${gate.message}`).join(' ');
271
+ const mentionsVerification = verificationPattern.test(lessonText);
272
+ const enforcedVerification = verificationPattern.test(`${ruleText} ${gateText}`);
273
+
274
+ if (parsed.whatWorked && enforcedVerification) return 'closed_loop';
275
+ if (enforcedVerification) return 'enforced';
276
+ if (mentionsVerification) return 'specified';
277
+ return 'missing';
278
+ }
279
+
280
+ function buildHarnessRecommendations(memory, parsed, sourceFeedback, ruleMatches, gateMatches) {
281
+ const recommendations = [];
282
+ const tags = Array.isArray(memory.tags) ? memory.tags : [];
283
+ const lessonQuery = buildLessonQuery(memory, parsed, sourceFeedback);
284
+ const priority = inferPriority(memory, tags);
285
+ const diagnosis = memory.diagnosis || {};
286
+ const correctiveText = parsed.howToAvoid || parsed.actionNeeded || parsed.summary || '';
287
+ const hasRule = ruleMatches.length > 0;
288
+ const hasGate = gateMatches.length > 0;
289
+ const verificationLike = /\b(attach|proof|review|rollback|test|validate|verification|verify)\b/i.test(lessonQuery);
290
+ const highRisk = tags.some((tag) => HIGH_RISK_TAGS.has(String(tag).toLowerCase()))
291
+ || ['pre_tool_use', 'release', 'security', 'verification'].includes(String(diagnosis.criticalFailureStep || '').toLowerCase())
292
+ || /\b(deploy|publish|push|release|ship)\b/i.test(lessonQuery);
293
+
294
+ if (memory.category === 'error' && correctiveText && !hasRule) {
295
+ recommendations.push({
296
+ type: 'prevention_rule',
297
+ priority,
298
+ reason: 'lesson captured a corrective action but no linked prevention rule exists yet',
299
+ action: correctiveText,
300
+ });
301
+ }
302
+
303
+ if (memory.category === 'error' && highRisk && !hasGate) {
304
+ recommendations.push({
305
+ type: 'pre_action_gate',
306
+ priority,
307
+ reason: 'high-risk lesson has no linked gate, so the failure is still relying on agent cooperation',
308
+ action: 'Promote a warning or blocking gate before the risky tool call executes.',
309
+ });
310
+ }
311
+
312
+ if (memory.category === 'error' && verificationLike && !(hasRule || hasGate)) {
313
+ recommendations.push({
314
+ type: 'verification_harness',
315
+ priority: priority === 'critical' ? 'critical' : 'high',
316
+ reason: 'verification or proof failed, but there is no upstream test or proof contract linked to the lesson',
317
+ action: 'Add a proof step or automated test that runs before merge, publish, or deploy.',
318
+ });
319
+ }
320
+
321
+ if (memory.category === 'error' && !diagnosis.rootCauseCategory && !parsed.reasoning) {
322
+ recommendations.push({
323
+ type: 'diagnostic_capture',
324
+ priority: 'medium',
325
+ reason: 'future automation will be stronger if this failure records a root cause and failed step',
326
+ action: 'Capture rootCauseCategory, criticalFailureStep, and reasoning on the next occurrence.',
327
+ });
328
+ }
329
+
330
+ const seen = new Set();
331
+ return recommendations.filter((recommendation) => {
332
+ const key = `${recommendation.type}:${recommendation.action}`;
333
+ if (seen.has(key)) return false;
334
+ seen.add(key);
335
+ return true;
336
+ });
337
+ }
338
+
339
+ function buildLifecycle(memory, parsed, sourceFeedback, ruleMatches, gateMatches, recommendations) {
340
+ const correctiveActionCaptured = Boolean(parsed.howToAvoid || parsed.actionNeeded || parsed.whatWorked || parsed.approach);
341
+ const preventionRuleLinked = ruleMatches.length > 0;
342
+ const gateLinked = gateMatches.length > 0;
343
+ const verificationState = inferVerificationState(parsed, memory, sourceFeedback, ruleMatches, gateMatches);
344
+ const enforcementState = gateMatches.some((gate) => gate.action === 'block')
345
+ ? 'blocking'
346
+ : gateLinked
347
+ ? 'warning'
348
+ : preventionRuleLinked
349
+ ? 'rule_only'
350
+ : 'memory_only';
351
+
352
+ let stage = 'detected';
353
+ if (memory.id) stage = 'promoted';
354
+ if (preventionRuleLinked || gateLinked) stage = 'enforced';
355
+ if (verificationState === 'closed_loop') stage = 'measured';
356
+
357
+ return {
358
+ feedbackCaptured: Boolean(sourceFeedback || memory.sourceFeedbackId),
359
+ promotedToMemory: true,
360
+ correctiveActionCaptured,
361
+ preventionRuleLinked,
362
+ gateLinked,
363
+ enforcementState,
364
+ verificationState,
365
+ impactMeasured: verificationState === 'closed_loop',
366
+ openRecommendations: recommendations.length,
367
+ stage,
368
+ };
369
+ }
370
+
371
+ function buildSystemActions(parsed, ruleMatches, gateMatches) {
372
+ const actions = [];
373
+ if (parsed.howToAvoid) {
374
+ actions.push({ type: 'avoid_repeat', source: 'memory', text: parsed.howToAvoid });
375
+ }
376
+ if (parsed.actionNeeded) {
377
+ actions.push({ type: 'investigate', source: 'memory', text: parsed.actionNeeded });
378
+ }
379
+ if (parsed.whatWorked) {
380
+ actions.push({ type: 'repeat_success', source: 'memory', text: parsed.whatWorked });
381
+ } else if (parsed.approach) {
382
+ actions.push({ type: 'repeat_success', source: 'memory', text: parsed.approach });
383
+ }
384
+ for (const rule of ruleMatches) {
385
+ actions.push({ type: 'prevention_rule', source: 'prevention_rules', text: rule.title });
386
+ }
387
+ for (const gate of gateMatches) {
388
+ actions.push({ type: gate.action === 'block' ? 'pre_action_block' : 'pre_action_warn', source: 'auto_gate', text: gate.message });
389
+ }
390
+ const seen = new Set();
391
+ return actions.filter((action) => {
392
+ const key = `${action.type}:${action.source}:${action.text}`;
393
+ if (seen.has(key)) return false;
394
+ seen.add(key);
395
+ return true;
396
+ });
397
+ }
398
+
399
+ function scoreLesson(queryText, memory, parsed, sourceFeedback) {
400
+ if (!queryText) {
401
+ return {
402
+ score: recencyScore(memory.timestamp),
403
+ matchedTokens: [],
404
+ };
405
+ }
406
+
407
+ const lessonText = buildLessonQuery(memory, parsed, sourceFeedback);
408
+ const queryTokens = tokenize(queryText);
409
+ const lessonTokens = tokenize(lessonText);
410
+ const score = jaccardSimilarity(queryTokens, lessonTokens)
411
+ + substringBoost(queryText, lessonText)
412
+ + recencyScore(memory.timestamp)
413
+ + (memory.category === 'error' ? 0.05 : 0);
414
+
415
+ return {
416
+ score,
417
+ matchedTokens: unique(queryTokens.filter((token) => lessonTokens.includes(token))),
418
+ };
419
+ }
420
+
421
+ function buildLessonResult(memory, sourceFeedback, options = {}) {
422
+ const parsed = parseLessonContent(memory.content);
423
+ const lessonQuery = buildLessonQuery(memory, parsed, sourceFeedback);
424
+ const ruleMatches = readPreventionRuleMatches(lessonQuery, Number(options.ruleLimit || 3), options);
425
+ const gateMatches = buildGateMatches(memory, parsed, Number(options.gateLimit || 3), options);
426
+ const { score, matchedTokens } = scoreLesson(options.query || '', memory, parsed, sourceFeedback);
427
+ const harnessRecommendations = buildHarnessRecommendations(memory, parsed, sourceFeedback, ruleMatches, gateMatches);
428
+ const lifecycle = buildLifecycle(memory, parsed, sourceFeedback, ruleMatches, gateMatches, harnessRecommendations);
429
+
430
+ return {
431
+ id: memory.id,
432
+ title: memory.title,
433
+ category: memory.category,
434
+ importance: memory.importance,
435
+ tags: Array.isArray(memory.tags) ? memory.tags : [],
436
+ timestamp: memory.timestamp || null,
437
+ sourceFeedbackId: memory.sourceFeedbackId || null,
438
+ score: Number(score.toFixed(4)),
439
+ matchedTokens,
440
+ lesson: {
441
+ summary: parsed.summary,
442
+ content: memory.content,
443
+ whatWentWrong: parsed.whatWentWrong,
444
+ whatWorked: parsed.whatWorked || parsed.approach,
445
+ howToAvoid: parsed.howToAvoid,
446
+ actionNeeded: parsed.actionNeeded,
447
+ reasoning: parsed.reasoning,
448
+ visualEvidence: parsed.visualEvidence,
449
+ rubric: parsed.rubric,
450
+ },
451
+ systemResponse: {
452
+ promotedToMemory: true,
453
+ lifecycle,
454
+ diagnosis: memory.diagnosis || null,
455
+ sourceFeedback: sourceFeedback
456
+ ? {
457
+ id: sourceFeedback.id || null,
458
+ signal: sourceFeedback.signal || sourceFeedback.feedback || null,
459
+ context: sourceFeedback.context || '',
460
+ timestamp: sourceFeedback.timestamp || null,
461
+ tags: Array.isArray(sourceFeedback.tags) ? sourceFeedback.tags : [],
462
+ }
463
+ : null,
464
+ linkedPreventionRules: ruleMatches,
465
+ linkedAutoGates: gateMatches,
466
+ correctiveActions: buildSystemActions(parsed, ruleMatches, gateMatches),
467
+ harnessRecommendations,
468
+ },
469
+ };
470
+ }
471
+
472
+ function searchLessons(query = '', options = {}) {
473
+ const { MEMORY_LOG_PATH, FEEDBACK_DIR, FEEDBACK_LOG_PATH } = resolveLessonPaths(options);
474
+
475
+ // Try SQLite FTS5 first — falls back to JSONL Jaccard if unavailable
476
+ const sqliteResults = tryFts5Search(query, options);
477
+ if (sqliteResults) return sqliteResults;
478
+
479
+ const memories = readJSONL(MEMORY_LOG_PATH);
480
+ const feedbackEntries = readJSONL(FEEDBACK_LOG_PATH);
481
+ const feedbackById = new Map(feedbackEntries.map((entry) => [entry.id, entry]));
482
+ const parsedLimit = Number(options.limit || 10);
483
+ const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? parsedLimit : 10;
484
+ const category = options.category ? String(options.category).trim() : '';
485
+ const requiredTags = Array.isArray(options.tags)
486
+ ? options.tags.filter(Boolean).map(String)
487
+ : String(options.tags || '')
488
+ .split(',')
489
+ .map((tag) => tag.trim())
490
+ .filter(Boolean);
491
+
492
+ let results = memories
493
+ .map((memory) => buildLessonResult(memory, feedbackById.get(memory.sourceFeedbackId), {
494
+ query,
495
+ ruleLimit: options.ruleLimit,
496
+ gateLimit: options.gateLimit,
497
+ }));
498
+
499
+ if (category) {
500
+ results = results.filter((entry) => entry.category === category);
501
+ }
502
+ if (requiredTags.length > 0) {
503
+ results = results.filter((entry) => requiredTags.every((tag) => entry.tags.includes(tag)));
504
+ }
505
+ if (query) {
506
+ results = results.filter((entry) => entry.score > 0);
507
+ }
508
+
509
+ results.sort((a, b) => {
510
+ if ((b.score || 0) !== (a.score || 0)) return (b.score || 0) - (a.score || 0);
511
+ return String(b.timestamp || '').localeCompare(String(a.timestamp || ''));
512
+ });
513
+
514
+ return {
515
+ query: String(query || ''),
516
+ limit,
517
+ filters: {
518
+ category: category || null,
519
+ tags: requiredTags,
520
+ },
521
+ feedbackDir: FEEDBACK_DIR,
522
+ totalLessons: memories.length,
523
+ returned: Math.min(limit, results.length),
524
+ results: results.slice(0, limit),
525
+ backend: 'jsonl-jaccard',
526
+ };
527
+ }
528
+
529
+ /**
530
+ * Try FTS5 search via lesson-db. Returns null if SQLite is unavailable
531
+ * or not opted in. Set LESSON_DB_SEARCH=1 to enable FTS5 as primary backend.
532
+ */
533
+ function tryFts5Search(query, options) {
534
+ if (!process.env.LESSON_DB_SEARCH && !options.useFts5) return null;
535
+ try {
536
+ const { initDB, searchLessons: fts5Search, getStats } = require('./lesson-db');
537
+ const db = initDB();
538
+ const stats = getStats(db);
539
+
540
+ // If DB is empty, skip (not yet backfilled)
541
+ if (stats.total === 0) return null;
542
+
543
+ const parsedLimit = Number(options.limit || 10);
544
+ const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? parsedLimit : 10;
545
+ const signal = options.category === 'error' ? 'negative' : undefined;
546
+ const requiredTags = Array.isArray(options.tags)
547
+ ? options.tags.filter(Boolean).map(String)
548
+ : String(options.tags || '')
549
+ .split(',')
550
+ .map((tag) => tag.trim())
551
+ .filter(Boolean);
552
+
553
+ const rows = fts5Search(db, query || '', {
554
+ limit,
555
+ signal,
556
+ tags: requiredTags.length > 0 ? requiredTags : undefined,
557
+ });
558
+
559
+ return {
560
+ query: String(query || ''),
561
+ limit,
562
+ filters: {
563
+ category: options.category || null,
564
+ tags: requiredTags,
565
+ },
566
+ totalLessons: stats.total,
567
+ returned: rows.length,
568
+ results: rows.map((row) => ({
569
+ id: row.id,
570
+ signal: row.signal,
571
+ context: row.context,
572
+ whatWentWrong: row.whatWentWrong,
573
+ whatToChange: row.whatToChange,
574
+ whatWorked: row.whatWorked,
575
+ domain: row.domain,
576
+ tags: row.tags,
577
+ importance: row.importance,
578
+ timestamp: row.timestamp,
579
+ })),
580
+ backend: 'sqlite-fts5',
581
+ };
582
+ } catch (_err) {
583
+ return null; // SQLite unavailable — fall through to JSONL
584
+ }
585
+ }
586
+
587
+ function formatLessonSearchResults(payload) {
588
+ const lines = [];
589
+ lines.push(`## Lesson Search${payload.query ? ` — ${payload.query}` : ''}`);
590
+ lines.push(`- Total lessons: ${payload.totalLessons}`);
591
+ lines.push(`- Returned: ${payload.returned}`);
592
+ if (payload.filters.category) {
593
+ lines.push(`- Category filter: ${payload.filters.category}`);
594
+ }
595
+ if (payload.filters.tags.length > 0) {
596
+ lines.push(`- Tag filter: ${payload.filters.tags.join(', ')}`);
597
+ }
598
+ lines.push('');
599
+
600
+ if (!payload.results.length) {
601
+ lines.push('No matching lessons found.');
602
+ return `${lines.join('\n')}\n`;
603
+ }
604
+
605
+ payload.results.forEach((result, index) => {
606
+ lines.push(`${index + 1}. ${result.title}`);
607
+ lines.push(` Category: ${result.category} | Tags: ${result.tags.join(', ') || 'none'} | Score: ${result.score}`);
608
+ if (result.lesson.summary) {
609
+ lines.push(` Lesson: ${result.lesson.summary}`);
610
+ }
611
+ const correctiveActions = result.systemResponse.correctiveActions || [];
612
+ if (correctiveActions.length > 0) {
613
+ lines.push(' Corrective actions:');
614
+ correctiveActions.slice(0, 4).forEach((action) => {
615
+ lines.push(` - [${action.source}] ${action.text}`);
616
+ });
617
+ }
618
+ if (result.systemResponse.diagnosis && result.systemResponse.diagnosis.rootCauseCategory) {
619
+ lines.push(` Diagnosis: ${result.systemResponse.diagnosis.rootCauseCategory}`);
620
+ }
621
+ const recommendations = result.systemResponse.harnessRecommendations || [];
622
+ if (recommendations.length > 0) {
623
+ lines.push(' Harness recommendations:');
624
+ recommendations.slice(0, 3).forEach((recommendation) => {
625
+ lines.push(` - [${recommendation.priority}] ${recommendation.type}: ${recommendation.action}`);
626
+ });
627
+ }
628
+ });
629
+
630
+ return `${lines.join('\n')}\n`;
631
+ }
632
+
633
+ module.exports = {
634
+ parseLessonContent,
635
+ resolveLessonPaths,
636
+ searchLessons,
637
+ formatLessonSearchResults,
638
+ };
639
+
640
+ if (require.main === module) {
641
+ const query = process.argv.slice(2).join(' ');
642
+ const result = searchLessons(query, { limit: 5 });
643
+ process.stdout.write(formatLessonSearchResults(result));
644
+ }