akm-cli 0.6.1 → 0.7.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 (333) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/{cli.js → src/cli.js} +712 -34
  3. package/dist/{commands → src/commands}/config-cli.js +47 -4
  4. package/dist/src/commands/distill.js +283 -0
  5. package/dist/src/commands/events.js +108 -0
  6. package/dist/src/commands/history.js +191 -0
  7. package/dist/{commands → src/commands}/installed-stashes.js +1 -1
  8. package/dist/src/commands/proposal.js +119 -0
  9. package/dist/src/commands/propose.js +171 -0
  10. package/dist/src/commands/reflect.js +193 -0
  11. package/dist/{commands → src/commands}/registry-search.js +71 -7
  12. package/dist/{commands → src/commands}/remember.js +12 -0
  13. package/dist/{commands → src/commands}/search.js +104 -4
  14. package/dist/{commands → src/commands}/self-update.js +4 -3
  15. package/dist/{commands → src/commands}/show.js +73 -0
  16. package/dist/{commands → src/commands}/source-add.js +5 -1
  17. package/dist/{commands → src/commands}/source-manage.js +7 -1
  18. package/dist/{core → src/core}/asset-ref.js +5 -5
  19. package/dist/{core → src/core}/asset-spec.js +12 -0
  20. package/dist/{core → src/core}/common.js +1 -1
  21. package/dist/{core → src/core}/config.js +203 -121
  22. package/dist/{core → src/core}/errors.js +4 -0
  23. package/dist/src/core/events.js +239 -0
  24. package/dist/src/core/lesson-lint.js +86 -0
  25. package/dist/src/core/proposals.js +406 -0
  26. package/dist/src/core/warn.js +72 -0
  27. package/dist/{core → src/core}/write-source.js +80 -5
  28. package/dist/{indexer → src/indexer}/db-search.js +114 -24
  29. package/dist/{indexer → src/indexer}/db.js +76 -23
  30. package/dist/{indexer → src/indexer}/file-context.js +0 -3
  31. package/dist/src/indexer/graph-boost.js +179 -0
  32. package/dist/src/indexer/graph-extraction.js +212 -0
  33. package/dist/{indexer → src/indexer}/indexer.js +88 -7
  34. package/dist/{indexer → src/indexer}/matchers.js +1 -1
  35. package/dist/src/indexer/memory-inference.js +263 -0
  36. package/dist/{indexer → src/indexer}/metadata.js +111 -3
  37. package/dist/{indexer → src/indexer}/search-source.js +4 -2
  38. package/dist/src/integrations/agent/config.js +292 -0
  39. package/dist/src/integrations/agent/detect.js +94 -0
  40. package/dist/src/integrations/agent/index.js +17 -0
  41. package/dist/src/integrations/agent/profiles.js +65 -0
  42. package/dist/src/integrations/agent/prompts.js +167 -0
  43. package/dist/src/integrations/agent/spawn.js +272 -0
  44. package/dist/{integrations → src/integrations}/github.js +9 -3
  45. package/dist/{integrations → src/integrations}/lockfile.js +0 -26
  46. package/dist/{llm → src/llm}/client.js +33 -2
  47. package/dist/{llm → src/llm}/embedders/remote.js +37 -3
  48. package/dist/src/llm/feature-gate.js +108 -0
  49. package/dist/src/llm/graph-extract.js +107 -0
  50. package/dist/src/llm/index-passes.js +35 -0
  51. package/dist/src/llm/memory-infer.js +86 -0
  52. package/dist/{output → src/output}/cli-hints.js +15 -2
  53. package/dist/{output → src/output}/renderers.js +63 -2
  54. package/dist/src/output/shapes.js +523 -0
  55. package/dist/src/output/text.js +1116 -0
  56. package/dist/{registry → src/registry}/build-index.js +19 -8
  57. package/dist/{registry → src/registry}/factory.js +0 -8
  58. package/dist/{registry → src/registry}/providers/static-index.js +6 -3
  59. package/dist/{registry → src/registry}/resolve.js +68 -2
  60. package/dist/{setup → src/setup}/setup.js +52 -5
  61. package/dist/{sources → src/sources}/providers/git.js +7 -15
  62. package/dist/{wiki → src/wiki}/wiki.js +54 -6
  63. package/dist/{workflows → src/workflows}/runs.js +37 -3
  64. package/dist/tests/add-website-source.test.js +119 -0
  65. package/dist/tests/agent/agent-config-loader.test.js +70 -0
  66. package/dist/tests/agent/agent-config.test.js +221 -0
  67. package/dist/tests/agent/agent-detect.test.js +100 -0
  68. package/dist/tests/agent/agent-spawn.test.js +234 -0
  69. package/dist/tests/agent-output.test.js +186 -0
  70. package/dist/tests/architecture/agent-no-llm-sdk-guard.test.js +103 -0
  71. package/dist/tests/architecture/agent-spawn-seam.test.js +193 -0
  72. package/dist/tests/architecture/llm-stateless-seam.test.js +112 -0
  73. package/dist/tests/asset-ref.test.js +192 -0
  74. package/dist/tests/asset-registry.test.js +103 -0
  75. package/dist/tests/asset-spec.test.js +241 -0
  76. package/dist/tests/bench/attribution.test.js +996 -0
  77. package/dist/tests/bench/cleanup-sigint.test.js +83 -0
  78. package/dist/tests/bench/cleanup.js +234 -0
  79. package/dist/tests/bench/cleanup.test.js +166 -0
  80. package/dist/tests/bench/cli.js +1018 -0
  81. package/dist/tests/bench/cli.test.js +445 -0
  82. package/dist/tests/bench/compare.test.js +556 -0
  83. package/dist/tests/bench/corpus.js +317 -0
  84. package/dist/tests/bench/corpus.test.js +258 -0
  85. package/dist/tests/bench/doctor.js +525 -0
  86. package/dist/tests/bench/driver.js +401 -0
  87. package/dist/tests/bench/driver.test.js +584 -0
  88. package/dist/tests/bench/environment.js +233 -0
  89. package/dist/tests/bench/environment.test.js +199 -0
  90. package/dist/tests/bench/evolve-metrics.js +179 -0
  91. package/dist/tests/bench/evolve-metrics.test.js +187 -0
  92. package/dist/tests/bench/evolve.js +647 -0
  93. package/dist/tests/bench/evolve.test.js +624 -0
  94. package/dist/tests/bench/failure-modes.test.js +349 -0
  95. package/dist/tests/bench/feedback-integrity.test.js +457 -0
  96. package/dist/tests/bench/leakage.test.js +228 -0
  97. package/dist/tests/bench/learning-curve.test.js +134 -0
  98. package/dist/tests/bench/metrics.js +2395 -0
  99. package/dist/tests/bench/metrics.test.js +1150 -0
  100. package/dist/tests/bench/no-os-tmpdir-invariant.test.js +43 -0
  101. package/dist/tests/bench/opencode-config.js +194 -0
  102. package/dist/tests/bench/opencode-config.test.js +370 -0
  103. package/dist/tests/bench/report.js +1885 -0
  104. package/dist/tests/bench/report.test.js +1038 -0
  105. package/dist/tests/bench/run-config.js +355 -0
  106. package/dist/tests/bench/run-config.test.js +298 -0
  107. package/dist/tests/bench/run-curate-test.js +32 -0
  108. package/dist/tests/bench/run-failing-tasks.js +56 -0
  109. package/dist/tests/bench/run-full-bench.js +51 -0
  110. package/dist/tests/bench/run-items36-targeted.js +69 -0
  111. package/dist/tests/bench/run-nano-quick.js +42 -0
  112. package/dist/tests/bench/run-waveg-targeted.js +62 -0
  113. package/dist/tests/bench/runner.js +699 -0
  114. package/dist/tests/bench/runner.test.js +958 -0
  115. package/dist/tests/bench/search-bridge.test.js +331 -0
  116. package/dist/tests/bench/tmp.js +131 -0
  117. package/dist/tests/bench/trajectory.js +116 -0
  118. package/dist/tests/bench/trajectory.test.js +127 -0
  119. package/dist/tests/bench/verifier.js +114 -0
  120. package/dist/tests/bench/verifier.test.js +118 -0
  121. package/dist/tests/bench/workflow-evaluator.js +557 -0
  122. package/dist/tests/bench/workflow-evaluator.test.js +421 -0
  123. package/dist/tests/bench/workflow-spec.js +345 -0
  124. package/dist/tests/bench/workflow-spec.test.js +363 -0
  125. package/dist/tests/bench/workflow-trace.js +472 -0
  126. package/dist/tests/bench/workflow-trace.test.js +254 -0
  127. package/dist/tests/benchmark-search-quality.js +536 -0
  128. package/dist/tests/benchmark-suite.js +1441 -0
  129. package/dist/tests/capture-cli.test.js +112 -0
  130. package/dist/tests/cli-errors.test.js +204 -0
  131. package/dist/tests/commands/events.test.js +370 -0
  132. package/dist/tests/commands/history.test.js +418 -0
  133. package/dist/tests/commands/import.test.js +103 -0
  134. package/dist/tests/commands/proposal-cli.test.js +209 -0
  135. package/dist/tests/commands/reflect-propose-cli.test.js +333 -0
  136. package/dist/tests/commands/remember.test.js +97 -0
  137. package/dist/tests/commands/scope-flags.test.js +300 -0
  138. package/dist/tests/commands/search.test.js +537 -0
  139. package/dist/tests/commands/show-indexer-parity.test.js +117 -0
  140. package/dist/tests/commands/show.test.js +294 -0
  141. package/dist/tests/common.test.js +266 -0
  142. package/dist/tests/completions.test.js +142 -0
  143. package/dist/tests/config-cli.test.js +193 -0
  144. package/dist/tests/config-llm-features.test.js +139 -0
  145. package/dist/tests/config.test.js +569 -0
  146. package/dist/tests/contracts/migration-baseline.test.js +43 -0
  147. package/dist/tests/contracts/reflect-propose-envelope.test.js +139 -0
  148. package/dist/tests/contracts/spec-helpers.js +46 -0
  149. package/dist/tests/contracts/v1-spec-section-11-proposal-queue.test.js +228 -0
  150. package/dist/tests/contracts/v1-spec-section-12-agent-config.test.js +56 -0
  151. package/dist/tests/contracts/v1-spec-section-13-lesson-type.test.js +34 -0
  152. package/dist/tests/contracts/v1-spec-section-14-llm-features.test.js +94 -0
  153. package/dist/tests/contracts/v1-spec-section-4-1-asset-types.test.js +39 -0
  154. package/dist/tests/contracts/v1-spec-section-4-2-quality-rules.test.js +44 -0
  155. package/dist/tests/contracts/v1-spec-section-5-configuration.test.js +47 -0
  156. package/dist/tests/contracts/v1-spec-section-6-orchestration.test.js +40 -0
  157. package/dist/tests/contracts/v1-spec-section-7-module-layout.test.js +58 -0
  158. package/dist/tests/contracts/v1-spec-section-8-extension-points.test.js +34 -0
  159. package/dist/tests/contracts/v1-spec-section-9-4-cli-surface.test.js +75 -0
  160. package/dist/tests/contracts/v1-spec-section-9-7-llm-agent-boundary.test.js +36 -0
  161. package/dist/tests/core/write-source.test.js +366 -0
  162. package/dist/tests/curate-command.test.js +87 -0
  163. package/dist/tests/db-scoring.test.js +201 -0
  164. package/dist/tests/db.test.js +654 -0
  165. package/dist/tests/distill-cli-flag.test.js +208 -0
  166. package/dist/tests/distill.test.js +515 -0
  167. package/dist/tests/docker-install.test.js +120 -0
  168. package/dist/tests/e2e.test.js +1419 -0
  169. package/dist/tests/embedder.test.js +340 -0
  170. package/dist/tests/embedding-model-config.test.js +379 -0
  171. package/dist/tests/feedback-command.test.js +172 -0
  172. package/dist/tests/file-context.test.js +552 -0
  173. package/dist/tests/fixtures/scripts/git/summarize-diff.js +9 -0
  174. package/dist/tests/fixtures/scripts/lint/eslint-check.js +7 -0
  175. package/dist/tests/fixtures/stashes/load.js +166 -0
  176. package/dist/tests/fixtures/stashes/load.test.js +97 -0
  177. package/dist/tests/fixtures/stashes/ranking-baseline/scripts/mem0-search.js +12 -0
  178. package/dist/tests/frontmatter.test.js +190 -0
  179. package/dist/tests/fts-field-weighting.test.js +254 -0
  180. package/dist/tests/fuzzy-search.test.js +230 -0
  181. package/dist/tests/git-provider-clone.test.js +45 -0
  182. package/dist/tests/github.test.js +161 -0
  183. package/dist/tests/graph-boost-ranking.test.js +305 -0
  184. package/dist/tests/graph-extraction.test.js +282 -0
  185. package/dist/tests/helpers/usage-events.js +8 -0
  186. package/dist/tests/index-pass-llm.test.js +161 -0
  187. package/dist/tests/indexer.test.js +570 -0
  188. package/dist/tests/info-command.test.js +166 -0
  189. package/dist/tests/init.test.js +69 -0
  190. package/dist/tests/install-script.test.js +246 -0
  191. package/dist/tests/integration/agent-real-profile.test.js +94 -0
  192. package/dist/tests/issue-36-repro.test.js +304 -0
  193. package/dist/tests/issues-191-194.test.js +160 -0
  194. package/dist/tests/lesson-lint.test.js +111 -0
  195. package/dist/tests/llm-client.test.js +115 -0
  196. package/dist/tests/llm-feature-gate.test.js +151 -0
  197. package/dist/tests/llm.test.js +139 -0
  198. package/dist/tests/lockfile.test.js +216 -0
  199. package/dist/tests/manifest.test.js +205 -0
  200. package/dist/tests/markdown.test.js +126 -0
  201. package/dist/tests/matchers-unit.test.js +189 -0
  202. package/dist/tests/memory-inference.test.js +299 -0
  203. package/dist/tests/merge-scoring.test.js +136 -0
  204. package/dist/tests/metadata.test.js +313 -0
  205. package/dist/tests/migration-help.test.js +89 -0
  206. package/dist/tests/origin-resolve.test.js +124 -0
  207. package/dist/tests/output-baseline.test.js +218 -0
  208. package/dist/tests/output-shapes-unit.test.js +478 -0
  209. package/dist/tests/parallel-search.test.js +272 -0
  210. package/dist/tests/parameter-metadata.test.js +365 -0
  211. package/dist/tests/paths.test.js +177 -0
  212. package/dist/tests/progressive-disclosure.test.js +280 -0
  213. package/dist/tests/proposals.test.js +279 -0
  214. package/dist/tests/proposed-quality.test.js +271 -0
  215. package/dist/tests/provider-registry.test.js +32 -0
  216. package/dist/tests/ranking-regression.test.js +548 -0
  217. package/dist/tests/reflect-propose.test.js +455 -0
  218. package/dist/tests/registry-build-index.test.js +394 -0
  219. package/dist/tests/registry-cli.test.js +290 -0
  220. package/dist/tests/registry-index-v2.test.js +430 -0
  221. package/dist/tests/registry-install.test.js +728 -0
  222. package/dist/tests/registry-providers/parity.test.js +189 -0
  223. package/dist/tests/registry-providers/skills-sh.test.js +309 -0
  224. package/dist/tests/registry-providers/static-index.test.js +238 -0
  225. package/dist/tests/registry-resolve.test.js +126 -0
  226. package/dist/tests/registry-search.test.js +923 -0
  227. package/dist/tests/remember-frontmatter.test.js +378 -0
  228. package/dist/tests/remember-unit.test.js +123 -0
  229. package/dist/tests/ripgrep-install.test.js +251 -0
  230. package/dist/tests/ripgrep-resolve.test.js +108 -0
  231. package/dist/tests/ripgrep.test.js +163 -0
  232. package/dist/tests/save-command.test.js +94 -0
  233. package/dist/tests/save-trust-qa-fixes.test.js +270 -0
  234. package/dist/tests/scoring-pipeline.test.js +648 -0
  235. package/dist/tests/search-include-proposed-cli.test.js +118 -0
  236. package/dist/tests/self-update.test.js +442 -0
  237. package/dist/tests/semantic-search-e2e.test.js +512 -0
  238. package/dist/tests/semantic-status.test.js +471 -0
  239. package/dist/tests/setup-run.integration.js +877 -0
  240. package/dist/tests/setup-wizard.test.js +198 -0
  241. package/dist/tests/setup.test.js +131 -0
  242. package/dist/tests/source-add.test.js +11 -0
  243. package/dist/tests/source-clone.test.js +254 -0
  244. package/dist/tests/source-manage.test.js +366 -0
  245. package/dist/tests/source-providers/filesystem.test.js +82 -0
  246. package/dist/tests/source-providers/git.test.js +252 -0
  247. package/dist/tests/source-providers/website.test.js +128 -0
  248. package/dist/tests/source-qa-fixes.test.js +286 -0
  249. package/dist/tests/source-registry.test.js +350 -0
  250. package/dist/tests/source-resolve.test.js +100 -0
  251. package/dist/tests/source-source.test.js +281 -0
  252. package/dist/tests/source.test.js +533 -0
  253. package/dist/tests/tar-utils-scan.test.js +73 -0
  254. package/dist/tests/toggle-components.test.js +73 -0
  255. package/dist/tests/usage-telemetry.test.js +265 -0
  256. package/dist/tests/utility-scoring.test.js +558 -0
  257. package/dist/tests/vault-load-error.test.js +78 -0
  258. package/dist/tests/vault-qa-fixes.test.js +194 -0
  259. package/dist/tests/vault.test.js +429 -0
  260. package/dist/tests/vector-search.test.js +608 -0
  261. package/dist/tests/walker.test.js +252 -0
  262. package/dist/tests/wave2-cluster-bc.test.js +228 -0
  263. package/dist/tests/wave2-cluster-d.test.js +180 -0
  264. package/dist/tests/wave2-cluster-e.test.js +179 -0
  265. package/dist/tests/wiki-qa-fixes.test.js +270 -0
  266. package/dist/tests/wiki.test.js +529 -0
  267. package/dist/tests/workflow-cli.test.js +271 -0
  268. package/dist/tests/workflow-markdown.test.js +171 -0
  269. package/dist/tests/workflow-path-escape.test.js +132 -0
  270. package/dist/tests/workflow-qa-fixes.test.js +395 -0
  271. package/dist/tests/workflows/indexer-rejection.test.js +213 -0
  272. package/docs/README.md +8 -0
  273. package/docs/migration/release-notes/0.7.0.md +244 -0
  274. package/package.json +2 -2
  275. package/dist/core/warn.js +0 -27
  276. package/dist/output/shapes.js +0 -212
  277. package/dist/output/text.js +0 -520
  278. /package/dist/{commands → src/commands}/completions.js +0 -0
  279. /package/dist/{commands → src/commands}/curate.js +0 -0
  280. /package/dist/{commands → src/commands}/info.js +0 -0
  281. /package/dist/{commands → src/commands}/init.js +0 -0
  282. /package/dist/{commands → src/commands}/install-audit.js +0 -0
  283. /package/dist/{commands → src/commands}/migration-help.js +0 -0
  284. /package/dist/{commands → src/commands}/source-clone.js +0 -0
  285. /package/dist/{commands → src/commands}/vault.js +0 -0
  286. /package/dist/{core → src/core}/asset-registry.js +0 -0
  287. /package/dist/{core → src/core}/frontmatter.js +0 -0
  288. /package/dist/{core → src/core}/markdown.js +0 -0
  289. /package/dist/{core → src/core}/paths.js +0 -0
  290. /package/dist/{indexer → src/indexer}/manifest.js +0 -0
  291. /package/dist/{indexer → src/indexer}/search-fields.js +0 -0
  292. /package/dist/{indexer → src/indexer}/semantic-status.js +0 -0
  293. /package/dist/{indexer → src/indexer}/usage-events.js +0 -0
  294. /package/dist/{indexer → src/indexer}/walker.js +0 -0
  295. /package/dist/{llm → src/llm}/embedder.js +0 -0
  296. /package/dist/{llm → src/llm}/embedders/cache.js +0 -0
  297. /package/dist/{llm → src/llm}/embedders/local.js +0 -0
  298. /package/dist/{llm → src/llm}/embedders/types.js +0 -0
  299. /package/dist/{llm → src/llm}/metadata-enhance.js +0 -0
  300. /package/dist/{output → src/output}/context.js +0 -0
  301. /package/dist/{registry → src/registry}/create-provider-registry.js +0 -0
  302. /package/dist/{registry → src/registry}/origin-resolve.js +0 -0
  303. /package/dist/{registry → src/registry}/providers/index.js +0 -0
  304. /package/dist/{registry → src/registry}/providers/skills-sh.js +0 -0
  305. /package/dist/{registry → src/registry}/providers/types.js +0 -0
  306. /package/dist/{registry → src/registry}/types.js +0 -0
  307. /package/dist/{setup → src/setup}/detect.js +0 -0
  308. /package/dist/{setup → src/setup}/ripgrep-install.js +0 -0
  309. /package/dist/{setup → src/setup}/ripgrep-resolve.js +0 -0
  310. /package/dist/{setup → src/setup}/steps.js +0 -0
  311. /package/dist/{sources → src/sources}/include.js +0 -0
  312. /package/dist/{sources → src/sources}/provider-factory.js +0 -0
  313. /package/dist/{sources → src/sources}/provider.js +0 -0
  314. /package/dist/{sources → src/sources}/providers/filesystem.js +0 -0
  315. /package/dist/{sources → src/sources}/providers/index.js +0 -0
  316. /package/dist/{sources → src/sources}/providers/install-types.js +0 -0
  317. /package/dist/{sources → src/sources}/providers/npm.js +0 -0
  318. /package/dist/{sources → src/sources}/providers/provider-utils.js +0 -0
  319. /package/dist/{sources → src/sources}/providers/sync-from-ref.js +0 -0
  320. /package/dist/{sources → src/sources}/providers/tar-utils.js +0 -0
  321. /package/dist/{sources → src/sources}/providers/website.js +0 -0
  322. /package/dist/{sources → src/sources}/resolve.js +0 -0
  323. /package/dist/{sources → src/sources}/types.js +0 -0
  324. /package/dist/{templates → src/templates}/wiki-templates.js +0 -0
  325. /package/dist/{version.js → src/version.js} +0 -0
  326. /package/dist/{workflows → src/workflows}/authoring.js +0 -0
  327. /package/dist/{workflows → src/workflows}/cli.js +0 -0
  328. /package/dist/{workflows → src/workflows}/db.js +0 -0
  329. /package/dist/{workflows → src/workflows}/document-cache.js +0 -0
  330. /package/dist/{workflows → src/workflows}/parser.js +0 -0
  331. /package/dist/{workflows → src/workflows}/renderer.js +0 -0
  332. /package/dist/{workflows → src/workflows}/schema.js +0 -0
  333. /package/dist/{workflows → src/workflows}/validator.js +0 -0
@@ -0,0 +1,558 @@
1
+ /**
2
+ * Tests for M-2: Utility-Based Re-ranking (MemRL Pattern).
3
+ *
4
+ * Validates utility_scores table creation, upsert/read helpers,
5
+ * utility boost in search scoring, recency decay, cap at 1.5x,
6
+ * recomputeUtilityScores aggregation, and whyMatched reporting.
7
+ */
8
+ import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test";
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { akmSearch } from "../src/commands/search";
13
+ import { saveConfig } from "../src/core/config";
14
+ import { getDbPath } from "../src/core/paths";
15
+ import { closeDatabase, getUtilityScore, openDatabase, upsertUtilityScore } from "../src/indexer/db";
16
+ import { akmIndex, recomputeUtilityScores } from "../src/indexer/indexer";
17
+ import { recordUsageEvent } from "./helpers/usage-events";
18
+ // ── Temp directory tracking ─────────────────────────────────────────────────
19
+ const createdTmpDirs = [];
20
+ function createTmpDir(prefix = "akm-utility-") {
21
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
22
+ createdTmpDirs.push(dir);
23
+ return dir;
24
+ }
25
+ afterAll(() => {
26
+ for (const dir of createdTmpDirs) {
27
+ fs.rmSync(dir, { recursive: true, force: true });
28
+ }
29
+ });
30
+ // ── Helpers ─────────────────────────────────────────────────────────────────
31
+ function writeFile(filePath, content = "") {
32
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
33
+ fs.writeFileSync(filePath, content);
34
+ }
35
+ function tmpStash() {
36
+ const dir = createTmpDir("akm-utility-stash-");
37
+ for (const sub of ["skills", "commands", "agents", "knowledge", "scripts"]) {
38
+ fs.mkdirSync(path.join(dir, sub), { recursive: true });
39
+ }
40
+ return dir;
41
+ }
42
+ async function buildTestIndex(stashDir, files = {}) {
43
+ for (const [relPath, content] of Object.entries(files)) {
44
+ const fullPath = path.join(stashDir, relPath);
45
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
46
+ fs.writeFileSync(fullPath, content);
47
+ }
48
+ process.env.AKM_STASH_DIR = stashDir;
49
+ saveConfig({ semanticSearchMode: "off" });
50
+ await akmIndex({ stashDir, full: true });
51
+ }
52
+ function expectDefined(value) {
53
+ expect(value).toBeDefined();
54
+ if (value === undefined || value === null) {
55
+ throw new Error("Expected value to be defined");
56
+ }
57
+ return value;
58
+ }
59
+ // ── Environment isolation ───────────────────────────────────────────────────
60
+ const originalXdgCacheHome = process.env.XDG_CACHE_HOME;
61
+ const originalXdgConfigHome = process.env.XDG_CONFIG_HOME;
62
+ const originalAkmStashDir = process.env.AKM_STASH_DIR;
63
+ let testCacheDir = "";
64
+ let testConfigDir = "";
65
+ beforeEach(() => {
66
+ testCacheDir = createTmpDir("akm-utility-cache-");
67
+ testConfigDir = createTmpDir("akm-utility-config-");
68
+ process.env.XDG_CACHE_HOME = testCacheDir;
69
+ process.env.XDG_CONFIG_HOME = testConfigDir;
70
+ });
71
+ afterEach(() => {
72
+ if (originalXdgCacheHome === undefined) {
73
+ delete process.env.XDG_CACHE_HOME;
74
+ }
75
+ else {
76
+ process.env.XDG_CACHE_HOME = originalXdgCacheHome;
77
+ }
78
+ if (originalXdgConfigHome === undefined) {
79
+ delete process.env.XDG_CONFIG_HOME;
80
+ }
81
+ else {
82
+ process.env.XDG_CONFIG_HOME = originalXdgConfigHome;
83
+ }
84
+ if (originalAkmStashDir === undefined) {
85
+ delete process.env.AKM_STASH_DIR;
86
+ }
87
+ else {
88
+ process.env.AKM_STASH_DIR = originalAkmStashDir;
89
+ }
90
+ if (testCacheDir) {
91
+ fs.rmSync(testCacheDir, { recursive: true, force: true });
92
+ testCacheDir = "";
93
+ }
94
+ if (testConfigDir) {
95
+ fs.rmSync(testConfigDir, { recursive: true, force: true });
96
+ testConfigDir = "";
97
+ }
98
+ });
99
+ // ── Test 1: utility_scores table is created by ensureSchema ─────────────────
100
+ describe("utility_scores table creation", () => {
101
+ test("ensureSchema creates utility_scores table", () => {
102
+ const dbPath = path.join(createTmpDir("akm-util-db-"), "test.db");
103
+ const db = openDatabase(dbPath);
104
+ try {
105
+ const row = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='utility_scores'").get();
106
+ expect(row).toBeDefined();
107
+ expect(row?.name).toBe("utility_scores");
108
+ }
109
+ finally {
110
+ closeDatabase(db);
111
+ }
112
+ });
113
+ test("utility_scores table has expected columns", () => {
114
+ const dbPath = path.join(createTmpDir("akm-util-db-"), "test.db");
115
+ const db = openDatabase(dbPath);
116
+ try {
117
+ const columns = db.prepare("PRAGMA table_info(utility_scores)").all();
118
+ const columnNames = columns.map((c) => c.name);
119
+ expect(columnNames).toContain("entry_id");
120
+ expect(columnNames).toContain("utility");
121
+ expect(columnNames).toContain("show_count");
122
+ expect(columnNames).toContain("search_count");
123
+ expect(columnNames).toContain("select_rate");
124
+ expect(columnNames).toContain("last_used_at");
125
+ expect(columnNames).toContain("updated_at");
126
+ }
127
+ finally {
128
+ closeDatabase(db);
129
+ }
130
+ });
131
+ });
132
+ // ── Test 2: upsertUtilityScore writes and reads correctly ────────────────────
133
+ describe("upsertUtilityScore / getUtilityScore", () => {
134
+ test("upsertUtilityScore writes and getUtilityScore reads correctly", () => {
135
+ const dbPath = path.join(createTmpDir("akm-util-db-"), "test.db");
136
+ const db = openDatabase(dbPath);
137
+ try {
138
+ // Insert a dummy entry first (utility_scores references entries)
139
+ db.prepare("INSERT INTO entries (entry_key, dir_path, file_path, stash_dir, entry_json, search_text, entry_type) VALUES (?, ?, ?, ?, ?, ?, ?)").run("test:script:foo", "/tmp", "/tmp/foo.sh", "/tmp", '{"name":"foo","type":"script"}', "foo script", "script");
140
+ const entryRow = db.prepare("SELECT id FROM entries WHERE entry_key = ?").get("test:script:foo");
141
+ const entryId = entryRow.id;
142
+ upsertUtilityScore(db, entryId, {
143
+ utility: 0.75,
144
+ showCount: 10,
145
+ searchCount: 20,
146
+ selectRate: 0.5,
147
+ lastUsedAt: "2026-03-17T00:00:00Z",
148
+ });
149
+ const score = getUtilityScore(db, entryId);
150
+ expect(score).toBeDefined();
151
+ expect(score?.utility).toBe(0.75);
152
+ expect(score?.showCount).toBe(10);
153
+ expect(score?.searchCount).toBe(20);
154
+ expect(score?.selectRate).toBe(0.5);
155
+ expect(score?.lastUsedAt).toBe("2026-03-17T00:00:00Z");
156
+ }
157
+ finally {
158
+ closeDatabase(db);
159
+ }
160
+ });
161
+ test("upsertUtilityScore updates existing row", () => {
162
+ const dbPath = path.join(createTmpDir("akm-util-db-"), "test.db");
163
+ const db = openDatabase(dbPath);
164
+ try {
165
+ db.prepare("INSERT INTO entries (entry_key, dir_path, file_path, stash_dir, entry_json, search_text, entry_type) VALUES (?, ?, ?, ?, ?, ?, ?)").run("test:script:bar", "/tmp", "/tmp/bar.sh", "/tmp", '{"name":"bar","type":"script"}', "bar script", "script");
166
+ const entryRow = db.prepare("SELECT id FROM entries WHERE entry_key = ?").get("test:script:bar");
167
+ const entryId = entryRow.id;
168
+ upsertUtilityScore(db, entryId, {
169
+ utility: 0.5,
170
+ showCount: 5,
171
+ searchCount: 10,
172
+ selectRate: 0.5,
173
+ lastUsedAt: "2026-03-15T00:00:00Z",
174
+ });
175
+ upsertUtilityScore(db, entryId, {
176
+ utility: 0.9,
177
+ showCount: 15,
178
+ searchCount: 30,
179
+ selectRate: 0.5,
180
+ lastUsedAt: "2026-03-17T00:00:00Z",
181
+ });
182
+ const score = getUtilityScore(db, entryId);
183
+ expect(score?.utility).toBe(0.9);
184
+ expect(score?.showCount).toBe(15);
185
+ }
186
+ finally {
187
+ closeDatabase(db);
188
+ }
189
+ });
190
+ test("getUtilityScore returns undefined for missing entry", () => {
191
+ const dbPath = path.join(createTmpDir("akm-util-db-"), "test.db");
192
+ const db = openDatabase(dbPath);
193
+ try {
194
+ const score = getUtilityScore(db, 99999);
195
+ expect(score).toBeUndefined();
196
+ }
197
+ finally {
198
+ closeDatabase(db);
199
+ }
200
+ });
201
+ });
202
+ // ── Test 3: Entries with usage data get utility boost in search ───────────────
203
+ describe("Utility boost in search scoring", () => {
204
+ test("entries with usage data get utility boost in search", async () => {
205
+ const stashDir = tmpStash();
206
+ // Create two entries with identical FTS content
207
+ writeFile(path.join(stashDir, "scripts", "boosted-tool", "boosted-tool.sh"), "#!/bin/bash\necho boosted\n");
208
+ writeFile(path.join(stashDir, "scripts", "boosted-tool", ".stash.json"), JSON.stringify({
209
+ entries: [
210
+ {
211
+ name: "boosted-tool",
212
+ type: "script",
213
+ description: "A deployment automation utility for servers",
214
+ filename: "boosted-tool.sh",
215
+ },
216
+ ],
217
+ }));
218
+ writeFile(path.join(stashDir, "scripts", "plain-tool", "plain-tool.sh"), "#!/bin/bash\necho plain\n");
219
+ writeFile(path.join(stashDir, "scripts", "plain-tool", ".stash.json"), JSON.stringify({
220
+ entries: [
221
+ {
222
+ name: "plain-tool",
223
+ type: "script",
224
+ description: "A deployment automation utility for servers",
225
+ filename: "plain-tool.sh",
226
+ },
227
+ ],
228
+ }));
229
+ await buildTestIndex(stashDir, {});
230
+ // Now inject utility score for the boosted entry
231
+ const dbPath = getDbPath();
232
+ const db = openDatabase(dbPath);
233
+ try {
234
+ const boostedEntry = db.prepare("SELECT id FROM entries WHERE entry_key LIKE '%boosted-tool%'").get();
235
+ if (boostedEntry) {
236
+ upsertUtilityScore(db, boostedEntry.id, {
237
+ utility: 0.8,
238
+ showCount: 20,
239
+ searchCount: 25,
240
+ selectRate: 0.8,
241
+ lastUsedAt: new Date().toISOString(),
242
+ });
243
+ }
244
+ }
245
+ finally {
246
+ closeDatabase(db);
247
+ }
248
+ const result = await akmSearch({ query: "deployment automation", source: "local" });
249
+ const localHits = result.hits.filter((h) => h.type !== "registry");
250
+ const boostedHit = localHits.find((h) => h.name === "boosted-tool");
251
+ const plainHit = localHits.find((h) => h.name === "plain-tool");
252
+ const resolvedBoosted = expectDefined(boostedHit);
253
+ const resolvedPlain = expectDefined(plainHit);
254
+ // The boosted entry should rank ahead of the plain one due to utility
255
+ // boost. Per CLAUDE.md / spec §9, displayed scores are clamped to [0,1];
256
+ // both hits may clamp to the ceiling on a strong-match query, so the
257
+ // observable contract is rank order, not raw score magnitude. The
258
+ // boosted score must still be at least as high as the plain one.
259
+ const boostedIdx = localHits.indexOf(resolvedBoosted);
260
+ const plainIdx = localHits.indexOf(resolvedPlain);
261
+ expect(boostedIdx).toBeLessThan(plainIdx);
262
+ expect(resolvedBoosted.score ?? 0).toBeGreaterThanOrEqual(resolvedPlain.score ?? 0);
263
+ });
264
+ });
265
+ // ── Test 4: Entries without usage data get no utility boost ──────────────────
266
+ describe("No utility boost for entries without usage data", () => {
267
+ test("entries without usage data get no utility boost (score unchanged)", async () => {
268
+ const stashDir = tmpStash();
269
+ writeFile(path.join(stashDir, "scripts", "no-usage", "no-usage.sh"), "#!/bin/bash\necho no usage\n");
270
+ writeFile(path.join(stashDir, "scripts", "no-usage", ".stash.json"), JSON.stringify({
271
+ entries: [
272
+ {
273
+ name: "no-usage",
274
+ type: "script",
275
+ description: "A simple test tool with no usage history",
276
+ filename: "no-usage.sh",
277
+ },
278
+ ],
279
+ }));
280
+ await buildTestIndex(stashDir, {});
281
+ const result = await akmSearch({ query: "simple test tool", source: "local" });
282
+ const localHits = result.hits.filter((h) => h.type !== "registry");
283
+ const hit = localHits.find((h) => h.name === "no-usage");
284
+ const resolved = expectDefined(hit);
285
+ // No utility data means no utilityBoost in whyMatched
286
+ expect(resolved.whyMatched).toBeDefined();
287
+ expect(resolved.whyMatched).not.toContain("usage history boost");
288
+ });
289
+ });
290
+ // ── Test 5: Utility boost is capped at 1.5x ─────────────────────────────────
291
+ describe("Utility boost cap", () => {
292
+ test("utility boost is capped at 1.5x", async () => {
293
+ const stashDir = tmpStash();
294
+ writeFile(path.join(stashDir, "scripts", "capped-a", "capped-a.sh"), "#!/bin/bash\necho capped\n");
295
+ writeFile(path.join(stashDir, "scripts", "capped-a", ".stash.json"), JSON.stringify({
296
+ entries: [
297
+ {
298
+ name: "capped-a",
299
+ type: "script",
300
+ description: "A network monitoring tool for production",
301
+ filename: "capped-a.sh",
302
+ },
303
+ ],
304
+ }));
305
+ writeFile(path.join(stashDir, "scripts", "capped-b", "capped-b.sh"), "#!/bin/bash\necho baseline\n");
306
+ writeFile(path.join(stashDir, "scripts", "capped-b", ".stash.json"), JSON.stringify({
307
+ entries: [
308
+ {
309
+ name: "capped-b",
310
+ type: "script",
311
+ description: "A network monitoring tool for production",
312
+ filename: "capped-b.sh",
313
+ },
314
+ ],
315
+ }));
316
+ await buildTestIndex(stashDir, {});
317
+ // Inject an extremely high utility score for capped-a
318
+ const dbPath = getDbPath();
319
+ const db = openDatabase(dbPath);
320
+ try {
321
+ const cappedEntry = db.prepare("SELECT id FROM entries WHERE entry_key LIKE '%capped-a%'").get();
322
+ if (cappedEntry) {
323
+ upsertUtilityScore(db, cappedEntry.id, {
324
+ utility: 10.0, // Extremely high utility
325
+ showCount: 1000,
326
+ searchCount: 1000,
327
+ selectRate: 1.0,
328
+ lastUsedAt: new Date().toISOString(),
329
+ });
330
+ }
331
+ }
332
+ finally {
333
+ closeDatabase(db);
334
+ }
335
+ const result = await akmSearch({ query: "network monitoring", source: "local" });
336
+ const localHits = result.hits.filter((h) => h.type !== "registry");
337
+ const cappedHit = localHits.find((h) => h.name === "capped-a");
338
+ const baselineHit = localHits.find((h) => h.name === "capped-b");
339
+ const resolvedCapped = expectDefined(cappedHit);
340
+ const resolvedBaseline = expectDefined(baselineHit);
341
+ // The ratio between boosted and baseline should be at most 1.5x
342
+ // (the cap). Allow a tiny tolerance for floating point + other small boosts.
343
+ const ratio = expectDefined(resolvedCapped.score) / expectDefined(resolvedBaseline.score);
344
+ expect(ratio).toBeLessThanOrEqual(1.55); // small tolerance for name boost differences
345
+ });
346
+ });
347
+ // ── Test 6: Recency decay reduces boost for old usage ────────────────────────
348
+ describe("Recency decay on utility boost", () => {
349
+ test("recent usage produces higher boost than old usage", async () => {
350
+ const stashDir = tmpStash();
351
+ writeFile(path.join(stashDir, "scripts", "recent-use", "recent-use.sh"), "#!/bin/bash\necho recent\n");
352
+ writeFile(path.join(stashDir, "scripts", "recent-use", ".stash.json"), JSON.stringify({
353
+ entries: [
354
+ {
355
+ name: "recent-use",
356
+ type: "script",
357
+ description: "A data processing pipeline tool for analytics",
358
+ filename: "recent-use.sh",
359
+ },
360
+ ],
361
+ }));
362
+ writeFile(path.join(stashDir, "scripts", "old-use", "old-use.sh"), "#!/bin/bash\necho old\n");
363
+ writeFile(path.join(stashDir, "scripts", "old-use", ".stash.json"), JSON.stringify({
364
+ entries: [
365
+ {
366
+ name: "old-use",
367
+ type: "script",
368
+ description: "A data processing pipeline tool for analytics",
369
+ filename: "old-use.sh",
370
+ },
371
+ ],
372
+ }));
373
+ await buildTestIndex(stashDir, {});
374
+ const dbPath = getDbPath();
375
+ const db = openDatabase(dbPath);
376
+ try {
377
+ const recentEntry = db.prepare("SELECT id FROM entries WHERE entry_key LIKE '%recent-use%'").get();
378
+ const oldEntry = db.prepare("SELECT id FROM entries WHERE entry_key LIKE '%old-use%'").get();
379
+ if (recentEntry) {
380
+ upsertUtilityScore(db, recentEntry.id, {
381
+ utility: 0.8,
382
+ showCount: 20,
383
+ searchCount: 25,
384
+ selectRate: 0.8,
385
+ lastUsedAt: new Date().toISOString(), // Just now
386
+ });
387
+ }
388
+ if (oldEntry) {
389
+ // Same utility score but last used 90 days ago
390
+ const oldDate = new Date();
391
+ oldDate.setDate(oldDate.getDate() - 90);
392
+ upsertUtilityScore(db, oldEntry.id, {
393
+ utility: 0.8,
394
+ showCount: 20,
395
+ searchCount: 25,
396
+ selectRate: 0.8,
397
+ lastUsedAt: oldDate.toISOString(),
398
+ });
399
+ }
400
+ }
401
+ finally {
402
+ closeDatabase(db);
403
+ }
404
+ const result = await akmSearch({ query: "data processing pipeline", source: "local" });
405
+ const localHits = result.hits.filter((h) => h.type !== "registry");
406
+ const recentHit = localHits.find((h) => h.name === "recent-use");
407
+ const oldHit = localHits.find((h) => h.name === "old-use");
408
+ const resolvedRecent = expectDefined(recentHit);
409
+ const resolvedOld = expectDefined(oldHit);
410
+ // Recent usage should rank ahead of old usage. Per CLAUDE.md / spec §9
411
+ // the displayed score is clamped to [0,1]; on a strong-match query both
412
+ // hits may clamp to the ceiling, so rank ordering is the observable
413
+ // contract for the recency signal.
414
+ const recentIdx = localHits.indexOf(resolvedRecent);
415
+ const oldIdx = localHits.indexOf(resolvedOld);
416
+ expect(recentIdx).toBeLessThan(oldIdx);
417
+ expect(resolvedRecent.score ?? 0).toBeGreaterThanOrEqual(resolvedOld.score ?? 0);
418
+ });
419
+ });
420
+ // ── Test 7: recomputeUtilityScores aggregates from usage_events ──────────────
421
+ describe("recomputeUtilityScores", () => {
422
+ test("aggregates search and show events from usage_events", () => {
423
+ const dbPath = path.join(createTmpDir("akm-util-db-"), "test.db");
424
+ const db = openDatabase(dbPath);
425
+ try {
426
+ // Insert a test entry
427
+ db.prepare("INSERT INTO entries (entry_key, dir_path, file_path, stash_dir, entry_json, search_text, entry_type) VALUES (?, ?, ?, ?, ?, ?, ?)").run("test:script:recompute-test", "/tmp", "/tmp/recompute.sh", "/tmp", '{"name":"recompute-test","type":"script"}', "recompute test script", "script");
428
+ const entryRow = db.prepare("SELECT id FROM entries WHERE entry_key = ?").get("test:script:recompute-test");
429
+ const entryId = entryRow.id;
430
+ // Record usage events: 5 searches that returned this entry, 3 shows
431
+ for (let i = 0; i < 5; i++) {
432
+ recordUsageEvent(db, {
433
+ eventType: "search",
434
+ entryId,
435
+ timestamp: new Date().toISOString(),
436
+ });
437
+ }
438
+ for (let i = 0; i < 3; i++) {
439
+ recordUsageEvent(db, {
440
+ eventType: "show",
441
+ entryId,
442
+ timestamp: new Date().toISOString(),
443
+ });
444
+ }
445
+ // Recompute utility scores
446
+ recomputeUtilityScores(db);
447
+ // Check that utility scores were computed
448
+ const score = getUtilityScore(db, entryId);
449
+ expect(score).toBeDefined();
450
+ expect(score?.searchCount).toBe(5);
451
+ expect(score?.showCount).toBe(3);
452
+ expect(score?.selectRate).toBeCloseTo(3 / 5, 2);
453
+ expect(score?.utility).toBeGreaterThan(0);
454
+ }
455
+ finally {
456
+ closeDatabase(db);
457
+ }
458
+ });
459
+ test("entries with no usage events get zero utility", () => {
460
+ const dbPath = path.join(createTmpDir("akm-util-db-"), "test.db");
461
+ const db = openDatabase(dbPath);
462
+ try {
463
+ // Insert a test entry with no usage events
464
+ db.prepare("INSERT INTO entries (entry_key, dir_path, file_path, stash_dir, entry_json, search_text, entry_type) VALUES (?, ?, ?, ?, ?, ?, ?)").run("test:script:no-usage-test", "/tmp", "/tmp/no-usage.sh", "/tmp", '{"name":"no-usage-test","type":"script"}', "no usage test script", "script");
465
+ recomputeUtilityScores(db);
466
+ const entryRow = db.prepare("SELECT id FROM entries WHERE entry_key = ?").get("test:script:no-usage-test");
467
+ const score = getUtilityScore(db, entryRow.id);
468
+ // Either undefined or zero utility
469
+ if (score) {
470
+ expect(score.utility).toBe(0);
471
+ }
472
+ }
473
+ finally {
474
+ closeDatabase(db);
475
+ }
476
+ });
477
+ });
478
+ // ── Test 8: whyMatched includes usage history boost when applicable ──────────
479
+ describe("whyMatched includes usage history boost", () => {
480
+ test("whyMatched includes usage history boost when utility > 0", async () => {
481
+ const stashDir = tmpStash();
482
+ writeFile(path.join(stashDir, "scripts", "why-util", "why-util.sh"), "#!/bin/bash\necho why utility\n");
483
+ writeFile(path.join(stashDir, "scripts", "why-util", ".stash.json"), JSON.stringify({
484
+ entries: [
485
+ {
486
+ name: "why-util",
487
+ type: "script",
488
+ description: "A logging infrastructure tool for debugging",
489
+ filename: "why-util.sh",
490
+ },
491
+ ],
492
+ }));
493
+ await buildTestIndex(stashDir, {});
494
+ // Inject utility score
495
+ const dbPath = getDbPath();
496
+ const db = openDatabase(dbPath);
497
+ try {
498
+ const entry = db.prepare("SELECT id FROM entries WHERE entry_key LIKE '%why-util%'").get();
499
+ if (entry) {
500
+ upsertUtilityScore(db, entry.id, {
501
+ utility: 0.6,
502
+ showCount: 10,
503
+ searchCount: 15,
504
+ selectRate: 0.67,
505
+ lastUsedAt: new Date().toISOString(),
506
+ });
507
+ }
508
+ }
509
+ finally {
510
+ closeDatabase(db);
511
+ }
512
+ const result = await akmSearch({ query: "logging infrastructure", source: "local" });
513
+ const localHits = result.hits.filter((h) => h.type !== "registry");
514
+ const hit = localHits.find((h) => h.name === "why-util");
515
+ const resolved = expectDefined(hit);
516
+ expect(resolved.whyMatched).toBeDefined();
517
+ expect(resolved.whyMatched).toContain("usage history boost");
518
+ });
519
+ });
520
+ // ── Test 9: Production path end-to-end ───────────────────────────────────────
521
+ describe("Production path end-to-end", () => {
522
+ test("index → search → usage_events have entry_id → recompute populates utility_scores", async () => {
523
+ const stashDir = tmpStash();
524
+ writeFile(path.join(stashDir, "scripts", "e2e-tool", "e2e-tool.sh"), "#!/bin/bash\necho e2e\n");
525
+ writeFile(path.join(stashDir, "scripts", "e2e-tool", ".stash.json"), JSON.stringify({
526
+ entries: [
527
+ {
528
+ name: "e2e-tool",
529
+ type: "script",
530
+ description: "An end-to-end test tool for production validation",
531
+ filename: "e2e-tool.sh",
532
+ },
533
+ ],
534
+ }));
535
+ await buildTestIndex(stashDir, {});
536
+ // Search to trigger usage event logging
537
+ const result = await akmSearch({ query: "end-to-end test", source: "local" });
538
+ const localHits = result.hits.filter((h) => h.type !== "registry");
539
+ expect(localHits.length).toBeGreaterThan(0);
540
+ // Verify usage_events have entry_id
541
+ const dbPath = getDbPath();
542
+ const db = openDatabase(dbPath);
543
+ try {
544
+ const events = db
545
+ .prepare("SELECT entry_id FROM usage_events WHERE event_type = 'search' AND entry_id IS NOT NULL")
546
+ .all();
547
+ expect(events.length).toBeGreaterThan(0);
548
+ // Recompute utility scores
549
+ recomputeUtilityScores(db);
550
+ // Verify utility_scores populated
551
+ const scores = db.prepare("SELECT entry_id, utility FROM utility_scores").all();
552
+ expect(scores.length).toBeGreaterThan(0);
553
+ }
554
+ finally {
555
+ closeDatabase(db);
556
+ }
557
+ });
558
+ });
@@ -0,0 +1,78 @@
1
+ import { afterAll, describe, expect, test } from "bun:test";
2
+ import { spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ // ── Helpers ──────────────────────────────────────────────────────────────────
7
+ const tempDirs = [];
8
+ function makeTempDir(prefix = "akm-vault-load-") {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
10
+ tempDirs.push(dir);
11
+ return dir;
12
+ }
13
+ afterAll(() => {
14
+ for (const dir of tempDirs) {
15
+ fs.rmSync(dir, { recursive: true, force: true });
16
+ }
17
+ });
18
+ const xdgCache = makeTempDir("akm-vle-cache-");
19
+ const xdgConfig = makeTempDir("akm-vle-config-");
20
+ const isolatedHome = makeTempDir("akm-vle-home-");
21
+ const repoRoot = path.resolve(import.meta.dir, "..");
22
+ const cliPath = path.join(repoRoot, "src", "cli.ts");
23
+ function runCli(args, extraEnv = {}) {
24
+ const result = spawnSync("bun", [cliPath, ...args], {
25
+ encoding: "utf8",
26
+ timeout: 15_000,
27
+ cwd: repoRoot,
28
+ env: {
29
+ ...process.env,
30
+ HOME: isolatedHome,
31
+ XDG_CACHE_HOME: xdgCache,
32
+ XDG_CONFIG_HOME: xdgConfig,
33
+ AKM_STASH_DIR: undefined,
34
+ ...extraEnv,
35
+ },
36
+ });
37
+ return {
38
+ stdout: result.stdout ?? "",
39
+ stderr: result.stderr ?? "",
40
+ status: result.status ?? 1,
41
+ };
42
+ }
43
+ // ── Tests ─────────────────────────────────────────────────────────────────────
44
+ describe("vault load: error envelope", () => {
45
+ test("returns {ok:false, error} JSON on stderr and exits 1 when vault does not exist", () => {
46
+ const stashDir = makeTempDir("akm-vle-stash-");
47
+ // Create the vaults sub-directory so akm resolves paths but the specific
48
+ // vault file is absent.
49
+ fs.mkdirSync(path.join(stashDir, "vaults"), { recursive: true });
50
+ const { stdout, stderr, status } = runCli(["vault", "load", "vault:does-not-exist"], {
51
+ AKM_STASH_DIR: stashDir,
52
+ });
53
+ // Must exit with code 1 (NotFoundError → EXIT_GENERAL).
54
+ expect(status).toBe(1);
55
+ // The JSON error envelope must appear on stderr (runWithJsonErrors writes
56
+ // to console.error).
57
+ const parsed = JSON.parse(stderr.trim());
58
+ expect(parsed.ok).toBe(false);
59
+ expect(typeof parsed.error).toBe("string");
60
+ expect(parsed.error).toContain("Vault not found");
61
+ // stdout must be empty — no shell snippet should leak on error.
62
+ expect(stdout.trim()).toBe("");
63
+ });
64
+ test("emits a shell snippet on stdout (not JSON) when the vault exists", () => {
65
+ const stashDir = makeTempDir("akm-vle-stash-ok-");
66
+ fs.mkdirSync(path.join(stashDir, "vaults"), { recursive: true });
67
+ fs.writeFileSync(path.join(stashDir, "vaults", "myvault.env"), "FOO=bar\n", "utf8");
68
+ const { stdout, stderr, status } = runCli(["vault", "load", "vault:myvault"], {
69
+ AKM_STASH_DIR: stashDir,
70
+ });
71
+ // Success path: exit 0 and a sourcing shell snippet on stdout.
72
+ expect(status).toBe(0);
73
+ expect(stdout).toContain(". ");
74
+ expect(stdout).toContain("rm -f");
75
+ // No error envelope on stderr.
76
+ expect(stderr.trim()).toBe("");
77
+ });
78
+ });