akm-cli 0.9.0-beta.6 → 0.9.0-rc.0

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