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,1966 @@
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
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { parseAssetRef } from "../../core/asset/asset-ref.js";
7
+ import { parseFrontmatter } from "../../core/asset/frontmatter.js";
8
+ import { daysToMs } from "../../core/common.js";
9
+ import { getDefaultLlmConfig, loadConfig } from "../../core/config/config.js";
10
+ import { rethrowIfTestIsolationError } from "../../core/errors.js";
11
+ import { appendEvent, readEvents } from "../../core/events.js";
12
+ import { listProposalGateDecisions, listStateProposals, openStateDatabase, persistPhaseThreshold, withStateDb, } from "../../core/state-db.js";
13
+ import { info, warn } from "../../core/warn.js";
14
+ import { closeDatabase, getRetrievalCounts, getZeroResultSearches, openExistingDatabase } from "../../indexer/db/db.js";
15
+ import { countUsageEventsByType } from "../../indexer/usage/usage-events.js";
16
+ import { getAvailableHarnesses } from "../../integrations/session-logs/index.js";
17
+ import { withLlmStage } from "../../llm/usage-telemetry.js";
18
+ import { akmLint } from "../lint/index.js";
19
+ import { getProposal, listProposals } from "../proposal/validators/proposals.js";
20
+ import { runSchemaRepairPass } from "../sources/schema-repair.js";
21
+ import { computeThresholdAutoTune, gateDecisionsToSamples, summarizeCalibration, } from "./calibration.js";
22
+ import { akmConsolidate, isSessionCaptureMemoryName } from "./consolidate.js";
23
+ // Eligibility / candidate-selection predicates live in ./eligibility.
24
+ import { buildLatestFeedbackTsMap, buildLatestProposalTsMap, buildUtilityMap, dedupeRefs, findAssetFilePath, isDistillCandidateRef, isLessonCandidate, isSignalDeltaEligible, } from "./eligibility.js";
25
+ import { akmExtract, countNewExtractCandidates } from "./extract.js";
26
+ import { computeValenceScore, FEEDBACK_WEIGHT, UTILITY_WEIGHT } from "./feedback-valence.js";
27
+ import { makeGateConfig, resolveExtractConfidence, runAutoAcceptGate } from "./improve-auto-accept.js";
28
+ import { resolveProcessEnabled } from "./improve-profiles.js";
29
+ import { applyMemoryCleanup } from "./memory/memory-improve.js";
30
+ import { computeProxyAdequacy, getAllAssetOutcomes, getOutcomeScoresByRef, outcomeScoreToSalience, updateAssetOutcome, } from "./outcome-loop.js";
31
+ import { DEFAULT_DUE_DAYS, DEFAULT_MAX_PER_RUN, selectProactiveMaintenanceRefs } from "./proactive-maintenance.js";
32
+ import { buildRankChangeReport, computeSalience, getAllRankScores, getAssetSalience, getConsecutiveNoOps, getLastUseMsByRef, isContentEncodingRow, SALIENCE_NO_OP_DAMPEN_FACTOR, SALIENCE_NO_OP_DAMPEN_THRESHOLD, upsertAssetSalience, } from "./salience.js";
33
+ // ── improve preparation stage ───────────────────────
34
+ // The pre-loop preparation pipeline (consolidation, session-extract, validation/
35
+ // repair, eligibility partitioning, selectors) extracted from improve.ts.
36
+ /**
37
+ * #612 / WS-4 — bounded, opt-in per-phase auto-accept threshold auto-tune.
38
+ *
39
+ * Reads `improve.calibration` from config. When `autoTune` is enabled, computes
40
+ * the calibration of recent gate decisions, derives a bounded threshold
41
+ * adjustment (clamped into the configured band, capped per step), logs it, and
42
+ * records a `calibration_autotune` event. Returns the new threshold (integer
43
+ * 0-100) when an adjustment was made, or `undefined` to leave the caller's
44
+ * threshold unchanged.
45
+ *
46
+ * WS-4 change: accepts an optional `phase` parameter. When provided, the tuned
47
+ * threshold is persisted to `improve_gate_thresholds` (state.db Migration 012)
48
+ * keyed by phase so `makeGateConfig` can read it back on the next run and each
49
+ * phase maintains its own calibrated threshold rather than a shared global.
50
+ *
51
+ * WS-4 ceiling: `maxThreshold` defaults to 85 (not 100) to prevent the gate
52
+ * converging to pure exploitation and shutting down Gap-3/4 novelty throughput.
53
+ *
54
+ * DEFAULT OFF: with no `improve.calibration` block (or `autoTune: false`) this
55
+ * returns `undefined` immediately, so the gate threshold is unchanged and
56
+ * behaviour is byte-identical to today.
57
+ */
58
+ export function maybeAutoTuneThreshold(currentThreshold, config, stateDbPath, ctx, phase) {
59
+ const cal = config.improve?.calibration;
60
+ if (!cal?.autoTune)
61
+ return undefined;
62
+ // WS-4: default maxThreshold is now 85 (ceiling to prevent pure exploitation).
63
+ // Callers that explicitly set maxThreshold in config override this default.
64
+ const tuneConfig = {
65
+ autoTune: true,
66
+ minThreshold: cal.minThreshold ?? 0,
67
+ maxThreshold: cal.maxThreshold ?? 85,
68
+ maxStep: cal.maxStep ?? 5,
69
+ minSamples: cal.minSamples ?? 20,
70
+ targetAcceptRate: cal.targetAcceptRate ?? 0.9,
71
+ };
72
+ // Defensive: an inverted band disables tuning rather than clamping to nonsense.
73
+ if (tuneConfig.minThreshold > tuneConfig.maxThreshold)
74
+ return undefined;
75
+ const summary = withStateDb((db) => {
76
+ const allDecisions = listProposalGateDecisions(db);
77
+ // WS-4 fix: when called with a phase label, restrict calibration to that
78
+ // phase's decision pool so a reflect-dominated run cannot tighten the
79
+ // consolidate gate (or vice-versa). The gate field is `improve:<phase>`,
80
+ // matching what improve-auto-accept.ts stamps at line ~163.
81
+ const gateLabel = phase ? `improve:${phase}` : undefined;
82
+ const decisions = gateLabel ? allDecisions.filter((d) => d.gate === gateLabel) : allDecisions;
83
+ return summarizeCalibration(gateDecisionsToSamples(decisions));
84
+ }, { path: stateDbPath });
85
+ const result = computeThresholdAutoTune(currentThreshold, summary, tuneConfig);
86
+ if (!result.adjusted)
87
+ return undefined;
88
+ const appendEventFn = ctx?.appendEventFn ?? appendEvent;
89
+ const phaseLabel = phase ?? "global";
90
+ info(`[improve] calibration auto-tune (${phaseLabel}): threshold ${result.previousThreshold} -> ${result.newThreshold} ` +
91
+ `(${result.reason}; samples=${summary.samples}, acceptRate=${summary.overallAcceptRate}, ` +
92
+ `gap=${summary.calibrationGap}, band=[${tuneConfig.minThreshold},${tuneConfig.maxThreshold}])`);
93
+ try {
94
+ appendEventFn({
95
+ eventType: "calibration_autotune",
96
+ ref: "improve:calibration",
97
+ metadata: {
98
+ phase: phaseLabel,
99
+ previousThreshold: result.previousThreshold,
100
+ newThreshold: result.newThreshold,
101
+ delta: result.delta,
102
+ reason: result.reason,
103
+ samples: summary.samples,
104
+ overallAcceptRate: summary.overallAcceptRate,
105
+ calibrationGap: summary.calibrationGap,
106
+ minThreshold: tuneConfig.minThreshold,
107
+ maxThreshold: tuneConfig.maxThreshold,
108
+ },
109
+ });
110
+ }
111
+ catch (err) {
112
+ warn(`[improve] calibration auto-tune event not recorded: ${err instanceof Error ? err.message : String(err)}`);
113
+ }
114
+ // WS-4: Persist the per-phase threshold so makeGateConfig reads it on the
115
+ // next run. Best-effort — a write failure must not abort the improve run.
116
+ if (phase) {
117
+ try {
118
+ withStateDb((persistDb) => persistPhaseThreshold(persistDb, phase, result.newThreshold), {
119
+ path: stateDbPath,
120
+ });
121
+ }
122
+ catch (err) {
123
+ warn(`[improve] calibration auto-tune: failed to persist phase threshold for ${phase}: ${err instanceof Error ? err.message : String(err)}`);
124
+ }
125
+ }
126
+ return result.newThreshold;
127
+ }
128
+ /**
129
+ * Run (or gate-skip) the memory consolidation pass.
130
+ *
131
+ * #551 — two coordinated changes live here:
132
+ *
133
+ * 1. STRUCTURAL: this runs before extract in the improve pipeline (see
134
+ * `runImprovePreparationStage`). Consolidation therefore only ever judges
135
+ * PRIOR-run memories; current-run extract promotions are invisible to it.
136
+ *
137
+ * 2. SMARTER POOL-DELTA GATE: even among on-disk files, a memory whose only
138
+ * post-`lastConsolidateTs` mtime bump came from its OWN auto-accept
139
+ * promotion (i.e. it was just promoted by extract in the immediately
140
+ * preceding run and has not had a full improve cycle to settle) does NOT
141
+ * count as "work to do". We exclude those paths from the pool-delta check
142
+ * using the `promoted` events already emitted with each promotion's
143
+ * `assetPath`. A genuinely-settled prior memory — one edited by feedback,
144
+ * reflect, manual edit, or simply older than the last consolidate — still
145
+ * triggers the run. This is gate-option (a) from the issue (same-run /
146
+ * adjacent-run promotion exclusion), chosen over option (b) because there
147
+ * is no `extract_completed` event in the data model to gate against;
148
+ * `promoted` events with `assetPath` already carry exactly the signal we
149
+ * need, so the fix is non-invasive and provably correct.
150
+ */
151
+ export async function runConsolidationPass(args) {
152
+ const { options, primaryStashDir, memorySummary, improveProfile, eventsCtx, budgetSignal, runBudgetMs } = args;
153
+ const baseConfig = options.config ?? loadConfig();
154
+ const MEMORY_VOLUME_THRESHOLD = options.memoryVolumeConsolidationThreshold ?? 100;
155
+ const hasLlm = !!(baseConfig.defaults?.llm || baseConfig.defaults?.agent);
156
+ const volumeTriggered = typeof memorySummary.eligible === "number" && memorySummary.eligible > MEMORY_VOLUME_THRESHOLD && hasLlm;
157
+ // When volume triggers a consolidation pass, force-enable the consolidate
158
+ // process on the default improve profile so the gate accepts the run even
159
+ // if the user's config disabled it. We synthesise a new profile override
160
+ // rather than mutating connection settings.
161
+ const consolidationConfig = volumeTriggered
162
+ ? {
163
+ ...baseConfig,
164
+ profiles: {
165
+ ...(baseConfig.profiles ?? {}),
166
+ improve: {
167
+ ...(baseConfig.profiles?.improve ?? {}),
168
+ default: {
169
+ ...(baseConfig.profiles?.improve?.default ?? {}),
170
+ processes: {
171
+ ...(baseConfig.profiles?.improve?.default?.processes ?? {}),
172
+ consolidate: {
173
+ ...(baseConfig.profiles?.improve?.default?.processes?.consolidate ?? {}),
174
+ enabled: true,
175
+ },
176
+ },
177
+ },
178
+ },
179
+ },
180
+ }
181
+ : baseConfig;
182
+ // 0.8.0 pool-delta gate for consolidate: re-eligible iff at least one
183
+ // memory file has been updated since the most recent successful
184
+ // consolidate_completed event. Time-based cooldowns produced the same
185
+ // synchronised-wave failure mode the reflect/distill cooldowns did; the
186
+ // pool-delta gate ties consolidation to actual work-to-do.
187
+ const recentConsolidations = readEvents({ type: "consolidate_completed" });
188
+ const lastConsolidation = recentConsolidations.events
189
+ .filter((e) => e.metadata?.processed && Number(e.metadata.processed) > 0)
190
+ .sort((a, b) => new Date(b.ts ?? 0).getTime() - new Date(a.ts ?? 0).getTime())[0];
191
+ const lastConsolidateTs = lastConsolidation?.ts;
192
+ // #551 smarter gate: build the set of memory asset paths whose only delta
193
+ // since the last consolidate is their OWN auto-accept promotion. Those files
194
+ // have not had a full improve cycle to settle, so they offer no merge /
195
+ // contradiction candidates yet — excluding them stops the gate firing on
196
+ // freshly-promoted single-source memories. We read `promoted` events emitted
197
+ // after the last consolidate; each carries the written `assetPath`.
198
+ const promotedSinceConsolidate = (() => {
199
+ const paths = new Set();
200
+ try {
201
+ const promoted = readEvents({
202
+ type: "promoted",
203
+ ...(lastConsolidateTs ? { since: lastConsolidateTs } : {}),
204
+ }).events;
205
+ for (const e of promoted) {
206
+ const ap = e.metadata?.assetPath;
207
+ if (typeof ap === "string" && ap.length > 0)
208
+ paths.add(path.resolve(ap));
209
+ }
210
+ }
211
+ catch {
212
+ // best-effort: if the events query fails, fall back to no exclusions
213
+ // (preserves pre-#551 behaviour rather than over-skipping).
214
+ }
215
+ return paths;
216
+ })();
217
+ // Pool-delta: any memory file with mtime > lastConsolidateTs flags work to do,
218
+ // EXCEPT files whose only post-consolidate change was their own promotion.
219
+ // Using file mtime keeps this query DB-free and matches what the indexer
220
+ // already uses as the canonical `memory.updated_at` proxy.
221
+ //
222
+ // Bootstrap: when no successful consolidate_completed event has ever been
223
+ // recorded, we cannot evaluate the pool-delta — treat as eligible so a
224
+ // fresh stash runs consolidate once before the steady-state gate kicks in.
225
+ const memoryUpdatedAfterLastConsolidate = (() => {
226
+ if (volumeTriggered)
227
+ return true; // volume override forces the run regardless.
228
+ if (!lastConsolidateTs)
229
+ return true; // bootstrap path: never consolidated.
230
+ if (!primaryStashDir)
231
+ return false;
232
+ const memoriesDir = path.join(primaryStashDir, "memories");
233
+ if (!fs.existsSync(memoriesDir))
234
+ return false;
235
+ try {
236
+ return fs.readdirSync(memoriesDir).some((f) => {
237
+ if (!f.endsWith(".md"))
238
+ return false;
239
+ const filePath = path.join(memoriesDir, f);
240
+ // #551: skip files that were only touched by their own promotion this
241
+ // cohort — they have no settled merge/contradiction candidates yet.
242
+ if (promotedSinceConsolidate.has(path.resolve(filePath)))
243
+ return false;
244
+ try {
245
+ return fs.statSync(filePath).mtime.toISOString() > lastConsolidateTs;
246
+ }
247
+ catch {
248
+ return false;
249
+ }
250
+ });
251
+ }
252
+ catch {
253
+ return false;
254
+ }
255
+ })();
256
+ const consolidationOnCooldown = !volumeTriggered && !memoryUpdatedAfterLastConsolidate;
257
+ // Profile gate: if profile explicitly disables consolidate, skip the entire pass.
258
+ const consolidateDisabledByProfile = improveProfile?.processes?.consolidate?.enabled === false;
259
+ // #553 minPoolSize guard: skip consolidation when the eligible memory pool is
260
+ // below a minimum size, rather than spending an LLM pass on a handful of
261
+ // memories. This is an INDEPENDENT skip condition from #551's mtime pool-delta
262
+ // gate — either can skip. Default 500; `minPoolSize: 0` disables the guard.
263
+ // Evaluated against the eligible-pool count BEFORE entering the LLM loop so a
264
+ // skip costs ZERO LLM calls.
265
+ const CONSOLIDATE_DEFAULT_MIN_POOL_SIZE = 500;
266
+ const configuredMinPoolSize = improveProfile?.processes?.consolidate?.minPoolSize;
267
+ const minPoolSize = typeof configuredMinPoolSize === "number" ? configuredMinPoolSize : CONSOLIDATE_DEFAULT_MIN_POOL_SIZE;
268
+ const eligiblePoolSize = typeof memorySummary.eligible === "number" ? memorySummary.eligible : 0;
269
+ // volumeTriggered means the pool already exceeds the volume threshold (100),
270
+ // so a force-triggered run never trips the pool-size guard. The guard only
271
+ // engages when minPoolSize > 0 and the eligible pool is strictly below it.
272
+ const poolBelowMinSize = !volumeTriggered && minPoolSize > 0 && eligiblePoolSize < minPoolSize;
273
+ let consolidation = {
274
+ schemaVersion: 1,
275
+ ok: true,
276
+ shape: "consolidate-result",
277
+ dryRun: false,
278
+ previewOnly: false,
279
+ target: "",
280
+ processed: 0,
281
+ merged: 0,
282
+ deleted: 0,
283
+ promoted: [],
284
+ contradicted: 0,
285
+ warnings: [],
286
+ durationMs: 0,
287
+ };
288
+ let gateAutoAcceptedCount = 0;
289
+ let gateAutoAcceptFailedCount = 0;
290
+ const consolidateGateCfg = makeGateConfig("consolidate", {
291
+ globalThreshold: options.autoAccept,
292
+ dryRun: options.dryRun ?? false,
293
+ stashDir: primaryStashDir,
294
+ config: consolidationConfig,
295
+ eventsCtx,
296
+ stateDbPath: eventsCtx?.dbPath,
297
+ }, { minimumThreshold: 95 });
298
+ if (consolidateDisabledByProfile) {
299
+ info("[improve] consolidation skipped (disabled by improve profile)");
300
+ }
301
+ else if (poolBelowMinSize) {
302
+ // #553: eligible pool below the configured minimum — skip with zero LLM
303
+ // calls. Reuse the #551 `improve_skipped` emission path so health surfaces
304
+ // it via the dynamic skipReasons aggregation under `pool_below_min_size`.
305
+ appendEvent({
306
+ eventType: "improve_skipped",
307
+ ref: "memory:_consolidation",
308
+ metadata: {
309
+ reason: "pool_below_min_size",
310
+ poolSize: eligiblePoolSize,
311
+ minPoolSize,
312
+ },
313
+ }, eventsCtx);
314
+ info(`[improve] consolidation skipped (pool ${eligiblePoolSize} < minPoolSize ${minPoolSize})`);
315
+ }
316
+ else if (!consolidationOnCooldown) {
317
+ consolidation = await withLlmStage("consolidate", () => akmConsolidate({
318
+ ...options.consolidateOptions,
319
+ config: consolidationConfig,
320
+ stashDir: options.stashDir,
321
+ autoTriggered: volumeTriggered,
322
+ // Tie consolidate proposals back to this improve invocation so
323
+ // accept-rate-per-run aggregation works. Mirrors reflect/propose/extract.
324
+ sourceRun: `consolidate-${Date.now()}`,
325
+ // Pass profile-configured options. incrementalSince narrows the pool to
326
+ // recently-changed memories + graph neighbours — use this for frequent
327
+ // passes (quick-shredder). Leave absent in the nightly default profile for
328
+ // a full-pool sweep that catches stale-but-unmerged duplicates.
329
+ incrementalSince: improveProfile?.processes?.consolidate?.incrementalSince,
330
+ limit: improveProfile?.processes?.consolidate?.limit,
331
+ neighborsPerChanged: improveProfile?.processes?.consolidate?.neighborsPerChanged,
332
+ maxChunkSize: improveProfile?.processes?.consolidate?.maxChunkSize,
333
+ // #617 — deterministic near-duplicate dedup pre-pass. DEFAULT OFF; only
334
+ // runs when the profile explicitly sets `consolidate.dedup.enabled`.
335
+ dedup: improveProfile?.processes?.consolidate?.dedup,
336
+ // #581 — judged-state cache. DEFAULT OFF; only engages when the profile
337
+ // explicitly sets `consolidate.judgedCache.enabled`. Skips memories
338
+ // judged-unchanged since their last judge so one run sweeps the full
339
+ // corpus instead of narrowing to a time-window slice.
340
+ judgedCache: improveProfile?.processes?.consolidate?.judgedCache,
341
+ // Honor profile.autoAccept (already merged into options.autoAccept at the
342
+ // top of akmImprove). The CLI parser always supplies 90 when --auto-accept
343
+ // is absent, so ?? 90 is not needed here and would prevent --auto-accept=false
344
+ // (which maps to undefined) from disabling consolidation auto-accept.
345
+ // options.consolidateOptions.autoAccept (if explicitly provided by caller)
346
+ // still wins because the spread above runs first.
347
+ autoAccept: options.consolidateOptions?.autoAccept ?? options.autoAccept,
348
+ // WS-3a: forward budget signal for graceful abort on timeout, and pass
349
+ // the profile's p90 estimate for cold-start budget reduction.
350
+ signal: budgetSignal,
351
+ p90ChunkSecondsDefault: improveProfile?.processes?.consolidate?.p90ChunkSecondsDefault,
352
+ // WS-5: pass total run budget so perfTelemetry.estimatedBudgetFractionUsed
353
+ // can flag when consolidation alone exceeded the budget.
354
+ runBudgetMs,
355
+ }));
356
+ {
357
+ const consolidateGr = await runAutoAcceptGate(consolidation.promoted.map((proposalId) => {
358
+ try {
359
+ if (!primaryStashDir)
360
+ return { proposalId, confidence: undefined };
361
+ const proposal = getProposal(primaryStashDir, proposalId);
362
+ return { proposalId, confidence: proposal.confidence };
363
+ }
364
+ catch {
365
+ return { proposalId, confidence: undefined };
366
+ }
367
+ }), consolidateGateCfg);
368
+ gateAutoAcceptedCount += consolidateGr.promoted.length;
369
+ gateAutoAcceptFailedCount += consolidateGr.failed.length;
370
+ }
371
+ if (consolidation.processed > 0) {
372
+ appendEvent({
373
+ eventType: "consolidate_completed",
374
+ ref: "memory:_consolidation",
375
+ metadata: {
376
+ processed: consolidation.processed,
377
+ merged: consolidation.merged,
378
+ deleted: consolidation.deleted,
379
+ contradicted: consolidation.contradicted,
380
+ failedChunks: consolidation.failedChunks ?? 0,
381
+ durationMs: consolidation.durationMs,
382
+ },
383
+ }, eventsCtx);
384
+ }
385
+ }
386
+ else {
387
+ appendEvent({
388
+ eventType: "improve_skipped",
389
+ ref: "memory:_consolidation",
390
+ metadata: {
391
+ reason: "consolidation_no_memory_updates",
392
+ lastEventTs: lastConsolidation?.ts ?? null,
393
+ },
394
+ }, eventsCtx);
395
+ info("[improve] consolidation skipped (no memory updates since last run)");
396
+ }
397
+ // D9: track whether consolidation wrote any data so graph extraction can reindex if needed
398
+ const consolidationRan = !consolidateDisabledByProfile && !poolBelowMinSize && !consolidationOnCooldown && consolidation.processed > 0;
399
+ // WS-4: Per-phase threshold auto-tune for the consolidate phase.
400
+ // Persists result for the NEXT run's makeGateConfig to read.
401
+ const consolidateTuneDbPath = eventsCtx?.dbPath;
402
+ if (options.autoAccept !== undefined && consolidateTuneDbPath) {
403
+ try {
404
+ maybeAutoTuneThreshold(consolidateGateCfg.phaseThreshold ?? options.autoAccept, consolidationConfig, consolidateTuneDbPath, undefined, "consolidate");
405
+ }
406
+ catch (err) {
407
+ warn(`[improve] calibration auto-tune (consolidate) skipped: ${err instanceof Error ? err.message : String(err)}`);
408
+ }
409
+ }
410
+ return { consolidation, consolidationRan, gateAutoAcceptedCount, gateAutoAcceptFailedCount };
411
+ }
412
+ /**
413
+ * Phase 0.4 — session-extract pass. Reads native session files through the
414
+ * SessionLogHarness registry, asks a bounded LLM for candidate proposals, gates
415
+ * them, and drains the extract backlog. Failures are non-fatal (collected into
416
+ * `warnings`). Returns the extract results + the gate counters seeded from the
417
+ * consolidation pass and accumulated here.
418
+ */
419
+ async function runSessionExtractPass(args) {
420
+ const { options, primaryStashDir, improveProfile, eventsCtx, seedGateAccepted, seedGateFailed } = args;
421
+ const warnings = [];
422
+ // Phase 0.4 — session-extract pass.
423
+ //
424
+ // Reads native session files (claude-code JSONL, opencode storage tree)
425
+ // through the SessionLogHarness registry, pre-filters noise, and asks a
426
+ // bounded in-tree LLM to produce candidate memory/lesson/knowledge
427
+ // proposals for content the agent did NOT preserve via inline `akm remember`
428
+ // / `akm feedback` invocations. Replaces the akm-plugin session-checkpoint
429
+ // hook with an on-demand pull pipeline.
430
+ //
431
+ // Default-on; opt out via the ACTIVE profile's `processes.extract.enabled: false`
432
+ // (#593: the gate respects the resolved improve profile, not just the
433
+ // hardcoded `default` profile path the legacy feature flag reads).
434
+ // Each available harness gets one call with the default --since window;
435
+ // already-seen sessions (tracked in state.db.extract_sessions_seen) are
436
+ // skipped automatically so re-runs don't burn LLM calls on unchanged data.
437
+ //
438
+ // Failures are non-fatal — one harness throwing doesn't abort improve.
439
+ // The extract envelope's own `warnings` field surfaces what went wrong.
440
+ let extractResults;
441
+ // Seed the preparation-stage gate counters with consolidation's auto-accept
442
+ // gate results (#551: consolidation now runs in this stage), then accumulate
443
+ // extract's gate results on top.
444
+ let gateAutoAcceptedCount = seedGateAccepted;
445
+ let gateAutoAcceptFailedCount = seedGateFailed;
446
+ const extractConfig = options.config ?? loadConfig();
447
+ const extractGateCfg = makeGateConfig("extract", {
448
+ globalThreshold: options.autoAccept,
449
+ dryRun: options.dryRun ?? false,
450
+ stashDir: primaryStashDir,
451
+ config: extractConfig,
452
+ eventsCtx,
453
+ stateDbPath: eventsCtx?.dbPath,
454
+ });
455
+ // #554 minNewSessions gate: skip the entire extract pass (ensureIndex was
456
+ // already done upstream; here we elide every akmExtract/processSession call)
457
+ // when the NEW (unseen, in-window) candidate-session pool is below a minimum.
458
+ // 22% of improve runs produce zero memory-inference writes because extract
459
+ // finds no new sessions, yet still burns the full extract pipeline. Default 0
460
+ // (disabled) preserves existing always-run behaviour; only opted-in profiles
461
+ // (e.g. `frequent`) set it. Evaluated BEFORE any LLM call so a skip costs zero
462
+ // LLM work AND writes nothing — which also means no extract auto-accept bumps
463
+ // memory mtimes, so a skipped extract never flags work for the NEXT run's
464
+ // consolidation mtime-gate (the downstream trigger #554 asks us to suppress).
465
+ const EXTRACT_DEFAULT_MIN_NEW_SESSIONS = 0;
466
+ // Read from the ACTIVE resolved profile (not always `default`), matching how
467
+ // `extract.enabled` resolves — otherwise a non-default profile (e.g.
468
+ // `frequent`) setting `minNewSessions` was silently ignored.
469
+ const configuredMinNewSessions = improveProfile.processes?.extract?.minNewSessions;
470
+ const minNewSessions = typeof configuredMinNewSessions === "number" ? configuredMinNewSessions : EXTRACT_DEFAULT_MIN_NEW_SESSIONS;
471
+ // #593/#594: the ACTIVE resolved improve profile is the single source of
472
+ // truth for whether extract runs. (Previously this also ANDed in the legacy
473
+ // `session_extraction` feature flag, which only reads
474
+ // `profiles.improve.default.processes.extract.enabled`; that made the default
475
+ // profile a global kill switch, so a non-default profile enabling extract was
476
+ // silently overridden. The default profile is now just another profile.)
477
+ // `akmExtract` re-checks the same active profile internally via `improveProfile`.
478
+ if (resolveProcessEnabled("extract", improveProfile)) {
479
+ const availableHarnesses = options.extractHarnesses ?? getAvailableHarnesses();
480
+ // The guard engages only when minNewSessions > 0; 0 disables it entirely.
481
+ let belowMinNewSessions = false;
482
+ if (minNewSessions > 0 && availableHarnesses.length > 0) {
483
+ const countFn = options.extractCandidateCountFn ?? countNewExtractCandidates;
484
+ const newCandidateCount = countFn(extractConfig, {
485
+ ...(options.extractHarnesses ? { harnesses: options.extractHarnesses } : {}),
486
+ // Use the ACTIVE profile's discovery window so the gate counts over the
487
+ // same window akmExtract will scan (not always `default`).
488
+ ...(improveProfile.processes?.extract?.defaultSince
489
+ ? { since: improveProfile.processes.extract.defaultSince }
490
+ : {}),
491
+ // C2: pin the candidate-count state.db open to the boundary-resolved path.
492
+ ...(eventsCtx?.dbPath ? { stateDbPath: eventsCtx.dbPath } : {}),
493
+ });
494
+ if (newCandidateCount < minNewSessions) {
495
+ belowMinNewSessions = true;
496
+ // Reuse the #551/#553 `improve_skipped` emission path so health's dynamic
497
+ // skipReasons aggregation surfaces this under `below_min_new_sessions`.
498
+ appendEvent({
499
+ eventType: "improve_skipped",
500
+ ref: "memory:_extract",
501
+ metadata: {
502
+ reason: "below_min_new_sessions",
503
+ newSessions: newCandidateCount,
504
+ minNewSessions,
505
+ },
506
+ }, eventsCtx);
507
+ info(`[improve] extract skipped (new sessions ${newCandidateCount} < minNewSessions ${minNewSessions})`);
508
+ }
509
+ }
510
+ if (!belowMinNewSessions && availableHarnesses.length > 0) {
511
+ extractResults = [];
512
+ for (const h of availableHarnesses) {
513
+ try {
514
+ const result = await withLlmStage("session-extraction", () => akmExtract({
515
+ type: h.name,
516
+ ...(primaryStashDir !== undefined ? { stashDir: primaryStashDir } : {}),
517
+ config: extractConfig,
518
+ // Thread the ACTIVE profile so extract's internal gate + per-process
519
+ // config read the running profile, not always `default`.
520
+ improveProfile,
521
+ dryRun: options.dryRun ?? false,
522
+ ...(options.extractHarnesses ? { harnesses: options.extractHarnesses } : {}),
523
+ // C2: pin extract's skip-tracking state.db open to the boundary path.
524
+ ...(eventsCtx?.dbPath ? { stateDbPath: eventsCtx.dbPath } : {}),
525
+ }));
526
+ extractResults.push(result);
527
+ {
528
+ const gr = await runAutoAcceptGate(primaryStashDir
529
+ ? result.proposals.map((proposalId) => {
530
+ const proposal = getProposal(primaryStashDir, proposalId);
531
+ return { proposalId, confidence: resolveExtractConfidence(proposal) };
532
+ })
533
+ : [], extractGateCfg);
534
+ gateAutoAcceptedCount += gr.promoted.length;
535
+ gateAutoAcceptFailedCount += gr.failed.length;
536
+ }
537
+ }
538
+ catch (err) {
539
+ const msg = err instanceof Error ? err.message : String(err);
540
+ warnings.push(`extract(${h.name}) failed: ${msg}`);
541
+ }
542
+ }
543
+ if (extractResults.length === 0) {
544
+ // All harnesses threw — clear so the envelope's `extract` field is
545
+ // absent rather than misleadingly empty.
546
+ extractResults = undefined;
547
+ }
548
+ }
549
+ }
550
+ // Backlog drain: gate any pending extract proposals that weren't created in
551
+ // this run (i.e. pre-date the gate or were produced by a run that timed out
552
+ // before the gate fired). Without this, eligible proposals accumulate
553
+ // indefinitely — the fresh-gate only covers the current run's output.
554
+ if (primaryStashDir && !options.dryRun && options.autoAccept !== undefined) {
555
+ const freshIds = new Set((extractResults ?? []).flatMap((r) => r.proposals));
556
+ const backlog = listProposals(primaryStashDir, { status: "pending" }).filter((p) => p.source === "extract" && !freshIds.has(p.id));
557
+ if (backlog.length > 0) {
558
+ const backlogCandidates = backlog.map((p) => ({
559
+ proposalId: p.id,
560
+ confidence: resolveExtractConfidence(p),
561
+ }));
562
+ const backlogGr = await runAutoAcceptGate(backlogCandidates, extractGateCfg);
563
+ gateAutoAcceptedCount += backlogGr.promoted.length;
564
+ gateAutoAcceptFailedCount += backlogGr.failed.length;
565
+ }
566
+ }
567
+ return { extractResults, gateAutoAcceptedCount, gateAutoAcceptFailedCount, warnings, extractGateCfg };
568
+ }
569
+ /**
570
+ * Phase 1 — validation + schema-repair pass. Scans postCleanupRefs for assets
571
+ * with structural problems (missing file, missing lesson description), attempts
572
+ * LLM schema repair, and returns the still-failing ref set + the repair records.
573
+ */
574
+ async function runValidationAndRepairPass(args) {
575
+ const { postCleanupRefs, options, startMs, budgetMs } = args;
576
+ const validationFailures = [];
577
+ for (const candidate of postCleanupRefs) {
578
+ try {
579
+ // #591: use the path pre-resolved at planning time when it is still on
580
+ // disk — a serial async DB lookup per ref cost ~500 s on a 9 000-ref
581
+ // stash. Fall back to findAssetFilePath only for refs that bypassed
582
+ // collectEligibleRefs' index scan or whose file moved since planning.
583
+ const filePath = candidate.filePath && fs.existsSync(candidate.filePath)
584
+ ? candidate.filePath
585
+ : await findAssetFilePath(candidate.ref, options.stashDir);
586
+ if (!filePath) {
587
+ validationFailures.push({ ref: candidate.ref, reason: "file not found on disk" });
588
+ continue;
589
+ }
590
+ if (path.extname(filePath).toLowerCase() !== ".md") {
591
+ continue;
592
+ }
593
+ if (isLessonCandidate(candidate.ref)) {
594
+ const raw = fs.readFileSync(filePath, "utf8");
595
+ const fm = parseFrontmatter(raw).data;
596
+ if (!fm.description)
597
+ validationFailures.push({ ref: candidate.ref, reason: "missing description" });
598
+ }
599
+ }
600
+ catch (e) {
601
+ validationFailures.push({ ref: candidate.ref, reason: String(e) });
602
+ }
603
+ }
604
+ if (validationFailures.length > 0) {
605
+ info(`[improve] ${validationFailures.length} assets have validation issues (will attempt schema repair):`);
606
+ for (const f of validationFailures)
607
+ info(` ${f.ref}: ${f.reason}`);
608
+ }
609
+ let schemaRepairs = [];
610
+ let repairedRefs = new Set();
611
+ // Schema repair pass: attempt to fix validation failures via LLM before skipping.
612
+ if (validationFailures.length > 0 && options.repairValidationFailures !== false) {
613
+ const baseConfigForRepair = options.config ?? loadConfig();
614
+ const llmCfg = getDefaultLlmConfig(baseConfigForRepair);
615
+ if (llmCfg) {
616
+ const result = await runSchemaRepairPass(validationFailures, {
617
+ startMs,
618
+ budgetMs,
619
+ llmConfig: llmCfg,
620
+ stashDir: options.stashDir,
621
+ findFilePath: findAssetFilePath,
622
+ isLessonCandidateFn: isLessonCandidate,
623
+ });
624
+ schemaRepairs = result.repairs;
625
+ repairedRefs = result.repairedRefs;
626
+ }
627
+ }
628
+ const validationFailureRefs = new Set(validationFailures.filter((f) => !repairedRefs.has(f.ref)).map((f) => f.ref));
629
+ if (repairedRefs.size > 0) {
630
+ info(`[improve] schema repair fixed ${repairedRefs.size}/${validationFailures.length} validation failures; ${validationFailureRefs.size} remain`);
631
+ }
632
+ return { validationFailures, validationFailureRefs, schemaRepairs };
633
+ }
634
+ export async function runImprovePreparationStage(args) {
635
+ const { scope, options, plannedRefs, memoryCleanupPlan, primaryStashDir, memorySummary, reindexFn, startMs, budgetMs, eventsCtx, initialCleanupWarnings, improveProfile, budgetSignal, } = args;
636
+ const actions = [];
637
+ const cleanupWarnings = initialCleanupWarnings ? [...initialCleanupWarnings] : [];
638
+ // Phase 0 — MEMORY.md budget check (200-line cap; warn at 180)
639
+ let memoryIndexHealth;
640
+ if (primaryStashDir) {
641
+ const memoryMdPath = path.join(primaryStashDir, "memories", "MEMORY.md");
642
+ if (fs.existsSync(memoryMdPath)) {
643
+ try {
644
+ const lines = fs.readFileSync(memoryMdPath, "utf8").split("\n").length;
645
+ const overBudget = lines >= 180;
646
+ memoryIndexHealth = { lineCount: lines, overBudget };
647
+ if (overBudget) {
648
+ cleanupWarnings.push(`MEMORY.md has ${lines} lines (budget: 200). Consolidation strongly recommended.`);
649
+ }
650
+ }
651
+ catch {
652
+ // best-effort
653
+ }
654
+ }
655
+ }
656
+ // Phase 0.3 — memory consolidation pass (#551).
657
+ //
658
+ // Consolidation runs BEFORE the session-extract pass. This is the structural
659
+ // half of the #551 fix: extract auto-accept writes brand-new memory .md files
660
+ // on every run, which previously made the consolidation pool-delta gate fire
661
+ // unconditionally (any new file => "memory updated since last consolidate").
662
+ // By running consolidation first, the gate and akmConsolidate only ever see
663
+ // memories that existed at the start of the run — current-run extract
664
+ // promotions are not on disk yet. The complementary smarter-gate logic
665
+ // (excluding adjacent-run promotions) lives in `runConsolidationPass`.
666
+ const consolidationPass = await runConsolidationPass({
667
+ options,
668
+ primaryStashDir,
669
+ memorySummary,
670
+ improveProfile,
671
+ eventsCtx,
672
+ budgetSignal,
673
+ runBudgetMs: budgetMs,
674
+ });
675
+ // Phase 0.4 — session-extract pass (see runSessionExtractPass).
676
+ const extractPass = await runSessionExtractPass({
677
+ options,
678
+ primaryStashDir,
679
+ improveProfile,
680
+ eventsCtx,
681
+ seedGateAccepted: consolidationPass.gateAutoAcceptedCount,
682
+ seedGateFailed: consolidationPass.gateAutoAcceptFailedCount,
683
+ });
684
+ const extractResults = extractPass.extractResults;
685
+ const gateAutoAcceptedCount = extractPass.gateAutoAcceptedCount;
686
+ const gateAutoAcceptFailedCount = extractPass.gateAutoAcceptFailedCount;
687
+ if (extractPass.warnings.length > 0)
688
+ cleanupWarnings.push(...extractPass.warnings);
689
+ // eligibleCount = raw pre-filter count (before cooldown/signal/cleanup filters).
690
+ // improve_completed.plannedRefs = post-filter count of refs that actually entered the loop.
691
+ appendEvent({
692
+ eventType: "improve_invoked",
693
+ ref: scope.mode === "ref" ? scope.value : `improve:${scope.mode}:${scope.value ?? "all"}`,
694
+ metadata: { scope, dryRun: options.dryRun ?? false, eligibleCount: plannedRefs.length },
695
+ }, eventsCtx);
696
+ // ensureIndex now runs in akmImprove() BEFORE collectEligibleRefs so the
697
+ // eligible-ref query sees a populated `entries` table on the very first
698
+ // pass after a DB version upgrade (#339). Any failure messages from that
699
+ // earlier call were threaded in via args.initialCleanupWarnings.
700
+ let appliedCleanup;
701
+ try {
702
+ appliedCleanup =
703
+ primaryStashDir && memoryCleanupPlan ? applyMemoryCleanup(primaryStashDir, memoryCleanupPlan) : undefined;
704
+ }
705
+ catch (err) {
706
+ cleanupWarnings.push(`applyMemoryCleanup failed: ${err instanceof Error ? err.message : String(err)}`);
707
+ }
708
+ const archivedRefs = appliedCleanup?.archived.map((record) => record.ref) ?? [];
709
+ const removed = new Set(archivedRefs);
710
+ const postCleanupRefs = archivedRefs.length === 0 ? plannedRefs : plannedRefs.filter((r) => !removed.has(r.ref));
711
+ // ── Phase 1: validation pass + schema repair (run on full postCleanupRefs) ──
712
+ // Identifies refs whose on-disk asset has structural problems. Validation
713
+ // failures are excluded from every downstream bucket. Run early so the
714
+ // cooldown partition operates on a clean set.
715
+ if (appliedCleanup) {
716
+ for (const candidate of memoryCleanupPlan?.pruneCandidates ?? []) {
717
+ const archived = appliedCleanup.archived.find((record) => record.ref === candidate.ref);
718
+ if (!archived)
719
+ continue;
720
+ actions.push({
721
+ ref: candidate.ref,
722
+ mode: "memory-prune",
723
+ result: { ok: true, pruned: true, reason: candidate.reason },
724
+ });
725
+ }
726
+ if ((appliedCleanup.archived.length > 0 || appliedCleanup.beliefStateTransitions.length > 0) && primaryStashDir) {
727
+ try {
728
+ await reindexFn({ stashDir: primaryStashDir });
729
+ }
730
+ catch (err) {
731
+ cleanupWarnings.push(`reindex after cleanup failed: ${err instanceof Error ? err.message : String(err)}`);
732
+ }
733
+ }
734
+ }
735
+ const { validationFailures, validationFailureRefs, schemaRepairs } = await runValidationAndRepairPass({
736
+ postCleanupRefs,
737
+ options,
738
+ startMs,
739
+ budgetMs,
740
+ });
741
+ // Phase 0.5 — structural hygiene pass
742
+ let lintSummary;
743
+ if (primaryStashDir) {
744
+ try {
745
+ const lintResult = akmLint({ fix: true, dir: primaryStashDir });
746
+ lintSummary = { fixed: lintResult.summary.fixed, flagged: lintResult.summary.flagged };
747
+ }
748
+ catch {
749
+ // lint is best-effort; never block improve
750
+ }
751
+ }
752
+ // O-5 / #378: Per-originator rolling error windows.
753
+ // Reflexion (arXiv:2303.11366) warns that cross-task verbal critique
754
+ // contamination degrades below single-shot baseline. Each originator key
755
+ // ("schema-repair", "reflect") maintains its own rolling window so that
756
+ // schema-repair failures are not injected as avoidPatterns into reflect calls.
757
+ const recentErrors = {};
758
+ const RECENT_ERRORS_CAP = 3;
759
+ // Helper: push an error onto an originator's rolling window.
760
+ function pushRecentError(originator, msg) {
761
+ if (!recentErrors[originator])
762
+ recentErrors[originator] = [];
763
+ recentErrors[originator].push(msg);
764
+ if (recentErrors[originator].length > RECENT_ERRORS_CAP)
765
+ recentErrors[originator].shift();
766
+ }
767
+ // Seed schema-repair originator window from any schema-repair errors.
768
+ for (const repair of schemaRepairs) {
769
+ if (repair.outcome === "error") {
770
+ const errMsg = repair.error ?? `schema repair error: ${repair.reason}`;
771
+ pushRecentError("schema-repair", errMsg);
772
+ }
773
+ }
774
+ // ── Phase 2: signal-delta eligibility sets built EARLY ────────────────────
775
+ // 0.8.0 replaces the flat time-based cooldowns (which produced synchronised
776
+ // waves whenever many refs cooled at the same instant — see the 2026-05-26
777
+ // 54-ref simultaneous-reflect incident) with a *signal-delta* gate:
778
+ //
779
+ // reflectEligible(ref) ≡ latestFeedbackTs(ref) > lastReflectProposalTs(ref)
780
+ // distillEligible(ref) ≡ latestFeedbackTs(ref) > lastDistillProposalTs(ref)
781
+ //
782
+ // i.e. a ref is re-eligible iff new feedback has landed since the last
783
+ // proposal was generated for it. Stable content with no new signal stays
784
+ // out of the queue regardless of clock time; a sudden burst of feedback
785
+ // surfaces only the refs that the burst actually touches.
786
+ //
787
+ // The 30-day FEEDBACK_SIGNAL_WINDOW_DAYS bound still applies — only feedback
788
+ // events newer than that count as "current signal". Ancient one-off
789
+ // negatives don't permanently lock a ref into every run.
790
+ //
791
+ // High-retrieval refs (P0-A path) use a simpler "eligible once" rule: a
792
+ // ref with no feedback signal but retrievalCount ≥ threshold is eligible
793
+ // exactly once (no prior reflect proposal). Subsequent re-eligibility for
794
+ // those refs requires either a new feedback event (then the normal
795
+ // signal-delta gate applies) or human action. Documented limitation: this
796
+ // path does not re-fire on retrieval-count growth alone in 0.8.0; storing
797
+ // the retrieval count in proposal metadata for proper delta-tracking is
798
+ // captured as future work.
799
+ const FEEDBACK_SIGNAL_WINDOW_DAYS = 30;
800
+ const feedbackSinceCutoff = new Date(Date.now() - daysToMs(FEEDBACK_SIGNAL_WINDOW_DAYS)).toISOString();
801
+ // Build the three timestamp maps once across the entire postCleanupRefs set.
802
+ // Per-ref queries would be N+1 and the planner is already the hottest path
803
+ // in `akm improve`.
804
+ const candidateRefs = postCleanupRefs.filter((r) => !validationFailureRefs.has(r.ref)).map((r) => r.ref);
805
+ const latestFeedbackTs = buildLatestFeedbackTsMap(candidateRefs, feedbackSinceCutoff);
806
+ const lastReflectProposalTs = buildLatestProposalTsMap(candidateRefs, "reflect");
807
+ const lastDistillProposalTs = buildLatestProposalTsMap(candidateRefs, "distill");
808
+ // Refs the distill signal-delta gate rejected at planning time. The main
809
+ // loop reads this to skip distill for these refs without re-checking
810
+ // eligibility per iteration.
811
+ const distillCooledRefs = new Set();
812
+ const preCooldownCount = postCleanupRefs.length;
813
+ // ── Phase 3: partition postCleanupRefs by signal-delta eligibility ────────
814
+ // Three buckets (validation failures are excluded entirely):
815
+ // eligibleRefs — reflect signal-delta passes (full reflect+distill
816
+ // loop path; distill guard remains in the loop for
817
+ // refs that fail the distill signal-delta gate).
818
+ // distillOnlyRefs — reflect blocked but distill signal-delta passes
819
+ // AND ref is a distill candidate.
820
+ // noFeedbackPool — neither signal-delta gate passes *and* the ref has
821
+ // no recent feedback signal at all. These are NOT
822
+ // skipped here: they are handed to the high-retrieval
823
+ // fallback (P0-A) below so frequently-retrieved but
824
+ // never-rated assets can still be improved. Only refs
825
+ // that P0-A declines are ultimately fully skipped.
826
+ // fullySkippedCount — has stale feedback but no signal delta → genuine
827
+ // skip (counted, aggregated event emitted post-loop),
828
+ // excluded from sort.
829
+ const eligibleRefs = [];
830
+ const distillOnlyRefs = [];
831
+ // Zero-(recent-)feedback refs deferred to the P0-A high-retrieval fallback.
832
+ const noFeedbackPool = [];
833
+ let fullySkippedCount = 0;
834
+ // O-2 (#365): explicit --scope <ref> bypasses every gate (user intent wins).
835
+ const scopeRefBypass = scope.mode === "ref";
836
+ for (const r of postCleanupRefs) {
837
+ if (validationFailureRefs.has(r.ref))
838
+ continue;
839
+ if (scopeRefBypass) {
840
+ eligibleRefs.push(r);
841
+ continue;
842
+ }
843
+ const reflectOk = isSignalDeltaEligible(r.ref, latestFeedbackTs, lastReflectProposalTs);
844
+ const distillOk = isSignalDeltaEligible(r.ref, latestFeedbackTs, lastDistillProposalTs);
845
+ const isDistillCandidate = isDistillCandidateRef(r.ref, options.stashDir);
846
+ if (reflectOk) {
847
+ if (!distillOk && isDistillCandidate) {
848
+ // Reflect passes the gate, distill does not — emit the synthetic
849
+ // distill-skipped action and event up-front so the in-loop guard
850
+ // does not have to re-derive eligibility.
851
+ distillCooledRefs.add(r.ref);
852
+ actions.push({ ref: r.ref, mode: "distill-skipped", result: { ok: true, reason: "distill signal-delta" } });
853
+ appendEvent({
854
+ eventType: "improve_skipped",
855
+ ref: r.ref,
856
+ metadata: { reason: "distill_no_new_signal" },
857
+ }, eventsCtx);
858
+ }
859
+ else if (!distillOk) {
860
+ // Not a distill candidate AND distill gate doesn't pass — just mark
861
+ // distillCooled so the loop's distill section is a no-op.
862
+ distillCooledRefs.add(r.ref);
863
+ }
864
+ eligibleRefs.push(r);
865
+ }
866
+ else if (distillOk && isDistillCandidate) {
867
+ // Reflect blocked but distill passes → distill-only bucket.
868
+ distillOnlyRefs.push(r);
869
+ }
870
+ else if (!latestFeedbackTs.has(r.ref)) {
871
+ // Neither signal-delta gate passes AND there is no recent feedback signal
872
+ // at all. Rather than skip outright, defer to the high-retrieval fallback
873
+ // (P0-A) below: a never-rated-but-frequently-retrieved asset is exactly
874
+ // what that path is meant to rescue. Refs P0-A declines are skipped there.
875
+ noFeedbackPool.push(r);
876
+ }
877
+ else {
878
+ // Has feedback on record but no signal delta since the last proposal —
879
+ // genuinely fully skipped. Counted here; a single aggregated
880
+ // improve_skipped event is emitted after the loop (mirrors
881
+ // profile_filtered_all_passes) instead of one event per ref.
882
+ fullySkippedCount++;
883
+ actions.push({
884
+ ref: r.ref,
885
+ mode: "distill-skipped",
886
+ result: { ok: true, reason: "no new signal since last proposal" },
887
+ });
888
+ }
889
+ }
890
+ // Emit ONE aggregated skip event for the fully-skipped bucket rather than one
891
+ // improve_skipped event per ref (#592 pattern, mirrors
892
+ // profile_filtered_all_passes above). The per-ref loop previously produced
893
+ // ~11K state.db writes per run on a large stash, the dominant contributor to
894
+ // 900 s timeouts. The in-memory `actions` log keeps the per-ref detail for the
895
+ // run summary; no downstream consumer needs a per-ref DB audit trail (health's
896
+ // skip histogram reads the `no_new_signal` counter from the count field).
897
+ if (fullySkippedCount > 0) {
898
+ appendEvent({
899
+ eventType: "improve_skipped",
900
+ ref: undefined,
901
+ metadata: {
902
+ reason: "no_new_signal",
903
+ count: fullySkippedCount,
904
+ },
905
+ }, eventsCtx);
906
+ }
907
+ // ── Phase 4: signal/feedback/utility/sort on the reduced set ──────────────
908
+ // Everything from here works on (eligibleRefs ∪ distillOnlyRefs) plus the
909
+ // deferred noFeedbackPool that may be rescued by the high-retrieval fallback
910
+ // (P0-A). The fully-skipped bucket has already been routed and its aggregated
911
+ // event emitted; we deliberately avoid spending DB/CPU on refs that the
912
+ // signal-delta gate rejected with feedback already on record.
913
+ const processableRefs = [...eligibleRefs, ...distillOnlyRefs];
914
+ // Refs eligible for the high-retrieval fallback (P0-A): the signal-delta
915
+ // partition above could not place these in a reflect/distill bucket, but they
916
+ // may still qualify if they have been retrieved often enough. Two disjoint
917
+ // sources feed this set:
918
+ // 1. noFeedbackPool — refs with no recent feedback that the partition loop
919
+ // deliberately deferred here (otherwise they would never reach P0-A).
920
+ // 2. processableRefs entries that turn out to carry no recent feedback
921
+ // *signal* once feedbackSummary is computed below.
922
+ // (1) is added here; (2) is folded in after feedbackSummary is built.
923
+ // Gap 6: only surface feedback signals from the last 30 days so that
924
+ // ancient one-off feedback events don't permanently lock an asset into
925
+ // every improve run. Assets with only stale signals fall through to the
926
+ // high-retrieval path (P0-A) or are skipped until new signals arrive.
927
+ // (FEEDBACK_SIGNAL_WINDOW_DAYS / feedbackSinceCutoff are already defined in
928
+ // Phase 2 above for the signal-delta gate; we reuse them here.)
929
+ // Pre-compute feedback summary per ref in a SINGLE bulk read so we don't
930
+ // open state.db once per asset (which caused 5000+ accumulated FDs and a
931
+ // 2-hour runaway on a 13K-asset stash). Pattern mirrors buildLatestFeedbackTsMap
932
+ // above: one readEvents() call fetches ALL feedback events, then we aggregate
933
+ // in-memory by ref — O(1) DB opens regardless of candidate set size.
934
+ // Cover processableRefs *and* the deferred noFeedbackPool so utility/feedback
935
+ // ratios are available for any noFeedbackPool ref that P0-A rescues below.
936
+ //
937
+ // Behavioral note: positive/negative COUNTS are all-time (same as the old
938
+ // per-ref readEvents call which had no `since` filter); hasSignal is bounded
939
+ // to feedbackSinceCutoff (same as the old inline `(e.ts ?? "") >= cutoff` guard).
940
+ const feedbackSummary = new Map();
941
+ {
942
+ const feedbackCandidateSet = new Set([...processableRefs, ...noFeedbackPool].map((r) => r.ref));
943
+ if (feedbackCandidateSet.size > 0) {
944
+ // Fetch ALL feedback events in one query (no ref filter, no since filter =
945
+ // single full table scan). Filtering per-ref in memory avoids N sequential
946
+ // state.db opens — the dominant FD-leak path on large stashes.
947
+ const { events: allFeedbackEvents } = readEvents({ type: "feedback" }, eventsCtx);
948
+ for (const e of allFeedbackEvents) {
949
+ const ref = e.ref;
950
+ if (!ref || !feedbackCandidateSet.has(ref))
951
+ continue;
952
+ const entry = feedbackSummary.get(ref) ?? { hasSignal: false, positive: 0, negative: 0 };
953
+ const meta = e.metadata;
954
+ // hasSignal: only count feedback events within the 30-day window.
955
+ if (!entry.hasSignal &&
956
+ (e.ts ?? "") >= feedbackSinceCutoff &&
957
+ meta !== undefined &&
958
+ (typeof meta.signal === "string" || typeof meta.note === "string")) {
959
+ entry.hasSignal = true;
960
+ }
961
+ // positive/negative: all-time counts (no since filter, matching prior behaviour).
962
+ if (meta?.signal === "positive")
963
+ entry.positive++;
964
+ else if (meta?.signal === "negative")
965
+ entry.negative++;
966
+ feedbackSummary.set(ref, entry);
967
+ }
968
+ // Ensure every candidate has an entry (even refs with zero feedback events).
969
+ for (const ref of feedbackCandidateSet) {
970
+ if (!feedbackSummary.has(ref)) {
971
+ feedbackSummary.set(ref, { hasSignal: false, positive: 0, negative: 0 });
972
+ }
973
+ }
974
+ }
975
+ }
976
+ const signalFiltered = processableRefs.filter((candidate) => feedbackSummary.get(candidate.ref)?.hasSignal === true);
977
+ // P0-A: also surface zero-feedback assets that have been retrieved many times.
978
+ const RETRIEVAL_COUNT_THRESHOLD = options.minRetrievalCount ?? 5;
979
+ const signalBearingSet = new Set(signalFiltered.map((r) => r.ref));
980
+ // Zero-feedback candidates for P0-A: processableRefs without a recent signal,
981
+ // plus the deferred noFeedbackPool. Dedupe by ref (the two sources are
982
+ // disjoint by construction, but guard against overlap defensively).
983
+ const noFeedbackSeen = new Set();
984
+ const noFeedbackCandidates = [];
985
+ for (const r of [...processableRefs.filter((r) => !signalBearingSet.has(r.ref)), ...noFeedbackPool]) {
986
+ if (noFeedbackSeen.has(r.ref))
987
+ continue;
988
+ noFeedbackSeen.add(r.ref);
989
+ noFeedbackCandidates.push(r);
990
+ }
991
+ let highRetrievalRefs = [];
992
+ // Retrieval counts for the zero-feedback pool, hoisted so the Layer-2
993
+ // proactive-maintenance selector below can reuse them without a second DB pass.
994
+ // Also fetch lastUseMs here for the proactive-maintenance recency term (plan §WS-1
995
+ // step 2: recency is MANDATORY — never pinned to floor).
996
+ let retrievalCounts = new Map();
997
+ let lastUseMsForProactive = new Map();
998
+ let dbForRetrieval;
999
+ try {
1000
+ dbForRetrieval = openExistingDatabase();
1001
+ const showEventCount = countUsageEventsByType(dbForRetrieval, "show");
1002
+ if (showEventCount === 0) {
1003
+ warn("Warning: show events not yet in usage_events — zero-feedback fallback will match only search-retrieved assets.");
1004
+ }
1005
+ // Fetch retrieval counts for ALL candidates — not only the zero-feedback pool.
1006
+ // Previously only noFeedbackCandidates were looked up, so feedback-bearing refs
1007
+ // had retrievalFreq=0 in computeSalience(), collapsing their retrievalSalience
1008
+ // to 0 regardless of actual use. Two assets of the same type — one
1009
+ // heavily-retrieved, one never-touched — would receive identical rankScores.
1010
+ // Fix (WS-1 blocker 3): union the feedback pool into the lookup.
1011
+ const allCandidateRefs = [...new Set([...signalFiltered, ...noFeedbackCandidates].map((r) => r.ref))];
1012
+ retrievalCounts = getRetrievalCounts(dbForRetrieval, allCandidateRefs);
1013
+ lastUseMsForProactive = getLastUseMsByRef(dbForRetrieval, noFeedbackCandidates.map((r) => r.ref));
1014
+ // High-retrieval signal-delta (simplified rule, 0.8.0): a no-feedback
1015
+ // ref qualifies exactly once — when it has actually been retrieved
1016
+ // (retrievalCount ≥ 1) AND retrievalCount ≥ threshold AND no prior reflect
1017
+ // proposal exists for it. Once a reflect proposal is on record, subsequent
1018
+ // re-eligibility requires explicit feedback (which flows through the normal
1019
+ // signal-delta gate above). The explicit `> 0` guard keeps a threshold of 0
1020
+ // from rescuing genuinely never-retrieved assets — the fallback is for
1021
+ // *retrieved* assets, not silent ones. Tracking growth in retrieval count
1022
+ // would require persisting the count in proposal metadata; deferred to a
1023
+ // follow-up.
1024
+ highRetrievalRefs = noFeedbackCandidates.filter((r) => {
1025
+ const count = retrievalCounts.get(r.ref) ?? 0;
1026
+ return count > 0 && count >= RETRIEVAL_COUNT_THRESHOLD && !lastReflectProposalTs.has(r.ref);
1027
+ });
1028
+ }
1029
+ catch (err) {
1030
+ rethrowIfTestIsolationError(err);
1031
+ // best-effort: if DB unavailable, highRetrievalRefs stays empty
1032
+ }
1033
+ finally {
1034
+ if (dbForRetrieval)
1035
+ closeDatabase(dbForRetrieval);
1036
+ }
1037
+ // ── Layer 2: PROACTIVE MAINTENANCE SELECTOR (third eligibility source) ─────
1038
+ // The signal-delta gate and P0-A only surface assets with fresh feedback or a
1039
+ // raw-retrieval spike. Neither revisits a stable, high-value asset on a
1040
+ // schedule, so on a quiet stash useful assets drift stale and are never
1041
+ // refreshed. When the `proactiveMaintenance` process is enabled (DEFAULT OFF)
1042
+ // and the run is whole-stash / type scope, this selector ranks the eligible
1043
+ // population by a composite maintenance priority, gates on staleness ("due"),
1044
+ // bounds to top-N, and folds the winners into the SAME candidate set the other
1045
+ // two sources feed — so they flow through the existing #580 empty-diff /
1046
+ // cosmetic suppression and additive-distill gates. It adds no new mutation
1047
+ // logic of its own. The due gate doubles as the rotation cooldown: a freshly
1048
+ // reflected asset is excluded until it ages back past `dueDays`, so successive
1049
+ // runs rotate through the due pool rather than re-selecting the same heads.
1050
+ let proactiveRefs = [];
1051
+ let proactiveMaintenanceSummary;
1052
+ const proactiveEnabled = scope.mode !== "ref" && resolveProcessEnabled("proactiveMaintenance", improveProfile);
1053
+ if (proactiveEnabled) {
1054
+ const pmCfg = improveProfile.processes?.proactiveMaintenance;
1055
+ const dueDays = pmCfg?.dueDays ?? DEFAULT_DUE_DAYS;
1056
+ const maxPerRun = pmCfg?.maxPerRun ?? pmCfg?.limit ?? DEFAULT_MAX_PER_RUN;
1057
+ // Candidate population: the zero-feedback / non-signal pool — exactly the
1058
+ // assets the other two sources would NOT pick this run. Exclude any P0-A
1059
+ // rescued this run so we never double-select the same ref.
1060
+ const alreadySelected = new Set(highRetrievalRefs.map((r) => r.ref));
1061
+ const pmCandidates = noFeedbackCandidates.filter((r) => !alreadySelected.has(r.ref));
1062
+ const selection = selectProactiveMaintenanceRefs({
1063
+ candidates: pmCandidates,
1064
+ lastReflectTs: lastReflectProposalTs,
1065
+ lastDistillTs: lastDistillProposalTs,
1066
+ retrievalCounts,
1067
+ // WS-1: wire lastUseMs so the recency decay term is genuine (plan §step 2).
1068
+ lastUseMs: lastUseMsForProactive,
1069
+ sizeBytesOf: (r) => {
1070
+ const fp = r.filePath;
1071
+ if (!fp)
1072
+ return undefined;
1073
+ try {
1074
+ return fs.statSync(fp).size;
1075
+ }
1076
+ catch {
1077
+ return undefined;
1078
+ }
1079
+ },
1080
+ dueDays,
1081
+ maxPerRun,
1082
+ });
1083
+ proactiveRefs = selection.selected;
1084
+ proactiveMaintenanceSummary = {
1085
+ selected: selection.selected.length,
1086
+ dueTotal: selection.dueTotal,
1087
+ neverReflected: selection.neverReflected,
1088
+ };
1089
+ // Aggregated observability event (never per-ref — avoids the event flood the
1090
+ // Layer-1 work eliminated). Mirrors the `no_new_signal` aggregation pattern.
1091
+ appendEvent({
1092
+ eventType: "proactive_selected",
1093
+ ref: undefined,
1094
+ metadata: {
1095
+ count: selection.selected.length,
1096
+ dueTotal: selection.dueTotal,
1097
+ neverReflected: selection.neverReflected,
1098
+ },
1099
+ }, eventsCtx);
1100
+ if (selection.selected.length > 0) {
1101
+ info(`[improve] proactive maintenance selected ${selection.selected.length}/${selection.dueTotal} due refs ` +
1102
+ `(${selection.neverReflected} never reflected, dueDays=${dueDays}, maxPerRun=${maxPerRun})`);
1103
+ }
1104
+ }
1105
+ // ── Layer 3: HIGH-SALIENCE ADMISSION GATE (#608) ──────────────────────────
1106
+ // Zero-feedback refs whose encoding_salience (set at distill time by
1107
+ // scoreEncodingSalience) exceeds the configured salienceThreshold are admitted
1108
+ // into the improve run even without retrieval or feedback signal. This rescues
1109
+ // newly distilled assets that the stash has not yet surfaced to users.
1110
+ //
1111
+ // Cap: at most 10% of the effective run limit so the lane cannot crowd out
1112
+ // reactive feedback. Requires state.db to have an asset_salience row — refs
1113
+ // without a row (pre-#608 assets still on the type-weight stub) are skipped.
1114
+ //
1115
+ // Cooldown: a ref qualifies at most once — when no prior reflect proposal
1116
+ // exists for it (`!lastReflectProposalTs.has`). Without this guard the lane
1117
+ // re-selects the same high-salience refs on EVERY run (auto-accept emits a
1118
+ // `promoted` event, not `feedback`, so the ref never leaves
1119
+ // noFeedbackCandidates), burning LLM calls and churning the asset. This
1120
+ // mirrors the P0-A high-retrieval gate's `!lastReflectProposalTs.has(r.ref)`
1121
+ // guard above so all "rescue" lanes share the same once-per-asset semantics.
1122
+ //
1123
+ // Content-provenance gate (#644 follow-up): the row must ALSO carry a genuine
1124
+ // content-derived encoding score (`isContentEncodingRow`). Otherwise the lane
1125
+ // admits the per-type WEIGHT STUB (skill/agent 0.9, command/workflow 0.8,
1126
+ // lesson 0.75 from DEFAULT_TYPE_ENCODING_WEIGHTS) for every distill-unscored
1127
+ // asset — i.e. "high-salience" degenerates into "is a skill/agent/command/
1128
+ // lesson", which selected the lore-writer type-stub agent on every run. Only
1129
+ // content-scored assets earn the high-salience rescue; type-stub rows must
1130
+ // earn retrieval/feedback signal via the other lanes. This PRESERVES #608's
1131
+ // intent — distilled assets (the lane's real targets) keep their real content
1132
+ // score and still qualify — while cutting the type-stub waste. See §5 F1 of
1133
+ // docs/design/improve-salience-working-reference.md and #608/#644.
1134
+ const highSalienceRefs = [];
1135
+ const salienceCfg = (options.config ?? loadConfig()).improve?.salience;
1136
+ const salienceThreshold = salienceCfg?.salienceThreshold ?? 0.75;
1137
+ const proactiveAndRetrievalSet = new Set([...highRetrievalRefs, ...proactiveRefs].map((r) => r.ref));
1138
+ try {
1139
+ withStateDb((dbForHighSalience) => {
1140
+ const effectiveLimit = options.limit ?? 10;
1141
+ const highSalienceCap = Math.max(1, Math.floor(effectiveLimit * 0.1));
1142
+ // #632/#4 — session-capture telemetry (checkpoints) must never consume
1143
+ // the scarce high-salience budget. Even with a content-scored row, these
1144
+ // are pipeline bookkeeping, not assets worth reflecting/rewriting.
1145
+ const candidates = noFeedbackCandidates.filter((r) => !proactiveAndRetrievalSet.has(r.ref) && !isSessionCaptureMemoryName(parseAssetRef(r.ref).name));
1146
+ for (const r of candidates) {
1147
+ if (highSalienceRefs.length >= highSalienceCap)
1148
+ break;
1149
+ const row = getAssetSalience(dbForHighSalience, r.ref);
1150
+ if (row &&
1151
+ isContentEncodingRow(row, parseAssetRef(r.ref).type) &&
1152
+ row.encoding_salience >= salienceThreshold &&
1153
+ !lastReflectProposalTs.has(r.ref)) {
1154
+ highSalienceRefs.push(r);
1155
+ }
1156
+ }
1157
+ }, { path: eventsCtx?.dbPath });
1158
+ }
1159
+ catch (err) {
1160
+ rethrowIfTestIsolationError(err);
1161
+ // best-effort: if DB unavailable, highSalienceRefs stays empty
1162
+ }
1163
+ if (highSalienceRefs.length > 0) {
1164
+ info(`[improve] high-salience lane admitted ${highSalienceRefs.length} content-scored ref(s) ` +
1165
+ `(threshold=${salienceThreshold}, requires content-derived encoding_source)`);
1166
+ }
1167
+ // Record an in-memory skip action for every zero-feedback ref that the
1168
+ // partition loop deferred to P0-A but P0-A then declined (retrievalCount below
1169
+ // threshold, or a prior reflect proposal already on record). These never make
1170
+ // it into mergedRefs, so without this they would silently vanish from the run
1171
+ // summary. No DB event is written here — these refs carry no signal at all, so
1172
+ // there is nothing for the skip histogram to aggregate; the action log alone
1173
+ // preserves the per-ref audit trail (mirrors the fully-skipped action above).
1174
+ const rescuedSet = new Set([...highRetrievalRefs, ...proactiveRefs, ...highSalienceRefs].map((r) => r.ref));
1175
+ for (const r of noFeedbackPool) {
1176
+ if (rescuedSet.has(r.ref))
1177
+ continue;
1178
+ actions.push({
1179
+ ref: r.ref,
1180
+ mode: "distill-skipped",
1181
+ result: { ok: true, reason: "no new signal since last proposal" },
1182
+ });
1183
+ }
1184
+ // If the user explicitly scoped to a single ref, always act on it —
1185
+ // skip the signal/retrieval filter entirely. The filter exists to avoid
1186
+ // noisy "improve everything" runs; it should not gate an intentional
1187
+ // per-ref invocation where the user's explicit choice is the signal.
1188
+ //
1189
+ // For type/all scope: only process refs with usage signals (recent feedback
1190
+ // or sufficient retrievals). A stash with no signals has 0 eligible refs —
1191
+ // usage is the gate. Run `akm feedback <ref> --positive` or retrieve assets
1192
+ // to bring them into the eligible pool.
1193
+ // Layer-2 proactive refs join the eligible set alongside feedback-signal and
1194
+ // high-retrieval (P0-A) refs. The four sources are disjoint by construction
1195
+ // (proactive draws from noFeedbackCandidates with the P0-A picks removed, and
1196
+ // high-salience draws from the remainder), but dedupe defensively so a ref can
1197
+ // never enter the loop twice. `requireFeedbackSignal` still suppresses all
1198
+ // fallback sources for callers that want feedback-only runs.
1199
+ const signalAndRetrievalRefs = dedupeRefs([
1200
+ ...signalFiltered,
1201
+ ...highRetrievalRefs,
1202
+ ...proactiveRefs,
1203
+ ...highSalienceRefs,
1204
+ ]);
1205
+ let mergedRefs = scope.mode === "ref" ? processableRefs : options.requireFeedbackSignal ? signalFiltered : signalAndRetrievalRefs;
1206
+ // ── Attribution tagging: stamp each ref with the eligibility lane that
1207
+ // selected it ──────────────────────────────────────────────────────────────
1208
+ // Every reflect/distill proposal must record WHICH lane chose its source asset
1209
+ // so downstream accept/reject/revert/retrieval outcomes can be sliced by lane
1210
+ // (does the PROACTIVE lane produce value vs the reactive lanes?). We build the
1211
+ // lane map here — the one place all four lanes are known — and stamp it onto
1212
+ // each ImproveEligibleRef object. Because the ref objects are shared by
1213
+ // reference across buckets, the stamp travels with the ref through the sort,
1214
+ // disk-check, and loop stages down to the reflect/distill event emit sites and
1215
+ // createProposal calls. See EligibilitySource for the lane vocabulary.
1216
+ //
1217
+ // Precedence (prefer the most specific reactive signal):
1218
+ // scope > signal-delta > high-retrieval > proactive > high-salience
1219
+ // A ref with real feedback is attributed to feedback even if it was also due
1220
+ // for proactive maintenance or had high encoding salience. We apply lanes
1221
+ // weakest-first so the strongest overwrites; the explicit --scope <ref> bypass
1222
+ // wins outright (user intent).
1223
+ const eligibilitySourceByRef = new Map();
1224
+ for (const r of highSalienceRefs)
1225
+ eligibilitySourceByRef.set(r.ref, "high-salience");
1226
+ for (const r of proactiveRefs)
1227
+ eligibilitySourceByRef.set(r.ref, "proactive");
1228
+ for (const r of highRetrievalRefs)
1229
+ eligibilitySourceByRef.set(r.ref, "high-retrieval");
1230
+ for (const r of signalFiltered)
1231
+ eligibilitySourceByRef.set(r.ref, "signal-delta");
1232
+ if (scope.mode === "ref") {
1233
+ // O-2 (#365): explicit --scope <ref> bypass — every ref in processableRefs
1234
+ // arrived via the scopeRefBypass branch, so attribute the whole set to scope.
1235
+ for (const r of processableRefs)
1236
+ eligibilitySourceByRef.set(r.ref, "scope");
1237
+ }
1238
+ for (const r of mergedRefs) {
1239
+ // "unknown" is a genuine fallback, never a silent alias for signal-delta:
1240
+ // only refs we truly cannot attribute land here (none in practice, since
1241
+ // mergedRefs is always a subset of the four lanes above).
1242
+ r.eligibilitySource = eligibilitySourceByRef.get(r.ref) ?? "unknown";
1243
+ }
1244
+ // WS-1 — Unified salience vector (S1 seam).
1245
+ //
1246
+ // The legacy sort combined three independent formulas (utility EMA, negative-only
1247
+ // ratio / symmetric-valence magnitude, and the proactive-maintenance priority
1248
+ // formula). WS-1 converges them into one `computeSalience()` call per ref, with
1249
+ // three independently-stored sub-scores and one documented rankScore projection.
1250
+ //
1251
+ // Migration note: if a profile still has `symmetricValence` set, emit a one-time
1252
+ // warning — its behaviour (symmetric |valence| attention) is now always-on as
1253
+ // part of the salience vector, so the knob is a no-op and will be removed in 0.10.
1254
+ if (improveProfile.symmetricValence === true) {
1255
+ warn("[improve] Profile option 'symmetricValence' is deprecated (WS-1 salience vector). " +
1256
+ "Symmetric valence is now always active; remove the option from your improve profile.");
1257
+ }
1258
+ // Fetch last-use timestamps from the index DB for the full merged set so the
1259
+ // recency term in retrievalSalience is genuinely decayable (plan §WS-1 step 2).
1260
+ // This reuses the index DB opened earlier for retrieval counts; a separate
1261
+ // lightweight open is used here to avoid holding the connection longer than needed.
1262
+ let lastUseMsByRef = new Map();
1263
+ // utilityMap is kept for backward-compatible observability (health report reads it).
1264
+ const utilityMap = buildUtilityMap(mergedRefs);
1265
+ let dbForSalience;
1266
+ try {
1267
+ dbForSalience = openExistingDatabase();
1268
+ lastUseMsByRef = getLastUseMsByRef(dbForSalience, mergedRefs.map((r) => r.ref));
1269
+ }
1270
+ catch (err) {
1271
+ rethrowIfTestIsolationError(err);
1272
+ // best-effort: if DB unavailable, recency term stays at floor (lastUseMs=0)
1273
+ }
1274
+ finally {
1275
+ if (dbForSalience)
1276
+ closeDatabase(dbForSalience);
1277
+ }
1278
+ // ── WS-2 Outcome loop ─────────────────────────────────────────────────────
1279
+ //
1280
+ // Update asset_outcome for every ref in the merged set BEFORE computing the
1281
+ // salience vector so the updated outcome_score feeds outcomeSalience this run.
1282
+ //
1283
+ // Inputs per ref:
1284
+ // - currentRetrievalCount: from retrievalCounts (index DB)
1285
+ // - lastRetrievedAt: from lastUseMsByRef (utility_scores.last_used_at)
1286
+ // - negativeFeedbackCount: cumulative negatives from feedbackSummary
1287
+ // - acceptedChangeCount: accepted proposals for this ref (state.db)
1288
+ // - valence: net valence from computeValenceScore(feedbackSummary.get(ref))
1289
+ // - utilityScore: from utilityMap (for warm-start seed on new rows)
1290
+ //
1291
+ // Best-effort: outcome failures never block the salience or ranking pass.
1292
+ const outcomeSalienceByRef = new Map();
1293
+ try {
1294
+ withStateDb((outcomeDb) => {
1295
+ // Count accepted proposals per ref in one pass (avoid N separate queries).
1296
+ // Scoped to primaryStashDir when available so multi-stash installs don't
1297
+ // inflate counts with proposals from other stashes.
1298
+ const acceptedCountByRef = new Map();
1299
+ try {
1300
+ const acceptedProposals = listStateProposals(outcomeDb, {
1301
+ status: "accepted",
1302
+ ...(primaryStashDir ? { stashDir: primaryStashDir } : {}),
1303
+ });
1304
+ for (const p of acceptedProposals) {
1305
+ acceptedCountByRef.set(p.ref, (acceptedCountByRef.get(p.ref) ?? 0) + 1);
1306
+ }
1307
+ }
1308
+ catch {
1309
+ // best-effort: if proposals query fails, accepted counts stay at 0
1310
+ }
1311
+ // Update each ref's outcome row and collect the resulting outcome scores.
1312
+ const rawOutcomeScores = new Map();
1313
+ const nowForOutcome = Date.now();
1314
+ for (const r of mergedRefs) {
1315
+ const fb = feedbackSummary.get(r.ref) ?? { positive: 0, negative: 0 };
1316
+ const valenceResult = computeValenceScore(fb);
1317
+ try {
1318
+ const result = updateAssetOutcome(outcomeDb, {
1319
+ ref: r.ref,
1320
+ currentRetrievalCount: retrievalCounts.get(r.ref) ?? 0,
1321
+ lastRetrievedAt: lastUseMsByRef.get(r.ref) ?? 0,
1322
+ acceptedChangeCount: acceptedCountByRef.get(r.ref) ?? 0,
1323
+ negativeFeedbackCount: fb.negative,
1324
+ valence: valenceResult.valence,
1325
+ utilityScore: utilityMap.get(r.ref),
1326
+ now: nowForOutcome,
1327
+ });
1328
+ rawOutcomeScores.set(r.ref, result.outcomeScore);
1329
+ }
1330
+ catch {
1331
+ // best-effort per-ref: skip this ref's outcome update on failure
1332
+ }
1333
+ }
1334
+ // Compute stash-wide max outcome_score for normalisation (diversity floor).
1335
+ // Read ALL rows (not just this run's batch) so the normalisation is
1336
+ // stash-relative, not pool-relative.
1337
+ let maxOutcomeScore = 0;
1338
+ try {
1339
+ const allOutcomes = getAllAssetOutcomes(outcomeDb);
1340
+ for (const row of allOutcomes) {
1341
+ if (row.outcome_score > maxOutcomeScore)
1342
+ maxOutcomeScore = row.outcome_score;
1343
+ }
1344
+ // Proxy-adequacy tripwire: emit a health event if outcome_score is
1345
+ // negatively correlated with accepted_change_rate (inverted proxy).
1346
+ const adequacy = computeProxyAdequacy(allOutcomes);
1347
+ if (adequacy.isInverted) {
1348
+ appendEvent({
1349
+ eventType: "outcome_proxy_inverted",
1350
+ ref: undefined,
1351
+ metadata: {
1352
+ correlation: adequacy.correlation,
1353
+ n: adequacy.n,
1354
+ note: "corr(outcome_score, accepted_change_rate) < −0.3: high-outcome_score assets have LOW accepted-change rates — the proxy's 'doing well' signal is inverted, so the coarse retrieval-delta signal is no longer trustworthy and the 0.10+ rich in-session signal is no longer deferrable. See plan §WS-2 proxy-adequacy tripwire.",
1355
+ },
1356
+ }, eventsCtx);
1357
+ }
1358
+ }
1359
+ catch {
1360
+ // best-effort: tripwire failure never blocks ranking
1361
+ }
1362
+ // Convert raw outcome scores → normalised outcomeSalience values in [0,1].
1363
+ for (const [ref, score] of rawOutcomeScores) {
1364
+ const normalised = outcomeScoreToSalience(score, maxOutcomeScore);
1365
+ outcomeSalienceByRef.set(ref, normalised);
1366
+ }
1367
+ // Also fetch outcome scores for refs NOT updated this run (stale or absent)
1368
+ // so the outcomeSalience read path works for all refs in the batch.
1369
+ const missingRefs = mergedRefs.map((r) => r.ref).filter((ref) => !rawOutcomeScores.has(ref));
1370
+ if (missingRefs.length > 0) {
1371
+ const storedScores = getOutcomeScoresByRef(outcomeDb, missingRefs);
1372
+ for (const [ref, score] of storedScores) {
1373
+ outcomeSalienceByRef.set(ref, outcomeScoreToSalience(score, maxOutcomeScore));
1374
+ }
1375
+ }
1376
+ }, { path: eventsCtx?.dbPath, borrowed: eventsCtx?.db });
1377
+ }
1378
+ catch (err) {
1379
+ rethrowIfTestIsolationError(err);
1380
+ // best-effort: outcome failures never block salience computation
1381
+ }
1382
+ // Compute the salience vector for every ref in the merged set.
1383
+ // retrievalCounts now covers the full candidate set (feedback-bearing + zero-feedback)
1384
+ // so feedback refs get their genuine retrieval frequency, not a 0-floor fallback.
1385
+ // outcomeSalienceByRef is populated by WS-2 above (or empty on first run).
1386
+ //
1387
+ // Part-V gate: read the operator opt-in flag from config. Default false
1388
+ // (WS-1 parity weights) until the maintainer runs scripts/akm-eval and sets
1389
+ // improve.salience.outcomeWeightEnabled: true in the config.
1390
+ const salienceConfig = (options.config ?? loadConfig()).improve?.salience;
1391
+ const outcomeWeightEnabled = salienceConfig?.outcomeWeightEnabled === true;
1392
+ const salienceMap = new Map();
1393
+ const nowForSalience = Date.now();
1394
+ // #644 — preserve content-derived encoding scores across runs.
1395
+ //
1396
+ // Before computing the salience vector, load each ref's stored encoding score
1397
+ // and its provenance. When the stored row carries a genuine content-derived
1398
+ // score (written by the distill path via `scoreEncodingSalience`), pass that
1399
+ // value back in as `inputs.encodingSalience` so `computeSalience` does NOT fall
1400
+ // back to the type-weight stub — keeping both the persisted `encoding_salience`
1401
+ // AND the derived `rank_score` keyed on real novelty/magnitude/prediction-error.
1402
+ // Refs that have never been content-scored keep the type-weight stub fallback.
1403
+ const storedEncodingByRef = new Map();
1404
+ try {
1405
+ withStateDb((dbForStoredEncoding) => {
1406
+ for (const r of mergedRefs) {
1407
+ const type = r.ref.includes(":") ? r.ref.slice(0, r.ref.indexOf(":")) : "";
1408
+ const row = getAssetSalience(dbForStoredEncoding, r.ref);
1409
+ if (row && isContentEncodingRow(row, type)) {
1410
+ storedEncodingByRef.set(r.ref, row.encoding_salience);
1411
+ }
1412
+ }
1413
+ }, { path: eventsCtx?.dbPath });
1414
+ }
1415
+ catch (err) {
1416
+ rethrowIfTestIsolationError(err);
1417
+ // best-effort: if DB unavailable, fall back to type-weight stub (prior behaviour)
1418
+ }
1419
+ for (const r of mergedRefs) {
1420
+ const type = r.ref.includes(":") ? r.ref.slice(0, r.ref.indexOf(":")) : "";
1421
+ const sizeBytes = (() => {
1422
+ const fp = r.filePath;
1423
+ if (!fp)
1424
+ return undefined;
1425
+ try {
1426
+ return fs.statSync(fp).size;
1427
+ }
1428
+ catch {
1429
+ return undefined;
1430
+ }
1431
+ })();
1432
+ const storedEncoding = storedEncodingByRef.get(r.ref);
1433
+ const vector = computeSalience({
1434
+ ref: r.ref,
1435
+ type,
1436
+ // #644: pass the stored content-derived score (if any) so the type-weight
1437
+ // stub is NOT re-asserted over a real distill-written encoding score.
1438
+ ...(storedEncoding !== undefined ? { encodingSalience: storedEncoding } : {}),
1439
+ retrievalFreq: retrievalCounts.get(r.ref) ?? 0,
1440
+ lastUseMs: lastUseMsByRef.get(r.ref),
1441
+ utilityScore: utilityMap.get(r.ref),
1442
+ outcomeSalience: outcomeSalienceByRef.get(r.ref),
1443
+ sizeBytes,
1444
+ now: nowForSalience,
1445
+ outcomeWeightEnabled,
1446
+ });
1447
+ salienceMap.set(r.ref, vector);
1448
+ }
1449
+ // Persist salience vectors to state.db (best-effort, non-blocking).
1450
+ // The canonical store enables WS-3 homeostatic demotion and WS-2 outcome reads.
1451
+ //
1452
+ // Forgetting-safety report (plan §WS-1 step 7) — stash-wide rank comparison:
1453
+ //
1454
+ // BEFORE persisting the new rankScores, read ALL existing rows from state.db
1455
+ // (not just the per-run candidate pool). This gives stash-wide rank positions so
1456
+ // the top-200/below-500 thresholds are meaningful.
1457
+ //
1458
+ // Two distinct scenarios:
1459
+ //
1460
+ // A. First WS-1 run (table empty): the old stash-wide combinedEligibilityScore
1461
+ // ordering was never persisted in state.db (asset_salience is a new WS-1 table).
1462
+ // However, the old formula's inputs are available in-scope for every candidate
1463
+ // in the current pool: utility comes from utilityMap and the attention term
1464
+ // from feedbackSummary (positive/negative counts). We reconstruct the old
1465
+ // combinedEligibilityScore = utility * UTILITY_WEIGHT + attention * FEEDBACK_WEIGHT
1466
+ // for every ref in salienceMap and rank them, giving a candidate-pool-scoped
1467
+ // old ordering. This is a partial reconstruction (only current-pool refs, not
1468
+ // stash-wide), but it is the most faithful comparison possible at cutover and
1469
+ // allows the top-200→below-500 forgetting guard to fire if the formula change
1470
+ // dramatically reorders the candidate pool.
1471
+ // See docs/archive/improve-reconciliation-plan.md §WS-1 step 7 — the stash-wide
1472
+ // ordering was unreconstructable (no prior state.db snapshot), so this candidate-
1473
+ // pool partial reconstruction is the documented resolution for the first-run case.
1474
+ // Emit `improve_salience_first_run` to mark the cutover moment and include the
1475
+ // reconstructed comparison result in the metadata.
1476
+ //
1477
+ // B. Subsequent runs (table has rows): use ALL existing rows as old ranks, merge
1478
+ // them with the current run's salienceMap updates for new ranks, and call
1479
+ // buildRankChangeReport with stash-wide positions. This detects real rank drift
1480
+ // — e.g. a retrieval-pattern shift causing a previously top-200 asset to slip
1481
+ // below position 500.
1482
+ //
1483
+ // Measurement-protocol deferral (plan §269, Part-V):
1484
+ // The Part-V T0 baseline (scripts/akm-eval + health report) and the throughput/
1485
+ // quality gate are deferred pending owner sign-off. Full measurement requires a
1486
+ // before/after `akm health` report. Owner-acknowledged deferral: WS-2 landing
1487
+ // will re-introduce outcome salience and trigger the full re-tuning pass at that
1488
+ // time. salience.ts already accepts outcomeSalience directly as an input
1489
+ // (see SalienceInputs.outcomeSalience); no separate hook is needed.
1490
+ //
1491
+ // Forgetting-safety collection: populated inside scenario B below, consumed
1492
+ // after the try/catch to union candidates into mergedRefs before the sort.
1493
+ // Only refs from a real pre-existing ordering (scenario B) are collected;
1494
+ // empty on scenario A or when no candidates dropped below the threshold.
1495
+ let pendingForgettingRefs = [];
1496
+ try {
1497
+ withStateDb((stateDb) => {
1498
+ // Step 7: stash-wide rank-change report BEFORE overwriting the table.
1499
+ //
1500
+ // Load ALL existing rows so rank positions are stash-relative, not pool-relative.
1501
+ const existingAllScores = getAllRankScores(stateDb);
1502
+ if (existingAllScores.size === 0) {
1503
+ // Scenario A: first WS-1 run — table empty.
1504
+ //
1505
+ // Reconstruct the old combinedEligibilityScore ordering for the current
1506
+ // candidate pool using inputs that are already in-scope: utility from
1507
+ // utilityMap and the attention term from feedbackSummary (positive/negative
1508
+ // counts). Old formula: score = utility * UTILITY_WEIGHT + attention * FEEDBACK_WEIGHT.
1509
+ //
1510
+ // Limitation: this covers only the current-run candidate pool, not the full
1511
+ // stash. The stash-wide ordering was never persisted (asset_salience is a new
1512
+ // WS-1 table), so this is the most faithful comparison possible at cutover.
1513
+ // See docs/archive/improve-reconciliation-plan.md §WS-1 step 7.
1514
+ const reconstructedOldScores = new Map();
1515
+ for (const ref of salienceMap.keys()) {
1516
+ const utility = utilityMap.get(ref) ?? 0;
1517
+ const fb = feedbackSummary.get(ref) ?? { positive: 0, negative: 0 };
1518
+ const attention = computeValenceScore(fb).attention;
1519
+ reconstructedOldScores.set(ref, utility * UTILITY_WEIGHT + attention * FEEDBACK_WEIGHT);
1520
+ }
1521
+ // Assign 1-indexed rank positions sorted by score desc (tie-break: ref asc).
1522
+ const toRanks = (scores) => {
1523
+ const sorted = [...scores.entries()].sort(([refA, a], [refB, b]) => b !== a ? b - a : refA < refB ? -1 : refA > refB ? 1 : 0);
1524
+ return new Map(sorted.map(([ref], i) => [ref, i + 1]));
1525
+ };
1526
+ const oldRanks = toRanks(reconstructedOldScores);
1527
+ const newRanks = toRanks(new Map([...salienceMap.entries()].map(([ref, v]) => [ref, v.rankScore])));
1528
+ const firstRunReport = buildRankChangeReport(oldRanks, newRanks);
1529
+ if (firstRunReport.forgettingCandidates.length > 0) {
1530
+ warn(`[improve/salience] WS-1 first-run rank-change report: ${firstRunReport.forgettingCandidates.length} asset(s) fell from top-200 to below position 500 (cutover formula change). ` +
1531
+ `Top drops: ${firstRunReport.forgettingCandidates
1532
+ .slice(0, 5)
1533
+ .map((e) => `${e.ref} (#${e.oldRank}→#${e.newRank})`)
1534
+ .join(", ")}`);
1535
+ pendingForgettingRefs = firstRunReport.forgettingCandidates.map((e) => e.ref);
1536
+ }
1537
+ appendEvent({
1538
+ eventType: "improve_salience_first_run",
1539
+ ref: undefined,
1540
+ metadata: {
1541
+ candidateCount: salienceMap.size,
1542
+ note: "first WS-1 salience run — partial reconstruction of old combinedEligibilityScore ordering for candidate pool (stash-wide ordering not available); see improve-reconciliation-plan.md §WS-1 step 7",
1543
+ forgettingCandidates: firstRunReport.forgettingCandidates.length,
1544
+ topDrops: firstRunReport.forgettingCandidates.slice(0, 10).map((e) => ({
1545
+ ref: e.ref,
1546
+ oldRank: e.oldRank,
1547
+ newRank: e.newRank,
1548
+ })),
1549
+ },
1550
+ }, eventsCtx);
1551
+ }
1552
+ else {
1553
+ // Scenario B: subsequent run — compare stash-wide old vs. new ranks.
1554
+ //
1555
+ // Build new scores by merging the full table with this run's updates.
1556
+ // Refs in salienceMap override their stored value; refs not in this run
1557
+ // retain their stored value unchanged. This gives a complete stash-wide
1558
+ // picture of what the new ordering looks like after this run.
1559
+ const mergedNewScores = new Map(existingAllScores);
1560
+ for (const [ref, vector] of salienceMap) {
1561
+ mergedNewScores.set(ref, vector.rankScore);
1562
+ }
1563
+ // Assign 1-indexed rank positions sorted by score desc (tie-break: ref asc).
1564
+ const toRanks = (scores) => {
1565
+ const sorted = [...scores.entries()].sort(([refA, a], [refB, b]) => b !== a ? b - a : refA < refB ? -1 : refA > refB ? 1 : 0);
1566
+ return new Map(sorted.map(([ref], i) => [ref, i + 1]));
1567
+ };
1568
+ const oldRanks = toRanks(existingAllScores);
1569
+ const newRanks = toRanks(mergedNewScores);
1570
+ const report = buildRankChangeReport(oldRanks, newRanks);
1571
+ if (report.forgettingCandidates.length > 0) {
1572
+ warn(`[improve/salience] WS-1 rank-change report: ${report.forgettingCandidates.length} asset(s) fell from top-200 to below position 500. ` +
1573
+ `Top drops: ${report.forgettingCandidates
1574
+ .slice(0, 5)
1575
+ .map((e) => `${e.ref} (#${e.oldRank}→#${e.newRank})`)
1576
+ .join(", ")}`);
1577
+ // Collect refs for protective consolidation pass (plan §WS-1 step 7).
1578
+ // These are force-included in the candidate pool (mergedRefs) after
1579
+ // this try block, bypassing cooldown/signal-delta gating.
1580
+ pendingForgettingRefs = report.forgettingCandidates.map((e) => e.ref);
1581
+ }
1582
+ appendEvent({
1583
+ eventType: "improve_salience_rank_change",
1584
+ ref: undefined,
1585
+ metadata: {
1586
+ stashSize: existingAllScores.size,
1587
+ totalChanged: report.allChanges.length,
1588
+ forgettingCandidates: report.forgettingCandidates.length,
1589
+ topDrops: report.forgettingCandidates.slice(0, 10).map((e) => ({
1590
+ ref: e.ref,
1591
+ oldRank: e.oldRank,
1592
+ newRank: e.newRank,
1593
+ })),
1594
+ },
1595
+ }, eventsCtx);
1596
+ }
1597
+ for (const [ref, vector] of salienceMap) {
1598
+ upsertAssetSalience(stateDb, ref, vector, nowForSalience);
1599
+ }
1600
+ }, { path: eventsCtx?.dbPath });
1601
+ }
1602
+ catch (err) {
1603
+ rethrowIfTestIsolationError(err);
1604
+ // best-effort: salience persistence failure never blocks ranking
1605
+ }
1606
+ // ── Protective consolidation pass (plan §WS-1 step 7) ─────────────────────
1607
+ // Forgetting candidates detected in scenario B are force-injected into
1608
+ // mergedRefs here, BEFORE the effectiveScore sort, bypassing cooldown and
1609
+ // signal-delta gating. Any ref already present in mergedRefs keeps its
1610
+ // existing eligibilitySource (stronger reactive signals win); refs not yet in
1611
+ // the pool are synthesised as minimal ImproveEligibleRef stubs and labelled
1612
+ // 'forgetting-safety' so S5/WS-5 can slice by lane. The dedupeRefs call
1613
+ // ensures no ref can enter the loop twice.
1614
+ if (pendingForgettingRefs.length > 0 && scope.mode !== "ref") {
1615
+ const existingRefSet = new Set(mergedRefs.map((r) => r.ref));
1616
+ const newForgettingRefs = [];
1617
+ for (const ref of pendingForgettingRefs) {
1618
+ if (!existingRefSet.has(ref)) {
1619
+ // Ref not already in the candidate pool — synthesise a stub so it
1620
+ // participates in the reflect/distill loop with proper attribution.
1621
+ newForgettingRefs.push({ ref, reason: "scope-type", eligibilitySource: "forgetting-safety" });
1622
+ }
1623
+ // Always stamp the lane in the attribution map (overwrites weaker lanes;
1624
+ // stronger reactive signals — scope/signal-delta/high-retrieval/proactive
1625
+ // — are written after this block so they take precedence).
1626
+ eligibilitySourceByRef.set(ref, "forgetting-safety");
1627
+ }
1628
+ if (newForgettingRefs.length > 0) {
1629
+ mergedRefs = dedupeRefs([...mergedRefs, ...newForgettingRefs]);
1630
+ }
1631
+ // Re-stamp attribution for any refs whose lane needs updating.
1632
+ // Precedence (weakest → strongest, each overwrites the previous):
1633
+ // proactive < high-retrieval < forgetting-safety < signal-delta
1634
+ // Scope mode is already excluded by the outer guard (`scope.mode !== "ref"`).
1635
+ // forgetting-safety sits above proactive and high-retrieval so that a ref
1636
+ // flagged as a forgetting candidate is always visible to S5/WS-5 as such,
1637
+ // even when it was also due for a proactive maintenance run. signal-delta
1638
+ // overrides forgetting-safety because a ref with fresh feedback is reactive
1639
+ // and doesn't need the protective pass label for measurement purposes.
1640
+ for (const r of highSalienceRefs)
1641
+ eligibilitySourceByRef.set(r.ref, "high-salience");
1642
+ for (const r of proactiveRefs)
1643
+ eligibilitySourceByRef.set(r.ref, "proactive");
1644
+ for (const r of highRetrievalRefs)
1645
+ eligibilitySourceByRef.set(r.ref, "high-retrieval");
1646
+ // Apply forgetting-safety OVER proactive, high-retrieval, and high-salience
1647
+ // (already stamped in the loop above via
1648
+ // `eligibilitySourceByRef.set(ref, "forgetting-safety")`). No-op here: the
1649
+ // set() calls above for proactive/high-retrieval/high-salience overwrite the
1650
+ // earlier forgetting-safety stamp — so we re-apply forgetting-safety now for
1651
+ // those refs that are both forgetting candidates AND in another fallback lane.
1652
+ for (const ref of pendingForgettingRefs) {
1653
+ eligibilitySourceByRef.set(ref, "forgetting-safety");
1654
+ }
1655
+ // signal-delta is the strongest reactive signal and overrides forgetting-safety.
1656
+ for (const r of signalFiltered)
1657
+ eligibilitySourceByRef.set(r.ref, "signal-delta");
1658
+ // Update eligibilitySource on the ref objects themselves for any refs whose
1659
+ // lane changed (covers both new stubs and pre-existing refs).
1660
+ for (const r of mergedRefs) {
1661
+ r.eligibilitySource = eligibilitySourceByRef.get(r.ref) ?? "unknown";
1662
+ }
1663
+ }
1664
+ // ── REPLAY SELECTION layer (#610) ─────────────────────────────────────────
1665
+ // Bounded, ADDITIVE replay budget: up to `replayBudget` top-salience refs are
1666
+ // revisited even with zero reactive signal (no feedback, no retrieval) and
1667
+ // regardless of cooldown — exactly like the forgetting-safety lane, replay is
1668
+ // injected AFTER cooldown/signal-delta partitioning so it bypasses those gates.
1669
+ //
1670
+ // Strictly additive: the replay slice is appended AFTER the --limit fresh slice
1671
+ // (see the loopRefs partition below), so it can never shrink the fresh-ref set.
1672
+ // Replay is the WEAKEST lane — it only stamps refs no other lane already claimed,
1673
+ // and budget is spent only on refs not already in mergedRefs (so a stronger lane
1674
+ // never has its budget wasted or its label overwritten).
1675
+ //
1676
+ // Default replayBudget=0 ⇒ this whole block is a no-op (no DB open, no event,
1677
+ // no mergedRefs mutation), preserving byte-identical pre-#610 selection behavior.
1678
+ const replayBudget = (options.config ?? loadConfig()).improve?.salience?.replayBudget ?? 0;
1679
+ const replayRefSet = new Set();
1680
+ if (replayBudget > 0 && scope.mode !== "ref" && !options.requireFeedbackSignal) {
1681
+ try {
1682
+ withStateDb((replayDb) => {
1683
+ const alreadyInPool = new Set(mergedRefs.map((r) => r.ref));
1684
+ const allRankScores = getAllRankScores(replayDb);
1685
+ // Candidate universe = every salience row NOT already in the pool, ordered by
1686
+ // rank_score desc with a deterministic ref-string tie-break (mirrors the main
1687
+ // sort). Converged refs (consecutive_no_ops >= dampener threshold) are fully
1688
+ // EXCLUDED — a stronger skip than the dampener (which only halves order).
1689
+ let convergedSkipped = 0;
1690
+ const candidates = [];
1691
+ for (const [ref, rankScore] of allRankScores) {
1692
+ if (alreadyInPool.has(ref))
1693
+ continue;
1694
+ const noOps = getConsecutiveNoOps(replayDb, ref);
1695
+ if (noOps >= SALIENCE_NO_OP_DAMPEN_THRESHOLD) {
1696
+ convergedSkipped++;
1697
+ continue;
1698
+ }
1699
+ candidates.push({ ref, rankScore });
1700
+ }
1701
+ candidates.sort((a, b) => b.rankScore !== a.rankScore ? b.rankScore - a.rankScore : a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0);
1702
+ const candidatePool = candidates.length;
1703
+ const selected = candidates.slice(0, replayBudget);
1704
+ const newReplayRefs = [];
1705
+ for (const { ref } of selected) {
1706
+ replayRefSet.add(ref);
1707
+ // Synthesise a stub (mirror the forgetting-safety stub). Resolve the
1708
+ // backing file from the planned-ref pool so the downstream existsSync
1709
+ // guard keeps the ref (a replay candidate from asset_salience whose file
1710
+ // is gone correctly drops out). Only refs present in the indexed pool can
1711
+ // be revisited — refs without a planned entry get no filePath and are
1712
+ // dropped by the disk check, which is the desired behavior.
1713
+ const planned = plannedRefs.find((p) => p.ref === ref);
1714
+ newReplayRefs.push({
1715
+ ref,
1716
+ reason: "scope-type",
1717
+ eligibilitySource: "replay",
1718
+ ...(planned?.filePath ? { filePath: planned.filePath } : {}),
1719
+ });
1720
+ // Seed the salienceMap so the sort/effectiveScore can rank the replay ref.
1721
+ if (!salienceMap.has(ref)) {
1722
+ salienceMap.set(ref, {
1723
+ encoding: 0,
1724
+ outcome: 0,
1725
+ retrieval: 0,
1726
+ rankScore: allRankScores.get(ref) ?? 0,
1727
+ });
1728
+ }
1729
+ }
1730
+ if (newReplayRefs.length > 0) {
1731
+ mergedRefs = dedupeRefs([...mergedRefs, ...newReplayRefs]);
1732
+ // Replay is the WEAKEST lane: stamp 'replay' ONLY for refs not already
1733
+ // keyed by a stronger lane.
1734
+ for (const ref of replayRefSet) {
1735
+ if (!eligibilitySourceByRef.has(ref))
1736
+ eligibilitySourceByRef.set(ref, "replay");
1737
+ }
1738
+ for (const r of mergedRefs) {
1739
+ r.eligibilitySource = eligibilitySourceByRef.get(r.ref) ?? "unknown";
1740
+ }
1741
+ }
1742
+ // Aggregated observability event (never per-ref).
1743
+ appendEvent({
1744
+ eventType: "improve_replay_selected",
1745
+ ref: undefined,
1746
+ metadata: {
1747
+ count: newReplayRefs.length,
1748
+ budget: replayBudget,
1749
+ convergedSkipped,
1750
+ candidatePool,
1751
+ },
1752
+ }, eventsCtx);
1753
+ }, { path: eventsCtx?.dbPath });
1754
+ }
1755
+ catch (err) {
1756
+ rethrowIfTestIsolationError(err);
1757
+ // best-effort: if DB unavailable, replayRefSet stays empty
1758
+ }
1759
+ }
1760
+ // Build no-op map for consolidation-selection dampener (plan §WS-1 step 8).
1761
+ // Reads consecutive_no_ops from the SAME pinned db handle used elsewhere in
1762
+ // this function. The effective score is used ONLY for processing/selection
1763
+ // order — the persisted rank_score in asset_salience is never mutated here.
1764
+ const noOpMap = new Map();
1765
+ try {
1766
+ const noOpDb = eventsCtx?.db ?? (eventsCtx?.dbPath ? openStateDatabase(eventsCtx.dbPath) : null);
1767
+ if (noOpDb) {
1768
+ const ownsNoOpDb = !eventsCtx?.db;
1769
+ try {
1770
+ for (const r of mergedRefs) {
1771
+ noOpMap.set(r.ref, getConsecutiveNoOps(noOpDb, r.ref));
1772
+ }
1773
+ }
1774
+ finally {
1775
+ if (ownsNoOpDb)
1776
+ noOpDb.close();
1777
+ }
1778
+ }
1779
+ }
1780
+ catch {
1781
+ // best-effort: dampener failure never blocks selection
1782
+ }
1783
+ // Sort by effective selection score (desc), with explicit ref-string tie-break
1784
+ // for determinism. The effective score applies the consolidation-selection
1785
+ // dampener: assets that have been repeatedly skipped (consecutive_no_ops >=
1786
+ // THRESHOLD) are penalised by FACTOR so they sort after peers with similar
1787
+ // rankScore. The persisted rank_score is left unchanged — this is the whole
1788
+ // point of the dampener (stable assets stay fully retrievable).
1789
+ //
1790
+ // WIRING NOTE (plan §WS-1 step 8 / "consolidation-selection" disambiguation):
1791
+ // "consolidation-selection" in the plan refers to THIS reflect/distill
1792
+ // eligibility ordering — i.e. which assets are chosen for the reflect/distill
1793
+ // LLM pass — NOT to akmConsolidate (the cluster-merge phase at ~line 1994,
1794
+ // which runs earlier and never reads noOpMap). The no-op counter originates
1795
+ // from no-change reflect / quality-rejected distill outcomes; the dampener
1796
+ // suppresses repeated LLM attempts on those same assets without touching their
1797
+ // persisted rank_score (so they remain fully retrievable).
1798
+ //
1799
+ // This is the ONLY ranking path — negativeOnlyRatio and the legacy
1800
+ // symmetricValence branch are replaced. The three eligibilitySource lanes
1801
+ // (signal-delta / high-retrieval / proactive) survive as labels (set above).
1802
+ const effectiveScore = (ref) => {
1803
+ const rankScore = salienceMap.get(ref)?.rankScore ?? 0;
1804
+ const noOps = noOpMap.get(ref) ?? 0;
1805
+ return noOps >= SALIENCE_NO_OP_DAMPEN_THRESHOLD ? rankScore * SALIENCE_NO_OP_DAMPEN_FACTOR : rankScore;
1806
+ };
1807
+ const sorted = [...mergedRefs].sort((a, b) => {
1808
+ const scoreA = effectiveScore(a.ref);
1809
+ const scoreB = effectiveScore(b.ref);
1810
+ if (scoreB !== scoreA)
1811
+ return scoreB - scoreA;
1812
+ // Stable tie-break: deterministic regardless of input ordering.
1813
+ return a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0;
1814
+ });
1815
+ // Phase 0: surface coverage gaps from zero-result search queries
1816
+ let coverageGaps = [];
1817
+ try {
1818
+ const dbForGaps = openExistingDatabase();
1819
+ try {
1820
+ coverageGaps = getZeroResultSearches(dbForGaps);
1821
+ }
1822
+ finally {
1823
+ closeDatabase(dbForGaps);
1824
+ }
1825
+ }
1826
+ catch (err) {
1827
+ rethrowIfTestIsolationError(err);
1828
+ // best-effort
1829
+ }
1830
+ // actionableRefs is the post-cooldown, post-validation, post-signal, post-sort
1831
+ // set — i.e. the genuinely processable refs in priority order. Note: this is
1832
+ // a semantic shift from earlier code where actionableRefs was the pre-cooldown
1833
+ // sorted set; the new meaning matches reality and is documented on
1834
+ // ImprovePreparationResult.actionableRefs.
1835
+ //
1836
+ // Final guard: drop any candidate whose backing file is no longer on disk.
1837
+ // Phase 1 validation captures missing files at the start of preparation, but
1838
+ // the gap between that check and dispatch can be minutes on large stashes —
1839
+ // long enough for a checkpoint / git checkout / external cleanup to delete
1840
+ // the asset. Empirically (improve-critical-review 2026-05-20) the single
1841
+ // biggest reject category was "Asset no longer exists on disk" (604/1407 =
1842
+ // 43%), meaning reflect/distill was producing proposals against deleted refs.
1843
+ // A cheap existsSync per surviving candidate eliminates that wasted work.
1844
+ const assetMissingOnDisk = [];
1845
+ const existsCheckedActionable = [];
1846
+ for (const candidate of sorted) {
1847
+ // #591: prefer the path pre-resolved at planning time (synchronous
1848
+ // existsSync) over a serial async DB lookup per ref.
1849
+ const filePath = candidate.filePath && fs.existsSync(candidate.filePath)
1850
+ ? candidate.filePath
1851
+ : await findAssetFilePath(candidate.ref, options.stashDir);
1852
+ if (filePath && fs.existsSync(filePath)) {
1853
+ existsCheckedActionable.push(candidate);
1854
+ }
1855
+ else {
1856
+ assetMissingOnDisk.push(candidate.ref);
1857
+ }
1858
+ }
1859
+ // #592 audit: one summary event instead of one per missing ref. Normally
1860
+ // tiny, but a stash deletion racing the run could make this O(n) sequential
1861
+ // state.db writes. `refs` is capped so the metadata row stays bounded.
1862
+ if (assetMissingOnDisk.length > 0) {
1863
+ appendEvent({
1864
+ eventType: "improve_skipped",
1865
+ ref: undefined,
1866
+ metadata: {
1867
+ reason: "asset_missing_on_disk",
1868
+ count: assetMissingOnDisk.length,
1869
+ refs: assetMissingOnDisk.slice(0, 50),
1870
+ },
1871
+ }, eventsCtx);
1872
+ }
1873
+ const actionableRefs = existsCheckedActionable;
1874
+ // Re-split actionableRefs (sorted) into reflect-path vs distill-only-path while
1875
+ // preserving sort order. distillOnlyRefs participate in the sort so --limit
1876
+ // picks them by score, not by arbitrary position.
1877
+ const distillOnlyRefSetForSort = new Set(distillOnlyRefs.map((r) => r.ref));
1878
+ const reflectAndDistillRefsAfterSort = [];
1879
+ const distillOnlyRefsAfterSort = [];
1880
+ for (const r of actionableRefs) {
1881
+ if (distillOnlyRefSetForSort.has(r.ref)) {
1882
+ distillOnlyRefsAfterSort.push(r);
1883
+ }
1884
+ else {
1885
+ reflectAndDistillRefsAfterSort.push(r);
1886
+ }
1887
+ }
1888
+ // ── Phase 5: --limit applies to the post-cooldown actionable set ──────────
1889
+ //
1890
+ // #610 ADDITIVITY: replay-lane refs are budgeted SEPARATELY from the --limit
1891
+ // fresh slice. Without this split, a high-rankScore replay ref could sort above
1892
+ // a fresh ref in the single combined slice and STEAL its slot (violating AC2).
1893
+ // We partition into the replay lane vs the rest, apply --limit to the
1894
+ // non-replay (fresh) refs only, then APPEND up to `replayBudget` replay refs
1895
+ // after the fresh slice. Sort order within each partition is preserved.
1896
+ //
1897
+ // Default replayBudget=0 reduces this to the exact pre-#610 expression: with no
1898
+ // replay refs, `nonReplayLoop === allLoopRefs`, so `baseLoop === old slice` and
1899
+ // `replayLoop.slice(0, 0) === []` — byte-identical.
1900
+ const allLoopRefs = [...reflectAndDistillRefsAfterSort, ...distillOnlyRefsAfterSort];
1901
+ const replayLoop = allLoopRefs.filter((r) => r.eligibilitySource === "replay");
1902
+ const nonReplayLoop = allLoopRefs.filter((r) => r.eligibilitySource !== "replay");
1903
+ const baseLoop = options.limit ? nonReplayLoop.slice(0, options.limit) : nonReplayLoop;
1904
+ const loopRefs = [...baseLoop, ...replayLoop.slice(0, replayBudget)];
1905
+ // Update the returned distillOnlyRefs to the sorted order so callers see the
1906
+ // ranked view (loop stage uses it as a Set so order is irrelevant, but the
1907
+ // shape change keeps downstream consumers consistent).
1908
+ const distillOnlyRefsResult = distillOnlyRefsAfterSort;
1909
+ const totalReflectBlocked = fullySkippedCount + distillOnlyRefs.length;
1910
+ if (totalReflectBlocked > 0) {
1911
+ info(`[improve] ${totalReflectBlocked} of ${preCooldownCount} indexed refs blocked by reflect signal-delta ` +
1912
+ `(${fullySkippedCount} fully skipped, ${distillOnlyRefs.length} routed to distill-only)`);
1913
+ }
1914
+ if (signalAndRetrievalRefs.length > 0) {
1915
+ info(`[improve] ${signalAndRetrievalRefs.length} refs with usage signals (${signalFiltered.length} feedback, ${highRetrievalRefs.length} high-retrieval${replayRefSet.size > 0 ? `, ${replayRefSet.size} replay` : ""})`);
1916
+ }
1917
+ if (validationFailureRefs.size > 0) {
1918
+ info(`[improve] ${validationFailureRefs.size} with validation failures excluded`);
1919
+ }
1920
+ if (assetMissingOnDisk.length > 0) {
1921
+ info(`[improve] ${assetMissingOnDisk.length} candidates dropped — file not on disk`);
1922
+ }
1923
+ const deferredCount = actionableRefs.length - loopRefs.length;
1924
+ info(`[improve] ${actionableRefs.length} actionable; ${loopRefs.length} will be processed` +
1925
+ (options.limit && deferredCount > 0 ? ` (--limit ${options.limit} applied; ${deferredCount} deferred)` : ""));
1926
+ // WS-4: Per-phase threshold auto-tune for the extract phase.
1927
+ // Persists result for the NEXT run's makeGateConfig to read.
1928
+ const extractTuneDbPath = eventsCtx?.dbPath;
1929
+ if (options.autoAccept !== undefined && extractTuneDbPath) {
1930
+ try {
1931
+ maybeAutoTuneThreshold(extractPass.extractGateCfg.phaseThreshold ?? options.autoAccept, options.config ?? loadConfig(), extractTuneDbPath, undefined, "extract");
1932
+ }
1933
+ catch (err) {
1934
+ warn(`[improve] calibration auto-tune (extract) skipped: ${err instanceof Error ? err.message : String(err)}`);
1935
+ }
1936
+ }
1937
+ return {
1938
+ actions,
1939
+ cleanupWarnings,
1940
+ appliedCleanup,
1941
+ memoryIndexHealth,
1942
+ extract: extractResults,
1943
+ actionableRefs,
1944
+ signalBearingSet,
1945
+ validationFailures,
1946
+ schemaRepairs,
1947
+ lintSummary,
1948
+ loopRefs,
1949
+ distillCooledRefs,
1950
+ distillOnlyRefs: distillOnlyRefsResult,
1951
+ coverageGaps,
1952
+ recentErrors,
1953
+ utilityMap,
1954
+ gateAutoAcceptedCount,
1955
+ gateAutoAcceptFailedCount,
1956
+ consolidation: consolidationPass.consolidation,
1957
+ consolidationRan: consolidationPass.consolidationRan,
1958
+ ...(proactiveMaintenanceSummary ? { proactiveMaintenance: proactiveMaintenanceSummary } : {}),
1959
+ };
1960
+ }
1961
+ // TODO(refactor): 13 args including `actions`/`recentErrors` mutation channels. Restructure into immutable plan + mutable context objects — deferred to dedicated refactor with isolated testing.
1962
+ /**
1963
+ * Parameter object for {@link runImproveLoopStage} (WS10). Pure type reshape of
1964
+ * the former inline arg struct — every field, name, and type is preserved so the
1965
+ * function body and all runtime values are byte-identical. No control-flow change.
1966
+ */