akm-cli 0.7.0 → 0.7.2

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 (332) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/{src/cli.js → cli.js} +22 -8
  3. package/dist/{src/commands → commands}/installed-stashes.js +1 -1
  4. package/dist/{src/commands → commands}/source-add.js +1 -1
  5. package/dist/{src/core → core}/common.js +16 -1
  6. package/dist/{src/core → core}/config.js +5 -2
  7. package/dist/{src/indexer → indexer}/db-search.js +16 -1
  8. package/dist/{src/indexer → indexer}/graph-extraction.js +5 -3
  9. package/dist/{src/indexer → indexer}/indexer.js +27 -11
  10. package/dist/{src/indexer → indexer}/memory-inference.js +47 -58
  11. package/dist/{src/indexer → indexer}/search-source.js +1 -1
  12. package/dist/{src/llm → llm}/client.js +61 -1
  13. package/dist/{src/llm → llm}/embedder.js +8 -5
  14. package/dist/{src/llm → llm}/embedders/local.js +8 -2
  15. package/dist/{src/llm → llm}/embedders/remote.js +4 -2
  16. package/dist/{src/llm → llm}/graph-extract.js +4 -4
  17. package/dist/llm/memory-infer.js +114 -0
  18. package/dist/{src/llm → llm}/metadata-enhance.js +2 -2
  19. package/dist/{src/output → output}/cli-hints.js +2 -0
  20. package/dist/{src/setup → setup}/setup.js +30 -20
  21. package/dist/sources/providers/website.js +27 -0
  22. package/dist/{src/sources/providers/website.js → sources/website-ingest.js} +38 -51
  23. package/docs/README.md +7 -0
  24. package/docs/migration/release-notes/0.7.0.md +14 -0
  25. package/package.json +11 -8
  26. package/dist/src/llm/memory-infer.js +0 -86
  27. package/dist/tests/add-website-source.test.js +0 -119
  28. package/dist/tests/agent/agent-config-loader.test.js +0 -70
  29. package/dist/tests/agent/agent-config.test.js +0 -221
  30. package/dist/tests/agent/agent-detect.test.js +0 -100
  31. package/dist/tests/agent/agent-spawn.test.js +0 -234
  32. package/dist/tests/agent-output.test.js +0 -186
  33. package/dist/tests/architecture/agent-no-llm-sdk-guard.test.js +0 -103
  34. package/dist/tests/architecture/agent-spawn-seam.test.js +0 -193
  35. package/dist/tests/architecture/llm-stateless-seam.test.js +0 -112
  36. package/dist/tests/asset-ref.test.js +0 -192
  37. package/dist/tests/asset-registry.test.js +0 -103
  38. package/dist/tests/asset-spec.test.js +0 -241
  39. package/dist/tests/bench/attribution.test.js +0 -996
  40. package/dist/tests/bench/cleanup-sigint.test.js +0 -83
  41. package/dist/tests/bench/cleanup.js +0 -234
  42. package/dist/tests/bench/cleanup.test.js +0 -166
  43. package/dist/tests/bench/cli.js +0 -1018
  44. package/dist/tests/bench/cli.test.js +0 -445
  45. package/dist/tests/bench/compare.test.js +0 -556
  46. package/dist/tests/bench/corpus.js +0 -317
  47. package/dist/tests/bench/corpus.test.js +0 -258
  48. package/dist/tests/bench/doctor.js +0 -525
  49. package/dist/tests/bench/driver.js +0 -401
  50. package/dist/tests/bench/driver.test.js +0 -584
  51. package/dist/tests/bench/environment.js +0 -233
  52. package/dist/tests/bench/environment.test.js +0 -199
  53. package/dist/tests/bench/evolve-metrics.js +0 -179
  54. package/dist/tests/bench/evolve-metrics.test.js +0 -187
  55. package/dist/tests/bench/evolve.js +0 -647
  56. package/dist/tests/bench/evolve.test.js +0 -624
  57. package/dist/tests/bench/failure-modes.test.js +0 -349
  58. package/dist/tests/bench/feedback-integrity.test.js +0 -457
  59. package/dist/tests/bench/leakage.test.js +0 -228
  60. package/dist/tests/bench/learning-curve.test.js +0 -134
  61. package/dist/tests/bench/metrics.js +0 -2395
  62. package/dist/tests/bench/metrics.test.js +0 -1150
  63. package/dist/tests/bench/no-os-tmpdir-invariant.test.js +0 -43
  64. package/dist/tests/bench/opencode-config.js +0 -194
  65. package/dist/tests/bench/opencode-config.test.js +0 -370
  66. package/dist/tests/bench/report.js +0 -1885
  67. package/dist/tests/bench/report.test.js +0 -1038
  68. package/dist/tests/bench/run-config.js +0 -355
  69. package/dist/tests/bench/run-config.test.js +0 -298
  70. package/dist/tests/bench/run-curate-test.js +0 -32
  71. package/dist/tests/bench/run-failing-tasks.js +0 -56
  72. package/dist/tests/bench/run-full-bench.js +0 -51
  73. package/dist/tests/bench/run-items36-targeted.js +0 -69
  74. package/dist/tests/bench/run-nano-quick.js +0 -42
  75. package/dist/tests/bench/run-waveg-targeted.js +0 -62
  76. package/dist/tests/bench/runner.js +0 -699
  77. package/dist/tests/bench/runner.test.js +0 -958
  78. package/dist/tests/bench/search-bridge.test.js +0 -331
  79. package/dist/tests/bench/tmp.js +0 -131
  80. package/dist/tests/bench/trajectory.js +0 -116
  81. package/dist/tests/bench/trajectory.test.js +0 -127
  82. package/dist/tests/bench/verifier.js +0 -114
  83. package/dist/tests/bench/verifier.test.js +0 -118
  84. package/dist/tests/bench/workflow-evaluator.js +0 -557
  85. package/dist/tests/bench/workflow-evaluator.test.js +0 -421
  86. package/dist/tests/bench/workflow-spec.js +0 -345
  87. package/dist/tests/bench/workflow-spec.test.js +0 -363
  88. package/dist/tests/bench/workflow-trace.js +0 -472
  89. package/dist/tests/bench/workflow-trace.test.js +0 -254
  90. package/dist/tests/benchmark-search-quality.js +0 -536
  91. package/dist/tests/benchmark-suite.js +0 -1441
  92. package/dist/tests/capture-cli.test.js +0 -112
  93. package/dist/tests/cli-errors.test.js +0 -204
  94. package/dist/tests/commands/events.test.js +0 -370
  95. package/dist/tests/commands/history.test.js +0 -418
  96. package/dist/tests/commands/import.test.js +0 -103
  97. package/dist/tests/commands/proposal-cli.test.js +0 -209
  98. package/dist/tests/commands/reflect-propose-cli.test.js +0 -333
  99. package/dist/tests/commands/remember.test.js +0 -97
  100. package/dist/tests/commands/scope-flags.test.js +0 -300
  101. package/dist/tests/commands/search.test.js +0 -537
  102. package/dist/tests/commands/show-indexer-parity.test.js +0 -117
  103. package/dist/tests/commands/show.test.js +0 -294
  104. package/dist/tests/common.test.js +0 -266
  105. package/dist/tests/completions.test.js +0 -142
  106. package/dist/tests/config-cli.test.js +0 -193
  107. package/dist/tests/config-llm-features.test.js +0 -139
  108. package/dist/tests/config.test.js +0 -569
  109. package/dist/tests/contracts/migration-baseline.test.js +0 -43
  110. package/dist/tests/contracts/reflect-propose-envelope.test.js +0 -139
  111. package/dist/tests/contracts/spec-helpers.js +0 -46
  112. package/dist/tests/contracts/v1-spec-section-11-proposal-queue.test.js +0 -228
  113. package/dist/tests/contracts/v1-spec-section-12-agent-config.test.js +0 -56
  114. package/dist/tests/contracts/v1-spec-section-13-lesson-type.test.js +0 -34
  115. package/dist/tests/contracts/v1-spec-section-14-llm-features.test.js +0 -94
  116. package/dist/tests/contracts/v1-spec-section-4-1-asset-types.test.js +0 -39
  117. package/dist/tests/contracts/v1-spec-section-4-2-quality-rules.test.js +0 -44
  118. package/dist/tests/contracts/v1-spec-section-5-configuration.test.js +0 -47
  119. package/dist/tests/contracts/v1-spec-section-6-orchestration.test.js +0 -40
  120. package/dist/tests/contracts/v1-spec-section-7-module-layout.test.js +0 -58
  121. package/dist/tests/contracts/v1-spec-section-8-extension-points.test.js +0 -34
  122. package/dist/tests/contracts/v1-spec-section-9-4-cli-surface.test.js +0 -75
  123. package/dist/tests/contracts/v1-spec-section-9-7-llm-agent-boundary.test.js +0 -36
  124. package/dist/tests/core/write-source.test.js +0 -366
  125. package/dist/tests/curate-command.test.js +0 -87
  126. package/dist/tests/db-scoring.test.js +0 -201
  127. package/dist/tests/db.test.js +0 -654
  128. package/dist/tests/distill-cli-flag.test.js +0 -208
  129. package/dist/tests/distill.test.js +0 -515
  130. package/dist/tests/docker-install.test.js +0 -120
  131. package/dist/tests/e2e.test.js +0 -1419
  132. package/dist/tests/embedder.test.js +0 -340
  133. package/dist/tests/embedding-model-config.test.js +0 -379
  134. package/dist/tests/feedback-command.test.js +0 -172
  135. package/dist/tests/file-context.test.js +0 -552
  136. package/dist/tests/fixtures/scripts/git/summarize-diff.js +0 -9
  137. package/dist/tests/fixtures/scripts/lint/eslint-check.js +0 -7
  138. package/dist/tests/fixtures/stashes/load.js +0 -166
  139. package/dist/tests/fixtures/stashes/load.test.js +0 -97
  140. package/dist/tests/fixtures/stashes/ranking-baseline/scripts/mem0-search.js +0 -12
  141. package/dist/tests/frontmatter.test.js +0 -190
  142. package/dist/tests/fts-field-weighting.test.js +0 -254
  143. package/dist/tests/fuzzy-search.test.js +0 -230
  144. package/dist/tests/git-provider-clone.test.js +0 -45
  145. package/dist/tests/github.test.js +0 -161
  146. package/dist/tests/graph-boost-ranking.test.js +0 -305
  147. package/dist/tests/graph-extraction.test.js +0 -282
  148. package/dist/tests/helpers/usage-events.js +0 -8
  149. package/dist/tests/index-pass-llm.test.js +0 -161
  150. package/dist/tests/indexer.test.js +0 -570
  151. package/dist/tests/info-command.test.js +0 -166
  152. package/dist/tests/init.test.js +0 -69
  153. package/dist/tests/install-script.test.js +0 -246
  154. package/dist/tests/integration/agent-real-profile.test.js +0 -94
  155. package/dist/tests/issue-36-repro.test.js +0 -304
  156. package/dist/tests/issues-191-194.test.js +0 -160
  157. package/dist/tests/lesson-lint.test.js +0 -111
  158. package/dist/tests/llm-client.test.js +0 -115
  159. package/dist/tests/llm-feature-gate.test.js +0 -151
  160. package/dist/tests/llm.test.js +0 -139
  161. package/dist/tests/lockfile.test.js +0 -216
  162. package/dist/tests/manifest.test.js +0 -205
  163. package/dist/tests/markdown.test.js +0 -126
  164. package/dist/tests/matchers-unit.test.js +0 -189
  165. package/dist/tests/memory-inference.test.js +0 -299
  166. package/dist/tests/merge-scoring.test.js +0 -136
  167. package/dist/tests/metadata.test.js +0 -313
  168. package/dist/tests/migration-help.test.js +0 -89
  169. package/dist/tests/origin-resolve.test.js +0 -124
  170. package/dist/tests/output-baseline.test.js +0 -218
  171. package/dist/tests/output-shapes-unit.test.js +0 -478
  172. package/dist/tests/parallel-search.test.js +0 -272
  173. package/dist/tests/parameter-metadata.test.js +0 -365
  174. package/dist/tests/paths.test.js +0 -177
  175. package/dist/tests/progressive-disclosure.test.js +0 -280
  176. package/dist/tests/proposals.test.js +0 -279
  177. package/dist/tests/proposed-quality.test.js +0 -271
  178. package/dist/tests/provider-registry.test.js +0 -32
  179. package/dist/tests/ranking-regression.test.js +0 -548
  180. package/dist/tests/reflect-propose.test.js +0 -455
  181. package/dist/tests/registry-build-index.test.js +0 -394
  182. package/dist/tests/registry-cli.test.js +0 -290
  183. package/dist/tests/registry-index-v2.test.js +0 -430
  184. package/dist/tests/registry-install.test.js +0 -728
  185. package/dist/tests/registry-providers/parity.test.js +0 -189
  186. package/dist/tests/registry-providers/skills-sh.test.js +0 -309
  187. package/dist/tests/registry-providers/static-index.test.js +0 -238
  188. package/dist/tests/registry-resolve.test.js +0 -126
  189. package/dist/tests/registry-search.test.js +0 -923
  190. package/dist/tests/remember-frontmatter.test.js +0 -378
  191. package/dist/tests/remember-unit.test.js +0 -123
  192. package/dist/tests/ripgrep-install.test.js +0 -251
  193. package/dist/tests/ripgrep-resolve.test.js +0 -108
  194. package/dist/tests/ripgrep.test.js +0 -163
  195. package/dist/tests/save-command.test.js +0 -94
  196. package/dist/tests/save-trust-qa-fixes.test.js +0 -270
  197. package/dist/tests/scoring-pipeline.test.js +0 -648
  198. package/dist/tests/search-include-proposed-cli.test.js +0 -118
  199. package/dist/tests/self-update.test.js +0 -442
  200. package/dist/tests/semantic-search-e2e.test.js +0 -512
  201. package/dist/tests/semantic-status.test.js +0 -471
  202. package/dist/tests/setup-run.integration.js +0 -877
  203. package/dist/tests/setup-wizard.test.js +0 -198
  204. package/dist/tests/setup.test.js +0 -131
  205. package/dist/tests/source-add.test.js +0 -11
  206. package/dist/tests/source-clone.test.js +0 -254
  207. package/dist/tests/source-manage.test.js +0 -366
  208. package/dist/tests/source-providers/filesystem.test.js +0 -82
  209. package/dist/tests/source-providers/git.test.js +0 -252
  210. package/dist/tests/source-providers/website.test.js +0 -128
  211. package/dist/tests/source-qa-fixes.test.js +0 -286
  212. package/dist/tests/source-registry.test.js +0 -350
  213. package/dist/tests/source-resolve.test.js +0 -100
  214. package/dist/tests/source-source.test.js +0 -281
  215. package/dist/tests/source.test.js +0 -533
  216. package/dist/tests/tar-utils-scan.test.js +0 -73
  217. package/dist/tests/toggle-components.test.js +0 -73
  218. package/dist/tests/usage-telemetry.test.js +0 -265
  219. package/dist/tests/utility-scoring.test.js +0 -558
  220. package/dist/tests/vault-load-error.test.js +0 -78
  221. package/dist/tests/vault-qa-fixes.test.js +0 -194
  222. package/dist/tests/vault.test.js +0 -429
  223. package/dist/tests/vector-search.test.js +0 -608
  224. package/dist/tests/walker.test.js +0 -252
  225. package/dist/tests/wave2-cluster-bc.test.js +0 -228
  226. package/dist/tests/wave2-cluster-d.test.js +0 -180
  227. package/dist/tests/wave2-cluster-e.test.js +0 -179
  228. package/dist/tests/wiki-qa-fixes.test.js +0 -270
  229. package/dist/tests/wiki.test.js +0 -529
  230. package/dist/tests/workflow-cli.test.js +0 -271
  231. package/dist/tests/workflow-markdown.test.js +0 -171
  232. package/dist/tests/workflow-path-escape.test.js +0 -132
  233. package/dist/tests/workflow-qa-fixes.test.js +0 -395
  234. package/dist/tests/workflows/indexer-rejection.test.js +0 -213
  235. /package/dist/{src/commands → commands}/completions.js +0 -0
  236. /package/dist/{src/commands → commands}/config-cli.js +0 -0
  237. /package/dist/{src/commands → commands}/curate.js +0 -0
  238. /package/dist/{src/commands → commands}/distill.js +0 -0
  239. /package/dist/{src/commands → commands}/events.js +0 -0
  240. /package/dist/{src/commands → commands}/history.js +0 -0
  241. /package/dist/{src/commands → commands}/info.js +0 -0
  242. /package/dist/{src/commands → commands}/init.js +0 -0
  243. /package/dist/{src/commands → commands}/install-audit.js +0 -0
  244. /package/dist/{src/commands → commands}/migration-help.js +0 -0
  245. /package/dist/{src/commands → commands}/proposal.js +0 -0
  246. /package/dist/{src/commands → commands}/propose.js +0 -0
  247. /package/dist/{src/commands → commands}/reflect.js +0 -0
  248. /package/dist/{src/commands → commands}/registry-search.js +0 -0
  249. /package/dist/{src/commands → commands}/remember.js +0 -0
  250. /package/dist/{src/commands → commands}/search.js +0 -0
  251. /package/dist/{src/commands → commands}/self-update.js +0 -0
  252. /package/dist/{src/commands → commands}/show.js +0 -0
  253. /package/dist/{src/commands → commands}/source-clone.js +0 -0
  254. /package/dist/{src/commands → commands}/source-manage.js +0 -0
  255. /package/dist/{src/commands → commands}/vault.js +0 -0
  256. /package/dist/{src/core → core}/asset-ref.js +0 -0
  257. /package/dist/{src/core → core}/asset-registry.js +0 -0
  258. /package/dist/{src/core → core}/asset-spec.js +0 -0
  259. /package/dist/{src/core → core}/errors.js +0 -0
  260. /package/dist/{src/core → core}/events.js +0 -0
  261. /package/dist/{src/core → core}/frontmatter.js +0 -0
  262. /package/dist/{src/core → core}/lesson-lint.js +0 -0
  263. /package/dist/{src/core → core}/markdown.js +0 -0
  264. /package/dist/{src/core → core}/paths.js +0 -0
  265. /package/dist/{src/core → core}/proposals.js +0 -0
  266. /package/dist/{src/core → core}/warn.js +0 -0
  267. /package/dist/{src/core → core}/write-source.js +0 -0
  268. /package/dist/{src/indexer → indexer}/db.js +0 -0
  269. /package/dist/{src/indexer → indexer}/file-context.js +0 -0
  270. /package/dist/{src/indexer → indexer}/graph-boost.js +0 -0
  271. /package/dist/{src/indexer → indexer}/manifest.js +0 -0
  272. /package/dist/{src/indexer → indexer}/matchers.js +0 -0
  273. /package/dist/{src/indexer → indexer}/metadata.js +0 -0
  274. /package/dist/{src/indexer → indexer}/search-fields.js +0 -0
  275. /package/dist/{src/indexer → indexer}/semantic-status.js +0 -0
  276. /package/dist/{src/indexer → indexer}/usage-events.js +0 -0
  277. /package/dist/{src/indexer → indexer}/walker.js +0 -0
  278. /package/dist/{src/integrations → integrations}/agent/config.js +0 -0
  279. /package/dist/{src/integrations → integrations}/agent/detect.js +0 -0
  280. /package/dist/{src/integrations → integrations}/agent/index.js +0 -0
  281. /package/dist/{src/integrations → integrations}/agent/profiles.js +0 -0
  282. /package/dist/{src/integrations → integrations}/agent/prompts.js +0 -0
  283. /package/dist/{src/integrations → integrations}/agent/spawn.js +0 -0
  284. /package/dist/{src/integrations → integrations}/github.js +0 -0
  285. /package/dist/{src/integrations → integrations}/lockfile.js +0 -0
  286. /package/dist/{src/llm → llm}/embedders/cache.js +0 -0
  287. /package/dist/{src/llm → llm}/embedders/types.js +0 -0
  288. /package/dist/{src/llm → llm}/feature-gate.js +0 -0
  289. /package/dist/{src/llm → llm}/index-passes.js +0 -0
  290. /package/dist/{src/output → output}/context.js +0 -0
  291. /package/dist/{src/output → output}/renderers.js +0 -0
  292. /package/dist/{src/output → output}/shapes.js +0 -0
  293. /package/dist/{src/output → output}/text.js +0 -0
  294. /package/dist/{src/registry → registry}/build-index.js +0 -0
  295. /package/dist/{src/registry → registry}/create-provider-registry.js +0 -0
  296. /package/dist/{src/registry → registry}/factory.js +0 -0
  297. /package/dist/{src/registry → registry}/origin-resolve.js +0 -0
  298. /package/dist/{src/registry → registry}/providers/index.js +0 -0
  299. /package/dist/{src/registry → registry}/providers/skills-sh.js +0 -0
  300. /package/dist/{src/registry → registry}/providers/static-index.js +0 -0
  301. /package/dist/{src/registry → registry}/providers/types.js +0 -0
  302. /package/dist/{src/registry → registry}/resolve.js +0 -0
  303. /package/dist/{src/registry → registry}/types.js +0 -0
  304. /package/dist/{src/setup → setup}/detect.js +0 -0
  305. /package/dist/{src/setup → setup}/ripgrep-install.js +0 -0
  306. /package/dist/{src/setup → setup}/ripgrep-resolve.js +0 -0
  307. /package/dist/{src/setup → setup}/steps.js +0 -0
  308. /package/dist/{src/sources → sources}/include.js +0 -0
  309. /package/dist/{src/sources → sources}/provider-factory.js +0 -0
  310. /package/dist/{src/sources → sources}/provider.js +0 -0
  311. /package/dist/{src/sources → sources}/providers/filesystem.js +0 -0
  312. /package/dist/{src/sources → sources}/providers/git.js +0 -0
  313. /package/dist/{src/sources → sources}/providers/index.js +0 -0
  314. /package/dist/{src/sources → sources}/providers/install-types.js +0 -0
  315. /package/dist/{src/sources → sources}/providers/npm.js +0 -0
  316. /package/dist/{src/sources → sources}/providers/provider-utils.js +0 -0
  317. /package/dist/{src/sources → sources}/providers/sync-from-ref.js +0 -0
  318. /package/dist/{src/sources → sources}/providers/tar-utils.js +0 -0
  319. /package/dist/{src/sources → sources}/resolve.js +0 -0
  320. /package/dist/{src/sources → sources}/types.js +0 -0
  321. /package/dist/{src/templates → templates}/wiki-templates.js +0 -0
  322. /package/dist/{src/version.js → version.js} +0 -0
  323. /package/dist/{src/wiki → wiki}/wiki.js +0 -0
  324. /package/dist/{src/workflows → workflows}/authoring.js +0 -0
  325. /package/dist/{src/workflows → workflows}/cli.js +0 -0
  326. /package/dist/{src/workflows → workflows}/db.js +0 -0
  327. /package/dist/{src/workflows → workflows}/document-cache.js +0 -0
  328. /package/dist/{src/workflows → workflows}/parser.js +0 -0
  329. /package/dist/{src/workflows → workflows}/renderer.js +0 -0
  330. /package/dist/{src/workflows → workflows}/runs.js +0 -0
  331. /package/dist/{src/workflows → workflows}/schema.js +0 -0
  332. /package/dist/{src/workflows → workflows}/validator.js +0 -0
@@ -1,558 +0,0 @@
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
- });
@@ -1,78 +0,0 @@
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
- });