akm-cli 0.9.0-beta.3 → 0.9.0-beta.31

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 (107) hide show
  1. package/CHANGELOG.md +613 -0
  2. package/dist/assets/prompts/consolidate-system.md +23 -0
  3. package/dist/assets/prompts/contradiction-judge.md +33 -0
  4. package/dist/assets/prompts/distill-knowledge-system.md +22 -0
  5. package/dist/assets/prompts/distill-lesson-system.md +36 -0
  6. package/dist/assets/prompts/extract-session.md +5 -1
  7. package/dist/assets/prompts/graph-extract-system.md +1 -0
  8. package/dist/assets/prompts/memory-infer-system.md +1 -0
  9. package/dist/assets/prompts/memory-infer-user.md +5 -0
  10. package/dist/assets/prompts/metadata-enhance-system.md +1 -0
  11. package/dist/assets/prompts/procedural-system.md +44 -0
  12. package/dist/assets/prompts/recombine-system.md +40 -0
  13. package/dist/assets/prompts/staleness-detect-system.md +6 -0
  14. package/dist/assets/prompts/validate-summary-judge.md +1 -0
  15. package/dist/assets/templates/html/health.html +281 -111
  16. package/dist/cli.js +14 -3
  17. package/dist/commands/agent/contribute-cli.js +16 -3
  18. package/dist/commands/feedback-cli.js +15 -6
  19. package/dist/commands/graph/graph.js +75 -71
  20. package/dist/commands/health/checks.js +48 -0
  21. package/dist/commands/health/html-report.js +422 -80
  22. package/dist/commands/health.js +381 -9
  23. package/dist/commands/improve/calibration.js +161 -0
  24. package/dist/commands/improve/consolidate.js +634 -111
  25. package/dist/commands/improve/dedup.js +482 -0
  26. package/dist/commands/improve/distill.js +145 -69
  27. package/dist/commands/improve/encoding-salience.js +205 -0
  28. package/dist/commands/improve/extract-cli.js +115 -1
  29. package/dist/commands/improve/extract-prompt.js +33 -2
  30. package/dist/commands/improve/extract-watch.js +140 -0
  31. package/dist/commands/improve/extract.js +244 -35
  32. package/dist/commands/improve/feedback-valence.js +54 -0
  33. package/dist/commands/improve/homeostatic.js +467 -0
  34. package/dist/commands/improve/improve-auto-accept.js +113 -6
  35. package/dist/commands/improve/improve-profiles.js +12 -0
  36. package/dist/commands/improve/improve.js +1974 -614
  37. package/dist/commands/improve/memory/memory-contradiction-detect.js +23 -28
  38. package/dist/commands/improve/outcome-loop.js +256 -0
  39. package/dist/commands/improve/proactive-maintenance.js +87 -0
  40. package/dist/commands/improve/procedural.js +409 -0
  41. package/dist/commands/improve/recombine.js +593 -0
  42. package/dist/commands/improve/reflect.js +26 -1
  43. package/dist/commands/improve/related-sessions.js +120 -0
  44. package/dist/commands/improve/salience.js +386 -0
  45. package/dist/commands/improve/triage.js +95 -0
  46. package/dist/commands/lint/agent-linter.js +19 -24
  47. package/dist/commands/lint/base-linter.js +173 -60
  48. package/dist/commands/lint/command-linter.js +19 -24
  49. package/dist/commands/lint/env-key-rules.js +34 -1
  50. package/dist/commands/lint/fact-linter.js +39 -0
  51. package/dist/commands/lint/index.js +31 -13
  52. package/dist/commands/lint/memory-linter.js +1 -1
  53. package/dist/commands/lint/registry.js +7 -2
  54. package/dist/commands/lint/task-linter.js +3 -3
  55. package/dist/commands/lint/workflow-linter.js +26 -1
  56. package/dist/commands/proposal/proposal.js +5 -0
  57. package/dist/commands/proposal/validators/proposals.js +71 -54
  58. package/dist/commands/read/curate.js +344 -80
  59. package/dist/commands/read/search-cli.js +7 -0
  60. package/dist/commands/read/search.js +1 -0
  61. package/dist/commands/read/show.js +67 -2
  62. package/dist/commands/sources/installed-stashes.js +5 -1
  63. package/dist/commands/sources/stash-cli.js +10 -2
  64. package/dist/core/asset/asset-registry.js +2 -0
  65. package/dist/core/asset/asset-spec.js +14 -0
  66. package/dist/core/asset/frontmatter.js +166 -167
  67. package/dist/core/asset/markdown.js +8 -0
  68. package/dist/core/config/config-schema.js +259 -2
  69. package/dist/core/config/config.js +2 -2
  70. package/dist/core/logs-db.js +4 -3
  71. package/dist/core/paths.js +3 -0
  72. package/dist/core/state-db.js +649 -30
  73. package/dist/indexer/db/db.js +364 -38
  74. package/dist/indexer/db/graph-db.js +129 -86
  75. package/dist/indexer/ensure-index.js +152 -17
  76. package/dist/indexer/graph/graph-boost.js +51 -41
  77. package/dist/indexer/graph/graph-extraction.js +203 -3
  78. package/dist/indexer/index-writer-lock.js +99 -0
  79. package/dist/indexer/indexer.js +114 -111
  80. package/dist/indexer/passes/memory-inference.js +10 -3
  81. package/dist/indexer/passes/staleness-detect.js +2 -5
  82. package/dist/indexer/search/db-search.js +15 -4
  83. package/dist/indexer/search/ranking-contributors.js +22 -0
  84. package/dist/indexer/search/ranking.js +4 -0
  85. package/dist/indexer/walk/matchers.js +9 -0
  86. package/dist/integrations/agent/prompts.js +1 -0
  87. package/dist/integrations/harnesses/claude/session-log.js +11 -1
  88. package/dist/integrations/harnesses/opencode/session-log.js +9 -0
  89. package/dist/integrations/session-logs/index.js +16 -0
  90. package/dist/llm/client.js +23 -4
  91. package/dist/llm/embedder.js +27 -3
  92. package/dist/llm/embedders/local.js +66 -2
  93. package/dist/llm/graph-extract.js +2 -1
  94. package/dist/llm/memory-infer.js +4 -8
  95. package/dist/llm/metadata-enhance.js +9 -1
  96. package/dist/output/renderers.js +73 -1
  97. package/dist/output/shapes/curate.js +14 -2
  98. package/dist/output/text/helpers.js +9 -0
  99. package/dist/runtime.js +25 -1
  100. package/dist/scripts/migrate-storage.js +1242 -594
  101. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +473 -270
  102. package/dist/sources/providers/tar-utils.js +16 -8
  103. package/dist/storage/sqlite-pragmas.js +146 -0
  104. package/dist/workflows/db.js +3 -4
  105. package/dist/workflows/validate-summary.js +2 -7
  106. package/docs/data-and-telemetry.md +1 -0
  107. package/package.json +9 -6
@@ -0,0 +1,593 @@
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 { decayUnseenRecombineHypotheses, findMatchingRecombineHypothesis, getRecombineHypothesis, getStateDbPath, markRecombineHypothesisPromoted, openStateDatabase, recordRecombineInduction, } from "../../core/state-db.js";
49
+ import { warn } from "../../core/warn.js";
50
+ import { closeDatabase, getAllEntries, getEntitiesByEntryIds, openExistingDatabase, } from "../../indexer/db/db.js";
51
+ import { resolveImproveProcessRunnerFromProfile, runnerIsLlm } from "../../integrations/agent/runner.js";
52
+ import { chatCompletion } from "../../llm/client.js";
53
+ import { validateProposalFrontmatter } from "../proposal/validators/proposal-quality-validators.js";
54
+ import { archiveProposal, createProposal, isProposalSkipped, listProposals } from "../proposal/validators/proposals.js";
55
+ import { isConsolidationEligibleMemoryName } from "./consolidate.js";
56
+ const RECOMBINE_SYSTEM_PROMPT = recombineSystemPrompt;
57
+ const DEFAULT_MIN_CLUSTER_SIZE = 3;
58
+ const DEFAULT_MAX_CLUSTERS_PER_RUN = 5;
59
+ const DEFAULT_RELATEDNESS_SOURCE = "tags";
60
+ /** #625 — re-induction count required before a hypothesis promotes to a lesson. */
61
+ const DEFAULT_CONFIRM_THRESHOLD = 2;
62
+ /**
63
+ * #633 — Jaccard membership-overlap threshold for matching a freshly-induced
64
+ * hypothesis to an existing pending row under the SAME signature. A growing
65
+ * stash drifts the exact member set every run; an overlap >= this lets the
66
+ * confirmation streak keep accumulating under one row instead of resetting to 1.
67
+ */
68
+ const DEFAULT_RECOMBINE_OVERLAP = 0.7;
69
+ // ── Clustering by relatedness (NOT similarity) ────────────────────────────────
70
+ /**
71
+ * #632 — English stopwords that occasionally leak into frontmatter tags
72
+ * (`is`, `the`, `for`, …). They carry no topical signal, so a cluster keyed on
73
+ * one is meaningless. Lowercased; matched case-insensitively.
74
+ */
75
+ const JUNK_STOPWORD_TAGS = new Set([
76
+ "a",
77
+ "an",
78
+ "and",
79
+ "the",
80
+ "to",
81
+ "of",
82
+ "in",
83
+ "on",
84
+ "for",
85
+ "is",
86
+ "are",
87
+ "be",
88
+ "no",
89
+ "not",
90
+ "or",
91
+ "if",
92
+ "it",
93
+ "as",
94
+ "at",
95
+ "by",
96
+ "we",
97
+ "us",
98
+ "do",
99
+ "so",
100
+ "when",
101
+ "then",
102
+ "than",
103
+ "with",
104
+ "from",
105
+ "this",
106
+ "that",
107
+ "uses",
108
+ "use",
109
+ "via",
110
+ ]);
111
+ /**
112
+ * #632 — a tag carries no clustering signal (and must be skipped) when it is
113
+ * purely a number / date / hash / version string, a single char, or a common
114
+ * stopword. Unlike `excludeTags` (a fixed project list), this catches the
115
+ * OPEN-ENDED junk — every new date or commit hash — without config upkeep.
116
+ */
117
+ export function isJunkTag(tag) {
118
+ const t = tag.trim().toLowerCase();
119
+ if (t.length <= 1)
120
+ return true;
121
+ if (JUNK_STOPWORD_TAGS.has(t))
122
+ return true;
123
+ if (/^\d+$/.test(t))
124
+ return true; // pure numbers + dates: 2026, 05, 23, 20260529
125
+ if (/^v?\d+(?:\.\d+)+$/.test(t))
126
+ return true; // versions: 0.8.0, v1.2
127
+ if (/^v\d+$/.test(t))
128
+ return true; // v0, v2
129
+ if (/^[0-9a-f]{4,}$/.test(t) && /\d/.test(t))
130
+ return true; // short hex hashes: 002c624c, 192d
131
+ return false;
132
+ }
133
+ /**
134
+ * Build relatedness clusters from the memory pool. Clustering is driven purely
135
+ * by shared tags / graph entities — it MUST NOT use embedding similarity, so
136
+ * textually near-identical memories that share no relatedness signal never
137
+ * cluster together.
138
+ *
139
+ * For `relatednessSource`:
140
+ * - `"tags"` — group by each frontmatter tag.
141
+ * - `"graph"` — group by shared `graph_file_entities.entity_norm`; falls back
142
+ * to tags when the graph table is empty (fail-open).
143
+ * - `"both"` — union of the tag and entity grouping keys.
144
+ *
145
+ * A cluster is a signal whose member set is >= `minClusterSize`. Overlapping
146
+ * clusters are de-duplicated by member-set identity, and the result is capped
147
+ * to `maxClustersPerRun` by member-count descending.
148
+ */
149
+ export function buildRelatednessClusters(entries, opts) {
150
+ // Only consolidation-eligible memories participate (exclude `.derived`).
151
+ const memories = entries.filter((e) => e.entry.type === "memory" && isConsolidationEligibleMemoryName(e.entry.name));
152
+ // signal -> member entries
153
+ const groups = new Map();
154
+ const add = (signal, entry) => {
155
+ const key = signal.trim();
156
+ if (!key)
157
+ return;
158
+ const list = groups.get(key);
159
+ if (list) {
160
+ if (!list.includes(entry))
161
+ list.push(entry);
162
+ }
163
+ else {
164
+ groups.set(key, [entry]);
165
+ }
166
+ };
167
+ const useTags = opts.relatednessSource === "tags" || opts.relatednessSource === "both";
168
+ // Graph relatedness falls open to tags when no entities are available.
169
+ const hasEntities = !!opts.entityByEntryId && opts.entityByEntryId.size > 0;
170
+ const useGraph = (opts.relatednessSource === "graph" || opts.relatednessSource === "both") && hasEntities;
171
+ const tagsFallback = !useTags && opts.relatednessSource === "graph" && !hasEntities;
172
+ // #632 — tags excluded from tag-based clustering (applies regardless of
173
+ // source). UNSET/[] leaves clustering byte-identical to the pre-#632 path.
174
+ const excludeTags = new Set(opts.excludeTags ?? []);
175
+ for (const entry of memories) {
176
+ if (useTags || tagsFallback) {
177
+ for (const tag of entry.entry.tags ?? []) {
178
+ if (excludeTags.has(tag))
179
+ continue;
180
+ if (isJunkTag(tag))
181
+ continue; // #632 — skip numeric/date/hash/version/stopword junk
182
+ add(`tag:${tag}`, entry);
183
+ }
184
+ }
185
+ if (useGraph && opts.entityByEntryId) {
186
+ for (const ent of opts.entityByEntryId.get(entry.id) ?? [])
187
+ add(`entity:${ent}`, entry);
188
+ }
189
+ }
190
+ // Keep only groups at or above the minimum cluster size. #632 — when
191
+ // maxClusterSize is set, also SKIP groups strictly larger than the cap so an
192
+ // over-broad bucket never reaches (and starves) the largest-first slice.
193
+ // UNSET = no upper bound = identical to the pre-#632 behaviour.
194
+ let clusters = [];
195
+ for (const [signature, members] of groups) {
196
+ if (members.length < opts.minClusterSize)
197
+ continue;
198
+ if (opts.maxClusterSize != null && members.length > opts.maxClusterSize)
199
+ continue;
200
+ clusters.push({ signature, members });
201
+ }
202
+ // De-duplicate clusters that share the exact same member set (e.g. a tag and
203
+ // an entity that co-occur on the same trio). Keep the first by signature.
204
+ const seenMemberKeys = new Set();
205
+ clusters = clusters.filter((c) => {
206
+ const memberKey = c.members
207
+ .map((m) => m.id)
208
+ .sort((a, b) => a - b)
209
+ .join(",");
210
+ if (seenMemberKeys.has(memberKey))
211
+ return false;
212
+ seenMemberKeys.add(memberKey);
213
+ return true;
214
+ });
215
+ // Cap to maxClustersPerRun, largest clusters first (deterministic tiebreak).
216
+ clusters.sort((a, b) => b.members.length - a.members.length || a.signature.localeCompare(b.signature));
217
+ return clusters.slice(0, Math.max(0, opts.maxClustersPerRun));
218
+ }
219
+ // ── Prompt + ref derivation ───────────────────────────────────────────────────
220
+ /** Read a memory body (frontmatter stripped) for the cluster prompt. */
221
+ function readBody(entry) {
222
+ try {
223
+ const raw = fs.readFileSync(entry.filePath, "utf8");
224
+ return parseFrontmatter(raw).content.trim();
225
+ }
226
+ catch {
227
+ return "";
228
+ }
229
+ }
230
+ /** Assemble the per-cluster user prompt fed to the recombine LLM. */
231
+ export function buildClusterPrompt(cluster) {
232
+ const lines = [
233
+ `Shared signal: ${cluster.signature}`,
234
+ `Cluster of ${cluster.members.length} related memories:`,
235
+ "",
236
+ ];
237
+ for (const m of cluster.members) {
238
+ lines.push(`[memory:${m.entry.name}]`);
239
+ if (m.entry.description)
240
+ lines.push(`Description: ${m.entry.description}`);
241
+ const body = readBody(m);
242
+ if (body)
243
+ lines.push(body);
244
+ lines.push("");
245
+ }
246
+ lines.push("Induce ONE cross-episodic generalization these memories support, or return an explicit null if none is defensible.");
247
+ return lines.join("\n");
248
+ }
249
+ /**
250
+ * Stable lesson ref for a cluster. The hash of the sorted member refs keeps the
251
+ * ref deterministic across runs (so re-induction maps to the same ref + the
252
+ * content-hash dedup in createProposal suppresses queue churn).
253
+ */
254
+ export function deriveRecombineLessonRef(cluster) {
255
+ const slug = cluster.signature
256
+ .replace(/^(tag|entity):/, "")
257
+ .toLowerCase()
258
+ .replace(/[^a-z0-9-]+/g, "-")
259
+ .replace(/-+/g, "-")
260
+ .replace(/^-|-$/g, "");
261
+ const memberKey = recombineMemberKey(cluster);
262
+ const hash = createHash("sha256").update(memberKey, "utf8").digest("hex").slice(0, 8);
263
+ return `lesson:recombined/${slug || "cluster"}-${hash}`;
264
+ }
265
+ /**
266
+ * The membership fingerprint of a cluster: its member entryKeys sorted and
267
+ * joined. Single source of truth shared by {@link deriveRecombineLessonRef}'s
268
+ * hash and the `recombine_hypotheses.member_key` column, so the table key and
269
+ * the ref hash always derive from the SAME member set. Adding/removing one
270
+ * memory yields a different fingerprint → a different ref → a fresh row (the
271
+ * old streak is correctly NOT inherited).
272
+ */
273
+ export function recombineMemberKey(cluster) {
274
+ return cluster.members
275
+ .map((m) => m.entryKey)
276
+ .sort()
277
+ .join("|");
278
+ }
279
+ /** Parse the raw LLM output into a generalization, or `null` for the justified-null path. */
280
+ function parseGeneralization(raw) {
281
+ if (raw === null)
282
+ return null;
283
+ const trimmed = raw.trim();
284
+ if (!trimmed || trimmed.toLowerCase() === "null")
285
+ return null;
286
+ const parsed = parseEmbeddedJsonResponse(trimmed);
287
+ if (parsed === undefined || parsed === null)
288
+ return null;
289
+ if (typeof parsed !== "object")
290
+ return null;
291
+ const obj = parsed;
292
+ const description = typeof obj.description === "string" ? obj.description : "";
293
+ const body = typeof obj.body === "string" ? obj.body : "";
294
+ const when_to_use = typeof obj.when_to_use === "string" ? obj.when_to_use : undefined;
295
+ // An empty object / all-empty fields is treated as a justified null.
296
+ if (!description && !body)
297
+ return null;
298
+ return { description, body, ...(when_to_use ? { when_to_use } : {}) };
299
+ }
300
+ /**
301
+ * Resolve the production LLM seam from the active improve profile. Returns a
302
+ * `RecombineLlmFn` that issues one bounded chatCompletion per call, or
303
+ * `undefined` when no LLM is configured (the pass then makes no calls).
304
+ */
305
+ function resolveProductionLlmFn(config, signal) {
306
+ const recombineProcess = config.profiles?.improve?.default?.processes?.recombine;
307
+ const runnerSpec = resolveImproveProcessRunnerFromProfile(recombineProcess, config);
308
+ const llmConfig = runnerSpec && runnerIsLlm(runnerSpec) ? runnerSpec.connection : getDefaultLlmConfig(config);
309
+ if (!llmConfig)
310
+ return undefined;
311
+ return async (clusterPrompt) => {
312
+ const messages = [
313
+ { role: "system", content: RECOMBINE_SYSTEM_PROMPT },
314
+ { role: "user", content: clusterPrompt },
315
+ ];
316
+ try {
317
+ return await chatCompletion(llmConfig, messages, { signal, enableThinking: false });
318
+ }
319
+ catch (e) {
320
+ warn(`[recombine] LLM call failed: ${String(e)}`);
321
+ return null;
322
+ }
323
+ };
324
+ }
325
+ // ── Main entry point ───────────────────────────────────────────────────────────
326
+ export async function akmRecombine(opts) {
327
+ const startMs = Date.now();
328
+ const config = opts.config ?? loadConfig();
329
+ const stashDir = opts.stashDir ?? resolveStashDir();
330
+ const sourceRun = opts.sourceRun ?? `recombine-${startMs}`;
331
+ const eligibilitySource = opts.eligibilitySource ?? "recombine";
332
+ const minClusterSize = opts.minClusterSize ?? DEFAULT_MIN_CLUSTER_SIZE;
333
+ const maxClustersPerRun = opts.maxClustersPerRun ?? DEFAULT_MAX_CLUSTERS_PER_RUN;
334
+ const relatednessSource = opts.relatednessSource ?? DEFAULT_RELATEDNESS_SOURCE;
335
+ const confirmThreshold = opts.confirmThreshold ?? DEFAULT_CONFIRM_THRESHOLD;
336
+ const warnings = [];
337
+ const finish = (over) => ({
338
+ schemaVersion: 1,
339
+ ok: true,
340
+ clustersFormed: 0,
341
+ proposalsEmitted: 0,
342
+ lessonsPromoted: 0,
343
+ nullsReturned: 0,
344
+ durationMs: Date.now() - startMs,
345
+ warnings,
346
+ ...over,
347
+ });
348
+ // Budget guard: an already-aborted signal short-circuits before any LLM call.
349
+ if (opts.signal?.aborted) {
350
+ return finish({ ok: false, warnings: [...warnings, "aborted-before-start"] });
351
+ }
352
+ // Load the memory pool + (optionally) graph entities from the index.
353
+ let entries = [];
354
+ let entityByEntryId;
355
+ let db;
356
+ try {
357
+ db = openExistingDatabase();
358
+ entries = getAllEntries(db, "memory");
359
+ if (relatednessSource === "graph" || relatednessSource === "both") {
360
+ try {
361
+ entityByEntryId = getEntitiesByEntryIds(db, entries.map((e) => e.id));
362
+ }
363
+ catch {
364
+ // Fail open to tag relatedness.
365
+ entityByEntryId = undefined;
366
+ }
367
+ }
368
+ }
369
+ catch (e) {
370
+ warnings.push(`recombine: failed to open index — ${String(e)}`);
371
+ return finish({ ok: false });
372
+ }
373
+ finally {
374
+ if (db)
375
+ closeDatabase(db);
376
+ }
377
+ const clusters = buildRelatednessClusters(entries, {
378
+ minClusterSize,
379
+ maxClustersPerRun,
380
+ relatednessSource,
381
+ ...(entityByEntryId ? { entityByEntryId } : {}),
382
+ ...(opts.maxClusterSize != null ? { maxClusterSize: opts.maxClusterSize } : {}),
383
+ ...(opts.excludeTags ? { excludeTags: opts.excludeTags } : {}),
384
+ });
385
+ let clustersFormed = 0;
386
+ let proposalsEmitted = 0;
387
+ let lessonsPromoted = 0;
388
+ let nullsReturned = 0;
389
+ const llmFn = opts.recombineLlmFn ?? resolveProductionLlmFn(config, opts.signal);
390
+ if (!llmFn) {
391
+ warnings.push("recombine: no LLM configured — skipping");
392
+ return finish({ clustersFormed: 0 });
393
+ }
394
+ // #625 — open the confirmation-count store once per run via the ctx seam,
395
+ // reusing a long-lived ctx.db handle when the caller provided one (mirrors
396
+ // proposals.ts). Only handles WE opened are closed in the finally below.
397
+ const ownStateDb = opts.ctx?.db ? undefined : openStateDatabase(opts.ctx?.dbPath ?? getStateDbPath());
398
+ const stateDb = opts.ctx?.db ?? ownStateDb;
399
+ // Refs re-induced (defensible generalization passed the quality gate) THIS
400
+ // run — everything else is decayed after the loop.
401
+ const seenThisRun = new Set();
402
+ try {
403
+ for (const cluster of clusters) {
404
+ if (opts.signal?.aborted) {
405
+ warnings.push("aborted-mid-run");
406
+ break;
407
+ }
408
+ clustersFormed += 1;
409
+ const prompt = buildClusterPrompt(cluster);
410
+ const raw = await llmFn(prompt);
411
+ const generalization = parseGeneralization(raw);
412
+ if (!generalization) {
413
+ nullsReturned += 1;
414
+ appendEvent({
415
+ eventType: "recombine_invoked",
416
+ ref: deriveRecombineLessonRef(cluster),
417
+ metadata: {
418
+ signal: cluster.signature,
419
+ memberCount: cluster.members.length,
420
+ outcome: "null_returned",
421
+ sourceRun,
422
+ },
423
+ }, opts.ctx);
424
+ continue;
425
+ }
426
+ // #633 — the confirmation identity is decoupled from the EXACT member
427
+ // set. We first look for an existing pending hypothesis row under the
428
+ // SAME signature whose membership overlaps this cluster (Jaccard >=
429
+ // threshold) and, if found, REUSE that row's stable ref so a
430
+ // drifting-but-overlapping cluster keeps accumulating its streak under one
431
+ // row instead of spawning a fresh row (count=1) every run. With no match
432
+ // (first induction, or membership drifted past the overlap floor) we fall
433
+ // back to the deterministic member-set ref exactly as before.
434
+ const memberKey = recombineMemberKey(cluster);
435
+ const derivedRef = deriveRecombineLessonRef(cluster);
436
+ const matchedRow = stateDb
437
+ ? findMatchingRecombineHypothesis(stateDb, {
438
+ signature: cluster.signature,
439
+ memberKey,
440
+ minOverlap: DEFAULT_RECOMBINE_OVERLAP,
441
+ })
442
+ : undefined;
443
+ const lessonRef = matchedRow?.hypothesis_ref ?? derivedRef;
444
+ const sourceRefs = cluster.members.map((m) => `memory:${m.entry.name}`);
445
+ // Quality gate (always-run): the frontmatter description must be present
446
+ // and non-truncated. This runs BEFORE createProposal on BOTH the
447
+ // hypothesis and the promotion paths — never bypassed.
448
+ const fmCheck = validateProposalFrontmatter({ description: generalization.description });
449
+ if (!fmCheck.ok) {
450
+ appendEvent({
451
+ eventType: "recombine_invoked",
452
+ ref: lessonRef,
453
+ metadata: {
454
+ signal: cluster.signature,
455
+ memberCount: cluster.members.length,
456
+ outcome: "quality_rejected",
457
+ reason: fmCheck.reason,
458
+ sourceRun,
459
+ },
460
+ }, opts.ctx);
461
+ continue;
462
+ }
463
+ // A defensible generalization was produced this run — record it so it is
464
+ // NOT decayed by the unseen sweep below.
465
+ seenThisRun.add(lessonRef);
466
+ // #625/#633 — record the re-induction and read the prior promotion state.
467
+ // `lessonRef` is the matched row's ref (overlap match) or the freshly
468
+ // derived member-set ref (first/non-overlapping induction). The induction
469
+ // refreshes the row's `member_key` to the current membership so the
470
+ // overlap window slides with the drifting cluster.
471
+ const nowIso = new Date().toISOString();
472
+ const priorRow = stateDb ? getRecombineHypothesis(stateDb, lessonRef) : undefined;
473
+ const alreadyPromoted = priorRow?.promoted_at != null;
474
+ const count = stateDb
475
+ ? recordRecombineInduction(stateDb, {
476
+ hypothesisRef: lessonRef,
477
+ signature: cluster.signature,
478
+ memberKey,
479
+ seenAt: nowIso,
480
+ run: sourceRun,
481
+ })
482
+ : 0;
483
+ // Promote to a `type: lesson` proposal when the confirmation streak
484
+ // reaches the threshold AND the hypothesis has not already been promoted.
485
+ const promote = stateDb != null && !alreadyPromoted && count >= confirmThreshold;
486
+ const proposalType = promote ? "lesson" : "hypothesis";
487
+ const frontmatter = {
488
+ type: proposalType,
489
+ description: generalization.description,
490
+ ...(generalization.when_to_use ? { when_to_use: generalization.when_to_use } : {}),
491
+ source_refs: sourceRefs,
492
+ };
493
+ const content = assembleContent(frontmatter, generalization.body);
494
+ if (promote && stateDb) {
495
+ // Supersede the prior pending `type: hypothesis` proposal for this ref so
496
+ // the queue never shows two proposals for one ref. The promoted lesson
497
+ // proposal has different content (type changed), so content-hash dedup
498
+ // would otherwise let both co-exist.
499
+ for (const stale of listProposals(stashDir, { status: "pending", ref: lessonRef }, opts.ctx)) {
500
+ if (stale.source === "recombine") {
501
+ archiveProposal(stashDir, stale.id, "rejected", "superseded by recombine lesson promotion", opts.ctx);
502
+ }
503
+ }
504
+ }
505
+ const proposalResult = createProposal(stashDir, {
506
+ ref: lessonRef,
507
+ source: "recombine",
508
+ sourceRun,
509
+ payload: { content, frontmatter: { description: generalization.description } },
510
+ eligibilitySource,
511
+ // The promotion is a distinct asset (lesson) for the same ref; force
512
+ // past the duplicate-pending guard (the stale hypothesis was just
513
+ // superseded, but force keeps the path robust to ordering).
514
+ ...(promote ? { force: true } : {}),
515
+ }, opts.ctx);
516
+ if (isProposalSkipped(proposalResult)) {
517
+ appendEvent({
518
+ eventType: "recombine_invoked",
519
+ ref: lessonRef,
520
+ metadata: {
521
+ signal: cluster.signature,
522
+ memberCount: cluster.members.length,
523
+ outcome: "skipped",
524
+ skipReason: proposalResult.reason,
525
+ sourceRun,
526
+ },
527
+ }, opts.ctx);
528
+ continue;
529
+ }
530
+ if (promote && stateDb) {
531
+ markRecombineHypothesisPromoted(stateDb, lessonRef, nowIso);
532
+ lessonsPromoted += 1;
533
+ appendEvent({
534
+ eventType: "recombine_invoked",
535
+ ref: lessonRef,
536
+ metadata: {
537
+ signal: cluster.signature,
538
+ memberCount: cluster.members.length,
539
+ outcome: "promoted",
540
+ proposalId: proposalResult.id,
541
+ confirmationCount: count,
542
+ sourceRun,
543
+ },
544
+ }, opts.ctx);
545
+ }
546
+ else {
547
+ proposalsEmitted += 1;
548
+ appendEvent({
549
+ eventType: "recombine_invoked",
550
+ ref: lessonRef,
551
+ metadata: {
552
+ signal: cluster.signature,
553
+ memberCount: cluster.members.length,
554
+ outcome: "queued",
555
+ proposalId: proposalResult.id,
556
+ confirmationCount: count,
557
+ sourceRun,
558
+ },
559
+ }, opts.ctx);
560
+ }
561
+ }
562
+ // #625 — decay hypotheses NOT re-induced this run (reset their consecutive
563
+ // streak) so confirmation is per-consecutive-run and conservative (AC4).
564
+ if (stateDb) {
565
+ const decayedCount = decayUnseenRecombineHypotheses(stateDb, sourceRun, [...seenThisRun]);
566
+ if (decayedCount > 0) {
567
+ appendEvent({
568
+ eventType: "recombine_invoked",
569
+ metadata: { outcome: "decayed", decayedCount, sourceRun },
570
+ }, opts.ctx);
571
+ }
572
+ }
573
+ }
574
+ finally {
575
+ if (ownStateDb)
576
+ ownStateDb.close();
577
+ }
578
+ return finish({ clustersFormed, proposalsEmitted, lessonsPromoted, nullsReturned });
579
+ }
580
+ /** Serialize frontmatter + body into a markdown asset string. */
581
+ function assembleContent(frontmatter, body) {
582
+ const lines = ["---"];
583
+ for (const [key, value] of Object.entries(frontmatter)) {
584
+ if (Array.isArray(value)) {
585
+ lines.push(`${key}: [${value.map((v) => JSON.stringify(v)).join(", ")}]`);
586
+ }
587
+ else {
588
+ lines.push(`${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
589
+ }
590
+ }
591
+ lines.push("---", "", body, "");
592
+ return lines.join("\n");
593
+ }
@@ -383,6 +383,25 @@ function splitFrontmatter(raw) {
383
383
  return { fmText: null, body: raw };
384
384
  return { fmText: m[1], body: m[2] };
385
385
  }
386
+ /**
387
+ * Strip an LLM-appended duplicate frontmatter block from a body string.
388
+ *
389
+ * When the LLM echoes the original source file verbatim after its rewrite,
390
+ * the resulting body contains a second `---...---` YAML block. We detect it
391
+ * by requiring BOTH a balanced fence (opening + closing `---`) AND YAML-like
392
+ * `key: value` content inside, so legitimate Markdown thematic breaks and
393
+ * code-fence examples are never truncated.
394
+ */
395
+ function stripAppendedFrontmatter(body) {
396
+ const fencePattern = /\n---\r?\n([\s\S]*?)\n---\r?\n/;
397
+ const match = body.match(fencePattern);
398
+ if (!match)
399
+ return body;
400
+ // Only strip when the captured block looks like YAML frontmatter.
401
+ if (!/^\w[\w-]*:/m.test(match[1]))
402
+ return body;
403
+ return body.slice(0, body.indexOf(match[0])).replace(/\s+$/, "");
404
+ }
386
405
  /**
387
406
  * Reflect post-processor — enforces the safety rails described at the top of
388
407
  * this file:
@@ -449,7 +468,7 @@ function sanitizeReflectPayload(payload, sourceContent, targetRef) {
449
468
  mergedFm[field] = sourceFm[field];
450
469
  }
451
470
  }
452
- const cleanedBody = rawLlmBody.replace(/^\s+/, "");
471
+ const cleanedBody = stripAppendedFrontmatter(rawLlmBody.replace(/^\s+/, ""));
453
472
  // Size guard — only when source body is meaningfully large. The pure
454
473
  // predicate lives in `core/proposal-quality-validators` so the same check
455
474
  // also runs inside `runProposalValidators` on `proposal accept`.
@@ -585,6 +604,9 @@ export async function akmReflect(options = {}) {
585
604
  metadata: {
586
605
  ...(options.task ? { task: options.task } : {}),
587
606
  ...(options.profile ? { profile: options.profile } : {}),
607
+ // Attribution tagging: stamp the eligibility lane so reflect_invoked can be
608
+ // sliced by lane downstream. See EligibilitySource.
609
+ ...(options.eligibilitySource ? { eligibilitySource: options.eligibilitySource } : {}),
588
610
  },
589
611
  });
590
612
  // Fix #3 (observability 0.8.0): every failure path below MUST emit
@@ -1228,6 +1250,9 @@ export async function akmReflect(options = {}) {
1228
1250
  // `parseAgentProposalPayload` already clamps to [0, 1] and drops non-
1229
1251
  // finite values; `createProposal` runs its own sanitizer as a safety net.
1230
1252
  ...(typeof payload.confidence === "number" ? { confidence: payload.confidence } : {}),
1253
+ // Attribution tagging: persist the eligibility lane on the proposal so it
1254
+ // survives to accept/reject/revert time even across runs. See EligibilitySource.
1255
+ ...(options.eligibilitySource ? { eligibilitySource: options.eligibilitySource } : {}),
1231
1256
  };
1232
1257
  const proposalResult = createProposal(stash, createInput, options.ctx);
1233
1258
  if (isProposalSkipped(proposalResult)) {