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
@@ -4,89 +4,45 @@
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
6
6
  import { assertNever } from "../../core/assert.js";
7
- import { makeAssetRef, parseAssetRef } from "../../core/asset/asset-ref.js";
8
- import { parseFrontmatter } from "../../core/asset/frontmatter.js";
9
- import { daysToMs, isAssetType } from "../../core/common.js";
10
- import { getDefaultLlmConfig, loadConfig } from "../../core/config/config.js";
11
- import { ConfigError, NotFoundError, rethrowIfTestIsolationError, UsageError } from "../../core/errors.js";
7
+ import { daysToMs } from "../../core/common.js";
8
+ import { loadConfig } from "../../core/config/config.js";
9
+ import { rethrowIfTestIsolationError } from "../../core/errors.js";
12
10
  import { appendEvent, readEvents } from "../../core/events.js";
13
- import { probeLock, releaseLock, releaseLockIfOwned, tryAcquireLockSync } from "../../core/file-lock.js";
14
11
  import { classifyImproveAction } from "../../core/improve-types.js";
15
- import { openLogsDatabase, purgeOldTaskLogs } from "../../core/logs-db.js";
16
12
  import { getDbPath, getStateDbPathInDataDir } from "../../core/paths.js";
17
- import { openStateDatabase, purgeOldEvents, purgeOldImproveRuns } from "../../core/state-db.js";
13
+ import { openStateDatabase } from "../../core/state-db.js";
18
14
  import { info, warn } from "../../core/warn.js";
19
- import { closeDatabase, getAllEntries, getEntryCount, getRetrievalCounts, getUtilityScoresByIds, getZeroResultSearches, openDatabase, openExistingDatabase, } from "../../indexer/db/db.js";
15
+ import { closeDatabase, getEntryCount, openExistingDatabase } from "../../indexer/db/db.js";
20
16
  import { ensureIndex } from "../../indexer/ensure-index.js";
21
- import { runGraphExtractionPass } from "../../indexer/graph/graph-extraction.js";
22
17
  import { akmIndex } from "../../indexer/indexer.js";
23
- import { runMemoryInferencePass } from "../../indexer/passes/memory-inference.js";
24
- import { runStalenessDetectionPass } from "../../indexer/passes/staleness-detect.js";
25
- import { getWritableStashDirs, resolveSourceEntries } from "../../indexer/search/search-source.js";
26
- import { countUsageEventsByType } from "../../indexer/usage/usage-events.js";
27
- import { resolveAssetPath } from "../../indexer/walk/path-resolver.js";
28
- import { resolveImproveProcessRunnerFromProfile, resolveTriageJudgmentRunner } from "../../integrations/agent/runner.js";
29
- import { getAvailableHarnesses } from "../../integrations/session-logs/index.js";
30
- import { isLlmFeatureEnabled, isProcessEnabled } from "../../llm/feature-gate.js";
18
+ import { resolveSourceEntries } from "../../indexer/search/search-source.js";
19
+ import { resolveTriageJudgmentRunner } from "../../integrations/agent/runner.js";
31
20
  import { installLlmUsagePersistence } from "../../llm/usage-persist.js";
32
21
  import { withLlmStage } from "../../llm/usage-telemetry.js";
33
22
  import { isGitBackedStash, resolveWritableOverride, saveGitStash } from "../../sources/providers/git.js";
34
- import { akmLint } from "../lint/index.js";
35
23
  import { drainProposals } from "../proposal/drain.js";
36
24
  import { resolveDrainPolicy } from "../proposal/drain-policies.js";
37
- import { createProposal, expireStaleProposals, getProposal, isProposalSkipped, listProposals, purgeOrphanProposals, } from "../proposal/validators/proposals.js";
38
- import { runSchemaRepairPass } from "../sources/schema-repair.js";
39
- import { checkDeadUrls } from "../url-checker.js";
40
- import { akmConsolidate } from "./consolidate.js";
41
- import { akmDistill, deriveLessonRef, isDistillRefusedInputType } from "./distill.js";
42
- import { deriveKnowledgeRef } from "./distill-promotion-policy.js";
43
- import { countEvalCases, writeEvalCase } from "./eval-cases.js";
44
- import { akmExtract, countNewExtractCandidates } from "./extract.js";
45
- import { makeGateConfig, resolveExtractConfidence, runAutoAcceptGate } from "./improve-auto-accept.js";
46
- import { isProfileFilteredForAllPasses, resolveImproveProfile, resolveProcessEnabled, shouldSkipRef, } from "./improve-profiles.js";
25
+ import { akmDistill } from "./distill.js";
26
+ // Eligibility / candidate-selection predicates live in ./eligibility.
27
+ import { buildLatestProposalTsMap, collectEligibleRefs, memoryCleanupParentRef, resolveImproveScope, shouldAnalyzeMemoryCleanup, } from "./eligibility.js";
28
+ import { countEvalCases } from "./eval-cases.js";
29
+ import { resolveImproveProfile, resolveProcessEnabled } from "./improve-profiles.js";
30
+ // #607 per-process lock primitives live in ./locks. Imported for internal use;
31
+ // resetHeldProcessLocks is re-exported (the test seam imports it from here).
32
+ import { PROCESS_LOCK_DEFS, processLockPath, releaseAllProcessLocks, releaseHeldLocksIfOwned, releaseProcessLock, tryAcquireProcessLock, withOptionalProcessLock, } from "./locks.js";
33
+ // The cycle loop / post-loop / maintenance stages live in ./loop-stages.
34
+ import { runImproveLoopStage, runImprovePostLoopStage } from "./loop-stages.js";
47
35
  import { detectAndWriteContradictions } from "./memory/memory-contradiction-detect.js";
48
- import { analyzeMemoryCleanup, applyMemoryCleanup } from "./memory/memory-improve.js";
36
+ import { analyzeMemoryCleanup } from "./memory/memory-improve.js";
37
+ // The pre-loop preparation pipeline lives in ./preparation.
38
+ import { runImprovePreparationStage } from "./preparation.js";
39
+ import { DEFAULT_DUE_DAYS, filterProactiveDue } from "./proactive-maintenance.js";
49
40
  import { akmReflect } from "./reflect.js";
50
- function resolveImproveScope(scope) {
51
- const trimmed = scope?.trim();
52
- if (!trimmed)
53
- return { mode: "all" };
54
- try {
55
- parseAssetRef(trimmed);
56
- return { mode: "ref", value: trimmed };
57
- }
58
- catch {
59
- if (!isAssetType(trimmed)) {
60
- throw new UsageError(`Unknown asset type: "${trimmed}". Valid types: memory, knowledge, skill, lesson, workflow, agent, command, script, wiki, env, secret, task.\n` +
61
- `If you passed --format to akm improve, that flag is not supported — use it with akm search or akm show instead.`, "INVALID_FLAG_VALUE");
62
- }
63
- return { mode: "type", value: trimmed };
64
- }
65
- }
66
- /**
67
- * Render the end-of-run stash-sync commit message, expanding `{token}`
68
- * placeholders against this run's results. Unknown tokens are passed through
69
- * verbatim so adding new tokens later never breaks an existing template, and so
70
- * a literal brace in a message is harmless.
71
- *
72
- * Supported tokens (the "free" set — derived from data already on the result):
73
- * {timestamp} `YYYY-MM-DD HH:MM:SS` (UTC)
74
- * {date} `YYYY-MM-DD` (UTC)
75
- * {time} `HH:MM:SS` (UTC)
76
- * {scope} scope value (e.g. a ref/type) or the scope mode (`all`)
77
- * {refs} number of planned refs this run processed
78
- * {accepted} number of proposals auto-accepted by the confidence gate
79
- * {triage_promoted} proposals promoted by the triage pre-pass (0 if triage did not run)
80
- * {triage_rejected} proposals rejected by the triage pre-pass (0 if triage did not run)
81
- * {runId} this run's id (empty string when absent)
82
- *
83
- * The result is still passed through `sanitizeCommitMessage` downstream in
84
- * `saveGitStash`, so token values never widen the commit-message attack surface
85
- * (newlines/control chars are collapsed there).
86
- *
87
- * `nowMs` is injected (not read from `Date.now()`) so the function is pure and
88
- * deterministically testable.
89
- */
41
+ export { resetHeldProcessLocks } from "./locks.js";
42
+ // Re-exported from ./loop-stages for test importers (improve-db-locking).
43
+ export { runImproveMaintenancePasses } from "./loop-stages.js";
44
+ // Re-exported from ./preparation so existing importers (tests, callers) resolve.
45
+ export { maybeAutoTuneThreshold } from "./preparation.js";
90
46
  export function renderSyncCommitMessage(template, result, nowMs) {
91
47
  const iso = new Date(nowMs).toISOString();
92
48
  const tokens = {
@@ -102,334 +58,6 @@ export function renderSyncCommitMessage(template, result, nowMs) {
102
58
  };
103
59
  return template.replace(/\{(\w+)\}/g, (match, key) => (Object.hasOwn(tokens, key) ? tokens[key] : match));
104
60
  }
105
- async function collectEligibleRefs(scope, stashDir, improveProfile) {
106
- if (scope.mode === "ref" && scope.value) {
107
- const parsed = parseAssetRef(scope.value);
108
- const writableDirs = new Set(getWritableStashDirs(stashDir).map((dir) => path.resolve(dir)));
109
- const filePath = await findAssetFilePath(scope.value, stashDir, writableDirs);
110
- if (!filePath) {
111
- return {
112
- plannedRefs: [],
113
- memorySummary: { eligible: 0, derived: 0 },
114
- profileFilteredRefs: [],
115
- };
116
- }
117
- return {
118
- plannedRefs: [{ ref: scope.value, reason: "scope-ref", filePath }],
119
- memorySummary: {
120
- eligible: parsed.type === "memory" ? 1 : 0,
121
- derived: parsed.type === "memory" && parsed.name.endsWith(".derived") ? 1 : 0,
122
- },
123
- profileFilteredRefs: [],
124
- };
125
- }
126
- let sources;
127
- try {
128
- sources = resolveSourceEntries(stashDir);
129
- }
130
- catch {
131
- return { plannedRefs: [], memorySummary: { eligible: 0, derived: 0 }, profileFilteredRefs: [] };
132
- }
133
- if (sources.length === 0) {
134
- return { plannedRefs: [], memorySummary: { eligible: 0, derived: 0 }, profileFilteredRefs: [] };
135
- }
136
- // Only operate on writable sources — never mutate read-only registry caches
137
- // or remote stashes that the user did not mark writable.
138
- let writableDirs;
139
- try {
140
- writableDirs = getWritableStashDirs(stashDir);
141
- }
142
- catch {
143
- writableDirs = sources.slice(0, 1).map((s) => s.path); // fallback: primary only
144
- }
145
- const writableDirSet = new Set(writableDirs.map((d) => path.resolve(d)));
146
- let db;
147
- try {
148
- db = openExistingDatabase();
149
- const entries = getAllEntries(db, scope.mode === "type" ? scope.value : undefined).filter((indexed) => {
150
- // First apply the existing stashDir-scope filter (no-op when stashDir is unset).
151
- if (!isEntryInScope(indexed.stashDir, indexed.filePath, stashDir))
152
- return false;
153
- // Then restrict to writable sources only.
154
- return isEntryInWritableSource(indexed.stashDir, indexed.filePath, writableDirSet);
155
- });
156
- const planned = new Map();
157
- const profileFiltered = new Map();
158
- let memoryEligible = 0;
159
- let memoryDerived = 0;
160
- for (const indexed of entries) {
161
- const ref = makeAssetRef(indexed.entry.type, indexed.entry.name);
162
- const isDerived = indexed.entry.name.endsWith(".derived");
163
- // `.derived` memories are LLM-inferred and intentionally skip reflect
164
- // (see the synthetic `derived-memory-reflect-skipped` branch in the
165
- // improve loop). Enqueueing them here just produced one synthetic skip
166
- // per derived memory per hour with no real work — pure churn observed
167
- // 2026-05-21: 11 derived refs re-planned every hour during idle periods.
168
- // The cleanup phase (analyzeMemoryCleanup) inspects derived memories
169
- // independently of `plannedRefs`, so dropping them here loses nothing.
170
- if (!isDerived && !planned.has(ref) && !profileFiltered.has(ref)) {
171
- // 2026-05-27: extend the .derived precedent to profile-incompatible
172
- // refs. If every per-ref pass (reflect + distill) on the active
173
- // profile would refuse this ref, drop it from `plannedRefs`. The
174
- // caller emits `improve_skipped { reason: profile_filtered_all_passes }`
175
- // once `eventsCtx` is available so the audit trail is preserved in a
176
- // single event per ref instead of 2× synthetic actions per run.
177
- // Background: see /tmp/akm-health-investigations/planner-profile-metrics-deep-analysis.md
178
- if (improveProfile && isProfileFilteredForAllPasses(ref, improveProfile)) {
179
- profileFiltered.set(ref, {
180
- ref,
181
- reason: "profile_filtered_all_passes",
182
- filePath: indexed.filePath,
183
- });
184
- }
185
- else {
186
- planned.set(ref, {
187
- ref,
188
- reason: scope.mode === "type" ? "scope-type" : indexed.entry.type === "memory" ? "memory-cleanup" : "scope-type",
189
- filePath: indexed.filePath,
190
- });
191
- }
192
- }
193
- if (indexed.entry.type === "memory") {
194
- memoryEligible += 1;
195
- if (isDerived)
196
- memoryDerived += 1;
197
- }
198
- }
199
- return {
200
- plannedRefs: [...planned.values()],
201
- memorySummary: { eligible: memoryEligible, derived: memoryDerived },
202
- profileFilteredRefs: [...profileFiltered.values()],
203
- };
204
- }
205
- catch (error) {
206
- // The bun-test isolation guard must never be downgraded to "empty plan".
207
- rethrowIfTestIsolationError(error);
208
- if (error instanceof NotFoundError || error instanceof Error) {
209
- return { plannedRefs: [], memorySummary: { eligible: 0, derived: 0 }, profileFilteredRefs: [] };
210
- }
211
- throw error;
212
- }
213
- finally {
214
- if (db)
215
- closeDatabase(db);
216
- }
217
- }
218
- function isEntryInScope(entryStashDir, filePath, stashDir) {
219
- if (!stashDir)
220
- return true;
221
- const resolvedEntryStashDir = path.resolve(entryStashDir);
222
- const resolvedFilePath = path.resolve(filePath);
223
- const resolvedScopeStashDir = path.resolve(stashDir);
224
- return (resolvedEntryStashDir === resolvedScopeStashDir ||
225
- resolvedEntryStashDir.startsWith(`${resolvedScopeStashDir}${path.sep}`) ||
226
- resolvedFilePath.startsWith(`${resolvedScopeStashDir}${path.sep}`));
227
- }
228
- /**
229
- * Return true when the indexed entry belongs to one of the writable source
230
- * directories. Entries from read-only registry caches or remote stashes that
231
- * the user has not marked writable must never enter the improve/distill loop.
232
- */
233
- function isEntryInWritableSource(entryStashDir, filePath, writableDirSet) {
234
- const resolvedEntryStashDir = path.resolve(entryStashDir);
235
- const resolvedFilePath = path.resolve(filePath);
236
- for (const writableDir of writableDirSet) {
237
- if (resolvedEntryStashDir === writableDir ||
238
- resolvedEntryStashDir.startsWith(`${writableDir}${path.sep}`) ||
239
- resolvedFilePath.startsWith(`${writableDir}${path.sep}`)) {
240
- return true;
241
- }
242
- }
243
- return false;
244
- }
245
- function memoryCleanupParentRef(scope, stashDir) {
246
- if (scope.mode !== "ref" || !scope.value)
247
- return undefined;
248
- const parsed = parseAssetRef(scope.value);
249
- if (parsed.type !== "memory")
250
- return undefined;
251
- if (!parsed.name.endsWith(".derived"))
252
- return scope.value;
253
- const sources = resolveSourceEntries(stashDir);
254
- for (const source of sources) {
255
- const candidate = path.join(source.path, "memories", `${parsed.name}.md`);
256
- if (!fs.existsSync(candidate))
257
- continue;
258
- const raw = fs.readFileSync(candidate, "utf8");
259
- const fm = parseFrontmatter(raw).data;
260
- const sourceRef = typeof fm.source === "string" ? fm.source : undefined;
261
- if (sourceRef) {
262
- try {
263
- const parent = parseAssetRef(sourceRef.trim());
264
- if (parent.type === "memory")
265
- return makeAssetRef(parent.type, parent.name);
266
- }
267
- catch { }
268
- }
269
- }
270
- return makeAssetRef("memory", parsed.name.slice(0, -".derived".length));
271
- }
272
- function isLessonCandidate(ref) {
273
- // Only lesson assets need lesson-schema validation (description + when_to_use).
274
- // Memories have their own distill path via shouldDistillMemoryRef.
275
- // All other types go through reflect, not distill.
276
- return parseAssetRef(ref).type === "lesson";
277
- }
278
- /**
279
- * Planner-side check: should this ref enter the distill queue?
280
- *
281
- * Distill produces lessons from non-lesson sources. Two cases are eligible:
282
- *
283
- * 1. Memory refs that pass {@link shouldDistillMemoryRef} (the existing
284
- * memory→lesson/knowledge promotion path).
285
- *
286
- * Refs whose `type` is in {@link DISTILL_REFUSED_INPUT_TYPES} (currently
287
- * `lesson:*`) are explicitly excluded — distill refuses them at runtime and
288
- * queuing them just produces a no-op `skipped` outcome per ref per hour. That
289
- * planner waste was the bug fixed in commit
290
- * fix(improve): drop distill-refused types from planner.
291
- *
292
- * Note: prior to this fix the gate used `isLessonCandidate(ref)` directly,
293
- * which was true *only* for `lesson:*` refs — exactly the set distill refuses.
294
- * The result: every hourly run re-queued the same lesson refs, the same skip
295
- * message returned, and no work was ever done. See
296
- * `tests/commands/improve-distill-planner-skip-lessons.test.ts`.
297
- */
298
- function isDistillCandidateRef(ref, stashDir) {
299
- const parsed = parseAssetRef(ref);
300
- if (isDistillRefusedInputType(parsed.type))
301
- return false;
302
- return shouldDistillMemoryRef(ref, stashDir);
303
- }
304
- function shouldDistillMemoryRef(ref, stashDir) {
305
- const parsed = parseAssetRef(ref);
306
- if (parsed.type !== "memory")
307
- return false;
308
- const sources = resolveSourceEntries(stashDir);
309
- for (const source of sources) {
310
- const candidate = `${source.path}/memories/${parsed.name}.md`;
311
- if (!fs.existsSync(candidate))
312
- continue;
313
- const raw = fs.readFileSync(candidate, "utf8");
314
- const fm = parseFrontmatter(raw).data;
315
- const quality = typeof fm.quality === "string" ? fm.quality : undefined;
316
- if (quality === "proposed")
317
- return false;
318
- return !parsed.name.endsWith(".derived");
319
- }
320
- return !parsed.name.endsWith(".derived");
321
- }
322
- // ── Signal-delta eligibility helpers (0.8.0) ────────────────────────────────
323
- //
324
- // The 0.8.0 redesign replaced flat time-based cooldowns for reflect/distill
325
- // with a *signal-delta* gate: a ref is re-eligible iff new feedback has
326
- // landed since the last proposal was generated for it. These helpers build
327
- // the two timestamp maps the gate needs in bulk, so the planner avoids
328
- // N+1 queries across the full postCleanupRefs set.
329
- /**
330
- * Latest feedback event timestamp per ref in the active window. Reads all
331
- * `feedback` events newer than `sinceIso` in one query and indexes by ref,
332
- * keeping the maximum `ts` per ref.
333
- *
334
- * Only events with a meaningful payload count as "signal" — `metadata.signal`
335
- * (positive/negative) OR `metadata.note` (a free-form annotation). Empty
336
- * metadata events are ignored so a stray `akm feedback <ref>` invocation
337
- * without a flag doesn't trigger downstream re-processing.
338
- */
339
- function buildLatestFeedbackTsMap(refs, sinceIso) {
340
- const out = new Map();
341
- if (refs.length === 0)
342
- return out;
343
- const refSet = new Set(refs);
344
- const { events } = readEvents({ type: "feedback", since: sinceIso });
345
- for (const e of events) {
346
- const ref = e.ref;
347
- if (!ref || !refSet.has(ref))
348
- continue;
349
- const meta = e.metadata;
350
- const hasSignal = meta !== undefined && (typeof meta.signal === "string" || typeof meta.note === "string");
351
- if (!hasSignal)
352
- continue;
353
- const ts = e.ts ?? "";
354
- if (ts > (out.get(ref) ?? ""))
355
- out.set(ref, ts);
356
- }
357
- return out;
358
- }
359
- /**
360
- * Latest proposal timestamp per input-ref, filtered by source ('reflect' or
361
- * 'distill'). Reads the corresponding `*_invoked` events from state.db —
362
- * these events are emitted at proposal creation time and carry the *input*
363
- * asset ref (memory:foo, skill:bar, etc.) directly. We use them rather than
364
- * `listProposals` because distill proposals are keyed by the derived
365
- * lesson/knowledge ref, not the source memory — joining back through the
366
- * payload would be fragile.
367
- */
368
- function buildLatestProposalTsMap(refs, source) {
369
- const out = new Map();
370
- if (refs.length === 0)
371
- return out;
372
- const refSet = new Set(refs);
373
- const eventType = source === "reflect" ? "reflect_invoked" : "distill_invoked";
374
- const { events } = readEvents({ type: eventType });
375
- for (const e of events) {
376
- const ref = e.ref;
377
- if (!ref || !refSet.has(ref))
378
- continue;
379
- // For distill_invoked we only count attempts that produced (or attempted
380
- // to produce) a real proposal — config_disabled / parse-error outcomes
381
- // should not move the signal-delta cursor forward.
382
- if (eventType === "distill_invoked") {
383
- const outcome = e.metadata?.outcome;
384
- if (outcome !== "queued" && outcome !== "skipped" && outcome !== "validation_failed")
385
- continue;
386
- }
387
- const ts = e.ts ?? "";
388
- if (ts > (out.get(ref) ?? ""))
389
- out.set(ref, ts);
390
- }
391
- return out;
392
- }
393
- /**
394
- * Signal-delta eligibility predicate.
395
- *
396
- * True iff `latestFeedback[ref]` is defined AND either no prior proposal
397
- * exists for this (ref, source) OR `latestFeedback[ref] > lastProposal[ref]`.
398
- *
399
- * Refs with no feedback signal at all are ineligible by definition — the
400
- * high-retrieval fallback path (see `noFeedbackCandidates` later in the
401
- * planner) handles never-touched-but-frequently-read assets separately.
402
- */
403
- function isSignalDeltaEligible(ref, latestFeedback, lastProposal) {
404
- const fb = latestFeedback.get(ref);
405
- if (!fb)
406
- return false;
407
- const lp = lastProposal.get(ref);
408
- if (!lp)
409
- return true;
410
- return fb > lp;
411
- }
412
- /**
413
- * H7 (#566): cooperative budget watchdog with a captured, RAII-cleared hard-kill.
414
- *
415
- * When the wall-clock budget expires, `onExhausted` (normally an
416
- * `AbortController.abort`) signals cooperative cancellation so the run can drain
417
- * its in-flight log/`state.db` flush and unwind naturally. A second hard-kill
418
- * timer is then armed as a watchdog: it only `exit(0)`s if the drain itself
419
- * overruns `hardKillGraceMs`, preventing the process from outliving the task
420
- * timeout window (lock-cascade fix).
421
- *
422
- * Both timers are captured; the returned dispose() clears whichever is still
423
- * pending. Callers invoke it from a `finally`, so a *clean* drain reaches the
424
- * `finally` and cancels the pending hard-kill before it can fire — the previous
425
- * detached `setTimeout(() => process.exit(0), 5000)` always fired, truncating a
426
- * clean flush. The hard-kill timer is `unref()`-ed so it never keeps the event
427
- * loop alive on its own: once the run drains it exits with its own code, not the
428
- * forced 0.
429
- *
430
- * Dependencies are injectable purely so the concurrency-sensitive timing
431
- * contract can be exercised deterministically in unit tests.
432
- */
433
61
  export function armBudgetWatchdog(budgetMs, controller, deps) {
434
62
  const setTimeoutFn = deps?.setTimeoutFn ?? setTimeout;
435
63
  const clearTimeoutFn = deps?.clearTimeoutFn ?? clearTimeout;
@@ -461,6 +89,11 @@ export async function akmImprove(options = {}) {
461
89
  const ensureIndexFn = options.ensureIndexFn ?? ensureIndex;
462
90
  const reindexFn = options.reindexFn ?? akmIndex;
463
91
  const drainProposalsFn = options.drainProposalsFn ?? drainProposals;
92
+ // #616 multi-cycle test seams. Default to the real module-local fns.
93
+ const collectEligibleRefsImpl = options.collectEligibleRefsFn ?? collectEligibleRefs;
94
+ const runImprovePreparationStageImpl = options.runImprovePreparationStageFn ?? runImprovePreparationStage;
95
+ const runImproveLoopStageImpl = options.runImproveLoopStageFn ?? runImproveLoopStage;
96
+ const runImprovePostLoopStageImpl = options.runImprovePostLoopStageFn ?? runImprovePostLoopStage;
464
97
  // Resolve the improve profile for this run. Profile drives type filtering,
465
98
  // process gating, and default autoAccept/limit values.
466
99
  const _earlyConfig = options.config ?? loadConfig();
@@ -471,8 +104,13 @@ export async function akmImprove(options = {}) {
471
104
  options = {
472
105
  ...options,
473
106
  autoAccept: options.autoAccept ?? improveProfile.autoAccept,
474
- limit: options.limit ?? improveProfile.limit,
107
+ // Profile-level limit, then process-level reflect.limit as fallback.
108
+ // CLI --limit takes precedence over both.
109
+ limit: options.limit ?? improveProfile?.processes?.reflect?.limit ?? improveProfile.limit,
475
110
  };
111
+ // #616 — bounded multi-cycle phasing. CLI/programmatic override wins over
112
+ // profile.maxCycles; default 1 => single pass (byte-identical to pre-#616).
113
+ const maxCycles = Math.max(1, Math.trunc(options.maxCycles ?? improveProfile.maxCycles ?? 1));
476
114
  let primaryStashDir;
477
115
  try {
478
116
  primaryStashDir = resolveSourceEntries(options.stashDir)[0]?.path;
@@ -489,174 +127,51 @@ export async function akmImprove(options = {}) {
489
127
  // timeout root cause). Because beforeEach runs synchronously, env is still the
490
128
  // calling test's own at this point; we capture it before yielding the loop.
491
129
  const resolvedStateDbPath = getStateDbPathInDataDir();
492
- // Phase 4 lock hoist (§7): the `improve.lock` setup is hoisted ABOVE
493
- // ensureIndex/collectEligibleRefs so the triage pre-pass (and improve's own
494
- // queue writes) run fully serialized under the lock. The dry-run early-return
495
- // below still skips the lock and triage (the lock+triage block is gated on
496
- // `!options.dryRun`); contradiction-detection and memory-cleanup analysis,
497
- // which previously ran before the lock, now sit after it for free.
498
- const resolvedLockPath = primaryStashDir
499
- ? path.join(primaryStashDir, ".akm", "improve.lock")
500
- : path.join(options.stashDir ?? ".", ".akm", "improve.lock");
501
- const MAX_LOCK_AGE_MS = 4 * 60 * 60 * 1000; // 4 hours
502
- const acquireLock = () => {
503
- fs.mkdirSync(path.dirname(resolvedLockPath), { recursive: true });
504
- const lockPayload = () => JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() });
505
- if (tryAcquireLockSync(resolvedLockPath, lockPayload()))
506
- return "acquired";
507
- // Lock file already exists probe to determine whether it's still held
508
- // or whether the prior run died without cleaning up.
509
- const probe = probeLock(resolvedLockPath, { staleAfterMs: MAX_LOCK_AGE_MS });
510
- const rawContent = probe.state === "absent" ? undefined : probe.rawContent;
511
- const lock = rawContent
512
- ? (() => {
513
- try {
514
- return JSON.parse(rawContent);
515
- }
516
- catch {
517
- return null;
518
- }
519
- })()
520
- : null;
521
- if (probe.state === "stale") {
522
- // O-7 / #394: Emit improve_lock_recovered event before recovery so the
523
- // audit trail records the abnormal prior-run exit (Temporal/Airflow pattern).
524
- try {
525
- appendEvent({
526
- eventType: "improve_lock_recovered",
527
- metadata: {
528
- stalePid: lock?.pid ?? null,
529
- lockedAt: lock?.startedAt ?? null,
530
- recoveredAt: new Date().toISOString(),
531
- lockAgeMs: probe.ageMs ?? null,
532
- reason: probe.reason === "pid_dead" ? "pid_not_alive" : probe.reason,
533
- },
534
- });
535
- }
536
- catch {
537
- /* event emission is best-effort; never block lock recovery */
538
- }
539
- releaseLock(resolvedLockPath);
540
- if (tryAcquireLockSync(resolvedLockPath, lockPayload()))
541
- return "acquired";
542
- // Lost the race to another run that grabbed the freed stale lock.
543
- if (options.skipIfLocked) {
544
- warn("[improve] another run acquired the lock during stale recovery; skipping (--skip-if-locked)");
545
- return "skipped";
546
- }
547
- throw new ConfigError(`akm improve is already running. Delete ${resolvedLockPath} to force.`, "INVALID_CONFIG_FILE");
548
- }
549
- // Lock is held by a live run within the staleness window.
550
- if (options.skipIfLocked) {
551
- warn(`[improve] another improve run holds the lock (PID ${lock?.pid}, started ${lock?.startedAt}); skipping (--skip-if-locked)`);
552
- return "skipped";
553
- }
554
- throw new ConfigError(`akm improve is already running (PID ${lock?.pid}, started ${lock?.startedAt}). Delete ${resolvedLockPath} to force.`, "INVALID_CONFIG_FILE");
555
- };
556
- // Phase 4 lock-leak guard (§7 ordering hazard): hoisting `improve.lock` above
557
- // the pre-index region (so the triage pre-pass runs under it) means the lock is
558
- // held while ensureIndex / collectEligibleRefs / contradiction-detection /
559
- // memory-cleanup analysis run — but the main protecting `try { … } finally {
560
- // unlinkSync(resolvedLockPath) }` does not begin until after them. A throw in
561
- // any of those steps would leak the lock. We close that window by wrapping the
562
- // whole region in a try whose catch releases the lock (when held) and
563
- // re-throws. The values this region computes are declared in the outer scope so
564
- // they remain visible to the main run below. The dry-run path never sets
565
- // `lockAcquired`, so its early return releases nothing.
566
- let lockAcquired = false;
567
- const releaseLockOnError = () => {
568
- if (!lockAcquired)
569
- return;
570
- try {
571
- fs.unlinkSync(resolvedLockPath);
572
- }
573
- catch {
574
- // best-effort release on the error path
575
- }
576
- lockAcquired = false;
577
- };
578
- // Signal-safe lock release. The SIGTERM/SIGINT/SIGHUP handler in improve-cli.ts
579
- // calls `process.exit()`, which does NOT run the `finally` below that owns lock
580
- // release — so a cron-timeout SIGTERM leaked `improve.lock` every run.
581
- // `process.exit()` DOES fire `'exit'` listeners, so we release the lock from
582
- // one. `releaseLockIfOwned` only unlinks a lock still owned by this PID, so it
583
- // is safe even if a later run re-acquired it. The listener is removed in the
584
- // `finally` so the normal path stays single-release and repeated in-process
585
- // `akmImprove` calls (tests) do not accumulate listeners.
586
- const releaseLockOnExit = () => {
587
- releaseLockIfOwned(resolvedLockPath, process.pid);
588
- };
130
+ // #612 / WS-4 bounded, OPT-IN per-phase auto-accept threshold auto-tune.
131
+ // DEFAULT OFF: `autoTune: false` (or absent) is a complete no-op.
132
+ //
133
+ // WS-4 change: thresholds are now PER PHASE. The old single global mutation
134
+ // of `options.autoAccept` is retired it caused every phase to share one
135
+ // calibration signal, so a reflect-dominated run could tighten the consolidate
136
+ // gate (or vice-versa). Instead:
137
+ // - Each `makeGateConfig` call reads the phase's stored threshold from
138
+ // state.db (Migration 012) and uses it as `phaseThreshold`, overriding
139
+ // the `globalThreshold` (= options.autoAccept) for that phase.
140
+ // - Per-phase `maybeAutoTuneThreshold` calls fire AFTER each phase's gate
141
+ // has run and persist the new threshold to state.db for the NEXT run.
142
+ // - `options.autoAccept` stays unchanged (it is the operator-supplied
143
+ // baseline, not a mutable run-time state).
144
+ //
145
+ // The global tune call is intentionally removed here. See per-phase calls
146
+ // below (near each makeGateConfig / runAutoAcceptGate block).
147
+ // #607 Lock decomposition: three per-process locks replace the single
148
+ // `improve.lock`. Each process acquires only the lock(s) it needs, so
149
+ // quick-shredder consolidate can run alongside daily reflect+distill.
150
+ //
151
+ // consolidate.lock — protects consolidate + memoryInference + graphExtraction (index.db writers)
152
+ // reflect-distill.lock — protects reflect + distill (state.db proposal writers)
153
+ // triage.lock — protects triage pre-pass (state.db proposal promotions)
154
+ //
155
+ // Lock base directory — same `.akm/` under the primary stash dir.
156
+ const lockBaseDir = primaryStashDir ? path.join(primaryStashDir, ".akm") : path.join(options.stashDir ?? ".", ".akm");
589
157
  const preEnsureCleanupWarnings = [];
590
- let plannedRefs;
591
- let memorySummary;
592
- let profileFilteredRefs;
158
+ // #616: assigned by runIndexAndCollect() (closure) so TS cannot prove definite
159
+ // assignment — seed with empty values; the first runIndexAndCollect() call
160
+ // (cycle 1, in the first try) always overwrites them before any read.
161
+ let plannedRefs = [];
162
+ let memorySummary = { eligible: 0, derived: 0 };
163
+ let profileFilteredRefs = [];
593
164
  let memoryCleanupPlan;
594
165
  let guidance;
595
166
  let triageDrain;
596
- try {
597
- // Acquire the lock and run the triage pre-pass for non-dry-run executions.
598
- // The dry-run branch below produces plannedRefs/memorySummary WITHOUT the lock
599
- // or triage (decision: dry-run never mutates the queue).
600
- if (!options.dryRun) {
601
- if (acquireLock() === "skipped") {
602
- // Another improve holds the lock and the caller asked to skip rather
603
- // than fail. Return a clean no-op result (exit 0) before any index/DB
604
- // work — never registered the exit listener, never set lockAcquired,
605
- // so we release nothing belonging to the run that owns the lock.
606
- return {
607
- schemaVersion: 1,
608
- ok: true,
609
- scope,
610
- dryRun: false,
611
- skipped: { reason: "lock-held" },
612
- memorySummary: { eligible: 0, derived: 0 },
613
- plannedRefs: [],
614
- };
615
- }
616
- lockAcquired = true;
617
- // Backstop release on process.exit() (signal handler / budget watchdog),
618
- // which skips the finally below. Removed in that finally on the normal path.
619
- process.on("exit", releaseLockOnExit);
620
- // Phase 4 triage pre-pass (§7, §13): drain the standing pending backlog
621
- // BEFORE ensureIndex so improve generates fresh proposals against a cleared
622
- // queue (no `duplicate_pending` collisions) and ensureIndex absorbs triage's
623
- // promotions for free. Gated on the triage process being enabled (opt-in,
624
- // defaults off) and on a whole-stash / type-scoped run — a single-ref
625
- // `akm improve skill:x` must never drain the whole queue. Best-effort: a
626
- // triage failure is a non-fatal warning, never an abort (mirrors the
627
- // contradiction-detection pass below).
628
- if (primaryStashDir && resolveProcessEnabled("triage", improveProfile)) {
629
- if (scope.mode === "ref") {
630
- warn("[improve] triage pre-pass skipped (single-ref scope never drains the whole queue)");
631
- }
632
- else {
633
- try {
634
- const triageConfig = improveProfile.processes?.triage;
635
- const policy = resolveDrainPolicy(triageConfig?.policy);
636
- const applyMode = triageConfig?.applyMode ?? "queue";
637
- const maxAccepts = triageConfig?.maxAcceptsPerRun ?? 25;
638
- const judgment = triageConfig?.judgment
639
- ? resolveTriageJudgmentRunner(triageConfig.judgment, _earlyConfig)
640
- : null;
641
- triageDrain = await drainProposalsFn({
642
- stashDir: primaryStashDir,
643
- policy,
644
- applyMode,
645
- maxAccepts,
646
- dryRun: false,
647
- // No fresh ids exist yet — triage runs before improve generates any.
648
- excludeIds: new Set(),
649
- ...(triageConfig?.maxDiffLines !== undefined ? { maxDiffLines: triageConfig.maxDiffLines } : {}),
650
- judgment,
651
- });
652
- }
653
- catch (err) {
654
- // Non-fatal: triage is a best-effort pre-pass and must never abort improve.
655
- warn(`[improve] triage pre-pass failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
656
- }
657
- }
658
- }
659
- }
167
+ // #616 — ensureIndex + collectEligibleRefs + memory-cleanup recompute, lifted
168
+ // into a helper so the SAME sequence runs once for cycle 1 (below, in the
169
+ // first try) and is re-run at the top of each subsequent multi-cycle cycle.
170
+ // Re-running ensureIndex between cycles makes cycle N's gate-promoted
171
+ // proposals visible to cycle N+1's collectEligibleRefs. Mutates the
172
+ // outer-scope plannedRefs/memorySummary/profileFilteredRefs/memoryCleanupPlan/
173
+ // guidance so for maxCycles:1 the body is byte-identical to pre-#616.
174
+ const runIndexAndCollect = async () => {
660
175
  // #339 fix: ensureIndex MUST run BEFORE collectEligibleRefs. The eligible-ref
661
176
  // query reads the `entries` table; if a DB version upgrade just dropped that
662
177
  // table (or the index is otherwise empty), the prior run order silently
@@ -684,7 +199,7 @@ export async function akmImprove(options = {}) {
684
199
  // best-effort; leave preEnsureEntryCount undefined
685
200
  }
686
201
  try {
687
- await ensureIndexFn(primaryStashDir);
202
+ await ensureIndexFn(primaryStashDir, { mode: "blocking" });
688
203
  }
689
204
  catch (err) {
690
205
  preEnsureCleanupWarnings.push(`ensureIndex failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -714,7 +229,7 @@ export async function akmImprove(options = {}) {
714
229
  }
715
230
  }
716
231
  }
717
- ({ plannedRefs, memorySummary, profileFilteredRefs } = await collectEligibleRefs(scope, options.stashDir, improveProfile));
232
+ ({ plannedRefs, memorySummary, profileFilteredRefs } = await collectEligibleRefsImpl(scope, options.stashDir, improveProfile));
718
233
  const cleanupParentRef = memoryCleanupParentRef(scope, options.stashDir);
719
234
  // M-1 (#367): Run contradiction-detection BEFORE analyzeMemoryCleanup so
720
235
  // the SCC resolver in resolveFamilyContradictions has edges to work on.
@@ -736,6 +251,70 @@ export async function akmImprove(options = {}) {
736
251
  memorySummary.eligible > 0
737
252
  ? "Improve folds memory cleanup into the same proposal queue: speculative promotions still go through reflect/distill proposals, while high-confidence redundant derived memories are moved into a recoverable cleanup archive instead of being left active in the stash."
738
253
  : undefined;
254
+ };
255
+ // Holds our own process.on("exit") backstop so the finally can remove EXACTLY
256
+ // that handler (not every exit listener in the process). Declared in the scope
257
+ // shared by the try and its finally; assigned when the backstop is registered.
258
+ let exitBackstop;
259
+ try {
260
+ // #607: Per-process lock acquisition. Each process acquires only the lock(s)
261
+ // it needs. The dry-run branch produces plannedRefs/memorySummary WITHOUT any
262
+ // locks (decision: dry-run never mutates the queue).
263
+ if (!options.dryRun) {
264
+ // Backstop release on process.exit() (signal handler / budget watchdog),
265
+ // which skips the finally below. Removed in that finally on the normal path.
266
+ const releaseAllOnExit = () => releaseHeldLocksIfOwned(process.pid);
267
+ exitBackstop = releaseAllOnExit;
268
+ process.on("exit", releaseAllOnExit);
269
+ // #607 triage pre-pass: acquire triage.lock, drain the standing pending
270
+ // backlog BEFORE ensureIndex so improve generates fresh proposals against
271
+ // a cleared queue (no `duplicate_pending` collisions) and ensureIndex
272
+ // absorbs triage's promotions for free. Release immediately after —
273
+ // triage.lock is not needed again until the next improve run.
274
+ if (primaryStashDir && resolveProcessEnabled("triage", improveProfile)) {
275
+ if (scope.mode === "ref") {
276
+ warn("[improve] triage pre-pass skipped (single-ref scope never drains the whole queue)");
277
+ }
278
+ else {
279
+ const triageLPath = processLockPath(lockBaseDir, "triage");
280
+ const triageResult = tryAcquireProcessLock(triageLPath, PROCESS_LOCK_DEFS.triage.staleAfterMs, options.skipIfLocked, "triage");
281
+ if (triageResult === "skipped") {
282
+ triageDrain = undefined;
283
+ }
284
+ else {
285
+ try {
286
+ const triageConfig = improveProfile.processes?.triage;
287
+ const policy = resolveDrainPolicy(triageConfig?.policy);
288
+ const applyMode = triageConfig?.applyMode ?? "queue";
289
+ const maxAccepts = triageConfig?.maxAcceptsPerRun ?? 25;
290
+ const judgment = triageConfig?.judgment
291
+ ? resolveTriageJudgmentRunner(triageConfig.judgment, _earlyConfig)
292
+ : null;
293
+ triageDrain = await drainProposalsFn({
294
+ stashDir: primaryStashDir,
295
+ policy,
296
+ applyMode,
297
+ maxAccepts,
298
+ dryRun: false,
299
+ excludeIds: new Set(),
300
+ ...(triageConfig?.maxDiffLines !== undefined ? { maxDiffLines: triageConfig.maxDiffLines } : {}),
301
+ judgment,
302
+ });
303
+ }
304
+ catch (err) {
305
+ warn(`[improve] triage pre-pass failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
306
+ }
307
+ finally {
308
+ releaseProcessLock(triageLPath);
309
+ }
310
+ }
311
+ }
312
+ }
313
+ }
314
+ // #339 fix: ensureIndex MUST run BEFORE collectEligibleRefs (now inside the
315
+ // helper). Cycle 1 runs it here; subsequent multi-cycle cycles re-run it via
316
+ // the same helper at the top of each cycle below.
317
+ await runIndexAndCollect();
739
318
  if (options.dryRun) {
740
319
  const result = {
741
320
  schemaVersion: 1,
@@ -752,17 +331,14 @@ export async function akmImprove(options = {}) {
752
331
  }
753
332
  }
754
333
  catch (err) {
755
- releaseLockOnError();
334
+ releaseAllProcessLocks();
756
335
  throw err;
757
336
  }
758
- // FIX 2 (lock-leak window): everything from here on runs UNDER the lock that
759
- // `acquireLock()` just took. The single `try { } finally { unlinkSync(lock) }`
760
- // below now spans the budget-timer setup, `openStateDatabase()`, and the
761
- // `profileFilteredRefs` audit-event loop too regions that previously sat in
762
- // the gap between the lock-acquire catch (above) and the main try. A throw in
763
- // any of them used to leak the lock (blocking the next improve up to 4h);
764
- // now the finally releases it exactly once. The dry-run path already returned
765
- // above without acquiring the lock, so it never reaches this finally; the
337
+ // #607: per-process locks are acquired/released around each stage below.
338
+ // The triage pre-pass already ran under triage.lock (released). The
339
+ // preparation stage runs under consolidate.lock, the loop stage under
340
+ // reflect-distill.lock, and the post-loop stage under consolidate.lock again.
341
+ // Each stage acquires its lock just before starting and releases in finally.
766
342
  // best-effort `unlinkSync` is a no-op when no lock file exists.
767
343
  const startMs = Date.now();
768
344
  const budgetMs = options.timeoutMs ?? 2 * 60 * 60 * 1000; // default 2 hours
@@ -771,6 +347,16 @@ export async function akmImprove(options = {}) {
771
347
  // run past the declared budget.
772
348
  // References: Anthropic *Building Effective Agents* (2024); CoALA §5 (arXiv:2309.02427).
773
349
  const budgetAbortController = new AbortController();
350
+ // Attach a live `remainingBudgetMs` getter to the signal so sub-callers
351
+ // (e.g. consolidate.ts cold-start budget estimation) can read the remaining
352
+ // wall-clock budget without needing an extra plumbing parameter. The property
353
+ // is computed at access time via a getter so it always reflects the actual
354
+ // elapsed time rather than a stale snapshot taken at arm time.
355
+ Object.defineProperty(budgetAbortController.signal, "remainingBudgetMs", {
356
+ get: () => Math.max(0, budgetMs - (Date.now() - startMs)),
357
+ enumerable: false,
358
+ configurable: true,
359
+ });
774
360
  // Declared in the outer scope so the `finally` can clear the timer even if a
775
361
  // throw occurs before/after it is armed. Defaults to a no-op until armed.
776
362
  let clearBudgetTimer = () => { };
@@ -785,6 +371,63 @@ export async function akmImprove(options = {}) {
785
371
  // #576: clears the per-run LLM usage sink. Defaults to a no-op until the sink
786
372
  // is installed inside the try; the `finally` always calls it.
787
373
  let disposeLlmUsageSink = () => { };
374
+ // ── Crash-safe / incremental stash sync (#662) ──────────────────────────────
375
+ // The primary stash writes as a filesystem source DURING the run
376
+ // (write-source.ts case-3); those writes become a git commit only when this
377
+ // closure runs. Historically the only call site was a single BATCH commit at
378
+ // the very end of the happy path, so a run interrupted AFTER writing but
379
+ // BEFORE finishing — a mid-cycle crash, a budget abort, or an external
380
+ // SIGTERM/`process.exit` — left every write uncommitted until some LATER run
381
+ // happened to finish cleanly and swept the whole backlog up. We now call this
382
+ // from THREE places: between cycles (bank each completed cycle), at end-of-run
383
+ // (the converged commit), and from the catch path (commit what was written
384
+ // before the crash). That shrinks the worst-case loss from "the entire run" to
385
+ // "the in-flight cycle".
386
+ //
387
+ // Declared in the OUTER scope (not inside the try) so the catch block can reach
388
+ // it. Idempotent + NON-FATAL: `saveGitStash` short-circuits a clean working
389
+ // tree ("nothing to commit") and a thrown sync error is swallowed here, so a
390
+ // repeat call after a no-op cycle is cheap and a failed push never fails the
391
+ // run. Gated identically to the original end-of-run block (git-backed primary
392
+ // stash, sync not disabled). `eventsCtx` is captured by reference, so calls
393
+ // after the db-backed context is installed inside the try use the live handle.
394
+ const effectiveSync = { ...improveProfile.sync, ...options.sync };
395
+ const commitStashBatch = (messageContext) => {
396
+ if (!primaryStashDir || effectiveSync.enabled === false || !isGitBackedStash(primaryStashDir)) {
397
+ return undefined;
398
+ }
399
+ const saveGitStashFn = options.saveGitStashFn ?? saveGitStash;
400
+ const writableOverride = resolveWritableOverride(_earlyConfig);
401
+ const push = effectiveSync.push !== false;
402
+ const message = renderSyncCommitMessage(effectiveSync.message ?? "akm improve auto-sync", messageContext, Date.now());
403
+ try {
404
+ const syncResult = saveGitStashFn(undefined, message, writableOverride, { push, repoDir: primaryStashDir });
405
+ appendEvent({
406
+ eventType: "stash_synced",
407
+ metadata: {
408
+ committed: syncResult.committed,
409
+ pushed: syncResult.pushed,
410
+ skipped: syncResult.skipped,
411
+ reason: syncResult.reason ?? null,
412
+ },
413
+ }, eventsCtx);
414
+ return {
415
+ committed: syncResult.committed,
416
+ pushed: syncResult.pushed,
417
+ skipped: syncResult.skipped,
418
+ ...(syncResult.reason !== undefined ? { reason: syncResult.reason } : {}),
419
+ };
420
+ }
421
+ catch (syncErr) {
422
+ const reason = syncErr instanceof Error ? syncErr.message : String(syncErr);
423
+ warn(`improve: stash sync failed (non-fatal): ${reason}`);
424
+ appendEvent({
425
+ eventType: "stash_synced",
426
+ metadata: { committed: false, pushed: false, skipped: true, reason },
427
+ }, eventsCtx);
428
+ return { committed: false, pushed: false, skipped: true, reason };
429
+ }
430
+ };
788
431
  try {
789
432
  // H7 (#566): arm the budget watchdog. `armBudgetWatchdog` captures both the
790
433
  // budget timer and the hard-kill timer it schedules on exhaustion, returning
@@ -826,71 +469,231 @@ export async function akmImprove(options = {}) {
826
469
  },
827
470
  }, eventsCtx);
828
471
  }
829
- const preparation = await runImprovePreparationStage({
830
- scope,
831
- options,
832
- plannedRefs,
833
- memoryCleanupPlan,
834
- primaryStashDir,
835
- memorySummary,
836
- reindexFn,
837
- startMs,
838
- budgetMs,
839
- eventsCtx,
840
- initialCleanupWarnings: preEnsureCleanupWarnings,
841
- improveProfile,
842
- });
843
- // D6: pre-load all proposal_rejected events from the last 30 days once,
844
- // so the per-asset loop can use a Map lookup instead of N DB round trips.
845
- const REJECTED_PROPOSAL_WINDOW_MS = daysToMs(30);
846
- const rejectedProposalSince = new Date(Date.now() - REJECTED_PROPOSAL_WINDOW_MS).toISOString();
847
- const allRejectedProposalEvents = readEvents({ type: "proposal_rejected", since: rejectedProposalSince }).events;
848
- const rejectedProposalsByRef = new Map();
849
- for (const e of allRejectedProposalEvents) {
850
- if (e.ref && (!rejectedProposalsByRef.has(e.ref) || e.ts > (rejectedProposalsByRef.get(e.ref)?.ts ?? ""))) {
851
- rejectedProposalsByRef.set(e.ref, e);
472
+ // #616 bounded multi-cycle phasing. The prep->loop->post-loop sequence is
473
+ // wrapped in an N-cycle loop. Each cycle re-runs ensureIndex +
474
+ // collectEligibleRefs (via runIndexAndCollect) so gate-accepted output of
475
+ // cycle N becomes selectable input to cycle N+1. The per-stage process locks
476
+ // (consolidate / reflect-distill) are acquired+released INSIDE each cycle,
477
+ // exactly as the single-pass path did. For maxCycles:1 the loop runs once and
478
+ // every accumulator below collapses to the single-cycle value (sum-of-one,
479
+ // concat-of-one, last==only) => BYTE-IDENTICAL to pre-#616.
480
+ //
481
+ // Accumulators (see CONSTRAINTS / aggregation plan in #616): SUM the count
482
+ // fields and durations; CONCAT the array fields; LAST-WINS for point-in-time
483
+ // objects (the final cycle's value reflects the converged state).
484
+ let cyclesRun = 0;
485
+ // Last-wins point-in-time values (assigned every cycle; the final cycle wins).
486
+ let preparation;
487
+ let memoryRefsForInference = new Set();
488
+ let consolidation;
489
+ let memoryInference;
490
+ let graphExtraction;
491
+ let stalenessDetection;
492
+ let recombination;
493
+ let proceduralCompilation;
494
+ // Summed counters/durations.
495
+ let prepGateCount = 0;
496
+ let prepGateFailedCount = 0;
497
+ let reflectsWithErrorContext = 0;
498
+ let loopGateCount = 0;
499
+ let loopGateFailedCount = 0;
500
+ let postLoopGateCount = 0;
501
+ let postLoopGateFailedCount = 0;
502
+ let memoryInferenceDurationMs = 0;
503
+ let graphExtractionDurationMs = 0;
504
+ let orphansPurged;
505
+ let proposalsExpired;
506
+ // Concatenated arrays.
507
+ const allWarnings = [];
508
+ let deadUrls;
509
+ const finalActions = [];
510
+ for (let cycleIndex = 0; cycleIndex < maxCycles; cycleIndex++) {
511
+ // #616 budget gate: never start a NEW cycle once the run's wall-clock
512
+ // budget is exhausted (or the run was aborted). Cycle 0 ALWAYS runs so
513
+ // maxCycles:1 is byte-identical regardless of budget.
514
+ if (cycleIndex > 0) {
515
+ const remaining = budgetAbortController.signal.remainingBudgetMs;
516
+ if (budgetAbortController.signal.aborted || (remaining !== undefined && remaining <= 0)) {
517
+ break;
518
+ }
519
+ }
520
+ // #662 incremental sync: bank the PREVIOUS cycle's writes before starting a
521
+ // new one, so a crash/abort/timeout mid-run loses at most the in-flight
522
+ // cycle rather than the whole run. Guarded on `cycleIndex > 0`, so the
523
+ // common maxCycles:1 path never calls this — its single end-of-run commit
524
+ // below stays the only sync and the serialized envelope is byte-identical
525
+ // to pre-#662. `saveGitStash` no-ops a clean tree, so a cycle that wrote
526
+ // nothing costs only a `git status`.
527
+ if (cycleIndex > 0) {
528
+ commitStashBatch({ scope, plannedRefs, runId: options.runId });
529
+ }
530
+ // Re-run ensureIndex + collectEligibleRefs + memory-cleanup recompute for
531
+ // cycles 2+ (cycle 1 already ran them in the first try above). This makes
532
+ // cycle N's gate-promoted proposals visible to this cycle's ref selection.
533
+ if (cycleIndex > 0) {
534
+ await runIndexAndCollect();
535
+ // Re-emit the profile-filtered audit summary for this cycle's selection.
536
+ if (profileFilteredRefs.length > 0) {
537
+ appendEvent({
538
+ eventType: "improve_skipped",
539
+ ref: undefined,
540
+ metadata: { reason: "profile_filtered_all_passes", count: profileFilteredRefs.length },
541
+ }, eventsCtx);
542
+ }
852
543
  }
544
+ // #607: acquire consolidate.lock for the preparation stage (consolidate,
545
+ // ensureIndex, extract all write index.db). Released immediately after.
546
+ const consolidateLPath = processLockPath(lockBaseDir, "consolidate");
547
+ preparation = await withOptionalProcessLock({
548
+ lockPath: consolidateLPath,
549
+ staleAfterMs: PROCESS_LOCK_DEFS.consolidate.staleAfterMs,
550
+ skipIfLocked: options.skipIfLocked,
551
+ label: "consolidate",
552
+ }, () => runImprovePreparationStageImpl({
553
+ scope,
554
+ options,
555
+ plannedRefs,
556
+ memoryCleanupPlan,
557
+ primaryStashDir,
558
+ memorySummary,
559
+ reindexFn,
560
+ startMs,
561
+ budgetMs,
562
+ eventsCtx,
563
+ initialCleanupWarnings: preEnsureCleanupWarnings,
564
+ improveProfile,
565
+ budgetSignal: budgetAbortController.signal,
566
+ }));
567
+ prepGateCount += preparation.gateAutoAcceptedCount;
568
+ prepGateFailedCount += preparation.gateAutoAcceptFailedCount;
569
+ // D6: pre-load all proposal_rejected events from the last 30 days once,
570
+ // so the per-asset loop can use a Map lookup instead of N DB round trips.
571
+ const REJECTED_PROPOSAL_WINDOW_MS = daysToMs(30);
572
+ const rejectedProposalSince = new Date(Date.now() - REJECTED_PROPOSAL_WINDOW_MS).toISOString();
573
+ const allRejectedProposalEvents = readEvents({ type: "proposal_rejected", since: rejectedProposalSince }).events;
574
+ const rejectedProposalsByRef = new Map();
575
+ for (const e of allRejectedProposalEvents) {
576
+ if (e.ref && (!rejectedProposalsByRef.has(e.ref) || e.ts > (rejectedProposalsByRef.get(e.ref)?.ts ?? ""))) {
577
+ rejectedProposalsByRef.set(e.ref, e);
578
+ }
579
+ }
580
+ // #607: acquire reflect-distill.lock for the loop stage (reflect + distill
581
+ // both write proposals to state.db). Released immediately after.
582
+ const reflectDistillLPath = processLockPath(lockBaseDir, "reflectDistill");
583
+ const loopResult = await withOptionalProcessLock({
584
+ lockPath: reflectDistillLPath,
585
+ staleAfterMs: PROCESS_LOCK_DEFS.reflectDistill.staleAfterMs,
586
+ skipIfLocked: options.skipIfLocked,
587
+ label: "reflect-distill",
588
+ }, () => {
589
+ // Post-lock cooldown re-filter for proactive refs (#SELECT-TIME-LEAK).
590
+ // Planning built `lastReflectProposalTs` BEFORE acquiring this lock, so a
591
+ // concurrent run's `reflect_invoked` writes are invisible to it. Now that
592
+ // we hold the lock, re-read fresh timestamp maps for the proactive subset
593
+ // and drop any ref whose cooldown has been consumed by the concurrent run.
594
+ const proactiveLoopRefs = preparation.loopRefs.filter((r) => r.eligibilitySource === "proactive");
595
+ let postLockLoopRefs = preparation.loopRefs;
596
+ if (proactiveLoopRefs.length > 0) {
597
+ const proactiveRefStrs = proactiveLoopRefs.map((r) => r.ref);
598
+ const freshReflectTs = buildLatestProposalTsMap(proactiveRefStrs, "reflect");
599
+ const freshDistillTs = buildLatestProposalTsMap(proactiveRefStrs, "distill");
600
+ const pmDueDays = improveProfile.processes?.proactiveMaintenance?.dueDays ?? DEFAULT_DUE_DAYS;
601
+ const stillDue = new Set(filterProactiveDue(proactiveLoopRefs, freshReflectTs, freshDistillTs, pmDueDays, Date.now()).map((r) => r.ref));
602
+ const dropped = proactiveLoopRefs.filter((r) => !stillDue.has(r.ref));
603
+ if (dropped.length > 0) {
604
+ info(`[improve] post-lock cooldown re-filter: dropped ${dropped.length} proactive ref(s) claimed by concurrent run (${dropped.map((r) => r.ref).join(", ")})`);
605
+ postLockLoopRefs = preparation.loopRefs.filter((r) => r.eligibilitySource !== "proactive" || stillDue.has(r.ref));
606
+ }
607
+ }
608
+ return runImproveLoopStageImpl({
609
+ scope,
610
+ options,
611
+ primaryStashDir,
612
+ reflectFn,
613
+ distillFn,
614
+ loopRefs: postLockLoopRefs,
615
+ actions: preparation.actions,
616
+ signalBearingSet: preparation.signalBearingSet,
617
+ distillCooledRefs: preparation.distillCooledRefs,
618
+ distillOnlyRefs: preparation.distillOnlyRefs,
619
+ recentErrors: preparation.recentErrors,
620
+ rejectedProposalsByRef,
621
+ utilityMap: preparation.utilityMap,
622
+ startMs,
623
+ budgetMs,
624
+ eventsCtx,
625
+ improveProfile,
626
+ budgetSignal: budgetAbortController.signal,
627
+ });
628
+ });
629
+ const loopGateCountThisCycle = loopResult.gateAutoAcceptedCount;
630
+ reflectsWithErrorContext += loopResult.reflectsWithErrorContext;
631
+ loopGateCount += loopResult.gateAutoAcceptedCount;
632
+ loopGateFailedCount += loopResult.gateAutoAcceptFailedCount;
633
+ memoryRefsForInference = loopResult.memoryRefsForInference;
634
+ // #551: consolidation now runs in the preparation stage (before extract);
635
+ // its result and run-flag are read from `preparation`, not the post-loop.
636
+ consolidation = preparation.consolidation;
637
+ // #607: acquire consolidate.lock for the post-loop stage (memoryInference +
638
+ // graphExtraction both write index.db). Released immediately after.
639
+ const consolidatePostLPath = processLockPath(lockBaseDir, "consolidate");
640
+ const postLoopResult = await withOptionalProcessLock({
641
+ lockPath: consolidatePostLPath,
642
+ staleAfterMs: PROCESS_LOCK_DEFS.consolidate.staleAfterMs,
643
+ skipIfLocked: options.skipIfLocked,
644
+ label: "consolidate",
645
+ }, () => runImprovePostLoopStageImpl({
646
+ scope,
647
+ options,
648
+ primaryStashDir,
649
+ actionableRefs: preparation.actionableRefs,
650
+ appliedCleanup: preparation.appliedCleanup,
651
+ cleanupWarnings: preparation.cleanupWarnings,
652
+ memoryRefsForInference,
653
+ reindexFn,
654
+ eventsCtx,
655
+ budgetSignal: budgetAbortController.signal,
656
+ improveProfile,
657
+ consolidationRan: preparation.consolidationRan,
658
+ }));
659
+ const postLoopGateCountThisCycle = postLoopResult.gateAutoAcceptedCount;
660
+ // Last-wins point-in-time objects.
661
+ memoryInference = postLoopResult.memoryInference;
662
+ graphExtraction = postLoopResult.graphExtraction;
663
+ stalenessDetection = postLoopResult.stalenessDetection;
664
+ recombination = postLoopResult.recombination;
665
+ proceduralCompilation = postLoopResult.proceduralCompilation;
666
+ // Summed counters/durations.
667
+ postLoopGateCount += postLoopResult.gateAutoAcceptedCount;
668
+ postLoopGateFailedCount += postLoopResult.gateAutoAcceptFailedCount;
669
+ memoryInferenceDurationMs += postLoopResult.memoryInferenceDurationMs;
670
+ graphExtractionDurationMs += postLoopResult.graphExtractionDurationMs;
671
+ if (postLoopResult.orphansPurged !== undefined) {
672
+ orphansPurged = (orphansPurged ?? 0) + postLoopResult.orphansPurged;
673
+ }
674
+ if (postLoopResult.proposalsExpired !== undefined) {
675
+ proposalsExpired = (proposalsExpired ?? 0) + postLoopResult.proposalsExpired;
676
+ }
677
+ // Concatenated arrays.
678
+ allWarnings.push(...postLoopResult.allWarnings);
679
+ if (postLoopResult.deadUrls !== undefined) {
680
+ deadUrls = [...(deadUrls ?? []), ...postLoopResult.deadUrls];
681
+ }
682
+ const maintenanceActions = postLoopResult.maintenanceActions;
683
+ if (maintenanceActions && maintenanceActions.length > 0) {
684
+ finalActions.push(...preparation.actions, ...maintenanceActions);
685
+ }
686
+ else {
687
+ finalActions.push(...preparation.actions);
688
+ }
689
+ cyclesRun++;
690
+ // #616 fixed-point stop: a cycle that produced ZERO gate-accepted proposals
691
+ // (summed across prep + loop + post-loop) would feed cycle N+1 an identical
692
+ // ref set, so end the loop here rather than spin a pointless next cycle.
693
+ const gateAcceptedThisCycle = preparation.gateAutoAcceptedCount + loopGateCountThisCycle + postLoopGateCountThisCycle;
694
+ if (gateAcceptedThisCycle === 0)
695
+ break;
853
696
  }
854
- const { reflectsWithErrorContext, memoryRefsForInference, gateAutoAcceptedCount: loopGateCount, gateAutoAcceptFailedCount: loopGateFailedCount, } = await runImproveLoopStage({
855
- scope,
856
- options,
857
- primaryStashDir,
858
- reflectFn,
859
- distillFn,
860
- loopRefs: preparation.loopRefs,
861
- actions: preparation.actions,
862
- signalBearingSet: preparation.signalBearingSet,
863
- distillCooledRefs: preparation.distillCooledRefs,
864
- distillOnlyRefs: preparation.distillOnlyRefs,
865
- recentErrors: preparation.recentErrors,
866
- rejectedProposalsByRef,
867
- utilityMap: preparation.utilityMap,
868
- startMs,
869
- budgetMs,
870
- eventsCtx,
871
- improveProfile,
872
- });
873
- // #551: consolidation now runs in the preparation stage (before extract);
874
- // its result and run-flag are read from `preparation`, not the post-loop.
875
- const consolidation = preparation.consolidation;
876
- const { allWarnings, deadUrls, memoryInference, graphExtraction, stalenessDetection, maintenanceActions, memoryInferenceDurationMs, graphExtractionDurationMs, orphansPurged, proposalsExpired, gateAutoAcceptedCount: postLoopGateCount, gateAutoAcceptFailedCount: postLoopGateFailedCount, } = await runImprovePostLoopStage({
877
- scope,
878
- options,
879
- primaryStashDir,
880
- actionableRefs: preparation.actionableRefs,
881
- appliedCleanup: preparation.appliedCleanup,
882
- cleanupWarnings: preparation.cleanupWarnings,
883
- memoryRefsForInference,
884
- reindexFn,
885
- eventsCtx,
886
- // O-1 (#364): propagate wall-clock budget signal to post-loop maintenance.
887
- budgetSignal: budgetAbortController.signal,
888
- improveProfile,
889
- consolidationRan: preparation.consolidationRan,
890
- });
891
- const finalActions = maintenanceActions && maintenanceActions.length > 0
892
- ? [...preparation.actions, ...maintenanceActions]
893
- : preparation.actions;
894
697
  const result = {
895
698
  schemaVersion: 1,
896
699
  ok: true,
@@ -949,17 +752,19 @@ export async function akmImprove(options = {}) {
949
752
  ...(memoryInferenceDurationMs > 0 ? { memoryInferenceDurationMs } : {}),
950
753
  ...(graphExtractionDurationMs > 0 ? { graphExtractionDurationMs } : {}),
951
754
  ...(stalenessDetection ? { stalenessDetection } : {}),
755
+ ...(recombination ? { recombination } : {}),
756
+ ...(proceduralCompilation ? { proceduralCompilation } : {}),
952
757
  ...(orphansPurged !== undefined ? { orphansPurged } : {}),
953
758
  ...(proposalsExpired !== undefined && proposalsExpired > 0 ? { proposalsExpired } : {}),
954
759
  reflectCooldownActions: finalActions.filter((a) => a.mode === "reflect-cooldown").length,
955
760
  reflectSkippedActions: finalActions.filter((a) => a.mode === "reflect-skipped").length,
956
761
  reflectGuardRejectedActions: finalActions.filter((a) => a.mode === "reflect-guard-rejected").length,
957
762
  ...(() => {
958
- const t = preparation.gateAutoAcceptedCount + loopGateCount + postLoopGateCount;
763
+ const t = prepGateCount + loopGateCount + postLoopGateCount;
959
764
  return t > 0 ? { gateAutoAcceptedCount: t } : {};
960
765
  })(),
961
766
  ...(() => {
962
- const f = preparation.gateAutoAcceptFailedCount + loopGateFailedCount + postLoopGateFailedCount;
767
+ const f = prepGateFailedCount + loopGateFailedCount + postLoopGateFailedCount;
963
768
  return f > 0 ? { gateAutoAcceptFailedCount: f } : {};
964
769
  })(),
965
770
  ...(triageDrain
@@ -972,6 +777,10 @@ export async function akmImprove(options = {}) {
972
777
  },
973
778
  }
974
779
  : {}),
780
+ ...(preparation.proactiveMaintenance ? { proactiveMaintenance: preparation.proactiveMaintenance } : {}),
781
+ // #616 — report cycles run only when >1 so the default single-pass
782
+ // serialized envelope stays byte-identical to pre-#616 (AC1).
783
+ ...(cyclesRun > 1 ? { cyclesRun } : {}),
975
784
  ...(options.runId !== undefined ? { runId: options.runId } : {}),
976
785
  };
977
786
  if (!result.dryRun)
@@ -982,57 +791,18 @@ export async function akmImprove(options = {}) {
982
791
  warningCount: allWarnings.length,
983
792
  orphansPurged: orphansPurged ?? 0,
984
793
  }, eventsCtx);
985
- // End-of-run BATCH auto-sync. Recognition is decoupled from the per-write
986
- // path (see write-source.ts case-3): the primary stash writes as a
987
- // filesystem source during the run, then is committed in one shot here via
988
- // the same `saveGitStash` that `akm sync` calls. Gated on a non-dry-run, a
989
- // git-backed primary stash (by `.git`, not by remote), and sync not
990
- // disabled. A sync failure is NON-FATAL it never fails a successful run
991
- // (mirrors the contradiction-detection best-effort pattern).
992
- const effectiveSync = { ...improveProfile.sync, ...options.sync };
993
- if (!result.dryRun && primaryStashDir && effectiveSync.enabled !== false && isGitBackedStash(primaryStashDir)) {
994
- const saveGitStashFn = options.saveGitStashFn ?? saveGitStash;
995
- // Reuse the config resolved at the top of the run (`_earlyConfig`) instead
996
- // of a second loadConfig(); the writable derivation is shared with
997
- // `akm sync` via resolveWritableOverride().
998
- const writableOverride = resolveWritableOverride(_earlyConfig);
999
- const push = effectiveSync.push !== false;
1000
- // `sync.message` may contain `{token}` placeholders (timestamp/date/time/
1001
- // scope/refs/accepted) expanded against this run's results; the default
1002
- // template has no tokens so it renders verbatim.
1003
- const message = renderSyncCommitMessage(effectiveSync.message ?? "akm improve auto-sync", result, Date.now());
1004
- try {
1005
- // Pass primaryStashDir as the explicit commit target so the gate above
1006
- // (which validated primaryStashDir via isGitBackedStash) and the commit
1007
- // operate on the SAME directory — avoids divergence when a caller passes
1008
- // a non-default options.stashDir (FIX 9).
1009
- const syncResult = saveGitStashFn(undefined, message, writableOverride, { push, repoDir: primaryStashDir });
1010
- result.sync = {
1011
- committed: syncResult.committed,
1012
- pushed: syncResult.pushed,
1013
- skipped: syncResult.skipped,
1014
- ...(syncResult.reason !== undefined ? { reason: syncResult.reason } : {}),
1015
- };
1016
- appendEvent({
1017
- eventType: "stash_synced",
1018
- metadata: {
1019
- committed: syncResult.committed,
1020
- pushed: syncResult.pushed,
1021
- skipped: syncResult.skipped,
1022
- reason: syncResult.reason ?? null,
1023
- },
1024
- }, eventsCtx);
1025
- }
1026
- catch (syncErr) {
1027
- const reason = syncErr instanceof Error ? syncErr.message : String(syncErr);
1028
- warn(`improve: end-of-run stash sync failed (non-fatal): ${reason}`);
1029
- result.sync = { committed: false, pushed: false, skipped: true, reason };
1030
- appendEvent({
1031
- eventType: "stash_synced",
1032
- metadata: { committed: false, pushed: false, skipped: true, reason },
1033
- }, eventsCtx);
1034
- }
1035
- }
794
+ // End-of-run BATCH auto-sync the converged commit. Recognition is
795
+ // decoupled from the per-write path (see write-source.ts case-3): the primary
796
+ // stash writes as a filesystem source during the run, then is committed via
797
+ // the same `saveGitStash` that `akm sync` calls. The gating (git-backed
798
+ // primary stash, sync not disabled) and the NON-FATAL guarantee now live in
799
+ // `commitStashBatch` (#662); the inter-cycle and catch-path calls reuse it.
800
+ // dry-run already returned above, so this always runs on a completed live
801
+ // run. `result.sync` reflects this final commit (for a one-cycle run it is
802
+ // the only commit; for a multi-cycle run the earlier cycles were banked by
803
+ // the inter-cycle calls and this records the last batch). `result` carries
804
+ // the full `{accepted}`/`{refs}`/`{triage_*}` token data for the message.
805
+ result.sync = commitStashBatch(result);
1036
806
  return result;
1037
807
  }
1038
808
  catch (err) {
@@ -1045,6 +815,13 @@ export async function akmImprove(options = {}) {
1045
815
  durationMs: Date.now() - startMs,
1046
816
  },
1047
817
  }, eventsCtx);
818
+ // #662 crash/abort safety net: commit whatever this run already wrote to the
819
+ // primary stash BEFORE rethrowing, so an interrupted run (mid-cycle crash or
820
+ // a cooperative budget abort that surfaces as a throw) does not leave its
821
+ // writes uncommitted until a later clean run sweeps them up. Best-effort —
822
+ // `commitStashBatch` swallows its own errors and no-ops a clean tree, so this
823
+ // never masks or supersedes the original failure being rethrown below.
824
+ commitStashBatch({ scope, plannedRefs, runId: options.runId });
1048
825
  throw err;
1049
826
  }
1050
827
  finally {
@@ -1054,15 +831,18 @@ export async function akmImprove(options = {}) {
1054
831
  // O-1 (#364): Clear the budget abort timer so it does not keep the event
1055
832
  // loop alive after the run completes.
1056
833
  clearBudgetTimer();
1057
- try {
1058
- fs.unlinkSync(resolvedLockPath);
1059
- }
1060
- catch {
1061
- // ignore
834
+ // #607: release any per-process locks still held (backstop for error paths;
835
+ // the normal path already released each lock after its stage completed).
836
+ releaseAllProcessLocks();
837
+ // Drop ONLY our own process.exit backstop so it does not fire later (or
838
+ // accumulate across repeated in-process calls). Must NOT use
839
+ // removeAllListeners("exit") here: in the in-process model (tests and
840
+ // programmatic callers import cli.ts) that would silently destroy exit
841
+ // handlers owned by the host or other commands.
842
+ if (exitBackstop) {
843
+ process.removeListener("exit", exitBackstop);
844
+ exitBackstop = undefined;
1062
845
  }
1063
- // The normal path released the lock above; drop the process.exit backstop so
1064
- // it does not fire later (or accumulate across repeated in-process calls).
1065
- process.removeListener("exit", releaseLockOnExit);
1066
846
  // I1: close the long-lived state.db connection opened at the top of the run.
1067
847
  try {
1068
848
  eventsDb?.close();
@@ -1089,7 +869,7 @@ function emitImproveCompletedEvent(result, durations, eventsCtx) {
1089
869
  // Coarse audit buckets, derived from the SAME classifyImproveAction the
1090
870
  // persisted metrics_json uses (state-db.ts#computeImproveRunMetrics) so the
1091
871
  // emitted event and the stored row can never disagree.
1092
- const classCounts = { accepted: 0, rejected: 0, error: 0, noop: 0 };
872
+ const classCounts = { accepted: 0, rejected: 0, skipped: 0, error: 0, noop: 0 };
1093
873
  for (const action of result.actions ?? []) {
1094
874
  classCounts[classifyImproveAction(action.mode)] += 1;
1095
875
  // Per-variant counters for the event metadata. The default arm makes any
@@ -1156,6 +936,7 @@ function emitImproveCompletedEvent(result, durations, eventsCtx) {
1156
936
  reflectGuardRejectedActions: actionCounts.reflectGuardRejected,
1157
937
  acceptedActions: classCounts.accepted,
1158
938
  rejectedActions: classCounts.rejected,
939
+ skippedActions: classCounts.skipped,
1159
940
  noopActions: classCounts.noop,
1160
941
  reflectsWithErrorContext: result.reflectsWithErrorContext ?? 0,
1161
942
  coverageGapCount: result.coverageGaps?.length ?? 0,
@@ -1175,6 +956,11 @@ function emitImproveCompletedEvent(result, durations, eventsCtx) {
1175
956
  memoryInferenceDurationMs: durations.memoryInferenceDurationMs,
1176
957
  graphExtractionExtractedFiles: result.graphExtraction?.quality.extractedFiles ?? 0,
1177
958
  graphExtractionDurationMs: durations.graphExtractionDurationMs,
959
+ // Layer-2 proactive-maintenance coverage (0 when the process is disabled
960
+ // or the run was ref-scoped) so a scheduled sweep's reach is trackable.
961
+ proactiveSelected: result.proactiveMaintenance?.selected ?? 0,
962
+ proactiveDueTotal: result.proactiveMaintenance?.dueTotal ?? 0,
963
+ proactiveNeverReflected: result.proactiveMaintenance?.neverReflected ?? 0,
1178
964
  // New metrics for tuning the improve loop.
1179
965
  ...(durations.totalDurationMs !== undefined ? { durationMs: durations.totalDurationMs } : {}),
1180
966
  ...(durations.warningCount !== undefined ? { warningCount: durations.warningCount } : {}),
@@ -1189,1760 +975,6 @@ function emitImproveCompletedEvent(result, durations, eventsCtx) {
1189
975
  },
1190
976
  }, eventsCtx);
1191
977
  }
1192
- /**
1193
- * Run (or gate-skip) the memory consolidation pass.
1194
- *
1195
- * #551 — two coordinated changes live here:
1196
- *
1197
- * 1. STRUCTURAL: this runs before extract in the improve pipeline (see
1198
- * `runImprovePreparationStage`). Consolidation therefore only ever judges
1199
- * PRIOR-run memories; current-run extract promotions are invisible to it.
1200
- *
1201
- * 2. SMARTER POOL-DELTA GATE: even among on-disk files, a memory whose only
1202
- * post-`lastConsolidateTs` mtime bump came from its OWN auto-accept
1203
- * promotion (i.e. it was just promoted by extract in the immediately
1204
- * preceding run and has not had a full improve cycle to settle) does NOT
1205
- * count as "work to do". We exclude those paths from the pool-delta check
1206
- * using the `promoted` events already emitted with each promotion's
1207
- * `assetPath`. A genuinely-settled prior memory — one edited by feedback,
1208
- * reflect, manual edit, or simply older than the last consolidate — still
1209
- * triggers the run. This is gate-option (a) from the issue (same-run /
1210
- * adjacent-run promotion exclusion), chosen over option (b) because there
1211
- * is no `extract_completed` event in the data model to gate against;
1212
- * `promoted` events with `assetPath` already carry exactly the signal we
1213
- * need, so the fix is non-invasive and provably correct.
1214
- */
1215
- async function runConsolidationPass(args) {
1216
- const { options, primaryStashDir, memorySummary, improveProfile, eventsCtx } = args;
1217
- const baseConfig = options.config ?? loadConfig();
1218
- const MEMORY_VOLUME_THRESHOLD = options.memoryVolumeConsolidationThreshold ?? 100;
1219
- const hasLlm = !!(baseConfig.defaults?.llm || baseConfig.defaults?.agent);
1220
- const volumeTriggered = typeof memorySummary.eligible === "number" && memorySummary.eligible > MEMORY_VOLUME_THRESHOLD && hasLlm;
1221
- // When volume triggers a consolidation pass, force-enable the consolidate
1222
- // process on the default improve profile so the gate accepts the run even
1223
- // if the user's config disabled it. We synthesise a new profile override
1224
- // rather than mutating connection settings.
1225
- const consolidationConfig = volumeTriggered
1226
- ? {
1227
- ...baseConfig,
1228
- profiles: {
1229
- ...(baseConfig.profiles ?? {}),
1230
- improve: {
1231
- ...(baseConfig.profiles?.improve ?? {}),
1232
- default: {
1233
- ...(baseConfig.profiles?.improve?.default ?? {}),
1234
- processes: {
1235
- ...(baseConfig.profiles?.improve?.default?.processes ?? {}),
1236
- consolidate: {
1237
- ...(baseConfig.profiles?.improve?.default?.processes?.consolidate ?? {}),
1238
- enabled: true,
1239
- },
1240
- },
1241
- },
1242
- },
1243
- },
1244
- }
1245
- : baseConfig;
1246
- // 0.8.0 pool-delta gate for consolidate: re-eligible iff at least one
1247
- // memory file has been updated since the most recent successful
1248
- // consolidate_completed event. Time-based cooldowns produced the same
1249
- // synchronised-wave failure mode the reflect/distill cooldowns did; the
1250
- // pool-delta gate ties consolidation to actual work-to-do.
1251
- const recentConsolidations = readEvents({ type: "consolidate_completed" });
1252
- const lastConsolidation = recentConsolidations.events
1253
- .filter((e) => e.metadata?.processed && Number(e.metadata.processed) > 0)
1254
- .sort((a, b) => new Date(b.ts ?? 0).getTime() - new Date(a.ts ?? 0).getTime())[0];
1255
- const lastConsolidateTs = lastConsolidation?.ts;
1256
- // #551 smarter gate: build the set of memory asset paths whose only delta
1257
- // since the last consolidate is their OWN auto-accept promotion. Those files
1258
- // have not had a full improve cycle to settle, so they offer no merge /
1259
- // contradiction candidates yet — excluding them stops the gate firing on
1260
- // freshly-promoted single-source memories. We read `promoted` events emitted
1261
- // after the last consolidate; each carries the written `assetPath`.
1262
- const promotedSinceConsolidate = (() => {
1263
- const paths = new Set();
1264
- try {
1265
- const promoted = readEvents({
1266
- type: "promoted",
1267
- ...(lastConsolidateTs ? { since: lastConsolidateTs } : {}),
1268
- }).events;
1269
- for (const e of promoted) {
1270
- const ap = e.metadata?.assetPath;
1271
- if (typeof ap === "string" && ap.length > 0)
1272
- paths.add(path.resolve(ap));
1273
- }
1274
- }
1275
- catch {
1276
- // best-effort: if the events query fails, fall back to no exclusions
1277
- // (preserves pre-#551 behaviour rather than over-skipping).
1278
- }
1279
- return paths;
1280
- })();
1281
- // Pool-delta: any memory file with mtime > lastConsolidateTs flags work to do,
1282
- // EXCEPT files whose only post-consolidate change was their own promotion.
1283
- // Using file mtime keeps this query DB-free and matches what the indexer
1284
- // already uses as the canonical `memory.updated_at` proxy.
1285
- //
1286
- // Bootstrap: when no successful consolidate_completed event has ever been
1287
- // recorded, we cannot evaluate the pool-delta — treat as eligible so a
1288
- // fresh stash runs consolidate once before the steady-state gate kicks in.
1289
- const memoryUpdatedAfterLastConsolidate = (() => {
1290
- if (volumeTriggered)
1291
- return true; // volume override forces the run regardless.
1292
- if (!lastConsolidateTs)
1293
- return true; // bootstrap path: never consolidated.
1294
- if (!primaryStashDir)
1295
- return false;
1296
- const memoriesDir = path.join(primaryStashDir, "memories");
1297
- if (!fs.existsSync(memoriesDir))
1298
- return false;
1299
- try {
1300
- return fs.readdirSync(memoriesDir).some((f) => {
1301
- if (!f.endsWith(".md"))
1302
- return false;
1303
- const filePath = path.join(memoriesDir, f);
1304
- // #551: skip files that were only touched by their own promotion this
1305
- // cohort — they have no settled merge/contradiction candidates yet.
1306
- if (promotedSinceConsolidate.has(path.resolve(filePath)))
1307
- return false;
1308
- try {
1309
- return fs.statSync(filePath).mtime.toISOString() > lastConsolidateTs;
1310
- }
1311
- catch {
1312
- return false;
1313
- }
1314
- });
1315
- }
1316
- catch {
1317
- return false;
1318
- }
1319
- })();
1320
- const consolidationOnCooldown = !volumeTriggered && !memoryUpdatedAfterLastConsolidate;
1321
- // Profile gate: if profile explicitly disables consolidate, skip the entire pass.
1322
- const consolidateDisabledByProfile = improveProfile?.processes?.consolidate?.enabled === false;
1323
- // #553 minPoolSize guard: skip consolidation when the eligible memory pool is
1324
- // below a minimum size, rather than spending an LLM pass on a handful of
1325
- // memories. This is an INDEPENDENT skip condition from #551's mtime pool-delta
1326
- // gate — either can skip. Default 500; `minPoolSize: 0` disables the guard.
1327
- // Evaluated against the eligible-pool count BEFORE entering the LLM loop so a
1328
- // skip costs ZERO LLM calls.
1329
- const CONSOLIDATE_DEFAULT_MIN_POOL_SIZE = 500;
1330
- const configuredMinPoolSize = improveProfile?.processes?.consolidate?.minPoolSize;
1331
- const minPoolSize = typeof configuredMinPoolSize === "number" ? configuredMinPoolSize : CONSOLIDATE_DEFAULT_MIN_POOL_SIZE;
1332
- const eligiblePoolSize = typeof memorySummary.eligible === "number" ? memorySummary.eligible : 0;
1333
- // volumeTriggered means the pool already exceeds the volume threshold (100),
1334
- // so a force-triggered run never trips the pool-size guard. The guard only
1335
- // engages when minPoolSize > 0 and the eligible pool is strictly below it.
1336
- const poolBelowMinSize = !volumeTriggered && minPoolSize > 0 && eligiblePoolSize < minPoolSize;
1337
- let consolidation = {
1338
- schemaVersion: 1,
1339
- ok: true,
1340
- shape: "consolidate-result",
1341
- dryRun: false,
1342
- previewOnly: false,
1343
- target: "",
1344
- processed: 0,
1345
- merged: 0,
1346
- deleted: 0,
1347
- promoted: [],
1348
- contradicted: 0,
1349
- warnings: [],
1350
- durationMs: 0,
1351
- };
1352
- let gateAutoAcceptedCount = 0;
1353
- let gateAutoAcceptFailedCount = 0;
1354
- const consolidateGateCfg = makeGateConfig("consolidate", {
1355
- globalThreshold: options.autoAccept,
1356
- dryRun: options.dryRun ?? false,
1357
- stashDir: primaryStashDir,
1358
- config: consolidationConfig,
1359
- eventsCtx,
1360
- }, { minimumThreshold: 95 });
1361
- if (consolidateDisabledByProfile) {
1362
- info("[improve] consolidation skipped (disabled by improve profile)");
1363
- }
1364
- else if (poolBelowMinSize) {
1365
- // #553: eligible pool below the configured minimum — skip with zero LLM
1366
- // calls. Reuse the #551 `improve_skipped` emission path so health surfaces
1367
- // it via the dynamic skipReasons aggregation under `pool_below_min_size`.
1368
- appendEvent({
1369
- eventType: "improve_skipped",
1370
- ref: "memory:_consolidation",
1371
- metadata: {
1372
- reason: "pool_below_min_size",
1373
- poolSize: eligiblePoolSize,
1374
- minPoolSize,
1375
- },
1376
- }, eventsCtx);
1377
- info(`[improve] consolidation skipped (pool ${eligiblePoolSize} < minPoolSize ${minPoolSize})`);
1378
- }
1379
- else if (!consolidationOnCooldown) {
1380
- consolidation = await withLlmStage("consolidate", () => akmConsolidate({
1381
- ...options.consolidateOptions,
1382
- config: consolidationConfig,
1383
- stashDir: options.stashDir,
1384
- autoTriggered: volumeTriggered,
1385
- // Tie consolidate proposals back to this improve invocation so
1386
- // accept-rate-per-run aggregation works. Mirrors reflect/propose/extract.
1387
- sourceRun: `consolidate-${Date.now()}`,
1388
- // Full-pool sweep: consolidation only runs on the nightly default-profile
1389
- // pass (quick/frequent disable it), so a complete re-cluster is correct and
1390
- // affordable here. Do NOT pass incrementalSince — the time-window narrowing
1391
- // it triggers permanently excludes stale-but-unmerged duplicate clusters,
1392
- // starving merge recall and letting the pool grow unbounded. (The narrowing
1393
- // was a band-aid for an every-30-min consolidation cadence that the profile
1394
- // split has since eliminated.) lastConsolidateTs still gates whether we run.
1395
- maxChunkSize: improveProfile?.processes?.consolidate?.maxChunkSize,
1396
- // Honor profile.autoAccept (already merged into options.autoAccept at the
1397
- // top of akmImprove). The CLI parser always supplies 90 when --auto-accept
1398
- // is absent, so ?? 90 is not needed here and would prevent --auto-accept=false
1399
- // (which maps to undefined) from disabling consolidation auto-accept.
1400
- // options.consolidateOptions.autoAccept (if explicitly provided by caller)
1401
- // still wins because the spread above runs first.
1402
- autoAccept: options.consolidateOptions?.autoAccept ?? options.autoAccept,
1403
- }));
1404
- {
1405
- const consolidateGr = await runAutoAcceptGate(consolidation.promoted.map((proposalId) => {
1406
- try {
1407
- if (!primaryStashDir)
1408
- return { proposalId, confidence: undefined };
1409
- const proposal = getProposal(primaryStashDir, proposalId);
1410
- return { proposalId, confidence: proposal.confidence };
1411
- }
1412
- catch {
1413
- return { proposalId, confidence: undefined };
1414
- }
1415
- }), consolidateGateCfg);
1416
- gateAutoAcceptedCount += consolidateGr.promoted.length;
1417
- gateAutoAcceptFailedCount += consolidateGr.failed.length;
1418
- }
1419
- if (consolidation.processed > 0) {
1420
- appendEvent({
1421
- eventType: "consolidate_completed",
1422
- ref: "memory:_consolidation",
1423
- metadata: { processed: consolidation.processed, merged: consolidation.merged },
1424
- }, eventsCtx);
1425
- }
1426
- }
1427
- else {
1428
- appendEvent({
1429
- eventType: "improve_skipped",
1430
- ref: "memory:_consolidation",
1431
- metadata: {
1432
- reason: "consolidation_no_memory_updates",
1433
- lastEventTs: lastConsolidation?.ts ?? null,
1434
- },
1435
- }, eventsCtx);
1436
- info("[improve] consolidation skipped (no memory updates since last run)");
1437
- }
1438
- // D9: track whether consolidation wrote any data so graph extraction can reindex if needed
1439
- const consolidationRan = !consolidateDisabledByProfile && !poolBelowMinSize && !consolidationOnCooldown && consolidation.processed > 0;
1440
- return { consolidation, consolidationRan, gateAutoAcceptedCount, gateAutoAcceptFailedCount };
1441
- }
1442
- async function runImprovePreparationStage(args) {
1443
- const { scope, options, plannedRefs, memoryCleanupPlan, primaryStashDir, memorySummary, reindexFn, startMs, budgetMs, eventsCtx, initialCleanupWarnings, improveProfile, } = args;
1444
- const actions = [];
1445
- const cleanupWarnings = initialCleanupWarnings ? [...initialCleanupWarnings] : [];
1446
- // Phase 0 — MEMORY.md budget check (200-line cap; warn at 180)
1447
- let memoryIndexHealth;
1448
- if (primaryStashDir) {
1449
- const memoryMdPath = path.join(primaryStashDir, "memories", "MEMORY.md");
1450
- if (fs.existsSync(memoryMdPath)) {
1451
- try {
1452
- const lines = fs.readFileSync(memoryMdPath, "utf8").split("\n").length;
1453
- const overBudget = lines >= 180;
1454
- memoryIndexHealth = { lineCount: lines, overBudget };
1455
- if (overBudget) {
1456
- cleanupWarnings.push(`MEMORY.md has ${lines} lines (budget: 200). Consolidation strongly recommended.`);
1457
- }
1458
- }
1459
- catch {
1460
- // best-effort
1461
- }
1462
- }
1463
- }
1464
- // Phase 0.3 — memory consolidation pass (#551).
1465
- //
1466
- // Consolidation runs BEFORE the session-extract pass. This is the structural
1467
- // half of the #551 fix: extract auto-accept writes brand-new memory .md files
1468
- // on every run, which previously made the consolidation pool-delta gate fire
1469
- // unconditionally (any new file => "memory updated since last consolidate").
1470
- // By running consolidation first, the gate and akmConsolidate only ever see
1471
- // memories that existed at the start of the run — current-run extract
1472
- // promotions are not on disk yet. The complementary smarter-gate logic
1473
- // (excluding adjacent-run promotions) lives in `runConsolidationPass`.
1474
- const consolidationPass = await runConsolidationPass({
1475
- options,
1476
- primaryStashDir,
1477
- memorySummary,
1478
- improveProfile,
1479
- eventsCtx,
1480
- });
1481
- // Phase 0.4 — session-extract pass.
1482
- //
1483
- // Reads native session files (claude-code JSONL, opencode storage tree)
1484
- // through the SessionLogHarness registry, pre-filters noise, and asks a
1485
- // bounded in-tree LLM to produce candidate memory/lesson/knowledge
1486
- // proposals for content the agent did NOT preserve via inline `akm remember`
1487
- // / `akm feedback` invocations. Replaces the akm-plugin session-checkpoint
1488
- // hook with an on-demand pull pipeline.
1489
- //
1490
- // Default-on; opt out via the ACTIVE profile's `processes.extract.enabled: false`
1491
- // (#593: the gate respects the resolved improve profile, not just the
1492
- // hardcoded `default` profile path the legacy feature flag reads).
1493
- // Each available harness gets one call with the default --since window;
1494
- // already-seen sessions (tracked in state.db.extract_sessions_seen) are
1495
- // skipped automatically so re-runs don't burn LLM calls on unchanged data.
1496
- //
1497
- // Failures are non-fatal — one harness throwing doesn't abort improve.
1498
- // The extract envelope's own `warnings` field surfaces what went wrong.
1499
- let extractResults;
1500
- // Seed the preparation-stage gate counters with consolidation's auto-accept
1501
- // gate results (#551: consolidation now runs in this stage), then accumulate
1502
- // extract's gate results on top.
1503
- let gateAutoAcceptedCount = consolidationPass.gateAutoAcceptedCount;
1504
- let gateAutoAcceptFailedCount = consolidationPass.gateAutoAcceptFailedCount;
1505
- const extractConfig = options.config ?? loadConfig();
1506
- const extractGateCfg = makeGateConfig("extract", {
1507
- globalThreshold: options.autoAccept,
1508
- dryRun: options.dryRun ?? false,
1509
- stashDir: primaryStashDir,
1510
- config: extractConfig,
1511
- eventsCtx,
1512
- });
1513
- // #554 minNewSessions gate: skip the entire extract pass (ensureIndex was
1514
- // already done upstream; here we elide every akmExtract/processSession call)
1515
- // when the NEW (unseen, in-window) candidate-session pool is below a minimum.
1516
- // 22% of improve runs produce zero memory-inference writes because extract
1517
- // finds no new sessions, yet still burns the full extract pipeline. Default 0
1518
- // (disabled) preserves existing always-run behaviour; only opted-in profiles
1519
- // (e.g. `frequent`) set it. Evaluated BEFORE any LLM call so a skip costs zero
1520
- // LLM work AND writes nothing — which also means no extract auto-accept bumps
1521
- // memory mtimes, so a skipped extract never flags work for the NEXT run's
1522
- // consolidation mtime-gate (the downstream trigger #554 asks us to suppress).
1523
- const EXTRACT_DEFAULT_MIN_NEW_SESSIONS = 0;
1524
- const configuredMinNewSessions = extractConfig.profiles?.improve?.default?.processes?.extract?.minNewSessions;
1525
- const minNewSessions = typeof configuredMinNewSessions === "number" ? configuredMinNewSessions : EXTRACT_DEFAULT_MIN_NEW_SESSIONS;
1526
- // #593: gate on BOTH the legacy feature flag (which only reads
1527
- // `profiles.improve.default.processes.extract.enabled` — kept for back-compat
1528
- // with users who disable extract via the default-profile path) AND the active
1529
- // resolved profile. Without the second check a non-default profile setting
1530
- // `extract.enabled: false` (e.g. the built-in `quick`) was silently ignored
1531
- // and extract ran on every improve call regardless.
1532
- if (isLlmFeatureEnabled(extractConfig, "session_extraction") && resolveProcessEnabled("extract", improveProfile)) {
1533
- const availableHarnesses = options.extractHarnesses ?? getAvailableHarnesses();
1534
- // The guard engages only when minNewSessions > 0; 0 disables it entirely.
1535
- let belowMinNewSessions = false;
1536
- if (minNewSessions > 0 && availableHarnesses.length > 0) {
1537
- const countFn = options.extractCandidateCountFn ?? countNewExtractCandidates;
1538
- const newCandidateCount = countFn(extractConfig, {
1539
- ...(options.extractHarnesses ? { harnesses: options.extractHarnesses } : {}),
1540
- // C2: pin the candidate-count state.db open to the boundary-resolved path.
1541
- ...(eventsCtx?.dbPath ? { stateDbPath: eventsCtx.dbPath } : {}),
1542
- });
1543
- if (newCandidateCount < minNewSessions) {
1544
- belowMinNewSessions = true;
1545
- // Reuse the #551/#553 `improve_skipped` emission path so health's dynamic
1546
- // skipReasons aggregation surfaces this under `below_min_new_sessions`.
1547
- appendEvent({
1548
- eventType: "improve_skipped",
1549
- ref: "memory:_extract",
1550
- metadata: {
1551
- reason: "below_min_new_sessions",
1552
- newSessions: newCandidateCount,
1553
- minNewSessions,
1554
- },
1555
- }, eventsCtx);
1556
- info(`[improve] extract skipped (new sessions ${newCandidateCount} < minNewSessions ${minNewSessions})`);
1557
- }
1558
- }
1559
- if (!belowMinNewSessions && availableHarnesses.length > 0) {
1560
- extractResults = [];
1561
- for (const h of availableHarnesses) {
1562
- try {
1563
- const result = await withLlmStage("session-extraction", () => akmExtract({
1564
- type: h.name,
1565
- ...(primaryStashDir !== undefined ? { stashDir: primaryStashDir } : {}),
1566
- config: extractConfig,
1567
- dryRun: options.dryRun ?? false,
1568
- ...(options.extractHarnesses ? { harnesses: options.extractHarnesses } : {}),
1569
- // C2: pin extract's skip-tracking state.db open to the boundary path.
1570
- ...(eventsCtx?.dbPath ? { stateDbPath: eventsCtx.dbPath } : {}),
1571
- }));
1572
- extractResults.push(result);
1573
- {
1574
- const gr = await runAutoAcceptGate(primaryStashDir
1575
- ? result.proposals.map((proposalId) => {
1576
- const proposal = getProposal(primaryStashDir, proposalId);
1577
- return { proposalId, confidence: resolveExtractConfidence(proposal) };
1578
- })
1579
- : [], extractGateCfg);
1580
- gateAutoAcceptedCount += gr.promoted.length;
1581
- gateAutoAcceptFailedCount += gr.failed.length;
1582
- }
1583
- }
1584
- catch (err) {
1585
- const msg = err instanceof Error ? err.message : String(err);
1586
- cleanupWarnings.push(`extract(${h.name}) failed: ${msg}`);
1587
- }
1588
- }
1589
- if (extractResults.length === 0) {
1590
- // All harnesses threw — clear so the envelope's `extract` field is
1591
- // absent rather than misleadingly empty.
1592
- extractResults = undefined;
1593
- }
1594
- }
1595
- }
1596
- // Backlog drain: gate any pending extract proposals that weren't created in
1597
- // this run (i.e. pre-date the gate or were produced by a run that timed out
1598
- // before the gate fired). Without this, eligible proposals accumulate
1599
- // indefinitely — the fresh-gate only covers the current run's output.
1600
- if (primaryStashDir && !options.dryRun && options.autoAccept !== undefined) {
1601
- const freshIds = new Set((extractResults ?? []).flatMap((r) => r.proposals));
1602
- const backlog = listProposals(primaryStashDir, { status: "pending" }).filter((p) => p.source === "extract" && !freshIds.has(p.id));
1603
- if (backlog.length > 0) {
1604
- const backlogCandidates = backlog.map((p) => ({
1605
- proposalId: p.id,
1606
- confidence: resolveExtractConfidence(p),
1607
- }));
1608
- const backlogGr = await runAutoAcceptGate(backlogCandidates, extractGateCfg);
1609
- gateAutoAcceptedCount += backlogGr.promoted.length;
1610
- gateAutoAcceptFailedCount += backlogGr.failed.length;
1611
- }
1612
- }
1613
- // eligibleCount = raw pre-filter count (before cooldown/signal/cleanup filters).
1614
- // improve_completed.plannedRefs = post-filter count of refs that actually entered the loop.
1615
- appendEvent({
1616
- eventType: "improve_invoked",
1617
- ref: scope.mode === "ref" ? scope.value : `improve:${scope.mode}:${scope.value ?? "all"}`,
1618
- metadata: { scope, dryRun: options.dryRun ?? false, eligibleCount: plannedRefs.length },
1619
- }, eventsCtx);
1620
- // ensureIndex now runs in akmImprove() BEFORE collectEligibleRefs so the
1621
- // eligible-ref query sees a populated `entries` table on the very first
1622
- // pass after a DB version upgrade (#339). Any failure messages from that
1623
- // earlier call were threaded in via args.initialCleanupWarnings.
1624
- let appliedCleanup;
1625
- try {
1626
- appliedCleanup =
1627
- primaryStashDir && memoryCleanupPlan ? applyMemoryCleanup(primaryStashDir, memoryCleanupPlan) : undefined;
1628
- }
1629
- catch (err) {
1630
- cleanupWarnings.push(`applyMemoryCleanup failed: ${err instanceof Error ? err.message : String(err)}`);
1631
- }
1632
- const archivedRefs = appliedCleanup?.archived.map((record) => record.ref) ?? [];
1633
- const removed = new Set(archivedRefs);
1634
- const postCleanupRefs = archivedRefs.length === 0 ? plannedRefs : plannedRefs.filter((r) => !removed.has(r.ref));
1635
- // ── Phase 1: validation pass + schema repair (run on full postCleanupRefs) ──
1636
- // Identifies refs whose on-disk asset has structural problems. Validation
1637
- // failures are excluded from every downstream bucket. Run early so the
1638
- // cooldown partition operates on a clean set.
1639
- if (appliedCleanup) {
1640
- for (const candidate of memoryCleanupPlan?.pruneCandidates ?? []) {
1641
- const archived = appliedCleanup.archived.find((record) => record.ref === candidate.ref);
1642
- if (!archived)
1643
- continue;
1644
- actions.push({
1645
- ref: candidate.ref,
1646
- mode: "memory-prune",
1647
- result: { ok: true, pruned: true, reason: candidate.reason },
1648
- });
1649
- }
1650
- if ((appliedCleanup.archived.length > 0 || appliedCleanup.beliefStateTransitions.length > 0) && primaryStashDir) {
1651
- try {
1652
- await reindexFn({ stashDir: primaryStashDir });
1653
- }
1654
- catch (err) {
1655
- cleanupWarnings.push(`reindex after cleanup failed: ${err instanceof Error ? err.message : String(err)}`);
1656
- }
1657
- }
1658
- }
1659
- const validationFailures = [];
1660
- for (const candidate of postCleanupRefs) {
1661
- try {
1662
- // #591: use the path pre-resolved at planning time when it is still on
1663
- // disk — a serial async DB lookup per ref cost ~500 s on a 9 000-ref
1664
- // stash. Fall back to findAssetFilePath only for refs that bypassed
1665
- // collectEligibleRefs' index scan or whose file moved since planning.
1666
- const filePath = candidate.filePath && fs.existsSync(candidate.filePath)
1667
- ? candidate.filePath
1668
- : await findAssetFilePath(candidate.ref, options.stashDir);
1669
- if (!filePath) {
1670
- validationFailures.push({ ref: candidate.ref, reason: "file not found on disk" });
1671
- continue;
1672
- }
1673
- if (path.extname(filePath).toLowerCase() !== ".md") {
1674
- continue;
1675
- }
1676
- if (isLessonCandidate(candidate.ref)) {
1677
- const raw = fs.readFileSync(filePath, "utf8");
1678
- const fm = parseFrontmatter(raw).data;
1679
- if (!fm.description)
1680
- validationFailures.push({ ref: candidate.ref, reason: "missing description" });
1681
- }
1682
- }
1683
- catch (e) {
1684
- validationFailures.push({ ref: candidate.ref, reason: String(e) });
1685
- }
1686
- }
1687
- if (validationFailures.length > 0) {
1688
- info(`[improve] ${validationFailures.length} assets have validation issues (will attempt schema repair):`);
1689
- for (const f of validationFailures)
1690
- info(` ${f.ref}: ${f.reason}`);
1691
- }
1692
- let schemaRepairs = [];
1693
- let repairedRefs = new Set();
1694
- // Schema repair pass: attempt to fix validation failures via LLM before skipping.
1695
- if (validationFailures.length > 0 && options.repairValidationFailures !== false) {
1696
- const baseConfigForRepair = options.config ?? loadConfig();
1697
- const llmCfg = getDefaultLlmConfig(baseConfigForRepair);
1698
- if (llmCfg) {
1699
- const result = await runSchemaRepairPass(validationFailures, {
1700
- startMs,
1701
- budgetMs,
1702
- llmConfig: llmCfg,
1703
- stashDir: options.stashDir,
1704
- findFilePath: findAssetFilePath,
1705
- isLessonCandidateFn: isLessonCandidate,
1706
- });
1707
- schemaRepairs = result.repairs;
1708
- repairedRefs = result.repairedRefs;
1709
- }
1710
- }
1711
- const validationFailureRefs = new Set(validationFailures.filter((f) => !repairedRefs.has(f.ref)).map((f) => f.ref));
1712
- if (repairedRefs.size > 0) {
1713
- info(`[improve] schema repair fixed ${repairedRefs.size}/${validationFailures.length} validation failures; ${validationFailureRefs.size} remain`);
1714
- }
1715
- // Phase 0.5 — structural hygiene pass
1716
- let lintSummary;
1717
- if (primaryStashDir) {
1718
- try {
1719
- const lintResult = akmLint({ fix: true, dir: primaryStashDir });
1720
- lintSummary = { fixed: lintResult.summary.fixed, flagged: lintResult.summary.flagged };
1721
- }
1722
- catch {
1723
- // lint is best-effort; never block improve
1724
- }
1725
- }
1726
- // O-5 / #378: Per-originator rolling error windows.
1727
- // Reflexion (arXiv:2303.11366) warns that cross-task verbal critique
1728
- // contamination degrades below single-shot baseline. Each originator key
1729
- // ("schema-repair", "reflect") maintains its own rolling window so that
1730
- // schema-repair failures are not injected as avoidPatterns into reflect calls.
1731
- const recentErrors = {};
1732
- const RECENT_ERRORS_CAP = 3;
1733
- // Helper: push an error onto an originator's rolling window.
1734
- function pushRecentError(originator, msg) {
1735
- if (!recentErrors[originator])
1736
- recentErrors[originator] = [];
1737
- recentErrors[originator].push(msg);
1738
- if (recentErrors[originator].length > RECENT_ERRORS_CAP)
1739
- recentErrors[originator].shift();
1740
- }
1741
- // Seed schema-repair originator window from any schema-repair errors.
1742
- for (const repair of schemaRepairs) {
1743
- if (repair.outcome === "error") {
1744
- const errMsg = repair.error ?? `schema repair error: ${repair.reason}`;
1745
- pushRecentError("schema-repair", errMsg);
1746
- }
1747
- }
1748
- // ── Phase 2: signal-delta eligibility sets built EARLY ────────────────────
1749
- // 0.8.0 replaces the flat time-based cooldowns (which produced synchronised
1750
- // waves whenever many refs cooled at the same instant — see the 2026-05-26
1751
- // 54-ref simultaneous-reflect incident) with a *signal-delta* gate:
1752
- //
1753
- // reflectEligible(ref) ≡ latestFeedbackTs(ref) > lastReflectProposalTs(ref)
1754
- // distillEligible(ref) ≡ latestFeedbackTs(ref) > lastDistillProposalTs(ref)
1755
- //
1756
- // i.e. a ref is re-eligible iff new feedback has landed since the last
1757
- // proposal was generated for it. Stable content with no new signal stays
1758
- // out of the queue regardless of clock time; a sudden burst of feedback
1759
- // surfaces only the refs that the burst actually touches.
1760
- //
1761
- // The 30-day FEEDBACK_SIGNAL_WINDOW_DAYS bound still applies — only feedback
1762
- // events newer than that count as "current signal". Ancient one-off
1763
- // negatives don't permanently lock a ref into every run.
1764
- //
1765
- // High-retrieval refs (P0-A path) use a simpler "eligible once" rule: a
1766
- // ref with no feedback signal but retrievalCount ≥ threshold is eligible
1767
- // exactly once (no prior reflect proposal). Subsequent re-eligibility for
1768
- // those refs requires either a new feedback event (then the normal
1769
- // signal-delta gate applies) or human action. Documented limitation: this
1770
- // path does not re-fire on retrieval-count growth alone in 0.8.0; storing
1771
- // the retrieval count in proposal metadata for proper delta-tracking is
1772
- // captured as future work.
1773
- const FEEDBACK_SIGNAL_WINDOW_DAYS = 30;
1774
- const feedbackSinceCutoff = new Date(Date.now() - daysToMs(FEEDBACK_SIGNAL_WINDOW_DAYS)).toISOString();
1775
- // Build the three timestamp maps once across the entire postCleanupRefs set.
1776
- // Per-ref queries would be N+1 and the planner is already the hottest path
1777
- // in `akm improve`.
1778
- const candidateRefs = postCleanupRefs.filter((r) => !validationFailureRefs.has(r.ref)).map((r) => r.ref);
1779
- const latestFeedbackTs = buildLatestFeedbackTsMap(candidateRefs, feedbackSinceCutoff);
1780
- const lastReflectProposalTs = buildLatestProposalTsMap(candidateRefs, "reflect");
1781
- const lastDistillProposalTs = buildLatestProposalTsMap(candidateRefs, "distill");
1782
- // Refs the distill signal-delta gate rejected at planning time. The main
1783
- // loop reads this to skip distill for these refs without re-checking
1784
- // eligibility per iteration.
1785
- const distillCooledRefs = new Set();
1786
- const preCooldownCount = postCleanupRefs.length;
1787
- // ── Phase 3: partition postCleanupRefs by signal-delta eligibility ────────
1788
- // Three buckets (validation failures are excluded entirely):
1789
- // eligibleRefs — reflect signal-delta passes (full reflect+distill
1790
- // loop path; distill guard remains in the loop for
1791
- // refs that fail the distill signal-delta gate).
1792
- // distillOnlyRefs — reflect blocked but distill signal-delta passes
1793
- // AND ref is a distill candidate.
1794
- // fullySkippedCount — neither gate passes → synthetic skip action
1795
- // + improve_skipped event, excluded from sort.
1796
- const eligibleRefs = [];
1797
- const distillOnlyRefs = [];
1798
- let fullySkippedCount = 0;
1799
- // O-2 (#365): explicit --scope <ref> bypasses every gate (user intent wins).
1800
- const scopeRefBypass = scope.mode === "ref";
1801
- for (const r of postCleanupRefs) {
1802
- if (validationFailureRefs.has(r.ref))
1803
- continue;
1804
- if (scopeRefBypass) {
1805
- eligibleRefs.push(r);
1806
- continue;
1807
- }
1808
- const reflectOk = isSignalDeltaEligible(r.ref, latestFeedbackTs, lastReflectProposalTs);
1809
- const distillOk = isSignalDeltaEligible(r.ref, latestFeedbackTs, lastDistillProposalTs);
1810
- const isDistillCandidate = isDistillCandidateRef(r.ref, options.stashDir);
1811
- if (reflectOk) {
1812
- if (!distillOk && isDistillCandidate) {
1813
- // Reflect passes the gate, distill does not — emit the synthetic
1814
- // distill-skipped action and event up-front so the in-loop guard
1815
- // does not have to re-derive eligibility.
1816
- distillCooledRefs.add(r.ref);
1817
- actions.push({ ref: r.ref, mode: "distill-skipped", result: { ok: true, reason: "distill signal-delta" } });
1818
- appendEvent({
1819
- eventType: "improve_skipped",
1820
- ref: r.ref,
1821
- metadata: { reason: "distill_no_new_signal" },
1822
- }, eventsCtx);
1823
- }
1824
- else if (!distillOk) {
1825
- // Not a distill candidate AND distill gate doesn't pass — just mark
1826
- // distillCooled so the loop's distill section is a no-op.
1827
- distillCooledRefs.add(r.ref);
1828
- }
1829
- eligibleRefs.push(r);
1830
- }
1831
- else if (distillOk && isDistillCandidate) {
1832
- // Reflect blocked but distill passes → distill-only bucket.
1833
- distillOnlyRefs.push(r);
1834
- }
1835
- else {
1836
- // Neither gate passes — fully skipped.
1837
- fullySkippedCount++;
1838
- actions.push({
1839
- ref: r.ref,
1840
- mode: "distill-skipped",
1841
- result: { ok: true, reason: "no new signal since last proposal" },
1842
- });
1843
- appendEvent({ eventType: "improve_skipped", ref: r.ref, metadata: { reason: "no_new_signal" } }, eventsCtx);
1844
- }
1845
- }
1846
- // ── Phase 4: signal/feedback/utility/sort on the reduced set ──────────────
1847
- // Everything from here works only on (eligibleRefs ∪ distillOnlyRefs). The
1848
- // fully-skipped bucket has already been routed and emitted; we deliberately
1849
- // avoid spending DB/CPU on refs that cannot enter the loop.
1850
- const processableRefs = [...eligibleRefs, ...distillOnlyRefs];
1851
- // Gap 6: only surface feedback signals from the last 30 days so that
1852
- // ancient one-off feedback events don't permanently lock an asset into
1853
- // every improve run. Assets with only stale signals fall through to the
1854
- // high-retrieval path (P0-A) or are skipped until new signals arrive.
1855
- // (FEEDBACK_SIGNAL_WINDOW_DAYS / feedbackSinceCutoff are already defined in
1856
- // Phase 2 above for the signal-delta gate; we reuse them here.)
1857
- // Pre-compute feedback summary per ref in a single pass so we don't issue
1858
- // two readEvents({type:"feedback", ref}) per asset (one for signal filtering,
1859
- // one for ratio computation).
1860
- const feedbackSummary = new Map();
1861
- for (const candidate of processableRefs) {
1862
- const { events } = readEvents({ type: "feedback", ref: candidate.ref });
1863
- let hasSignal = false;
1864
- let positive = 0;
1865
- let negative = 0;
1866
- for (const e of events) {
1867
- if (!hasSignal &&
1868
- (e.ts ?? "") >= feedbackSinceCutoff &&
1869
- e.metadata !== undefined &&
1870
- (typeof e.metadata.signal === "string" || typeof e.metadata.note === "string")) {
1871
- hasSignal = true;
1872
- }
1873
- if (e.metadata?.signal === "positive")
1874
- positive++;
1875
- else if (e.metadata?.signal === "negative")
1876
- negative++;
1877
- }
1878
- feedbackSummary.set(candidate.ref, { hasSignal, positive, negative });
1879
- }
1880
- const signalFiltered = processableRefs.filter((candidate) => feedbackSummary.get(candidate.ref)?.hasSignal === true);
1881
- // P0-A: also surface zero-feedback assets that have been retrieved many times.
1882
- const RETRIEVAL_COUNT_THRESHOLD = options.minRetrievalCount ?? 5;
1883
- const signalBearingSet = new Set(signalFiltered.map((r) => r.ref));
1884
- const noFeedbackCandidates = processableRefs.filter((r) => !signalBearingSet.has(r.ref));
1885
- let highRetrievalRefs = [];
1886
- let dbForRetrieval;
1887
- try {
1888
- dbForRetrieval = openExistingDatabase();
1889
- const showEventCount = countUsageEventsByType(dbForRetrieval, "show");
1890
- if (showEventCount === 0) {
1891
- warn("Warning: show events not yet in usage_events — zero-feedback fallback will match only search-retrieved assets.");
1892
- }
1893
- const retrievalCounts = getRetrievalCounts(dbForRetrieval, noFeedbackCandidates.map((r) => r.ref));
1894
- // High-retrieval signal-delta (simplified rule, 0.8.0): a no-feedback
1895
- // ref qualifies exactly once — when retrievalCount ≥ threshold AND no
1896
- // prior reflect proposal exists for it. Once a reflect proposal is on
1897
- // record, subsequent re-eligibility requires explicit feedback (which
1898
- // flows through the normal signal-delta gate above). Tracking growth in
1899
- // retrieval count would require persisting the count in proposal
1900
- // metadata; deferred to a follow-up.
1901
- highRetrievalRefs = noFeedbackCandidates.filter((r) => (retrievalCounts.get(r.ref) ?? 0) >= RETRIEVAL_COUNT_THRESHOLD && !lastReflectProposalTs.has(r.ref));
1902
- }
1903
- catch (err) {
1904
- rethrowIfTestIsolationError(err);
1905
- // best-effort: if DB unavailable, highRetrievalRefs stays empty
1906
- }
1907
- finally {
1908
- if (dbForRetrieval)
1909
- closeDatabase(dbForRetrieval);
1910
- }
1911
- // If the user explicitly scoped to a single ref, always act on it —
1912
- // skip the signal/retrieval filter entirely. The filter exists to avoid
1913
- // noisy "improve everything" runs; it should not gate an intentional
1914
- // per-ref invocation where the user's explicit choice is the signal.
1915
- //
1916
- // For type/all scope: only process refs with usage signals (recent feedback
1917
- // or sufficient retrievals). A stash with no signals has 0 eligible refs —
1918
- // usage is the gate. Run `akm feedback <ref> --positive` or retrieve assets
1919
- // to bring them into the eligible pool.
1920
- const signalAndRetrievalRefs = [...signalFiltered, ...highRetrievalRefs];
1921
- const mergedRefs = scope.mode === "ref" ? processableRefs : options.requireFeedbackSignal ? signalFiltered : signalAndRetrievalRefs;
1922
- const utilityMap = buildUtilityMap(mergedRefs);
1923
- // Load feedback ratio per ref from the pre-computed summary (no extra DB pass).
1924
- const feedbackRatios = new Map();
1925
- for (const ref of mergedRefs) {
1926
- const summary = feedbackSummary.get(ref.ref);
1927
- const positive = summary?.positive ?? 0;
1928
- const negative = summary?.negative ?? 0;
1929
- const total = positive + negative;
1930
- // ratio = negative proportion (high = needs more improvement)
1931
- feedbackRatios.set(ref.ref, total > 0 ? negative / total : 0);
1932
- }
1933
- // Sort: combine utility (desc) with feedback negativity (desc) — high-negative assets rank higher
1934
- const sorted = [...mergedRefs].sort((a, b) => {
1935
- const utilA = utilityMap.get(a.ref) ?? 0;
1936
- const utilB = utilityMap.get(b.ref) ?? 0;
1937
- const ratioA = feedbackRatios.get(a.ref) ?? 0;
1938
- const ratioB = feedbackRatios.get(b.ref) ?? 0;
1939
- // Combined score: 70% utility, 30% negative ratio
1940
- const scoreA = utilA * 0.7 + ratioA * 0.3;
1941
- const scoreB = utilB * 0.7 + ratioB * 0.3;
1942
- return scoreB - scoreA;
1943
- });
1944
- // Phase 0: surface coverage gaps from zero-result search queries
1945
- let coverageGaps = [];
1946
- try {
1947
- const dbForGaps = openExistingDatabase();
1948
- try {
1949
- coverageGaps = getZeroResultSearches(dbForGaps);
1950
- }
1951
- finally {
1952
- closeDatabase(dbForGaps);
1953
- }
1954
- }
1955
- catch (err) {
1956
- rethrowIfTestIsolationError(err);
1957
- // best-effort
1958
- }
1959
- // actionableRefs is the post-cooldown, post-validation, post-signal, post-sort
1960
- // set — i.e. the genuinely processable refs in priority order. Note: this is
1961
- // a semantic shift from earlier code where actionableRefs was the pre-cooldown
1962
- // sorted set; the new meaning matches reality and is documented on
1963
- // ImprovePreparationResult.actionableRefs.
1964
- //
1965
- // Final guard: drop any candidate whose backing file is no longer on disk.
1966
- // Phase 1 validation captures missing files at the start of preparation, but
1967
- // the gap between that check and dispatch can be minutes on large stashes —
1968
- // long enough for a checkpoint / git checkout / external cleanup to delete
1969
- // the asset. Empirically (improve-critical-review 2026-05-20) the single
1970
- // biggest reject category was "Asset no longer exists on disk" (604/1407 =
1971
- // 43%), meaning reflect/distill was producing proposals against deleted refs.
1972
- // A cheap existsSync per surviving candidate eliminates that wasted work.
1973
- const assetMissingOnDisk = [];
1974
- const existsCheckedActionable = [];
1975
- for (const candidate of sorted) {
1976
- // #591: prefer the path pre-resolved at planning time (synchronous
1977
- // existsSync) over a serial async DB lookup per ref.
1978
- const filePath = candidate.filePath && fs.existsSync(candidate.filePath)
1979
- ? candidate.filePath
1980
- : await findAssetFilePath(candidate.ref, options.stashDir);
1981
- if (filePath && fs.existsSync(filePath)) {
1982
- existsCheckedActionable.push(candidate);
1983
- }
1984
- else {
1985
- assetMissingOnDisk.push(candidate.ref);
1986
- }
1987
- }
1988
- // #592 audit: one summary event instead of one per missing ref. Normally
1989
- // tiny, but a stash deletion racing the run could make this O(n) sequential
1990
- // state.db writes. `refs` is capped so the metadata row stays bounded.
1991
- if (assetMissingOnDisk.length > 0) {
1992
- appendEvent({
1993
- eventType: "improve_skipped",
1994
- ref: undefined,
1995
- metadata: {
1996
- reason: "asset_missing_on_disk",
1997
- count: assetMissingOnDisk.length,
1998
- refs: assetMissingOnDisk.slice(0, 50),
1999
- },
2000
- }, eventsCtx);
2001
- }
2002
- const actionableRefs = existsCheckedActionable;
2003
- // Re-split actionableRefs (sorted) into reflect-path vs distill-only-path while
2004
- // preserving sort order. distillOnlyRefs participate in the sort so --limit
2005
- // picks them by score, not by arbitrary position.
2006
- const distillOnlyRefSetForSort = new Set(distillOnlyRefs.map((r) => r.ref));
2007
- const reflectAndDistillRefsAfterSort = [];
2008
- const distillOnlyRefsAfterSort = [];
2009
- for (const r of actionableRefs) {
2010
- if (distillOnlyRefSetForSort.has(r.ref)) {
2011
- distillOnlyRefsAfterSort.push(r);
2012
- }
2013
- else {
2014
- reflectAndDistillRefsAfterSort.push(r);
2015
- }
2016
- }
2017
- // ── Phase 5: --limit applies to the post-cooldown actionable set ──────────
2018
- const allLoopRefs = [...reflectAndDistillRefsAfterSort, ...distillOnlyRefsAfterSort];
2019
- const loopRefs = options.limit ? allLoopRefs.slice(0, options.limit) : allLoopRefs;
2020
- // Update the returned distillOnlyRefs to the sorted order so callers see the
2021
- // ranked view (loop stage uses it as a Set so order is irrelevant, but the
2022
- // shape change keeps downstream consumers consistent).
2023
- const distillOnlyRefsResult = distillOnlyRefsAfterSort;
2024
- const totalReflectBlocked = fullySkippedCount + distillOnlyRefs.length;
2025
- if (totalReflectBlocked > 0) {
2026
- info(`[improve] ${totalReflectBlocked} of ${preCooldownCount} indexed refs blocked by reflect signal-delta ` +
2027
- `(${fullySkippedCount} fully skipped, ${distillOnlyRefs.length} routed to distill-only)`);
2028
- }
2029
- if (signalAndRetrievalRefs.length > 0) {
2030
- info(`[improve] ${signalAndRetrievalRefs.length} refs with usage signals (${signalFiltered.length} feedback, ${highRetrievalRefs.length} high-retrieval)`);
2031
- }
2032
- if (validationFailureRefs.size > 0) {
2033
- info(`[improve] ${validationFailureRefs.size} with validation failures excluded`);
2034
- }
2035
- if (assetMissingOnDisk.length > 0) {
2036
- info(`[improve] ${assetMissingOnDisk.length} candidates dropped — file not on disk`);
2037
- }
2038
- const deferredCount = actionableRefs.length - loopRefs.length;
2039
- info(`[improve] ${actionableRefs.length} actionable; ${loopRefs.length} will be processed` +
2040
- (options.limit && deferredCount > 0 ? ` (--limit ${options.limit} applied; ${deferredCount} deferred)` : ""));
2041
- return {
2042
- actions,
2043
- cleanupWarnings,
2044
- appliedCleanup,
2045
- memoryIndexHealth,
2046
- extract: extractResults,
2047
- actionableRefs,
2048
- signalBearingSet,
2049
- validationFailures,
2050
- schemaRepairs,
2051
- lintSummary,
2052
- loopRefs,
2053
- distillCooledRefs,
2054
- distillOnlyRefs: distillOnlyRefsResult,
2055
- coverageGaps,
2056
- recentErrors,
2057
- utilityMap,
2058
- gateAutoAcceptedCount,
2059
- gateAutoAcceptFailedCount,
2060
- consolidation: consolidationPass.consolidation,
2061
- consolidationRan: consolidationPass.consolidationRan,
2062
- };
2063
- }
2064
- async function runImproveLoopStage(args) {
2065
- const { scope, options, primaryStashDir, reflectFn, distillFn, loopRefs, actions, signalBearingSet, distillCooledRefs, distillOnlyRefs, recentErrors, rejectedProposalsByRef, utilityMap, startMs, budgetMs, eventsCtx, improveProfile, } = args;
2066
- // O-1 (#364): compute remaining budget at call time so each sub-call
2067
- // receives only its fair share of the wall-clock budget.
2068
- const remainingBudgetMs = () => Math.max(0, budgetMs - (Date.now() - startMs));
2069
- const RECENT_ERRORS_CAP = 3;
2070
- // R-2 / #389: Self-Consistency multi-sample voting helpers.
2071
- // Wang et al. arXiv:2203.11171 — N=3 samples beat single-shot on reasoning tasks.
2072
- const SC_THRESHOLD = options.selfConsistencyThreshold ?? 0.7;
2073
- const SC_N = Math.min(Math.max(2, options.selfConsistencyN ?? 3), 5);
2074
- /**
2075
- * Compute Jaccard token overlap between two strings.
2076
- * Tokenizes by whitespace; returns 0 when both are empty.
2077
- */
2078
- function jaccardSimilarity(a, b) {
2079
- const tokensA = new Set(a.split(/\s+/).filter(Boolean));
2080
- const tokensB = new Set(b.split(/\s+/).filter(Boolean));
2081
- if (tokensA.size === 0 && tokensB.size === 0)
2082
- return 1;
2083
- let intersection = 0;
2084
- for (const t of tokensA) {
2085
- if (tokensB.has(t))
2086
- intersection++;
2087
- }
2088
- const union = tokensA.size + tokensB.size - intersection;
2089
- return union > 0 ? intersection / union : 0;
2090
- }
2091
- /**
2092
- * Given N reflect results, return the one with the highest average Jaccard
2093
- * similarity to all other successful results (majority-vote winner).
2094
- * Falls back to the first successful result when N < 2.
2095
- */
2096
- function pickMajorityVote(results) {
2097
- const successful = results.filter((r) => r.ok);
2098
- if (successful.length === 0)
2099
- return (results[0] ?? {
2100
- schemaVersion: 1,
2101
- ok: false,
2102
- reason: "non_zero_exit",
2103
- error: "all samples failed",
2104
- exitCode: null,
2105
- });
2106
- if (successful.length === 1)
2107
- return successful[0];
2108
- let bestIdx = 0;
2109
- let bestScore = -1;
2110
- for (let i = 0; i < successful.length; i++) {
2111
- let totalSim = 0;
2112
- for (let j = 0; j < successful.length; j++) {
2113
- if (i === j)
2114
- continue;
2115
- totalSim += jaccardSimilarity(successful[i].proposal.payload.content ?? "", successful[j].proposal.payload.content ?? "");
2116
- }
2117
- const avgSim = totalSim / (successful.length - 1);
2118
- if (avgSim > bestScore) {
2119
- bestScore = avgSim;
2120
- bestIdx = i;
2121
- }
2122
- }
2123
- return successful[bestIdx] ?? successful[0];
2124
- }
2125
- // O-5 / #378: helper to push per-originator errors into the rolling window.
2126
- function pushRecentError(originator, msg) {
2127
- if (!recentErrors[originator])
2128
- recentErrors[originator] = [];
2129
- recentErrors[originator].push(msg);
2130
- if (recentErrors[originator].length > RECENT_ERRORS_CAP)
2131
- recentErrors[originator].shift();
2132
- }
2133
- // Build a Set for O(1) membership test — these refs skip the reflect call (Bug D2).
2134
- const distillOnlyRefSet = new Set(distillOnlyRefs.map((r) => r.ref));
2135
- let completedCount = 0;
2136
- let reflectsWithErrorContext = 0;
2137
- const memoryRefsForInference = new Set();
2138
- // Pre-load all pending proposals once instead of querying per asset in the loop.
2139
- const dedupeStashDirForProposals = primaryStashDir ?? options.stashDir;
2140
- const pendingProposalRefSet = new Set(dedupeStashDirForProposals
2141
- ? listProposals(dedupeStashDirForProposals, { status: "pending" }).map((p) => p.ref)
2142
- : []);
2143
- let gateAutoAcceptedCount = 0;
2144
- let gateAutoAcceptFailedCount = 0;
2145
- const reflectGateCfg = makeGateConfig("reflect", {
2146
- globalThreshold: options.autoAccept,
2147
- dryRun: options.dryRun ?? false,
2148
- stashDir: primaryStashDir,
2149
- config: options.config ?? loadConfig(),
2150
- eventsCtx,
2151
- });
2152
- const distillGateCfg = makeGateConfig("distill", {
2153
- globalThreshold: options.autoAccept,
2154
- dryRun: options.dryRun ?? false,
2155
- stashDir: primaryStashDir,
2156
- config: options.config ?? loadConfig(),
2157
- eventsCtx,
2158
- });
2159
- for (const planned of loopRefs) {
2160
- if (Date.now() - startMs >= budgetMs) {
2161
- const remaining = loopRefs.length - completedCount;
2162
- info(`[improve] budget exhausted after ${Math.round((Date.now() - startMs) / 60000)}min — ${remaining} assets skipped`);
2163
- appendEvent({
2164
- eventType: "improve_skipped",
2165
- ref: planned.ref,
2166
- metadata: {
2167
- reason: "budget_exhausted",
2168
- remaining,
2169
- },
2170
- }, eventsCtx);
2171
- // B11: Emit improve_skipped for all remaining assets that will not be processed.
2172
- for (const remainingRef of loopRefs.slice(completedCount + 1)) {
2173
- appendEvent({
2174
- eventType: "improve_skipped",
2175
- ref: remainingRef.ref,
2176
- metadata: { reason: "budget_exhausted_batch", remaining: loopRefs.length - completedCount - 1 },
2177
- }, eventsCtx);
2178
- }
2179
- actions.push({
2180
- ref: planned.ref,
2181
- mode: "error",
2182
- result: { ok: false, error: "timeout: improve wall-clock budget exhausted" },
2183
- });
2184
- break;
2185
- }
2186
- try {
2187
- // Bug D2: distillOnlyRefs skip the reflect call but still run the distill path.
2188
- // Bug D1: in-loop distill-cooldown check removed — distill-cooled candidates
2189
- // have their synthetic actions emitted in runImprovePreparationStage.
2190
- const isDistillOnly = distillOnlyRefSet.has(planned.ref);
2191
- const parsedPlannedRef = parseAssetRef(planned.ref);
2192
- // B6: derived memories are machine-generated; skip reflect to avoid noisy proposals.
2193
- // shouldDistillMemoryRef already returns false for .derived refs, so the distill
2194
- // path is also a no-op for them — we just avoid unnecessary agent spawns.
2195
- // D2: distillOnlyRefs also skip the reflect call (reflect-cooled, distill path only).
2196
- if (!isDistillOnly && !planned.ref.endsWith(".derived")) {
2197
- // Type guard: skip reflect for unsupported types (script, env, task, etc.)
2198
- // and raw wiki directories, driven by the active improve profile.
2199
- const reflectSkip = shouldSkipRef(planned.ref, "reflect", improveProfile);
2200
- if (reflectSkip.skip) {
2201
- actions.push({
2202
- ref: planned.ref,
2203
- mode: "reflect-skipped",
2204
- result: { ok: true, reason: reflectSkip.reason },
2205
- });
2206
- }
2207
- else {
2208
- // O-5 / #378: only inject reflect-originator errors into the reflect call.
2209
- // Cross-task errors (e.g. schema-repair) must NOT contaminate reflect prompts.
2210
- const reflectErrors = recentErrors.reflect ?? [];
2211
- if (reflectErrors.length > 0)
2212
- reflectsWithErrorContext++;
2213
- // O-1 (#364): pass remaining budget as timeoutMs so the agent spawn is
2214
- // bounded by the wall-clock deadline rather than the default per-profile timeout.
2215
- const reflectBudgetMs = remainingBudgetMs();
2216
- // Wire profile.processes.reflect.{mode, profile, timeoutMs} into the reflect
2217
- // dispatch when present. Falls back to akmReflect's own config-based resolution
2218
- // (profiles.improve.<name>.processes.reflect → defaults.llm) when the profile
2219
- // does not specify.
2220
- const reflectProfileRunner = resolveImproveProcessRunnerFromProfile(improveProfile.processes?.reflect, options.config ?? loadConfig());
2221
- const reflectCallArgs = {
2222
- ref: planned.ref,
2223
- task: options.task,
2224
- ...(options.stashDir ? { stashDir: options.stashDir } : {}),
2225
- ...(reflectErrors.length > 0 ? { avoidPatterns: [...reflectErrors] } : {}),
2226
- agentProcess: options.agentProcess ?? "reflect",
2227
- eventSource: "improve",
2228
- ...(reflectBudgetMs > 0 ? { timeoutMs: reflectBudgetMs } : {}),
2229
- ...(reflectProfileRunner ? { runner: reflectProfileRunner } : {}),
2230
- };
2231
- // R-2 / #389: Self-consistency multi-sample voting for high-utility refs.
2232
- // Self-Consistency arXiv:2203.11171 — N=3 samples beat single-shot quality.
2233
- const refUtility = utilityMap.get(planned.ref) ?? 0;
2234
- const useConsistency = refUtility >= SC_THRESHOLD && SC_N >= 2;
2235
- let reflectResult;
2236
- if (useConsistency) {
2237
- const samples = [];
2238
- for (let s = 0; s < SC_N; s++) {
2239
- if (remainingBudgetMs() <= 0)
2240
- break;
2241
- // draftMode: skip DB write so each sample doesn't create a proposal.
2242
- samples.push(await withLlmStage("reflect", () => reflectFn({ ...reflectCallArgs, draftMode: true })));
2243
- }
2244
- const winner = pickMajorityVote(samples.length > 0
2245
- ? samples
2246
- : [await withLlmStage("reflect", () => reflectFn({ ...reflectCallArgs, draftMode: true }))]);
2247
- // Persist only the majority-vote winner as a single real proposal.
2248
- if (winner.ok && primaryStashDir) {
2249
- const persistResult = createProposal(primaryStashDir, {
2250
- ref: winner.proposal.ref,
2251
- source: "reflect",
2252
- sourceRun: `reflect-sc-${Date.now()}`,
2253
- payload: winner.proposal.payload,
2254
- });
2255
- reflectResult = isProposalSkipped(persistResult)
2256
- ? {
2257
- schemaVersion: 1,
2258
- ok: false,
2259
- reason: "cooldown",
2260
- error: `SC proposal skipped: ${persistResult.message}`,
2261
- ref: winner.ref,
2262
- exitCode: null,
2263
- }
2264
- : { ...winner, proposal: persistResult };
2265
- }
2266
- else {
2267
- reflectResult = winner;
2268
- }
2269
- }
2270
- else {
2271
- reflectResult = await withLlmStage("reflect", () => reflectFn(reflectCallArgs));
2272
- }
2273
- const isCooldown = !reflectResult.ok && reflectResult.reason === "cooldown";
2274
- // Content-policy guard hits (reflect size-rail rejections) are NOT
2275
- // LLM faults — the agent responded fine, the downstream guard
2276
- // blocked the output. Route them to a distinct `reflect-guard-rejected`
2277
- // mode so health metrics can split deterministic guard hits out of
2278
- // true LLM failures. See
2279
- // `/tmp/akm-health-investigations/metrics-taxonomy-review.md` §1a.
2280
- const isGuardReject = !reflectResult.ok && reflectResult.reason === "content_policy_reject";
2281
- // Type-guard rejection (reflect refused a script/env/task ref) is
2282
- // also NOT an LLM failure — the LLM is never invoked. Route to the
2283
- // existing `reflect-skipped` bucket so it does not inflate the
2284
- // failure-rate numerator. ~9% of `reflect-failed` events in the
2285
- // user's stack were this case; see review §1a row "Reflect refused
2286
- // asset type".
2287
- const isTypeRefused = !reflectResult.ok && reflectResult.reason === "unsupported_type";
2288
- // Noise-gate suppression (#580): the candidate edit was an empty
2289
- // diff or a cosmetic-only reformat of the current asset. Like
2290
- // `unsupported_type`, this is a deterministic skip — not an LLM
2291
- // fault — so it routes to the `reflect-skipped` bucket and stays
2292
- // out of recentErrors/avoidPatterns.
2293
- const isNoChange = !reflectResult.ok && reflectResult.reason === "no_change";
2294
- actions.push({
2295
- ref: planned.ref,
2296
- mode: reflectResult.ok
2297
- ? "reflect"
2298
- : isCooldown
2299
- ? "reflect-cooldown"
2300
- : isGuardReject
2301
- ? "reflect-guard-rejected"
2302
- : isTypeRefused || isNoChange
2303
- ? "reflect-skipped"
2304
- : "reflect-failed",
2305
- result: reflectResult,
2306
- });
2307
- // Cooldown skips, guard rejects, type-refused skips, and noise-gate
2308
- // skips are not failures — do not pollute recentErrors with them
2309
- // (those get injected as `avoidPatterns` into the next reflect
2310
- // prompt). Guard rejects ARE worth showing the LLM as a learn-signal
2311
- // so the next iteration sees "your last expansion was too large";
2312
- // type-refused and no-change are deterministic and add no learning
2313
- // signal.
2314
- if (!reflectResult.ok && !isCooldown && !isTypeRefused && !isNoChange) {
2315
- const errMsg = reflectResult.error ?? reflectResult.reason ?? "unknown reflect error";
2316
- pushRecentError("reflect", errMsg);
2317
- }
2318
- // improve_reflect_outcome — per-asset metric for tuning the reflect path.
2319
- appendEvent({
2320
- eventType: "improve_reflect_outcome",
2321
- ref: planned.ref,
2322
- metadata: {
2323
- ok: reflectResult.ok,
2324
- durationMs: reflectResult.ok ? reflectResult.durationMs : undefined,
2325
- agentProfile: reflectResult.ok ? reflectResult.agentProfile : undefined,
2326
- reason: reflectResult.ok ? undefined : reflectResult.reason,
2327
- },
2328
- }, eventsCtx);
2329
- if (reflectResult.ok) {
2330
- const reflectGr = await runAutoAcceptGate([{ proposalId: reflectResult.proposal.id, confidence: reflectResult.proposal.confidence }], reflectGateCfg);
2331
- gateAutoAcceptedCount += reflectGr.promoted.length;
2332
- gateAutoAcceptFailedCount += reflectGr.failed.length;
2333
- }
2334
- } // end else (reflect type/profile check)
2335
- }
2336
- else if (!isDistillOnly && planned.ref.endsWith(".derived")) {
2337
- // B6: .derived refs skip reflect; record synthetic skip action.
2338
- actions.push({
2339
- ref: planned.ref,
2340
- mode: "distill-skipped",
2341
- result: { ok: true, reason: "derived-memory-reflect-skipped" },
2342
- });
2343
- appendEvent({
2344
- eventType: "improve_skipped",
2345
- ref: planned.ref,
2346
- metadata: { reason: "derived_memory_reflect_skipped" },
2347
- }, eventsCtx);
2348
- }
2349
- // isDistillOnly refs: no reflect action emitted — proceed directly to distill path below.
2350
- const hasRecentFeedbackSignal = signalBearingSet.has(planned.ref);
2351
- const explicitRefScope = scope.mode === "ref";
2352
- // Profile gate: apply the full type-filter / raw-wiki / disabled rules to
2353
- // distill so callers who configure `profile.processes.distill.allowedTypes`
2354
- // or land on raw-wiki refs get a recorded skip action instead of silently
2355
- // proceeding.
2356
- const distillSkip = shouldSkipRef(planned.ref, "distill", improveProfile);
2357
- if (distillSkip.skip) {
2358
- actions.push({
2359
- ref: planned.ref,
2360
- mode: "distill-skipped",
2361
- result: { ok: true, reason: distillSkip.reason },
2362
- });
2363
- completedCount++;
2364
- info(`[improve] ${completedCount}/${loopRefs.length} ${planned.ref}`);
2365
- continue;
2366
- }
2367
- // See `isDistillCandidateRef` — excludes `lesson:*` (and anything else in
2368
- // DISTILL_REFUSED_INPUT_TYPES) so distill never gets queued for an input
2369
- // it will refuse.
2370
- const shouldAttemptDistill = isDistillCandidateRef(planned.ref, options.stashDir);
2371
- const skipMemoryDistillForWeakSignal = !isDistillOnly && parsedPlannedRef.type === "memory" && !hasRecentFeedbackSignal && !explicitRefScope;
2372
- // distillCooledRefs guard: pre-filter emitted synthetic actions for distill-candidate
2373
- // refs; non-candidate refs in the set are blocked here.
2374
- // O-2 (#365): bypass the distill cooldown when the user explicitly targeted
2375
- // this ref via --scope — their intent overrides unattended-run policies.
2376
- if (shouldAttemptDistill &&
2377
- !skipMemoryDistillForWeakSignal &&
2378
- (!distillCooledRefs.has(planned.ref) || explicitRefScope)) {
2379
- // TODO(refactor): single call site needs both lesson+knowledge refs for proposal dedup. If a third target ref type is added, extract deriveAllTargetRefs(inputRef): string[].
2380
- const lessonRef = deriveLessonRef(planned.ref);
2381
- const knowledgeRef = deriveKnowledgeRef(planned.ref);
2382
- const dedupeStashDir = primaryStashDir ?? options.stashDir;
2383
- if (dedupeStashDir) {
2384
- // B2: check both lesson ref and knowledge ref since auto-promoted memories
2385
- // create knowledge: proposals, not lesson: proposals.
2386
- const hasExistingPending = pendingProposalRefSet.has(lessonRef) || pendingProposalRefSet.has(knowledgeRef);
2387
- if (hasExistingPending) {
2388
- actions.push({
2389
- ref: planned.ref,
2390
- mode: "distill-skipped",
2391
- result: { ok: true, reason: "pending proposal exists" },
2392
- });
2393
- appendEvent({
2394
- eventType: "improve_skipped",
2395
- ref: planned.ref,
2396
- metadata: { reason: "pending_proposal_exists" },
2397
- }, eventsCtx);
2398
- completedCount++;
2399
- info(`[improve] ${completedCount}/${loopRefs.length} ${planned.ref}`);
2400
- continue;
2401
- }
2402
- // D-2 (#370): reject-aware cooldown for distill. When the reviewer
2403
- // recently rejected a distilled lesson or knowledge proposal for this
2404
- // asset, skip re-distillation for a 1-day grace window. Prevents the
2405
- // same rejected proposal from being regenerated immediately. The
2406
- // window is fixed (the 0.8.0 redesign moved per-ref cooldowns to
2407
- // signal-delta gates and dropped --distill-cooldown-days; a short
2408
- // reject grace is preserved here so a fresh rejection isn't
2409
- // overridden by the same run).
2410
- // References: ExpeL arXiv:2308.10144, STaR arXiv:2203.14465.
2411
- const DISTILL_REJECT_COOLDOWN_MS = daysToMs(1);
2412
- const recentlyRejectedLesson = !explicitRefScope && // O-2: bypass when --scope <ref> is explicit
2413
- (rejectedProposalsByRef.has(lessonRef) || rejectedProposalsByRef.has(knowledgeRef));
2414
- if (recentlyRejectedLesson) {
2415
- const rejectedEntry = rejectedProposalsByRef.get(lessonRef) ?? rejectedProposalsByRef.get(knowledgeRef);
2416
- const rejectedAgeMs = rejectedEntry ? Date.now() - new Date(rejectedEntry.ts).getTime() : 0;
2417
- if (rejectedAgeMs < DISTILL_REJECT_COOLDOWN_MS) {
2418
- actions.push({
2419
- ref: planned.ref,
2420
- mode: "distill-skipped",
2421
- result: { ok: true, reason: "distill reject grace window" },
2422
- });
2423
- appendEvent({
2424
- eventType: "improve_skipped",
2425
- ref: planned.ref,
2426
- metadata: {
2427
- reason: "distill_reject_grace_window",
2428
- },
2429
- }, eventsCtx);
2430
- completedCount++;
2431
- info(`[improve] ${completedCount}/${loopRefs.length} ${planned.ref}`);
2432
- continue;
2433
- }
2434
- }
2435
- }
2436
- const distillResult = await withLlmStage("distill", () => distillFn({
2437
- ref: planned.ref,
2438
- ...(parsedPlannedRef.type === "memory" ? { proposalKind: "auto" } : {}),
2439
- ...(options.stashDir ? { stashDir: options.stashDir } : {}),
2440
- }));
2441
- actions.push({ ref: planned.ref, mode: "distill", result: distillResult });
2442
- if (distillResult.outcome === "queued" && distillResult.proposal) {
2443
- const distillGr = await runAutoAcceptGate([{ proposalId: distillResult.proposal.id, confidence: distillResult.proposal.confidence }], distillGateCfg);
2444
- gateAutoAcceptedCount += distillGr.promoted.length;
2445
- gateAutoAcceptFailedCount += distillGr.failed.length;
2446
- }
2447
- if (parsedPlannedRef.type === "memory") {
2448
- const promotedToKnowledge = distillResult.outcome === "queued" && distillResult.proposalKind === "knowledge";
2449
- if (!promotedToKnowledge)
2450
- memoryRefsForInference.add(planned.ref);
2451
- }
2452
- if (distillResult.outcome === "quality_rejected" && primaryStashDir) {
2453
- const slug = planned.ref
2454
- .replace(/[^a-z0-9]/gi, "-")
2455
- .toLowerCase()
2456
- .slice(0, 60);
2457
- writeEvalCase(primaryStashDir, {
2458
- ref: planned.ref,
2459
- failureReason: distillResult.reason ?? "quality gate rejected",
2460
- assetType: parseAssetRef(planned.ref).type ?? "unknown",
2461
- rejectedAt: Date.now(),
2462
- source: "distill_quality_rejected",
2463
- slug: `${slug}-${Date.now()}`,
2464
- });
2465
- }
2466
- // D6: use pre-loaded map instead of per-iteration DB query
2467
- const rejectedProposalEvent = rejectedProposalsByRef.get(planned.ref);
2468
- if (rejectedProposalEvent && primaryStashDir) {
2469
- const slug = planned.ref
2470
- .replace(/[^a-z0-9]/gi, "-")
2471
- .toLowerCase()
2472
- .slice(0, 60);
2473
- writeEvalCase(primaryStashDir, {
2474
- ref: planned.ref,
2475
- failureReason: rejectedProposalEvent.metadata?.reason ?? "proposal rejected",
2476
- assetType: parseAssetRef(planned.ref).type ?? "unknown",
2477
- rejectedAt: new Date(rejectedProposalEvent.ts).getTime(),
2478
- source: "proposal_rejected",
2479
- slug: `${slug}-rejected`,
2480
- });
2481
- }
2482
- }
2483
- else if (skipMemoryDistillForWeakSignal) {
2484
- actions.push({
2485
- ref: planned.ref,
2486
- mode: "distill-skipped",
2487
- result: { ok: true, reason: "memory requires recent feedback signal" },
2488
- });
2489
- appendEvent({
2490
- eventType: "improve_skipped",
2491
- ref: planned.ref,
2492
- metadata: { reason: "memory_distill_requires_feedback" },
2493
- }, eventsCtx);
2494
- }
2495
- }
2496
- catch (err) {
2497
- // B7: UsageError thrown by akmDistill on validation_failed should be recorded
2498
- // as mode:"distill" with outcome:"validation_failed", NOT as a generic error.
2499
- // The distill_invoked event was already emitted inside akmDistill before the throw.
2500
- if (err instanceof UsageError) {
2501
- actions.push({
2502
- ref: planned.ref,
2503
- mode: "distill",
2504
- result: { ok: false, outcome: "validation_failed", error: err.message },
2505
- });
2506
- }
2507
- else {
2508
- actions.push({
2509
- ref: planned.ref,
2510
- mode: "error",
2511
- result: { ok: false, error: err instanceof Error ? err.message : String(err) },
2512
- });
2513
- }
2514
- }
2515
- completedCount++;
2516
- info(`[improve] ${completedCount}/${loopRefs.length} ${planned.ref}`);
2517
- }
2518
- return { reflectsWithErrorContext, memoryRefsForInference, gateAutoAcceptedCount, gateAutoAcceptFailedCount };
2519
- }
2520
- async function runImprovePostLoopStage(args) {
2521
- const { scope, options, primaryStashDir, actionableRefs, appliedCleanup, cleanupWarnings, memoryRefsForInference, reindexFn, eventsCtx, budgetSignal, improveProfile, consolidationRan, } = args;
2522
- const allWarnings = [...cleanupWarnings, ...(appliedCleanup?.warnings ?? [])];
2523
- info("[improve] post-loop maintenance starting");
2524
- const maintenanceResult = await runImproveMaintenancePasses({
2525
- options,
2526
- primaryStashDir,
2527
- actionableRefs,
2528
- memoryRefsForInference,
2529
- allWarnings,
2530
- reindexFn,
2531
- consolidationRan,
2532
- // O-1 (#364): forward the budget signal to memory inference + graph extraction.
2533
- budgetSignal,
2534
- eventsCtx,
2535
- improveProfile,
2536
- });
2537
- let deadUrls;
2538
- if (scope.mode === "all" && primaryStashDir && actionableRefs.length > 0) {
2539
- try {
2540
- const knowledgeEntries = actionableRefs
2541
- .filter((r) => {
2542
- try {
2543
- return parseAssetRef(r.ref).type === "knowledge";
2544
- }
2545
- catch {
2546
- return false;
2547
- }
2548
- })
2549
- .slice(0, 10)
2550
- .map((r) => ({ ref: r.ref, body: "" }));
2551
- if (knowledgeEntries.length > 0) {
2552
- info(`[improve] checking URLs in ${knowledgeEntries.length} knowledge refs`);
2553
- deadUrls = await checkDeadUrls(primaryStashDir, knowledgeEntries);
2554
- info(`[improve] URL check complete (${deadUrls.length} dead/timeout URLs)`);
2555
- }
2556
- }
2557
- catch {
2558
- // best-effort
2559
- }
2560
- }
2561
- return {
2562
- allWarnings,
2563
- deadUrls,
2564
- ...(maintenanceResult.memoryInference ? { memoryInference: maintenanceResult.memoryInference } : {}),
2565
- ...(maintenanceResult.graphExtraction ? { graphExtraction: maintenanceResult.graphExtraction } : {}),
2566
- ...(maintenanceResult.stalenessDetection ? { stalenessDetection: maintenanceResult.stalenessDetection } : {}),
2567
- ...(maintenanceResult.actions && maintenanceResult.actions.length > 0
2568
- ? { maintenanceActions: maintenanceResult.actions }
2569
- : {}),
2570
- memoryInferenceDurationMs: maintenanceResult.memoryInferenceDurationMs,
2571
- graphExtractionDurationMs: maintenanceResult.graphExtractionDurationMs,
2572
- orphansPurged: maintenanceResult.orphansPurged,
2573
- proposalsExpired: maintenanceResult.proposalsExpired,
2574
- // Consolidation's auto-accept gate counts now accrue in the preparation
2575
- // stage (#551); post-loop no longer runs an auto-accept gate of its own.
2576
- gateAutoAcceptedCount: 0,
2577
- gateAutoAcceptFailedCount: 0,
2578
- };
2579
- }
2580
- // TODO(refactor): mutates the passed-in `allWarnings` array as a hidden side channel. Return warnings in ImproveMaintenanceResult and merge in caller — invasive signature change deferred to next refactor pass.
2581
- // Exported for tests (#584/#585 DB-locking regression coverage); production
2582
- // callers reach it only through akmImprove → runImprovePostLoopStage.
2583
- export async function runImproveMaintenancePasses(args) {
2584
- const { options, primaryStashDir, memoryRefsForInference, allWarnings, reindexFn, consolidationRan, budgetSignal, eventsCtx, improveProfile, } = args;
2585
- if (!primaryStashDir)
2586
- return { memoryInferenceDurationMs: 0, graphExtractionDurationMs: 0 };
2587
- const config = options.config ?? loadConfig();
2588
- const sources = resolveSourceEntries(options.stashDir, config);
2589
- const memoryInferenceFn = options.memoryInferenceFn ?? runMemoryInferencePass;
2590
- const graphExtractionFn = options.graphExtractionFn ?? runGraphExtractionPass;
2591
- const stalenessDetectionFn = options.stalenessDetectionFn ?? runStalenessDetectionPass;
2592
- let db;
2593
- let memoryInference;
2594
- let graphExtraction;
2595
- let stalenessDetection;
2596
- let reindexedAfterInference = false;
2597
- const actions = [];
2598
- let memoryInferenceDurationMs = 0;
2599
- let graphExtractionDurationMs = 0;
2600
- let orphansPurged = 0;
2601
- let proposalsExpired = 0;
2602
- const openIndexDb = () => openDatabase(getDbPath(), config.embedding?.dimension ? { embeddingDim: config.embedding.dimension } : undefined);
2603
- // #584: reindexFn opens its own write handle on the same index.db WAL file.
2604
- // Holding our handle across that call produced SQLITE_BUSY / "database is
2605
- // locked" failures in production, so the handle is closed BEFORE every
2606
- // reindex and reopened after — the fresh handle also sees the post-reindex
2607
- // state that graph extraction and staleness detection below rely on. The
2608
- // reopen runs in `finally` so a failed reindex still leaves a usable handle.
2609
- const reindexWithIndexDbReleased = async (stashDir) => {
2610
- if (db) {
2611
- closeDatabase(db);
2612
- db = undefined;
2613
- }
2614
- try {
2615
- await reindexFn({ stashDir });
2616
- }
2617
- finally {
2618
- db = openIndexDb();
2619
- }
2620
- };
2621
- try {
2622
- db = openIndexDb();
2623
- // Memory inference candidate-discovery (post-Item 9 fix from
2624
- // memory:akm-improve-critical-review-2026-05-20). Previously this pass
2625
- // was gated on memoryRefsForInference.size > 0 AND passed those refs as a
2626
- // candidateRefs filter. But memoryRefsForInference is populated from refs
2627
- // distilled THIS RUN — by the time that happens, those parents are
2628
- // already split (`inferenceProcessed: true`) and `isPendingMemory` excludes
2629
- // them. The genuinely-pending parents in the stash never entered the
2630
- // filter. Result: 0/0/0 for 25 consecutive runs.
2631
- //
2632
- // Fix: always run the pass when the feature is enabled; let the pass's
2633
- // own `collectPendingMemories` + `isPendingMemory` predicate find
2634
- // candidates from the filesystem-of-truth. The this-run set is still
2635
- // logged as a hint but no longer used as a filter.
2636
- const memoryInferenceDisabledByProfile = improveProfile?.processes?.memoryInference?.enabled === false;
2637
- if (memoryInferenceDisabledByProfile) {
2638
- info("[improve] memory inference skipped (disabled by improve profile)");
2639
- }
2640
- else {
2641
- const hintRefs = memoryRefsForInference.size;
2642
- info(hintRefs > 0
2643
- ? `[improve] memory inference starting (${hintRefs} hint refs touched this run; pass discovers all pending)`
2644
- : "[improve] memory inference starting (discovering pending parents)");
2645
- const inferenceStart = Date.now();
2646
- try {
2647
- // O-1 (#364): pass budget signal so a hung inference call is cancelled.
2648
- memoryInference = await withLlmStage("memory-inference", () => memoryInferenceFn({
2649
- config,
2650
- sources,
2651
- signal: budgetSignal,
2652
- db,
2653
- reEnrich: false,
2654
- onProgress: (event) => {
2655
- const current = event.currentRef ? ` ${event.currentRef}` : "";
2656
- info(`[improve] memory inference ${event.processed}/${event.total}${current} (written ${event.writtenFacts}, skipped ${event.skippedNoFacts})`);
2657
- },
2658
- }));
2659
- memoryInferenceDurationMs = Date.now() - inferenceStart;
2660
- actions.push({ ref: "memory:_inference", mode: "memory-inference", result: memoryInference });
2661
- info(`[improve] memory inference complete (${memoryInference.writtenFacts} facts written from ${memoryInference.splitParents} parents)`);
2662
- }
2663
- catch (err) {
2664
- memoryInferenceDurationMs = Date.now() - inferenceStart;
2665
- allWarnings.push(`memory inference failed: ${err instanceof Error ? err.message : String(err)}`);
2666
- }
2667
- }
2668
- if (memoryInference && (memoryInference.splitParents > 0 || memoryInference.writtenFacts > 0)) {
2669
- info("[improve] reindexing after memory inference writes");
2670
- try {
2671
- await reindexWithIndexDbReleased(primaryStashDir);
2672
- reindexedAfterInference = true;
2673
- info("[improve] reindex after memory inference complete");
2674
- }
2675
- catch (err) {
2676
- allWarnings.push(`reindex after memory inference failed: ${err instanceof Error ? err.message : String(err)}`);
2677
- }
2678
- }
2679
- const graphEnabled = isProcessEnabled("index", "graph_extraction", config);
2680
- const graphExtractionDisabledByProfile = improveProfile?.processes?.graphExtraction?.enabled === false;
2681
- const graphExtractionFullScan = improveProfile?.processes?.graphExtraction?.fullScan === true;
2682
- // Build the set of refs actually touched this run.
2683
- const touchedRefs = new Set();
2684
- for (const r of args.actionableRefs)
2685
- touchedRefs.add(r.ref);
2686
- for (const r of memoryRefsForInference)
2687
- touchedRefs.add(r);
2688
- // INVARIANT: graph extraction normally runs only on files touched by
2689
- // actionable refs (candidatePaths). Full-corpus scans are opt-in via
2690
- // profile.processes.graphExtraction.fullScan = true (used by the
2691
- // `graph-refresh` built-in profile and its weekly scheduled task).
2692
- // The empty-Set fallback is intentional when no refs were touched —
2693
- // the extractor's filter rejects every file and returns empty, keeping
2694
- // the pass invoked so the action is recorded and tests stay exercised.
2695
- if (graphExtractionDisabledByProfile) {
2696
- info("[improve] graph extraction skipped (disabled by improve profile)");
2697
- }
2698
- else if (sources.length > 0 && graphEnabled) {
2699
- info(`[improve] graph extraction starting${graphExtractionFullScan ? " (full-corpus scan)" : ""}`);
2700
- const extractionStart = Date.now();
2701
- try {
2702
- // D9: if consolidation ran but memory inference did not reindex, force a reindex
2703
- // so graph extraction sees current DB state after consolidation writes.
2704
- if (consolidationRan && !reindexedAfterInference) {
2705
- info("[improve] reindexing after consolidation (graph extraction needs current state)");
2706
- try {
2707
- await reindexWithIndexDbReleased(primaryStashDir);
2708
- reindexedAfterInference = true;
2709
- info("[improve] reindex after consolidation complete");
2710
- }
2711
- catch (err) {
2712
- allWarnings.push(`reindex after consolidation failed: ${err instanceof Error ? err.message : String(err)}`);
2713
- }
2714
- }
2715
- // #584: no close/reopen needed here — reindexWithIndexDbReleased
2716
- // already swapped in a fresh post-reindex handle.
2717
- // Resolve touched refs to absolute file paths. Skipped for fullScan
2718
- // (candidatePaths stays undefined → extractor processes all files).
2719
- let candidatePaths;
2720
- if (!graphExtractionFullScan) {
2721
- candidatePaths = new Set();
2722
- if (primaryStashDir && touchedRefs.size > 0) {
2723
- const writableDirSet = new Set(getWritableStashDirs(primaryStashDir).map((d) => path.resolve(d)));
2724
- const resolved = await Promise.all([...touchedRefs].map((ref) => findAssetFilePath(ref, primaryStashDir, writableDirSet).catch(() => null)));
2725
- for (const p of resolved) {
2726
- if (typeof p === "string" && p.length > 0)
2727
- candidatePaths.add(p);
2728
- }
2729
- }
2730
- }
2731
- const progressHandler = (event) => {
2732
- const current = event.currentPath ? ` ${path.basename(event.currentPath)}` : "";
2733
- info(`[improve] graph extraction ${event.processed}/${event.total}${current} (extracted ${event.extracted}, entities ${event.totalEntities}, relations ${event.totalRelations})`);
2734
- };
2735
- // O-1 (#364): pass budget signal so a hung graph extraction call is cancelled.
2736
- graphExtraction = await withLlmStage("graph-extraction", () => graphExtractionFn({
2737
- config,
2738
- sources,
2739
- signal: budgetSignal,
2740
- db,
2741
- reEnrich: false,
2742
- onProgress: progressHandler,
2743
- options: { candidatePaths },
2744
- }));
2745
- graphExtractionDurationMs = Date.now() - extractionStart;
2746
- actions.push({ ref: "graph:_artifact", mode: "graph-extraction", result: graphExtraction });
2747
- info(`[improve] graph extraction complete (${graphExtraction.quality.extractedFiles} files, ${graphExtraction.quality.entityCount} entities, ${graphExtraction.quality.relationCount} relations)`);
2748
- }
2749
- catch (err) {
2750
- graphExtractionDurationMs = Date.now() - extractionStart;
2751
- allWarnings.push(`graph extraction failed: ${err instanceof Error ? err.message : String(err)}`);
2752
- }
2753
- }
2754
- else if (sources.length > 0 && !graphEnabled) {
2755
- info("[improve] graph extraction skipped (features.index.graph_extraction is disabled)");
2756
- }
2757
- // Orphan proposal purge — reject pending reflect proposals whose target
2758
- // asset no longer exists on disk. Runs after graph extraction so newly
2759
- // promoted assets from accept flows during this run are already present.
2760
- if (primaryStashDir) {
2761
- try {
2762
- const purgeResult = purgeOrphanProposals(primaryStashDir, sources.map((s) => s.path));
2763
- orphansPurged = purgeResult.rejected;
2764
- if (purgeResult.rejected > 0) {
2765
- info(`[improve] orphan purge: ${purgeResult.rejected}/${purgeResult.checked} orphaned proposals rejected (${purgeResult.durationMs}ms)`);
2766
- }
2767
- appendEvent({
2768
- eventType: "proposal_orphan_purge",
2769
- ref: "proposals:_orphan-purge",
2770
- metadata: {
2771
- checked: purgeResult.checked,
2772
- rejected: purgeResult.rejected,
2773
- durationMs: purgeResult.durationMs,
2774
- byType: purgeResult.byType,
2775
- orphans: purgeResult.orphans.map((o) => o.ref),
2776
- },
2777
- }, eventsCtx);
2778
- }
2779
- catch (err) {
2780
- allWarnings.push(`orphan purge failed: ${err instanceof Error ? err.message : String(err)}`);
2781
- }
2782
- // Phase 6B (Advantage D6b): expire pending proposals that have aged past
2783
- // the retention window. Runs AFTER orphan purge so we never double-archive
2784
- // a proposal that orphan-purge already moved. `expireStaleProposals` emits
2785
- // its own per-proposal `proposal_expired` events; we additionally emit a
2786
- // single roll-up event here for parity with the orphan-purge surface.
2787
- try {
2788
- const expireResult = expireStaleProposals(primaryStashDir, config);
2789
- proposalsExpired = expireResult.expired;
2790
- if (expireResult.expired > 0) {
2791
- info(`[improve] expiration: ${expireResult.expired}/${expireResult.checked} pending proposals expired ` +
2792
- `(retention=${expireResult.retentionDays}d, ${expireResult.durationMs}ms)`);
2793
- }
2794
- appendEvent({
2795
- eventType: "proposal_expiration_pass",
2796
- ref: "proposals:_expiration",
2797
- metadata: {
2798
- checked: expireResult.checked,
2799
- expired: expireResult.expired,
2800
- durationMs: expireResult.durationMs,
2801
- retentionDays: expireResult.retentionDays,
2802
- expiredProposals: expireResult.expiredProposals,
2803
- },
2804
- }, eventsCtx);
2805
- }
2806
- catch (err) {
2807
- allWarnings.push(`proposal expiration failed: ${err instanceof Error ? err.message : String(err)}`);
2808
- }
2809
- }
2810
- // Fix #2 (observability 0.8.0): trim the events table in state.db so it
2811
- // doesn't grow unbounded. `akm health` writes a `health_probe` row on every
2812
- // invocation, and every command surface emits at least one event besides —
2813
- // without this trim, state.db is a permanent append-only log. Config key
2814
- // `improve.eventRetentionDays` (default 90, set 0 to disable) controls the
2815
- // window. The purge runs against state.db (a different SQLite file from
2816
- // the index `db` above).
2817
- {
2818
- const retentionDays = typeof config.improve?.eventRetentionDays === "number" ? config.improve.eventRetentionDays : 90;
2819
- if (retentionDays > 0) {
2820
- // #585: reuse the long-lived eventsCtx.db connection when akmImprove
2821
- // opened one — opening a second state.db write connection while
2822
- // eventsDb is still live made two simultaneous writers contend on the
2823
- // same WAL file ("database is locked"). Only the eventsCtx.dbPath
2824
- // fallback path (state.db failed to open up-front) opens — and then
2825
- // owns and closes — its own handle. C2 still holds: the fallback uses
2826
- // the boundary-pinned path, never a live `process.env` re-read.
2827
- const ownsStateDb = !eventsCtx?.db;
2828
- let stateDb;
2829
- try {
2830
- stateDb = eventsCtx?.db ?? openStateDatabase(eventsCtx?.dbPath);
2831
- const purgedCount = purgeOldEvents(stateDb, retentionDays);
2832
- if (purgedCount > 0) {
2833
- info(`[improve] events purge: ${purgedCount} event(s) older than ${retentionDays}d removed from state.db`);
2834
- }
2835
- appendEvent({
2836
- eventType: "events_purged",
2837
- ref: "events:_purge",
2838
- metadata: { purgedCount, retentionDays },
2839
- }, eventsCtx);
2840
- // improve_runs uses the same retention window as events — both are
2841
- // observability/audit data, both grow append-only, both have a
2842
- // dedicated purge helper. Mirroring the events purge here means a
2843
- // single retention knob (improve.eventRetentionDays) governs both.
2844
- const improveRunsPurged = purgeOldImproveRuns(stateDb, retentionDays);
2845
- if (improveRunsPurged > 0) {
2846
- info(`[improve] improve_runs purge: ${improveRunsPurged} run(s) older than ${retentionDays}d removed from state.db`);
2847
- }
2848
- appendEvent({
2849
- eventType: "improve_runs_purged",
2850
- ref: "improve_runs:_purge",
2851
- metadata: { purgedCount: improveRunsPurged, retentionDays },
2852
- }, eventsCtx);
2853
- }
2854
- catch (err) {
2855
- allWarnings.push(`events purge failed: ${err instanceof Error ? err.message : String(err)}`);
2856
- }
2857
- finally {
2858
- if (ownsStateDb && stateDb) {
2859
- try {
2860
- stateDb.close();
2861
- }
2862
- catch {
2863
- // best-effort
2864
- }
2865
- }
2866
- }
2867
- // task_logs in logs.db (#579) shares the same retention window as
2868
- // events/improve_runs — all three are observability data governed by
2869
- // the single improve.eventRetentionDays knob. Separate try/finally
2870
- // because logs.db is a different file: a locked/missing logs.db must
2871
- // not block the state.db purges above.
2872
- let logsDb;
2873
- try {
2874
- logsDb = openLogsDatabase();
2875
- const taskLogsPurged = purgeOldTaskLogs(logsDb, retentionDays);
2876
- if (taskLogsPurged > 0) {
2877
- info(`[improve] task_logs purge: ${taskLogsPurged} log line(s) older than ${retentionDays}d removed from logs.db`);
2878
- }
2879
- appendEvent({
2880
- eventType: "task_logs_purged",
2881
- ref: "task_logs:_purge",
2882
- metadata: { purgedCount: taskLogsPurged, retentionDays },
2883
- }, eventsCtx);
2884
- }
2885
- catch (err) {
2886
- allWarnings.push(`task_logs purge failed: ${err instanceof Error ? err.message : String(err)}`);
2887
- }
2888
- finally {
2889
- if (logsDb) {
2890
- try {
2891
- logsDb.close();
2892
- }
2893
- catch {
2894
- // best-effort
2895
- }
2896
- }
2897
- }
2898
- }
2899
- }
2900
- // Phase 4A (staleness detection). Activates the `deprecated` belief-state
2901
- // machinery shipped in Phase 1A. Default OFF — gated by
2902
- // `features.index.staleness_detection.enabled`. Runs after orphan purge
2903
- // and before the URL check (which lives in the outer caller).
2904
- if (sources.length > 0) {
2905
- try {
2906
- stalenessDetection = await withLlmStage("staleness-detection", () => stalenessDetectionFn({ config, sources, signal: budgetSignal, db }));
2907
- if (stalenessDetection.considered > 0) {
2908
- info(`[improve] staleness detection complete (considered ${stalenessDetection.considered}, ` +
2909
- `deprecated ${stalenessDetection.deprecated}, confirmed ${stalenessDetection.confirmed}, ` +
2910
- `skipped ${stalenessDetection.skipped}, ${stalenessDetection.durationMs}ms)`);
2911
- }
2912
- for (const w of stalenessDetection.warnings)
2913
- allWarnings.push(`[improve] staleness detection: ${w}`);
2914
- }
2915
- catch (err) {
2916
- allWarnings.push(`staleness detection failed: ${err instanceof Error ? err.message : String(err)}`);
2917
- }
2918
- }
2919
- }
2920
- finally {
2921
- if (db)
2922
- closeDatabase(db);
2923
- }
2924
- return {
2925
- ...(memoryInference ? { memoryInference } : {}),
2926
- ...(graphExtraction ? { graphExtraction } : {}),
2927
- ...(stalenessDetection ? { stalenessDetection } : {}),
2928
- ...(actions.length > 0 ? { actions } : {}),
2929
- memoryInferenceDurationMs,
2930
- graphExtractionDurationMs,
2931
- orphansPurged,
2932
- proposalsExpired,
2933
- };
2934
- }
2935
- function shouldAnalyzeMemoryCleanup(scope, eligibleMemories, primaryStashDir) {
2936
- if (!primaryStashDir || eligibleMemories === 0)
2937
- return false;
2938
- if (scope.mode === "all")
2939
- return true;
2940
- if (scope.mode === "type")
2941
- return scope.value === "memory";
2942
- if (!scope.value)
2943
- return false;
2944
- return parseAssetRef(scope.value).type === "memory";
2945
- }
2946
978
  function shapeMemoryCleanup(plan) {
2947
979
  return {
2948
980
  analyzedDerived: plan.analyzedDerived,
@@ -2953,48 +985,3 @@ function shapeMemoryCleanup(plan) {
2953
985
  ...(plan.relativeDateCandidates.length > 0 ? { relativeDateCandidates: plan.relativeDateCandidates } : {}),
2954
986
  };
2955
987
  }
2956
- function buildUtilityMap(refs) {
2957
- const map = new Map();
2958
- if (refs.length === 0)
2959
- return map;
2960
- const refSet = new Set(refs.map((r) => r.ref));
2961
- let db;
2962
- try {
2963
- db = openExistingDatabase();
2964
- const allDbEntries = getAllEntries(db);
2965
- const idToRef = new Map();
2966
- for (const indexed of allDbEntries) {
2967
- const ref = makeAssetRef(indexed.entry.type, indexed.entry.name);
2968
- if (refSet.has(ref))
2969
- idToRef.set(indexed.id, ref);
2970
- }
2971
- const ids = [...idToRef.keys()];
2972
- if (ids.length > 0) {
2973
- const { global: scores } = getUtilityScoresByIds(db, ids);
2974
- for (const [id, score] of scores) {
2975
- const ref = idToRef.get(id);
2976
- if (ref)
2977
- map.set(ref, score.utility);
2978
- }
2979
- }
2980
- }
2981
- catch (err) {
2982
- rethrowIfTestIsolationError(err);
2983
- // best-effort: if DB unavailable, all utilities default to 0
2984
- }
2985
- finally {
2986
- if (db)
2987
- closeDatabase(db);
2988
- }
2989
- return map;
2990
- }
2991
- async function findAssetFilePath(ref, stashDir, writableDirSet) {
2992
- return resolveAssetPath(ref, {
2993
- stashDir,
2994
- mode: "disk-only",
2995
- writableDirSet,
2996
- directoryIndexNames: ["SKILL.md"],
2997
- preserveDirectNameFallback: true,
2998
- honorOrigin: false,
2999
- });
3000
- }