akm-cli 0.9.0-beta.5 → 0.9.0-beta.51

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 (221) hide show
  1. package/CHANGELOG.md +711 -0
  2. package/README.md +12 -4
  3. package/dist/akm +38 -0
  4. package/dist/akm-migrate-storage +38 -0
  5. package/dist/assets/profiles/default.json +9 -4
  6. package/dist/assets/profiles/frequent.json +1 -1
  7. package/dist/assets/profiles/memory-focus.json +1 -1
  8. package/dist/assets/profiles/quick.json +1 -1
  9. package/dist/assets/profiles/synthesize.json +15 -0
  10. package/dist/assets/profiles/thorough.json +1 -1
  11. package/dist/assets/prompts/consolidate-system.md +23 -0
  12. package/dist/assets/prompts/contradiction-judge.md +33 -0
  13. package/dist/assets/prompts/distill-knowledge-system.md +22 -0
  14. package/dist/assets/prompts/distill-lesson-system.md +36 -0
  15. package/dist/assets/prompts/extract-session.md +6 -2
  16. package/dist/assets/prompts/graph-extract-system.md +1 -0
  17. package/dist/assets/prompts/graph-extract-user-prompt.md +1 -1
  18. package/dist/assets/prompts/memory-infer-system.md +1 -0
  19. package/dist/assets/prompts/memory-infer-user.md +5 -0
  20. package/dist/assets/prompts/metadata-enhance-system.md +1 -0
  21. package/dist/assets/prompts/procedural-system.md +44 -0
  22. package/dist/assets/prompts/recombine-system.md +40 -0
  23. package/dist/assets/prompts/staleness-detect-system.md +6 -0
  24. package/dist/assets/prompts/validate-summary-judge.md +1 -0
  25. package/dist/assets/stash-skeleton/facts/conventions/assets/agent.md +38 -0
  26. package/dist/assets/stash-skeleton/facts/conventions/assets/command.md +38 -0
  27. package/dist/assets/stash-skeleton/facts/conventions/assets/fact.md +39 -0
  28. package/dist/assets/stash-skeleton/facts/conventions/assets/knowledge.md +40 -0
  29. package/dist/assets/stash-skeleton/facts/conventions/assets/lesson.md +43 -0
  30. package/dist/assets/stash-skeleton/facts/conventions/assets/memory.md +38 -0
  31. package/dist/assets/stash-skeleton/facts/conventions/assets/script.md +43 -0
  32. package/dist/assets/stash-skeleton/facts/conventions/assets/skill.md +40 -0
  33. package/dist/assets/stash-skeleton/facts/conventions/assets/workflow.md +43 -0
  34. package/dist/assets/templates/html/health.html +281 -111
  35. package/dist/assets/wiki/ingest-workflow-template.md +38 -10
  36. package/dist/cli/parse-args.js +46 -1
  37. package/dist/cli/shared.js +28 -0
  38. package/dist/cli.js +27 -11
  39. package/dist/commands/agent/agent-dispatch.js +2 -2
  40. package/dist/commands/agent/agent-support.js +0 -7
  41. package/dist/commands/agent/contribute-cli.js +17 -4
  42. package/dist/commands/config-cli.js +18 -2
  43. package/dist/commands/env/child-env.js +47 -0
  44. package/dist/commands/env/env-cli.js +33 -26
  45. package/dist/commands/env/secret-cli.js +36 -22
  46. package/dist/commands/feedback-cli.js +15 -6
  47. package/dist/commands/graph/graph-cli.js +5 -13
  48. package/dist/commands/graph/graph.js +76 -72
  49. package/dist/commands/health/checks.js +49 -1
  50. package/dist/commands/health/html-report.js +422 -80
  51. package/dist/commands/health.js +386 -9
  52. package/dist/commands/improve/calibration.js +161 -0
  53. package/dist/commands/improve/consolidate/chunking.js +141 -0
  54. package/dist/commands/improve/consolidate/eligibility.js +81 -0
  55. package/dist/commands/improve/consolidate/merge.js +145 -0
  56. package/dist/commands/improve/consolidate/sanitize.js +231 -0
  57. package/dist/commands/{lint.js → improve/consolidate/types.js} +1 -1
  58. package/dist/commands/improve/consolidate.js +635 -660
  59. package/dist/commands/improve/dedup.js +482 -0
  60. package/dist/commands/improve/distill.js +159 -69
  61. package/dist/commands/improve/eligibility.js +434 -0
  62. package/dist/commands/improve/encoding-salience.js +205 -0
  63. package/dist/commands/improve/extract-cli.js +124 -2
  64. package/dist/commands/improve/extract-prompt.js +39 -2
  65. package/dist/commands/improve/extract-watch.js +140 -0
  66. package/dist/commands/improve/extract.js +389 -40
  67. package/dist/commands/improve/feedback-valence.js +54 -0
  68. package/dist/commands/improve/homeostatic.js +467 -0
  69. package/dist/commands/improve/improve-auto-accept.js +138 -7
  70. package/dist/commands/improve/improve-cli.js +36 -61
  71. package/dist/commands/improve/improve-profiles.js +14 -0
  72. package/dist/commands/improve/improve-result-file.js +14 -25
  73. package/dist/commands/improve/improve-session.js +58 -0
  74. package/dist/commands/improve/improve.js +485 -2498
  75. package/dist/commands/improve/locks.js +154 -0
  76. package/dist/commands/improve/loop-stages.js +1083 -0
  77. package/dist/commands/improve/memory/memory-contradiction-detect.js +23 -28
  78. package/dist/commands/improve/outcome-loop.js +256 -0
  79. package/dist/commands/improve/preparation.js +1966 -0
  80. package/dist/commands/improve/proactive-maintenance.js +115 -0
  81. package/dist/commands/improve/procedural.js +418 -0
  82. package/dist/commands/improve/recombine.js +850 -0
  83. package/dist/commands/improve/reflect-noise.js +0 -0
  84. package/dist/commands/improve/reflect.js +183 -40
  85. package/dist/commands/improve/salience.js +438 -0
  86. package/dist/commands/improve/triage.js +93 -0
  87. package/dist/commands/lint/agent-linter.js +19 -24
  88. package/dist/commands/lint/base-linter.js +173 -60
  89. package/dist/commands/lint/command-linter.js +19 -24
  90. package/dist/commands/lint/env-key-rules.js +38 -1
  91. package/dist/commands/lint/fact-linter.js +39 -0
  92. package/dist/commands/lint/index.js +31 -13
  93. package/dist/commands/lint/memory-linter.js +1 -1
  94. package/dist/commands/lint/registry.js +7 -2
  95. package/dist/commands/lint/task-linter.js +3 -3
  96. package/dist/commands/lint/workflow-linter.js +26 -1
  97. package/dist/commands/proposal/drain-policies.js +5 -0
  98. package/dist/commands/proposal/drain.js +43 -50
  99. package/dist/commands/proposal/proposal-cli.js +21 -31
  100. package/dist/commands/proposal/proposal.js +5 -0
  101. package/dist/commands/proposal/propose.js +7 -2
  102. package/dist/commands/proposal/validators/proposal-quality-validators.js +9 -8
  103. package/dist/commands/proposal/validators/proposals.js +189 -63
  104. package/dist/commands/read/curate.js +414 -94
  105. package/dist/commands/read/knowledge.js +6 -3
  106. package/dist/commands/read/search-cli.js +9 -4
  107. package/dist/commands/read/search.js +10 -6
  108. package/dist/commands/read/show.js +86 -7
  109. package/dist/commands/sources/init.js +49 -17
  110. package/dist/commands/sources/installed-stashes.js +11 -3
  111. package/dist/commands/sources/schema-repair.js +43 -45
  112. package/dist/commands/sources/self-update.js +2 -2
  113. package/dist/commands/sources/source-add.js +7 -3
  114. package/dist/commands/sources/stash-cli.js +28 -40
  115. package/dist/commands/sources/stash-skeleton.js +23 -8
  116. package/dist/commands/tasks/tasks-cli.js +19 -27
  117. package/dist/commands/tasks/tasks.js +39 -11
  118. package/dist/commands/wiki-cli.js +21 -35
  119. package/dist/core/asset/asset-registry.js +3 -1
  120. package/dist/core/asset/asset-spec.js +18 -2
  121. package/dist/core/asset/frontmatter.js +166 -167
  122. package/dist/core/asset/markdown.js +8 -0
  123. package/dist/core/authoring-rules.js +92 -0
  124. package/dist/core/common.js +0 -5
  125. package/dist/core/config/config-migration.js +12 -11
  126. package/dist/core/config/config-schema.js +340 -56
  127. package/dist/core/config/config-types.js +3 -3
  128. package/dist/core/config/config.js +28 -7
  129. package/dist/core/events.js +3 -7
  130. package/dist/core/improve-types.js +11 -8
  131. package/dist/core/logs-db.js +10 -66
  132. package/dist/core/parse.js +36 -16
  133. package/dist/core/paths.js +3 -0
  134. package/dist/core/standards/resolve-standards-context.js +87 -0
  135. package/dist/core/standards/resolve-stash-standards.js +99 -0
  136. package/dist/core/standards/resolve-type-conventions.js +66 -0
  137. package/dist/core/state/migrations.js +714 -0
  138. package/dist/core/state-db.js +525 -474
  139. package/dist/indexer/db/db.js +439 -247
  140. package/dist/indexer/db/graph-db.js +129 -86
  141. package/dist/indexer/ensure-index.js +152 -17
  142. package/dist/indexer/graph/graph-boost.js +51 -41
  143. package/dist/indexer/graph/graph-extraction.js +218 -4
  144. package/dist/indexer/index-writer-lock.js +99 -0
  145. package/dist/indexer/indexer.js +123 -221
  146. package/dist/indexer/passes/dir-staleness.js +114 -0
  147. package/dist/indexer/passes/memory-inference.js +13 -5
  148. package/dist/indexer/passes/staleness-detect.js +2 -5
  149. package/dist/indexer/search/db-search.js +19 -6
  150. package/dist/indexer/search/ranking-contributors.js +22 -0
  151. package/dist/indexer/search/ranking.js +4 -0
  152. package/dist/indexer/search/search-source.js +17 -18
  153. package/dist/indexer/search/semantic-status.js +4 -0
  154. package/dist/indexer/walk/matchers.js +9 -0
  155. package/dist/integrations/agent/config.js +6 -53
  156. package/dist/integrations/agent/index.js +2 -18
  157. package/dist/integrations/agent/prompts.js +75 -9
  158. package/dist/integrations/agent/runner-dispatch.js +59 -0
  159. package/dist/integrations/harnesses/claude/session-log.js +11 -1
  160. package/dist/integrations/harnesses/index.js +2 -3
  161. package/dist/integrations/harnesses/opencode/session-log.js +173 -3
  162. package/dist/integrations/harnesses/opencode-sdk/index.js +2 -2
  163. package/dist/integrations/harnesses/opencode-sdk/sdk-runner.js +0 -2
  164. package/dist/integrations/session-logs/index.js +16 -0
  165. package/dist/llm/client.js +45 -15
  166. package/dist/llm/embedder.js +42 -3
  167. package/dist/llm/embedders/deterministic.js +66 -0
  168. package/dist/llm/embedders/local.js +66 -2
  169. package/dist/llm/feature-gate.js +8 -4
  170. package/dist/llm/graph-extract.js +67 -44
  171. package/dist/llm/memory-infer-impl.js +138 -0
  172. package/dist/llm/memory-infer.js +1 -127
  173. package/dist/llm/metadata-enhance.js +44 -31
  174. package/dist/llm/structured-call.js +49 -0
  175. package/dist/migrate-storage-node.mjs +8 -0
  176. package/dist/output/context.js +5 -5
  177. package/dist/output/renderers.js +74 -2
  178. package/dist/output/shapes/curate.js +14 -2
  179. package/dist/output/shapes/passthrough.js +0 -1
  180. package/dist/output/text/helpers.js +16 -1
  181. package/dist/registry/providers/skills-sh.js +21 -147
  182. package/dist/registry/providers/static-index.js +15 -157
  183. package/dist/registry/resolve.js +22 -9
  184. package/dist/runtime.js +25 -1
  185. package/dist/scripts/migrate-storage.js +2617 -1961
  186. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +759 -510
  187. package/dist/setup/setup.js +29 -8
  188. package/dist/sources/include.js +6 -2
  189. package/dist/sources/providers/filesystem.js +0 -1
  190. package/dist/sources/providers/git-install.js +210 -0
  191. package/dist/sources/providers/git-provider.js +234 -0
  192. package/dist/sources/providers/git-stash.js +248 -0
  193. package/dist/sources/providers/git.js +10 -661
  194. package/dist/sources/providers/npm.js +2 -6
  195. package/dist/sources/providers/provider-utils.js +13 -7
  196. package/dist/sources/providers/sync-from-ref.js +9 -1
  197. package/dist/sources/providers/tar-utils.js +16 -8
  198. package/dist/sources/providers/website.js +9 -5
  199. package/dist/sources/website-ingest.js +187 -29
  200. package/dist/sources/wiki-fetchers/registry.js +53 -0
  201. package/dist/sources/wiki-fetchers/youtube.js +239 -0
  202. package/dist/storage/database.js +45 -10
  203. package/dist/storage/managed-db.js +82 -0
  204. package/dist/storage/repositories/registry-cache.js +92 -0
  205. package/dist/storage/sqlite-pragmas.js +146 -0
  206. package/dist/tasks/backends/cron.js +1 -1
  207. package/dist/tasks/backends/launchd.js +1 -1
  208. package/dist/tasks/backends/schtasks.js +1 -1
  209. package/dist/tasks/{resolveAkmBin.js → resolve-akm-bin.js} +2 -2
  210. package/dist/tasks/runner.js +5 -13
  211. package/dist/text-import-hook.mjs +0 -0
  212. package/dist/wiki/wiki.js +37 -0
  213. package/dist/workflows/db.js +3 -4
  214. package/dist/workflows/runtime/runs.js +1 -117
  215. package/dist/workflows/runtime/workflow-asset-loader.js +125 -0
  216. package/dist/workflows/validate-summary.js +2 -7
  217. package/docs/data-and-telemetry.md +3 -2
  218. package/docs/migration/release-notes/0.9.0.md +39 -0
  219. package/package.json +13 -11
  220. package/dist/commands/db-cli.js +0 -23
  221. package/dist/indexer/db/db-backup.js +0 -376
@@ -0,0 +1,850 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+ /**
5
+ * #609 — recombine / synthesize pass.
6
+ *
7
+ * A whole-corpus synthesis stage that runs AFTER consolidation and is OPT-IN
8
+ * (default disabled via `IMPROVE_PROCESS_DEFAULTS.recombine`). It clusters
9
+ * memories by RELATEDNESS (shared tags / graph entities — NEVER embedding
10
+ * similarity), issues ONE bounded LLM call per cluster to induce a single
11
+ * cross-episodic generalization, and emits the result as a NORMAL pending
12
+ * proposal with frontmatter `type: hypothesis` through the existing proposal
13
+ * queue + quality gate.
14
+ *
15
+ * Two-pass contract: the first pass ONLY ever emits `type: hypothesis`
16
+ * proposals — never a `type: lesson`. Promotion to a lesson happens on a later
17
+ * confirmation run once the same generalization has been re-induced
18
+ * `confirmThreshold` times (#625). The confirmation count is persisted in the
19
+ * `recombine_hypotheses` state.db table (migration 014), keyed by the
20
+ * deterministic `deriveRecombineLessonRef` value so re-induction of the SAME
21
+ * member-set maps back to the SAME row. When the count reaches the threshold,
22
+ * the run emits ONE `type: lesson` promotion proposal through the SAME proposal
23
+ * queue + quality gate (createProposal + validateProposalFrontmatter), NEVER a
24
+ * direct stash write, then marks the row promoted (resetting its count) so it is
25
+ * not re-promoted on every subsequent run. Hypotheses NOT re-induced in a run
26
+ * have their consecutive streak reset (decay-to-zero).
27
+ *
28
+ * NAMESPACE note: the ref stays `lesson:recombined/<slug>-<hash>` for BOTH
29
+ * passes. The ref is the promotion TARGET asset (a lesson in both the hypothesis
30
+ * and promoted states), so re-induction must map to the same ref and the ref
31
+ * cannot encode the proposal type. The hypothesis-vs-lesson distinction is
32
+ * carried ONLY by the proposal frontmatter `type` field. On promotion the prior
33
+ * pending `type: hypothesis` proposal for that ref is superseded (rejected) so
34
+ * the queue never shows two proposals for one ref.
35
+ *
36
+ * A justified null (the LLM determines no defensible generalization exists) is
37
+ * an acceptable outcome: it produces no proposal and records a
38
+ * `recombine_invoked` event with `outcome: 'null_returned'`.
39
+ */
40
+ import { createHash } from "node:crypto";
41
+ import fs from "node:fs";
42
+ import recombineSystemPrompt from "../../assets/prompts/recombine-system.md" with { type: "text" };
43
+ import { parseFrontmatter } from "../../core/asset/frontmatter.js";
44
+ import { resolveStashDir } from "../../core/common.js";
45
+ import { getDefaultLlmConfig, loadConfig } from "../../core/config/config.js";
46
+ import { appendEvent } from "../../core/events.js";
47
+ import { parseEmbeddedJsonResponse } from "../../core/parse.js";
48
+ import { resolveStashStandards } from "../../core/standards/resolve-stash-standards.js";
49
+ import { decayUnseenRecombineHypotheses, findMatchingRecombineHypothesis, getRecombineHypothesis, markRecombineHypothesisPromoted, recordRecombineInduction, withStateDbAsync, } from "../../core/state-db.js";
50
+ import { warn } from "../../core/warn.js";
51
+ import { closeDatabase, getAllEntries, getEntitiesByEntryIds, openExistingDatabase, } from "../../indexer/db/db.js";
52
+ import { resolveImproveProcessRunnerFromProfile, runnerIsLlm } from "../../integrations/agent/runner.js";
53
+ import { chatCompletion } from "../../llm/client.js";
54
+ import { isValidDescription, isValidWhenToUse, validateProposalFrontmatter, } from "../proposal/validators/proposal-quality-validators.js";
55
+ import { archiveProposal, createProposal, isProposalSkipped, listProposals } from "../proposal/validators/proposals.js";
56
+ import { isConsolidationEligibleMemoryName, isSessionCaptureMemoryName } from "./consolidate.js";
57
+ const RECOMBINE_SYSTEM_PROMPT = recombineSystemPrompt;
58
+ const DEFAULT_MIN_CLUSTER_SIZE = 3;
59
+ const DEFAULT_MAX_CLUSTERS_PER_RUN = 5;
60
+ // #632 — slots in each run's processed budget reserved for the top TAG clusters
61
+ // when entity clusters are present, so tag-only topics (a topic with a good tag
62
+ // but no extracted graph entity) are never fully starved by entity preference.
63
+ // Entities still take the rest of the budget; whichever kind is short, the other
64
+ // backfills. UNSET of entities (tags-only stash) ignores this and takes top-N tags.
65
+ const RESERVED_TAG_SLOTS = 3;
66
+ // #632 — a tag cluster larger than this is treated as an over-broad project
67
+ // mega-bucket (low-coherence, the bland signal #632 de-emphasizes), so the
68
+ // reserved tag slots prefer TIGHTER clusters at or below this size first.
69
+ const TAG_RESERVE_SOFT_CAP = 20;
70
+ // #632 — default to the UNION of tag + graph-entity relatedness, with entity
71
+ // clusters PREFERRED at selection time (see the rank in buildRelatednessClusters).
72
+ // Entity clustering surfaces coherent, subject-scoped clusters (a tool/subsystem)
73
+ // that the coarse stash-wide tag buckets miss, while tags still cover memories the
74
+ // graph has no entity for. The `entity:` vs `tag:` signature namespaces are
75
+ // independent, so a pure tag cluster's confirmation streak is only re-baselined
76
+ // when its OWN membership changes — which is exactly what the session-capture pool
77
+ // exclusion intends for the telemetry-polluted buckets (re-baselining a noisy
78
+ // cluster's streak is correct, not a regression). A stash with no extracted graph
79
+ // entities falls through to tag-only.
80
+ const DEFAULT_RELATEDNESS_SOURCE = "both";
81
+ /** #625 — re-induction count required before a hypothesis promotes to a lesson. */
82
+ const DEFAULT_CONFIRM_THRESHOLD = 2;
83
+ /**
84
+ * #633 — Jaccard membership-overlap threshold for matching a freshly-induced
85
+ * hypothesis to an existing pending row under the SAME signature. A growing
86
+ * stash drifts the exact member set every run; an overlap >= this lets the
87
+ * confirmation streak keep accumulating under one row instead of resetting to 1.
88
+ */
89
+ const DEFAULT_RECOMBINE_OVERLAP = 0.7;
90
+ // ── Clustering by relatedness (NOT similarity) ────────────────────────────────
91
+ /**
92
+ * #632 — English stopwords that occasionally leak into frontmatter tags
93
+ * (`is`, `the`, `for`, …). They carry no topical signal, so a cluster keyed on
94
+ * one is meaningless. Lowercased; matched case-insensitively.
95
+ */
96
+ const JUNK_STOPWORD_TAGS = new Set([
97
+ "a",
98
+ "an",
99
+ "and",
100
+ "the",
101
+ "to",
102
+ "of",
103
+ "in",
104
+ "on",
105
+ "for",
106
+ "is",
107
+ "are",
108
+ "be",
109
+ "no",
110
+ "not",
111
+ "or",
112
+ "if",
113
+ "it",
114
+ "as",
115
+ "at",
116
+ "by",
117
+ "we",
118
+ "us",
119
+ "do",
120
+ "so",
121
+ "when",
122
+ "then",
123
+ "than",
124
+ "with",
125
+ "from",
126
+ "this",
127
+ "that",
128
+ "uses",
129
+ "use",
130
+ "via",
131
+ ]);
132
+ /**
133
+ * #632 — a tag carries no clustering signal (and must be skipped) when it is
134
+ * purely a number / date / hash / version string, a single char, or a common
135
+ * stopword. Unlike `excludeTags` (a fixed project list), this catches the
136
+ * OPEN-ENDED junk — every new date or commit hash — without config upkeep.
137
+ */
138
+ export function isJunkTag(tag) {
139
+ const t = tag.trim().toLowerCase();
140
+ if (t.length <= 1)
141
+ return true;
142
+ if (JUNK_STOPWORD_TAGS.has(t))
143
+ return true;
144
+ if (/^\d+$/.test(t))
145
+ return true; // pure numbers + dates: 2026, 05, 23, 20260529
146
+ if (/^v?\d+(?:\.\d+)+$/.test(t))
147
+ return true; // versions: 0.8.0, v1.2
148
+ if (/^v\d+$/.test(t))
149
+ return true; // v0, v2
150
+ if (/^[0-9a-f]{4,}$/.test(t) && /\d/.test(t))
151
+ return true; // short hex hashes: 002c624c, 192d
152
+ return false;
153
+ }
154
+ /**
155
+ * #632 — generic extraction-artefact entities the graph routinely emits: session
156
+ * bookkeeping (`session_id`, `session_checkpoint`), structured-log field names
157
+ * (`reason`, `harness`, `structured event log`), and the like. They are
158
+ * stash-wide and carry no topical signal, so an `entity:<norm>` cluster keyed on
159
+ * one is exactly the bland mega-bucket #632 aims to remove. Lowercased; matched
160
+ * against the already-normalised `entity_norm`.
161
+ */
162
+ const JUNK_ENTITY_NORMS = new Set([
163
+ "session",
164
+ "session_id",
165
+ "session_checkpoint",
166
+ "checkpoint",
167
+ "reason",
168
+ "harness",
169
+ "event",
170
+ "event log",
171
+ "structured event",
172
+ "structured event log",
173
+ "timestamp",
174
+ "metadata",
175
+ "status",
176
+ ]);
177
+ // #632 — `isSessionCaptureMemoryName` now lives in ./consolidate/eligibility so
178
+ // both recombine and consolidate can reuse it without a circular import. It is
179
+ // re-exported here for back-compat (existing importers + tests).
180
+ export { isSessionCaptureMemoryName };
181
+ /**
182
+ * #632 — an entity carries no clustering signal (and must be skipped) when it is
183
+ * a generic extraction artefact (session / structured-log bookkeeping), a raw
184
+ * filesystem path (absolute paths the extractor lifts verbatim), or the same
185
+ * number / date / hash / version / stopword junk `isJunkTag` rejects. Mirrors
186
+ * `isJunkTag` so the graph relatedness source does not reintroduce the very
187
+ * bland buckets entity clustering is meant to replace. Unlike `excludeEntities`
188
+ * (a fixed user list), this catches the OPEN-ENDED junk without config upkeep.
189
+ */
190
+ export function isJunkEntity(entity) {
191
+ const e = entity.trim().toLowerCase();
192
+ if (e.length <= 1)
193
+ return true;
194
+ if (JUNK_ENTITY_NORMS.has(e))
195
+ return true;
196
+ if (JUNK_STOPWORD_TAGS.has(e))
197
+ return true;
198
+ if (e.includes("/") || e.includes("\\"))
199
+ return true; // raw file paths
200
+ if (/^\d+$/.test(e))
201
+ return true; // pure numbers + dates
202
+ if (/^v?\d+(?:\.\d+)+$/.test(e))
203
+ return true; // versions
204
+ if (/^v\d+$/.test(e))
205
+ return true; // v0, v2
206
+ if (/^[0-9a-f]{4,}$/.test(e) && /\d/.test(e))
207
+ return true; // short hex hashes
208
+ return false;
209
+ }
210
+ /**
211
+ * Build relatedness clusters from the memory pool. Clustering is driven purely
212
+ * by shared tags / graph entities — it MUST NOT use embedding similarity, so
213
+ * textually near-identical memories that share no relatedness signal never
214
+ * cluster together.
215
+ *
216
+ * For `relatednessSource`:
217
+ * - `"tags"` — group by each frontmatter tag.
218
+ * - `"graph"` — group by shared `graph_file_entities.entity_norm`; falls back
219
+ * to tags when the graph table is empty (fail-open).
220
+ * - `"both"` — union of the tag and entity grouping keys.
221
+ *
222
+ * A cluster is a signal whose member set is >= `minClusterSize`. Overlapping
223
+ * clusters are de-duplicated by member-set identity, and the result is RANKED
224
+ * by member-count descending (deterministic alphabetical tiebreak). The
225
+ * `maxClustersPerRun` cap is NOT applied here — call {@link selectClustersForRun}
226
+ * (entity-aware blend) or {@link capClusters} (tags-only) on the result for the
227
+ * processed slice; the full ranked list is retained so the cap-aware decay sweep
228
+ * can tell cap-displacement from corpus absence (#658).
229
+ */
230
+ export function buildRelatednessClusters(entries, opts) {
231
+ // Only consolidation-eligible memories participate (exclude `.derived`).
232
+ // #632 — durable memories only: exclude `.derived` (via
233
+ // `isConsolidationEligibleMemoryName`) AND session-capture telemetry dumps
234
+ // whose embedded metadata pollutes both tag and entity clustering.
235
+ const memories = entries.filter((e) => e.entry.type === "memory" &&
236
+ isConsolidationEligibleMemoryName(e.entry.name) &&
237
+ !isSessionCaptureMemoryName(e.entry.name));
238
+ // signal -> member entries
239
+ const groups = new Map();
240
+ const add = (signal, entry) => {
241
+ const key = signal.trim();
242
+ if (!key)
243
+ return;
244
+ const list = groups.get(key);
245
+ if (list) {
246
+ if (!list.includes(entry))
247
+ list.push(entry);
248
+ }
249
+ else {
250
+ groups.set(key, [entry]);
251
+ }
252
+ };
253
+ const useTags = opts.relatednessSource === "tags" || opts.relatednessSource === "both";
254
+ // Graph relatedness falls open to tags when no entities are available.
255
+ const hasEntities = !!opts.entityByEntryId && opts.entityByEntryId.size > 0;
256
+ const useGraph = (opts.relatednessSource === "graph" || opts.relatednessSource === "both") && hasEntities;
257
+ const tagsFallback = !useTags && opts.relatednessSource === "graph" && !hasEntities;
258
+ // #632 — tags/entities excluded from clustering (applies regardless of
259
+ // source). UNSET/[] leaves tag clustering byte-identical to the pre-#632 path.
260
+ const excludeTags = new Set(opts.excludeTags ?? []);
261
+ // `entity_norm` is always lowercased (graph-dedup.ts), so normalise the
262
+ // user-supplied exclusion list to match — `excludeEntities: ["OpenCode"]`
263
+ // should suppress the stored `opencode` entity (Reviewer A, #632).
264
+ const excludeEntities = new Set((opts.excludeEntities ?? []).map((e) => e.toLowerCase()));
265
+ for (const entry of memories) {
266
+ if (useTags || tagsFallback) {
267
+ for (const tag of entry.entry.tags ?? []) {
268
+ if (excludeTags.has(tag))
269
+ continue;
270
+ if (isJunkTag(tag))
271
+ continue; // #632 — skip numeric/date/hash/version/stopword junk
272
+ add(`tag:${tag}`, entry);
273
+ }
274
+ }
275
+ if (useGraph && opts.entityByEntryId) {
276
+ for (const ent of opts.entityByEntryId.get(entry.id) ?? []) {
277
+ if (excludeEntities.has(ent))
278
+ continue;
279
+ if (isJunkEntity(ent))
280
+ continue; // #632 — skip generic extraction-artefact / path entities
281
+ add(`entity:${ent}`, entry);
282
+ }
283
+ }
284
+ }
285
+ // Keep only groups at or above the minimum cluster size. #632 — when
286
+ // maxClusterSize is set, also SKIP groups strictly larger than the cap so an
287
+ // over-broad bucket never reaches (and starves) the largest-first slice.
288
+ // UNSET = no upper bound = identical to the pre-#632 behaviour.
289
+ let clusters = [];
290
+ for (const [signature, members] of groups) {
291
+ if (members.length < opts.minClusterSize)
292
+ continue;
293
+ if (opts.maxClusterSize != null && members.length > opts.maxClusterSize)
294
+ continue;
295
+ clusters.push({ signature, members });
296
+ }
297
+ // De-duplicate clusters that share the exact same member set (e.g. a tag and
298
+ // an entity that co-occur on the same trio). Keep the first by signature.
299
+ const seenMemberKeys = new Set();
300
+ clusters = clusters.filter((c) => {
301
+ const memberKey = c.members
302
+ .map((m) => m.id)
303
+ .sort((a, b) => a - b)
304
+ .join(",");
305
+ if (seenMemberKeys.has(memberKey))
306
+ return false;
307
+ seenMemberKeys.add(memberKey);
308
+ return true;
309
+ });
310
+ // #632 — rank ENTITY clusters ahead of tag clusters, then largest-first within
311
+ // each kind (deterministic alphabetical tiebreak). A graph entity is an
312
+ // EXTRACTED SUBJECT (a tool / subsystem / component), so it is a far
313
+ // higher-signal cluster key than an auto-tokenized frontmatter tag, whose
314
+ // broadest buckets (`tag:<project>` — e.g. every memory tagged `akm`) are the
315
+ // coarse, bland clusters #632 set out to kill. Largest-first ALONE let those
316
+ // tag mega-buckets fill the `maxClustersPerRun` slice every run and starve the
317
+ // coherent entity clusters this pass produces. Preferring entities keeps tag
318
+ // clustering as the fallback (a stash with no graph entities, or a topic with a
319
+ // tag but no extracted entity, still clusters) while ensuring the better signal
320
+ // wins the cap. The processed slice is chosen by the caller via
321
+ // {@link selectClustersForRun} (NOT here), so the FULL formed set stays
322
+ // available for the cap-aware decay sweep —
323
+ // a cluster displaced by the cap must not be confused with a cluster that
324
+ // vanished from the corpus (#658).
325
+ const entityRank = (sig) => (sig.startsWith("entity:") ? 0 : 1);
326
+ clusters.sort((a, b) => entityRank(a.signature) - entityRank(b.signature) ||
327
+ b.members.length - a.members.length ||
328
+ a.signature.localeCompare(b.signature));
329
+ return clusters;
330
+ }
331
+ /**
332
+ * #658 — apply the `maxClustersPerRun` cap to a largest-first ranked cluster
333
+ * list. Split out from {@link buildRelatednessClusters} so callers retain the
334
+ * full pre-cap set: the clusters BELOW the cap still re-formed this run and must
335
+ * spare their hypotheses from decay (cap-displacement is a SCHEDULING miss, not
336
+ * a substance miss). Callers that only need the processed slice call this; the
337
+ * full ranked list feeds {@link decayUnseenRecombineHypotheses}.
338
+ */
339
+ export function capClusters(ranked, maxClustersPerRun) {
340
+ return ranked.slice(0, Math.max(0, maxClustersPerRun));
341
+ }
342
+ /**
343
+ * #632 — pick the per-run PROCESSED slice from the full ranked list, BLENDING
344
+ * entity and tag clusters so neither starves the other:
345
+ *
346
+ * - No entity clusters → top `maxClustersPerRun` TAG clusters (a tags-only
347
+ * stash is byte-identical to {@link capClusters}).
348
+ * - Entity clusters present → ENTITIES LEAD the budget (the higher-signal key —
349
+ * an extracted subject vs an auto-tokenized filename tag), but RESERVE up to
350
+ * `RESERVED_TAG_SLOTS` for tag clusters so tag-only topics still surface every
351
+ * run. Entities are never starved below one slot when present and the budget
352
+ * allows. Whichever kind is short, the other backfills, so the full budget is
353
+ * always used when enough clusters exist.
354
+ *
355
+ * The reserved tag slots prefer TIGHTER tag clusters (size <= `TAG_RESERVE_SOFT_CAP`,
356
+ * largest-first within that band, then the over-cap buckets): a broad
357
+ * auto-tokenized `tag:<project>` mega-bucket is exactly the bland, low-coherence
358
+ * signal #632 de-emphasizes, so the reserve should not spend its protected slots
359
+ * on the largest tags. Entities themselves stay largest-first — an entity is a
360
+ * coherent subject at any size.
361
+ *
362
+ * Entities lead the returned order. The FULL pre-cap `ranked` list (not this
363
+ * slice) still feeds the cap-aware decay sweep (#658), so a cluster left out of
364
+ * the processed slice this run is NOT decayed as if it vanished.
365
+ */
366
+ export function selectClustersForRun(ranked, maxClustersPerRun) {
367
+ const max = Math.max(0, maxClustersPerRun);
368
+ if (max === 0)
369
+ return [];
370
+ const entities = ranked.filter((c) => c.signature.startsWith("entity:"));
371
+ if (entities.length === 0)
372
+ return ranked.slice(0, max); // tags-only → top-N (capClusters parity)
373
+ const tags = ranked.filter((c) => !c.signature.startsWith("entity:"));
374
+ // Reserve up to RESERVED_TAG_SLOTS for tags, but never below one slot for the
375
+ // leading entities when the budget allows (so a small `maxClustersPerRun` does
376
+ // not silently invert the entity preference).
377
+ const reservedForTags = Math.min(tags.length, RESERVED_TAG_SLOTS, Math.max(0, max - 1));
378
+ const entityTake = Math.min(entities.length, max - reservedForTags);
379
+ const tagTake = Math.min(tags.length, max - entityTake); // tags take their reserve + any slot entities left
380
+ // Prefer tight tags (<= soft cap) over broad mega-buckets for the reserve.
381
+ const reserveTags = [...tags]
382
+ .sort((a, b) => {
383
+ const aOver = a.members.length > TAG_RESERVE_SOFT_CAP ? 1 : 0;
384
+ const bOver = b.members.length > TAG_RESERVE_SOFT_CAP ? 1 : 0;
385
+ return aOver - bOver || b.members.length - a.members.length || a.signature.localeCompare(b.signature);
386
+ })
387
+ .slice(0, tagTake);
388
+ return [...entities.slice(0, entityTake), ...reserveTags];
389
+ }
390
+ // ── Prompt + ref derivation ───────────────────────────────────────────────────
391
+ /** Read a memory body (frontmatter stripped) for the cluster prompt. */
392
+ function readBody(entry) {
393
+ try {
394
+ const raw = fs.readFileSync(entry.filePath, "utf8");
395
+ return parseFrontmatter(raw).content.trim();
396
+ }
397
+ catch {
398
+ return "";
399
+ }
400
+ }
401
+ /** Assemble the per-cluster user prompt fed to the recombine LLM. */
402
+ export function buildClusterPrompt(cluster, standardsContext = "") {
403
+ const lines = [
404
+ `Shared signal: ${cluster.signature}`,
405
+ `Cluster of ${cluster.members.length} related memories:`,
406
+ "",
407
+ ];
408
+ if (standardsContext.trim()) {
409
+ lines.push("Standards to follow (the rulebook for this target):");
410
+ lines.push(standardsContext.trim());
411
+ lines.push("");
412
+ }
413
+ for (const m of cluster.members) {
414
+ lines.push(`[memory:${m.entry.name}]`);
415
+ if (m.entry.description)
416
+ lines.push(`Description: ${m.entry.description}`);
417
+ const body = readBody(m);
418
+ if (body)
419
+ lines.push(body);
420
+ lines.push("");
421
+ }
422
+ lines.push("Induce ONE cross-episodic generalization these memories support, or return an explicit null if none is defensible.");
423
+ return lines.join("\n");
424
+ }
425
+ /**
426
+ * Stable lesson ref for a cluster. The hash of the sorted member refs keeps the
427
+ * ref deterministic across runs (so re-induction maps to the same ref + the
428
+ * content-hash dedup in createProposal suppresses queue churn).
429
+ */
430
+ export function deriveRecombineLessonRef(cluster) {
431
+ const slug = cluster.signature
432
+ .replace(/^(tag|entity):/, "")
433
+ .toLowerCase()
434
+ .replace(/[^a-z0-9-]+/g, "-")
435
+ .replace(/-+/g, "-")
436
+ .replace(/^-|-$/g, "");
437
+ const memberKey = recombineMemberKey(cluster);
438
+ const hash = createHash("sha256").update(memberKey, "utf8").digest("hex").slice(0, 8);
439
+ return `lesson:recombined/${slug || "cluster"}-${hash}`;
440
+ }
441
+ function validatePromotedLessonFrontmatter(ref, frontmatter) {
442
+ const descCheck = isValidDescription(frontmatter.description, ref);
443
+ if (!descCheck.ok)
444
+ return { ok: false, reason: descCheck.reason };
445
+ const whenToUseCheck = isValidWhenToUse(frontmatter.when_to_use, ref);
446
+ if (!whenToUseCheck.ok)
447
+ return { ok: false, reason: whenToUseCheck.reason };
448
+ if (typeof frontmatter.description === "string" &&
449
+ typeof frontmatter.when_to_use === "string" &&
450
+ frontmatter.description.trim().toLowerCase() === frontmatter.when_to_use.trim().toLowerCase()) {
451
+ return { ok: false, reason: "description and when_to_use are identical" };
452
+ }
453
+ return { ok: true };
454
+ }
455
+ /**
456
+ * The membership fingerprint of a cluster: its member entryKeys sorted and
457
+ * joined. Single source of truth shared by {@link deriveRecombineLessonRef}'s
458
+ * hash and the `recombine_hypotheses.member_key` column, so the table key and
459
+ * the ref hash always derive from the SAME member set. Adding/removing one
460
+ * memory yields a different fingerprint → a different ref → a fresh row (the
461
+ * old streak is correctly NOT inherited).
462
+ */
463
+ export function recombineMemberKey(cluster) {
464
+ return cluster.members
465
+ .map((m) => m.entryKey)
466
+ .sort()
467
+ .join("|");
468
+ }
469
+ /** Parse the raw LLM output into a generalization, or `null` for the justified-null path. */
470
+ function parseGeneralization(raw) {
471
+ if (raw === null)
472
+ return null;
473
+ const trimmed = raw.trim();
474
+ if (!trimmed || trimmed.toLowerCase() === "null")
475
+ return null;
476
+ const parsed = parseEmbeddedJsonResponse(trimmed);
477
+ if (parsed === undefined || parsed === null)
478
+ return null;
479
+ if (typeof parsed !== "object")
480
+ return null;
481
+ const obj = parsed;
482
+ const description = typeof obj.description === "string" ? obj.description : "";
483
+ const body = typeof obj.body === "string" ? obj.body : "";
484
+ const when_to_use = typeof obj.when_to_use === "string" ? obj.when_to_use : undefined;
485
+ // An empty object / all-empty fields is treated as a justified null.
486
+ if (!description && !body)
487
+ return null;
488
+ return { description, body, ...(when_to_use ? { when_to_use } : {}) };
489
+ }
490
+ /**
491
+ * Resolve the production LLM seam from the active improve profile. Returns a
492
+ * `RecombineLlmFn` that issues one bounded chatCompletion per call, or
493
+ * `undefined` when no LLM is configured (the pass then makes no calls).
494
+ */
495
+ function resolveProductionLlmFn(config, signal) {
496
+ const recombineProcess = config.profiles?.improve?.default?.processes?.recombine;
497
+ const runnerSpec = resolveImproveProcessRunnerFromProfile(recombineProcess, config);
498
+ const llmConfig = runnerSpec && runnerIsLlm(runnerSpec) ? runnerSpec.connection : getDefaultLlmConfig(config);
499
+ if (!llmConfig)
500
+ return undefined;
501
+ return async (clusterPrompt) => {
502
+ const messages = [
503
+ { role: "system", content: RECOMBINE_SYSTEM_PROMPT },
504
+ { role: "user", content: clusterPrompt },
505
+ ];
506
+ try {
507
+ return await chatCompletion(llmConfig, messages, { signal, enableThinking: false });
508
+ }
509
+ catch (e) {
510
+ warn(`[recombine] LLM call failed: ${String(e)}`);
511
+ return null;
512
+ }
513
+ };
514
+ }
515
+ // ── Main entry point ───────────────────────────────────────────────────────────
516
+ export async function akmRecombine(opts) {
517
+ const startMs = Date.now();
518
+ const config = opts.config ?? loadConfig();
519
+ const stashDir = opts.stashDir ?? resolveStashDir();
520
+ const sourceRun = opts.sourceRun ?? `recombine-${startMs}`;
521
+ const eligibilitySource = opts.eligibilitySource ?? "recombine";
522
+ const minClusterSize = opts.minClusterSize ?? DEFAULT_MIN_CLUSTER_SIZE;
523
+ const maxClustersPerRun = opts.maxClustersPerRun ?? DEFAULT_MAX_CLUSTERS_PER_RUN;
524
+ const relatednessSource = opts.relatednessSource ?? DEFAULT_RELATEDNESS_SOURCE;
525
+ const confirmThreshold = opts.confirmThreshold ?? DEFAULT_CONFIRM_THRESHOLD;
526
+ const warnings = [];
527
+ const finish = (over) => ({
528
+ schemaVersion: 1,
529
+ ok: true,
530
+ clustersFormed: 0,
531
+ proposalsEmitted: 0,
532
+ lessonsPromoted: 0,
533
+ nullsReturned: 0,
534
+ durationMs: Date.now() - startMs,
535
+ warnings,
536
+ ...over,
537
+ });
538
+ // Budget guard: an already-aborted signal short-circuits before any LLM call.
539
+ if (opts.signal?.aborted) {
540
+ return finish({ ok: false, warnings: [...warnings, "aborted-before-start"] });
541
+ }
542
+ // Load the memory pool + (optionally) graph entities from the index.
543
+ let entries = [];
544
+ let entityByEntryId;
545
+ let db;
546
+ try {
547
+ db = openExistingDatabase();
548
+ entries = getAllEntries(db, "memory");
549
+ if (relatednessSource === "graph" || relatednessSource === "both") {
550
+ try {
551
+ entityByEntryId = getEntitiesByEntryIds(db, entries.map((e) => e.id));
552
+ }
553
+ catch {
554
+ // Fail open to tag relatedness.
555
+ entityByEntryId = undefined;
556
+ }
557
+ }
558
+ }
559
+ catch (e) {
560
+ warnings.push(`recombine: failed to open index — ${String(e)}`);
561
+ return finish({ ok: false });
562
+ }
563
+ finally {
564
+ if (db)
565
+ closeDatabase(db);
566
+ }
567
+ // #658 — `rankedClusters` is the FULL set that re-formed this run (ranked,
568
+ // pre-cap); `clusters` is the processed top-`maxClustersPerRun` slice. The
569
+ // decay sweep below uses the full set so a cap-displaced (but present)
570
+ // cluster spares its hypothesis from reset.
571
+ const rankedClusters = buildRelatednessClusters(entries, {
572
+ minClusterSize,
573
+ relatednessSource,
574
+ ...(entityByEntryId ? { entityByEntryId } : {}),
575
+ ...(opts.maxClusterSize != null ? { maxClusterSize: opts.maxClusterSize } : {}),
576
+ ...(opts.excludeTags ? { excludeTags: opts.excludeTags } : {}),
577
+ ...(opts.excludeEntities ? { excludeEntities: opts.excludeEntities } : {}),
578
+ });
579
+ const clusters = selectClustersForRun(rankedClusters, maxClustersPerRun);
580
+ let clustersFormed = 0;
581
+ let proposalsEmitted = 0;
582
+ let lessonsPromoted = 0;
583
+ let nullsReturned = 0;
584
+ const llmFn = opts.recombineLlmFn ?? resolveProductionLlmFn(config, opts.signal);
585
+ if (!llmFn) {
586
+ warnings.push("recombine: no LLM configured — skipping");
587
+ return finish({ clustersFormed: 0 });
588
+ }
589
+ // Refs re-induced (defensible generalization passed the quality gate) THIS
590
+ // run — everything else is decayed after the loop.
591
+ const seenThisRun = new Set();
592
+ // Recombine output is knowledge/lesson (non-wiki) → stash authoring
593
+ // standards. Resolved ONCE per run and passed to each cluster prompt.
594
+ const standardsContext = resolveStashStandards(stashDir);
595
+ // #625 — open the confirmation-count store once per run via the ctx seam,
596
+ // reusing a long-lived ctx.db handle when the caller provided one (mirrors
597
+ // proposals.ts). Only handles WE opened are closed by the seam.
598
+ await withStateDbAsync(async (stateDb) => {
599
+ for (const cluster of clusters) {
600
+ if (opts.signal?.aborted) {
601
+ warnings.push("aborted-mid-run");
602
+ break;
603
+ }
604
+ clustersFormed += 1;
605
+ // #9 — promotion is terminal. If this cluster Jaccard-matches a
606
+ // hypothesis that was ALREADY promoted, generating again can at best
607
+ // re-queue a redundant `type: hypothesis` for a settled ref (promotion
608
+ // gates on !alreadyPromoted below), so the LLM output is wasted. Skip the
609
+ // per-cluster call entirely. The decay sweep still spares the row — it
610
+ // matches a present cluster via `presentClusters` (independent of
611
+ // `seenThisRun`), so the promotion record is preserved.
612
+ if (stateDb) {
613
+ const promotedMatch = findMatchingRecombineHypothesis(stateDb, {
614
+ signature: cluster.signature,
615
+ memberKey: recombineMemberKey(cluster),
616
+ minOverlap: DEFAULT_RECOMBINE_OVERLAP,
617
+ });
618
+ if (promotedMatch?.hypothesis_ref &&
619
+ getRecombineHypothesis(stateDb, promotedMatch.hypothesis_ref)?.promoted_at != null) {
620
+ appendEvent({
621
+ eventType: "recombine_invoked",
622
+ ref: promotedMatch.hypothesis_ref,
623
+ metadata: {
624
+ signal: cluster.signature,
625
+ memberCount: cluster.members.length,
626
+ outcome: "skipped_promoted",
627
+ sourceRun,
628
+ },
629
+ }, opts.ctx);
630
+ continue;
631
+ }
632
+ }
633
+ const prompt = buildClusterPrompt(cluster, standardsContext);
634
+ const raw = await llmFn(prompt);
635
+ const generalization = parseGeneralization(raw);
636
+ if (!generalization) {
637
+ nullsReturned += 1;
638
+ appendEvent({
639
+ eventType: "recombine_invoked",
640
+ ref: deriveRecombineLessonRef(cluster),
641
+ metadata: {
642
+ signal: cluster.signature,
643
+ memberCount: cluster.members.length,
644
+ outcome: "null_returned",
645
+ sourceRun,
646
+ },
647
+ }, opts.ctx);
648
+ continue;
649
+ }
650
+ // #633 — the confirmation identity is decoupled from the EXACT member
651
+ // set. We first look for an existing pending hypothesis row under the
652
+ // SAME signature whose membership overlaps this cluster (Jaccard >=
653
+ // threshold) and, if found, REUSE that row's stable ref so a
654
+ // drifting-but-overlapping cluster keeps accumulating its streak under one
655
+ // row instead of spawning a fresh row (count=1) every run. With no match
656
+ // (first induction, or membership drifted past the overlap floor) we fall
657
+ // back to the deterministic member-set ref exactly as before.
658
+ const memberKey = recombineMemberKey(cluster);
659
+ const derivedRef = deriveRecombineLessonRef(cluster);
660
+ const matchedRow = stateDb
661
+ ? findMatchingRecombineHypothesis(stateDb, {
662
+ signature: cluster.signature,
663
+ memberKey,
664
+ minOverlap: DEFAULT_RECOMBINE_OVERLAP,
665
+ })
666
+ : undefined;
667
+ const lessonRef = matchedRow?.hypothesis_ref ?? derivedRef;
668
+ const sourceRefs = cluster.members.map((m) => `memory:${m.entry.name}`);
669
+ const priorRow = stateDb ? getRecombineHypothesis(stateDb, lessonRef) : undefined;
670
+ const alreadyPromoted = priorRow?.promoted_at != null;
671
+ const nextCount = stateDb == null
672
+ ? 0
673
+ : priorRow == null
674
+ ? 1
675
+ : priorRow.last_run === sourceRun
676
+ ? priorRow.consecutive_count
677
+ : priorRow.consecutive_count + 1;
678
+ // Quality gate (always-run): the frontmatter description must be present
679
+ // and non-truncated. Promotion adds the full lesson frontmatter check so
680
+ // `when_to_use` never bypasses validation on the promote=true path.
681
+ const fmCheck = validateProposalFrontmatter({ description: generalization.description });
682
+ if (!fmCheck.ok) {
683
+ appendEvent({
684
+ eventType: "recombine_invoked",
685
+ ref: lessonRef,
686
+ metadata: {
687
+ signal: cluster.signature,
688
+ memberCount: cluster.members.length,
689
+ outcome: "quality_rejected",
690
+ reason: fmCheck.reason,
691
+ sourceRun,
692
+ },
693
+ }, opts.ctx);
694
+ continue;
695
+ }
696
+ const promote = stateDb != null && !alreadyPromoted && nextCount >= confirmThreshold;
697
+ if (promote) {
698
+ const lessonFmCheck = validatePromotedLessonFrontmatter(lessonRef, {
699
+ description: generalization.description,
700
+ when_to_use: generalization.when_to_use,
701
+ });
702
+ if (!lessonFmCheck.ok) {
703
+ appendEvent({
704
+ eventType: "recombine_invoked",
705
+ ref: lessonRef,
706
+ metadata: {
707
+ signal: cluster.signature,
708
+ memberCount: cluster.members.length,
709
+ outcome: "quality_rejected",
710
+ reason: lessonFmCheck.reason,
711
+ sourceRun,
712
+ },
713
+ }, opts.ctx);
714
+ continue;
715
+ }
716
+ }
717
+ // A defensible generalization was produced this run — record it so it is
718
+ // NOT decayed by the unseen sweep below.
719
+ seenThisRun.add(lessonRef);
720
+ // #625/#633 — record the re-induction only AFTER the quality gate passed.
721
+ // Quality-rejected outputs must not advance the confirmation streak.
722
+ const count = stateDb
723
+ ? recordRecombineInduction(stateDb, {
724
+ hypothesisRef: lessonRef,
725
+ signature: cluster.signature,
726
+ memberKey,
727
+ seenAt: new Date().toISOString(),
728
+ run: sourceRun,
729
+ })
730
+ : 0;
731
+ // Promote to a `type: lesson` proposal when the confirmation streak
732
+ // reaches the threshold AND the hypothesis has not already been promoted.
733
+ const proposalType = promote ? "lesson" : "hypothesis";
734
+ const frontmatter = {
735
+ type: proposalType,
736
+ description: generalization.description,
737
+ ...(generalization.when_to_use ? { when_to_use: generalization.when_to_use } : {}),
738
+ source_refs: sourceRefs,
739
+ };
740
+ const content = assembleContent(frontmatter, generalization.body);
741
+ if (promote && stateDb) {
742
+ // Supersede the prior pending `type: hypothesis` proposal for this ref so
743
+ // the queue never shows two proposals for one ref. The promoted lesson
744
+ // proposal has different content (type changed), so content-hash dedup
745
+ // would otherwise let both co-exist.
746
+ for (const stale of listProposals(stashDir, { status: "pending", ref: lessonRef }, opts.ctx)) {
747
+ if (stale.source === "recombine") {
748
+ archiveProposal(stashDir, stale.id, "rejected", "superseded by recombine lesson promotion", opts.ctx);
749
+ }
750
+ }
751
+ }
752
+ const proposalResult = createProposal(stashDir, {
753
+ ref: lessonRef,
754
+ source: "recombine",
755
+ sourceRun,
756
+ payload: { content, frontmatter },
757
+ eligibilitySource,
758
+ // The promotion is a distinct asset (lesson) for the same ref; force
759
+ // past the duplicate-pending guard (the stale hypothesis was just
760
+ // superseded, but force keeps the path robust to ordering).
761
+ ...(promote ? { force: true } : {}),
762
+ }, opts.ctx);
763
+ if (isProposalSkipped(proposalResult)) {
764
+ appendEvent({
765
+ eventType: "recombine_invoked",
766
+ ref: lessonRef,
767
+ metadata: {
768
+ signal: cluster.signature,
769
+ memberCount: cluster.members.length,
770
+ outcome: "skipped",
771
+ skipReason: proposalResult.reason,
772
+ sourceRun,
773
+ },
774
+ }, opts.ctx);
775
+ continue;
776
+ }
777
+ if (promote && stateDb) {
778
+ markRecombineHypothesisPromoted(stateDb, lessonRef, new Date().toISOString());
779
+ lessonsPromoted += 1;
780
+ appendEvent({
781
+ eventType: "recombine_invoked",
782
+ ref: lessonRef,
783
+ metadata: {
784
+ signal: cluster.signature,
785
+ memberCount: cluster.members.length,
786
+ outcome: "promoted",
787
+ proposalId: proposalResult.id,
788
+ confirmationCount: count,
789
+ sourceRun,
790
+ },
791
+ }, opts.ctx);
792
+ }
793
+ else {
794
+ proposalsEmitted += 1;
795
+ appendEvent({
796
+ eventType: "recombine_invoked",
797
+ ref: lessonRef,
798
+ metadata: {
799
+ signal: cluster.signature,
800
+ memberCount: cluster.members.length,
801
+ outcome: "queued",
802
+ proposalId: proposalResult.id,
803
+ confirmationCount: count,
804
+ sourceRun,
805
+ },
806
+ }, opts.ctx);
807
+ }
808
+ }
809
+ // #625 — decay hypotheses NOT re-induced this run (reset their consecutive
810
+ // streak) so confirmation is per-consecutive-run and conservative (AC4).
811
+ // #658 — but a hypothesis whose cluster genuinely re-formed this run and was
812
+ // merely cap-displaced (outside the top-`maxClustersPerRun` slice) must NOT
813
+ // be decayed — that is a scheduling miss, not a substance miss. We pass
814
+ // EVERY cluster that formed this run (the full pre-cap `rankedClusters`) as
815
+ // `presentClusters`; decay spares any row that Jaccard-matches a present
816
+ // cluster under the SAME overlap rule used for re-induction. Only rows with
817
+ // no matching current cluster (the corpus stopped supporting them) decay.
818
+ if (stateDb) {
819
+ const presentClusters = rankedClusters.map((c) => ({
820
+ signature: c.signature,
821
+ memberKey: recombineMemberKey(c),
822
+ }));
823
+ const decayedCount = decayUnseenRecombineHypotheses(stateDb, sourceRun, [...seenThisRun], {
824
+ presentClusters,
825
+ minOverlap: DEFAULT_RECOMBINE_OVERLAP,
826
+ });
827
+ if (decayedCount > 0) {
828
+ appendEvent({
829
+ eventType: "recombine_invoked",
830
+ metadata: { outcome: "decayed", decayedCount, sourceRun },
831
+ }, opts.ctx);
832
+ }
833
+ }
834
+ }, { path: opts.ctx?.dbPath, borrowed: opts.ctx?.db });
835
+ return finish({ clustersFormed, proposalsEmitted, lessonsPromoted, nullsReturned });
836
+ }
837
+ /** Serialize frontmatter + body into a markdown asset string. */
838
+ function assembleContent(frontmatter, body) {
839
+ const lines = ["---"];
840
+ for (const [key, value] of Object.entries(frontmatter)) {
841
+ if (Array.isArray(value)) {
842
+ lines.push(`${key}: [${value.map((v) => JSON.stringify(v)).join(", ")}]`);
843
+ }
844
+ else {
845
+ lines.push(`${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
846
+ }
847
+ }
848
+ lines.push("---", "", body, "");
849
+ return lines.join("\n");
850
+ }