akm-cli 0.8.0-rc2 → 0.8.1

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 (313) hide show
  1. package/{.github/CHANGELOG.md → CHANGELOG.md} +238 -3
  2. package/README.md +22 -6
  3. package/SECURITY.md +93 -0
  4. package/dist/assets/help/help-accept.md +12 -0
  5. package/dist/assets/help/help-improve.md +81 -0
  6. package/dist/{commands → assets}/help/help-proposals.md +7 -4
  7. package/dist/assets/help/help-reject.md +11 -0
  8. package/dist/{output → assets/hints}/cli-hints-full.md +60 -32
  9. package/dist/{output → assets/hints}/cli-hints-short.md +10 -7
  10. package/dist/assets/profiles/default.json +15 -0
  11. package/dist/assets/profiles/graph-refresh.json +13 -0
  12. package/dist/assets/profiles/memory-focus.json +12 -0
  13. package/dist/assets/profiles/quick.json +15 -0
  14. package/dist/assets/profiles/thorough.json +15 -0
  15. package/dist/assets/prompts/extract-session.md +80 -0
  16. package/dist/assets/prompts/graph-extract-user-prompt.md +35 -0
  17. package/dist/assets/tasks/graph-refresh-weekly.yml +10 -0
  18. package/dist/cli/config-migrate.js +144 -0
  19. package/dist/cli/config-validate.js +39 -0
  20. package/dist/cli/confirm.js +73 -0
  21. package/dist/cli/parse-args.js +93 -3
  22. package/dist/cli/shared.js +129 -0
  23. package/dist/cli.js +2141 -1268
  24. package/dist/commands/add-cli.js +279 -0
  25. package/dist/commands/agent-dispatch.js +20 -12
  26. package/dist/commands/agent-support.js +11 -5
  27. package/dist/commands/completions.js +3 -0
  28. package/dist/commands/config-cli.js +129 -517
  29. package/dist/commands/consolidate.js +1557 -147
  30. package/dist/commands/curate.js +44 -3
  31. package/dist/commands/db-cli.js +23 -0
  32. package/dist/commands/distill-promotion-policy.js +5 -3
  33. package/dist/commands/distill.js +906 -100
  34. package/dist/commands/env.js +213 -0
  35. package/dist/commands/eval-cases.js +3 -0
  36. package/dist/commands/events.js +3 -0
  37. package/dist/commands/extract-cli.js +127 -0
  38. package/dist/commands/extract-prompt.js +217 -0
  39. package/dist/commands/extract.js +477 -0
  40. package/dist/commands/feedback-cli.js +331 -0
  41. package/dist/commands/graph.js +260 -5
  42. package/dist/commands/health.js +1042 -55
  43. package/dist/commands/history.js +51 -16
  44. package/dist/commands/improve-auto-accept.js +97 -0
  45. package/dist/commands/improve-cli.js +236 -0
  46. package/dist/commands/improve-profiles.js +138 -0
  47. package/dist/commands/improve-result-file.js +167 -0
  48. package/dist/commands/improve.js +1736 -346
  49. package/dist/commands/info.js +26 -28
  50. package/dist/commands/init.js +49 -1
  51. package/dist/commands/installed-stashes.js +6 -23
  52. package/dist/commands/knowledge.js +3 -0
  53. package/dist/commands/lint/agent-linter.js +3 -0
  54. package/dist/commands/lint/base-linter.js +199 -5
  55. package/dist/commands/lint/command-linter.js +3 -0
  56. package/dist/commands/lint/default-linter.js +3 -0
  57. package/dist/commands/lint/env-key-rules.js +154 -0
  58. package/dist/commands/lint/index.js +92 -3
  59. package/dist/commands/lint/knowledge-linter.js +3 -0
  60. package/dist/commands/lint/markdown-insertion.js +343 -0
  61. package/dist/commands/lint/memory-linter.js +3 -0
  62. package/dist/commands/lint/registry.js +3 -0
  63. package/dist/commands/lint/skill-linter.js +3 -0
  64. package/dist/commands/lint/task-linter.js +15 -12
  65. package/dist/commands/lint/types.js +3 -0
  66. package/dist/commands/lint/workflow-linter.js +3 -0
  67. package/dist/commands/lint.js +3 -0
  68. package/dist/commands/migration-help.js +5 -2
  69. package/dist/commands/proposal-drain-policies.js +128 -0
  70. package/dist/commands/proposal-drain.js +477 -0
  71. package/dist/commands/proposal.js +60 -6
  72. package/dist/commands/propose.js +24 -19
  73. package/dist/commands/reflect.js +1004 -94
  74. package/dist/commands/registry-cli.js +150 -0
  75. package/dist/commands/registry-search.js +3 -0
  76. package/dist/commands/remember-cli.js +257 -0
  77. package/dist/commands/remember.js +15 -6
  78. package/dist/commands/schema-repair.js +88 -15
  79. package/dist/commands/search.js +99 -14
  80. package/dist/commands/secret.js +173 -0
  81. package/dist/commands/self-update.js +3 -0
  82. package/dist/commands/show.js +32 -13
  83. package/dist/commands/source-add.js +7 -35
  84. package/dist/commands/source-clone.js +3 -0
  85. package/dist/commands/source-manage.js +3 -0
  86. package/dist/commands/tasks.js +161 -95
  87. package/dist/commands/url-checker.js +3 -0
  88. package/dist/core/action-contributors.js +3 -0
  89. package/dist/core/asset-ref.js +13 -2
  90. package/dist/core/asset-registry.js +9 -2
  91. package/dist/core/asset-serialize.js +88 -0
  92. package/dist/core/asset-spec.js +61 -5
  93. package/dist/core/common.js +93 -5
  94. package/dist/core/concurrent.js +3 -0
  95. package/dist/core/config-io.js +347 -0
  96. package/dist/core/config-migration.js +622 -0
  97. package/dist/core/config-schema.js +558 -0
  98. package/dist/core/config-sources.js +108 -0
  99. package/dist/core/config-types.js +4 -0
  100. package/dist/core/config-walker.js +337 -0
  101. package/dist/core/config.js +366 -1077
  102. package/dist/core/errors.js +42 -20
  103. package/dist/core/events.js +31 -25
  104. package/dist/core/file-lock.js +104 -0
  105. package/dist/core/frontmatter.js +75 -10
  106. package/dist/core/lesson-lint.js +3 -0
  107. package/dist/core/markdown.js +3 -0
  108. package/dist/core/memory-belief.js +62 -0
  109. package/dist/core/memory-contradiction-detect.js +274 -0
  110. package/dist/core/memory-improve.js +142 -14
  111. package/dist/core/parse.js +3 -0
  112. package/dist/core/paths.js +218 -50
  113. package/dist/core/proposal-quality-validators.js +380 -0
  114. package/dist/core/proposal-validators.js +11 -3
  115. package/dist/core/proposals.js +464 -5
  116. package/dist/core/state-db.js +349 -56
  117. package/dist/core/text-truncation.js +107 -0
  118. package/dist/core/time.js +3 -0
  119. package/dist/core/tty.js +59 -0
  120. package/dist/core/warn.js +7 -2
  121. package/dist/core/write-source.js +12 -0
  122. package/dist/indexer/db-backup.js +391 -0
  123. package/dist/indexer/db-search.js +136 -28
  124. package/dist/indexer/db.js +661 -166
  125. package/dist/indexer/ensure-index.js +3 -0
  126. package/dist/indexer/file-context.js +3 -0
  127. package/dist/indexer/graph-boost.js +162 -40
  128. package/dist/indexer/graph-db.js +241 -51
  129. package/dist/indexer/graph-dedup.js +3 -7
  130. package/dist/indexer/graph-extraction.js +242 -149
  131. package/dist/indexer/index-context.js +3 -9
  132. package/dist/indexer/indexer.js +86 -16
  133. package/dist/indexer/llm-cache.js +24 -19
  134. package/dist/indexer/manifest.js +3 -0
  135. package/dist/indexer/matchers.js +184 -11
  136. package/dist/indexer/memory-inference.js +94 -50
  137. package/dist/indexer/metadata-contributors.js +3 -0
  138. package/dist/indexer/metadata.js +110 -50
  139. package/dist/indexer/path-resolver.js +3 -0
  140. package/dist/indexer/project-context.js +192 -0
  141. package/dist/indexer/ranking-contributors.js +134 -7
  142. package/dist/indexer/ranking.js +8 -1
  143. package/dist/indexer/search-fields.js +5 -9
  144. package/dist/indexer/search-hit-enrichers.js +91 -2
  145. package/dist/indexer/search-source.js +20 -1
  146. package/dist/indexer/semantic-status.js +4 -1
  147. package/dist/indexer/staleness-detect.js +447 -0
  148. package/dist/indexer/usage-events.js +12 -9
  149. package/dist/indexer/walker.js +3 -0
  150. package/dist/integrations/agent/builders.js +135 -0
  151. package/dist/integrations/agent/config.js +121 -401
  152. package/dist/integrations/agent/detect.js +3 -0
  153. package/dist/integrations/agent/index.js +6 -14
  154. package/dist/integrations/agent/model-aliases.js +55 -0
  155. package/dist/integrations/agent/profiles.js +3 -0
  156. package/dist/integrations/agent/prompts.js +137 -8
  157. package/dist/integrations/agent/runner.js +208 -0
  158. package/dist/integrations/agent/sdk-runner.js +8 -2
  159. package/dist/integrations/agent/spawn.js +54 -14
  160. package/dist/integrations/github.js +3 -0
  161. package/dist/integrations/lockfile.js +22 -51
  162. package/dist/integrations/session-logs/index.js +4 -0
  163. package/dist/integrations/session-logs/inline-refs.js +35 -0
  164. package/dist/integrations/session-logs/pre-filter.js +152 -0
  165. package/dist/integrations/session-logs/providers/claude-code.js +226 -0
  166. package/dist/integrations/session-logs/providers/opencode.js +231 -25
  167. package/dist/integrations/session-logs/types.js +3 -0
  168. package/dist/llm/call-ai.js +14 -26
  169. package/dist/llm/client.js +16 -2
  170. package/dist/llm/embedder.js +20 -29
  171. package/dist/llm/embedders/cache.js +3 -7
  172. package/dist/llm/embedders/local.js +42 -1
  173. package/dist/llm/embedders/remote.js +20 -8
  174. package/dist/llm/embedders/types.js +3 -7
  175. package/dist/llm/feature-gate.js +92 -56
  176. package/dist/llm/graph-extract.js +402 -31
  177. package/dist/llm/index-passes.js +44 -29
  178. package/dist/llm/memory-infer.js +30 -2
  179. package/dist/llm/metadata-enhance.js +3 -7
  180. package/dist/output/cli-hints.js +7 -4
  181. package/dist/output/context.js +60 -8
  182. package/dist/output/renderers.js +170 -194
  183. package/dist/output/shapes/curate.js +56 -0
  184. package/dist/output/shapes/distill.js +10 -0
  185. package/dist/output/shapes/env-list.js +19 -0
  186. package/dist/output/shapes/events.js +11 -0
  187. package/dist/output/shapes/helpers.js +424 -0
  188. package/dist/output/shapes/history.js +7 -0
  189. package/dist/output/shapes/passthrough.js +105 -0
  190. package/dist/output/shapes/proposal-accept.js +7 -0
  191. package/dist/output/shapes/proposal-diff.js +7 -0
  192. package/dist/output/shapes/proposal-list.js +7 -0
  193. package/dist/output/shapes/proposal-producer.js +11 -0
  194. package/dist/output/shapes/proposal-reject.js +7 -0
  195. package/dist/output/shapes/proposal-show.js +7 -0
  196. package/dist/output/shapes/registry-search.js +6 -0
  197. package/dist/output/shapes/registry.js +30 -0
  198. package/dist/output/shapes/search.js +6 -0
  199. package/dist/output/shapes/secret-list.js +19 -0
  200. package/dist/output/shapes/show.js +6 -0
  201. package/dist/output/shapes/vault-list.js +19 -0
  202. package/dist/output/shapes.js +51 -549
  203. package/dist/output/text/add.js +6 -0
  204. package/dist/output/text/clone.js +6 -0
  205. package/dist/output/text/config.js +6 -0
  206. package/dist/output/text/curate.js +6 -0
  207. package/dist/output/text/distill.js +7 -0
  208. package/dist/output/text/enable-disable.js +7 -0
  209. package/dist/output/text/events.js +10 -0
  210. package/dist/output/text/feedback.js +6 -0
  211. package/dist/output/text/helpers.js +1059 -0
  212. package/dist/output/text/history.js +7 -0
  213. package/dist/output/text/import.js +6 -0
  214. package/dist/output/text/index.js +6 -0
  215. package/dist/output/text/info.js +6 -0
  216. package/dist/output/text/init.js +6 -0
  217. package/dist/output/text/list.js +6 -0
  218. package/dist/output/text/proposal-producer.js +8 -0
  219. package/dist/output/text/proposal.js +12 -0
  220. package/dist/output/text/registry-commands.js +11 -0
  221. package/dist/output/text/registry.js +30 -0
  222. package/dist/output/text/remember.js +6 -0
  223. package/dist/output/text/remove.js +6 -0
  224. package/dist/output/text/save.js +6 -0
  225. package/dist/output/text/search.js +6 -0
  226. package/dist/output/text/show.js +6 -0
  227. package/dist/output/text/update.js +6 -0
  228. package/dist/output/text/upgrade.js +6 -0
  229. package/dist/output/text/vault.js +16 -0
  230. package/dist/output/text/wiki.js +15 -0
  231. package/dist/output/text/workflow.js +14 -0
  232. package/dist/output/text.js +44 -1329
  233. package/dist/registry/build-index.js +3 -0
  234. package/dist/registry/create-provider-registry.js +3 -0
  235. package/dist/registry/factory.js +4 -1
  236. package/dist/registry/origin-resolve.js +3 -0
  237. package/dist/registry/providers/index.js +3 -0
  238. package/dist/registry/providers/skills-sh.js +11 -2
  239. package/dist/registry/providers/static-index.js +10 -1
  240. package/dist/registry/providers/types.js +3 -24
  241. package/dist/registry/resolve.js +11 -16
  242. package/dist/registry/types.js +3 -0
  243. package/dist/scripts/migrate-storage.js +17767 -0
  244. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +9031 -0
  245. package/dist/scripts/migrations/v16-to-v17.js +141 -0
  246. package/dist/setup/detect.js +3 -0
  247. package/dist/setup/ripgrep-install.js +3 -0
  248. package/dist/setup/ripgrep-resolve.js +3 -0
  249. package/dist/setup/setup.js +306 -67
  250. package/dist/setup/steps.js +3 -15
  251. package/dist/sources/include.js +3 -0
  252. package/dist/sources/provider-factory.js +3 -11
  253. package/dist/sources/provider.js +3 -20
  254. package/dist/sources/providers/filesystem.js +19 -23
  255. package/dist/sources/providers/git.js +171 -21
  256. package/dist/sources/providers/index.js +3 -0
  257. package/dist/sources/providers/install-types.js +3 -13
  258. package/dist/sources/providers/npm.js +3 -4
  259. package/dist/sources/providers/provider-utils.js +3 -0
  260. package/dist/sources/providers/sync-from-ref.js +3 -11
  261. package/dist/sources/providers/tar-utils.js +3 -0
  262. package/dist/sources/providers/website.js +18 -22
  263. package/dist/sources/resolve.js +3 -0
  264. package/dist/sources/types.js +3 -0
  265. package/dist/sources/website-ingest.js +3 -0
  266. package/dist/tasks/backends/cron.js +3 -0
  267. package/dist/tasks/backends/exec-utils.js +3 -0
  268. package/dist/tasks/backends/index.js +3 -11
  269. package/dist/tasks/backends/launchd.js +4 -1
  270. package/dist/tasks/backends/schtasks.js +4 -1
  271. package/dist/tasks/parser.js +51 -38
  272. package/dist/tasks/resolveAkmBin.js +3 -0
  273. package/dist/tasks/runner.js +35 -9
  274. package/dist/tasks/schedule.js +20 -1
  275. package/dist/tasks/schema.js +5 -3
  276. package/dist/tasks/validator.js +6 -3
  277. package/dist/version.js +3 -0
  278. package/dist/wiki/wiki-templates.js +6 -3
  279. package/dist/wiki/wiki.js +4 -1
  280. package/dist/workflows/authoring.js +4 -1
  281. package/dist/workflows/cli.js +3 -0
  282. package/dist/workflows/db.js +140 -10
  283. package/dist/workflows/document-cache.js +3 -10
  284. package/dist/workflows/parser.js +3 -0
  285. package/dist/workflows/renderer.js +3 -0
  286. package/dist/workflows/runs.js +18 -1
  287. package/dist/workflows/schema.js +3 -0
  288. package/dist/workflows/scope-key.js +3 -0
  289. package/dist/workflows/validator.js +5 -9
  290. package/docs/README.md +7 -2
  291. package/docs/data-and-telemetry.md +225 -0
  292. package/docs/migration/release-notes/0.7.5.md +2 -2
  293. package/docs/migration/release-notes/0.8.0.md +57 -5
  294. package/docs/migration/v0.7-to-v0.8.md +1378 -0
  295. package/package.json +28 -11
  296. package/.github/LICENSE +0 -374
  297. package/dist/commands/help/help-accept.md +0 -9
  298. package/dist/commands/help/help-improve.md +0 -53
  299. package/dist/commands/help/help-reject.md +0 -8
  300. package/dist/commands/install-audit.js +0 -385
  301. package/dist/commands/vault.js +0 -310
  302. package/dist/indexer/match-contributors.js +0 -141
  303. package/dist/integrations/agent/pipeline.js +0 -39
  304. package/dist/integrations/agent/runners.js +0 -31
  305. package/dist/llm/prompts/graph-extract-user-prompt.md +0 -12
  306. /package/dist/{tasks → assets}/backends/launchd-template.xml +0 -0
  307. /package/dist/{tasks → assets}/backends/schtasks-template.xml +0 -0
  308. /package/dist/{commands → assets}/help/help-propose.md +0 -0
  309. /package/dist/{wiki → assets/wiki}/index-template.md +0 -0
  310. /package/dist/{wiki → assets/wiki}/ingest-workflow-template.md +0 -0
  311. /package/dist/{wiki → assets/wiki}/log-template.md +0 -0
  312. /package/dist/{wiki → assets/wiki}/schema-template.md +0 -0
  313. /package/dist/{workflows → assets/workflows}/workflow-template.md +0 -0
@@ -0,0 +1,213 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+ /**
5
+ * Environment asset type (`env`) — whole `.env` file storage.
6
+ *
7
+ * An `env` asset holds a GROUP of related CONFIGURATION for an app or service
8
+ * (URLs, feature flags, and any credentials it needs) in a single `.env` file,
9
+ * sourced/injected wholesale. Values may or may not be sensitive — akm protects
10
+ * them all the same. For a single sensitive value used on its own for
11
+ * authentication (a token, key, or cert), use the `secret` type instead.
12
+ *
13
+ * Unlike the deprecated `vault` type it replaces, akm does NOT manage individual
14
+ * KEY=value entries (no `set`/`unset`/quoting): you edit the `.env` file with
15
+ * your own editor, and akm loads it. The simplification removes the
16
+ * hand-rolled quoting/escaping surface; the safety guarantee moves to the READ
17
+ * path instead (see `buildShellExportScript` + `akm env export`).
18
+ *
19
+ * Invariant: env values must never be written to stdout, returned through the
20
+ * indexer, the `akm show` renderer, or any structured output channel. Key
21
+ * NAMES and start-of-line comments ARE surfaced by design (discoverability) —
22
+ * only values are secret. The supported value-load paths are:
23
+ *
24
+ * - `akm env run <ref> -- <command>` — values injected into the child
25
+ * process env (never via a shell), see `injectIntoEnv` / `loadEnv`. This is
26
+ * the primary path and the only one safe for AI agents (no values ever
27
+ * reach stdout). For an interactive shell, `akm env run <ref> -- $SHELL`.
28
+ * - `akm env export <ref> --out <file>` — write parse-then-reserialized safe
29
+ * `export KEY='value'` lines to a file (mode 0600) for `source`-ing. Values
30
+ * are re-emitted single-quoted so a raw `.env` containing `X=$(cmd)` cannot
31
+ * execute on load. `export` never prints values to stdout (would leak into
32
+ * an agent's context); `path` prints only the file path.
33
+ *
34
+ * Value parsing is delegated to the `dotenv` package — we deliberately do not
35
+ * implement our own quoting/escaping rules for security-sensitive content.
36
+ */
37
+ import fs from "node:fs";
38
+ import path from "node:path";
39
+ import dotenv from "dotenv";
40
+ import { writeFileAtomic } from "../core/common";
41
+ /** Matches a KEY=value assignment line, capturing only the key. */
42
+ const ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;
43
+ /** Scan lines and return KEY names in file order, without duplicates. */
44
+ function scanKeys(text) {
45
+ const keys = [];
46
+ const seen = new Set();
47
+ for (const line of text.split(/\r?\n/)) {
48
+ const m = line.match(ASSIGN_RE);
49
+ if (!m)
50
+ continue;
51
+ const key = m[1];
52
+ if (seen.has(key))
53
+ continue;
54
+ seen.add(key);
55
+ keys.push(key);
56
+ }
57
+ return keys;
58
+ }
59
+ /**
60
+ * Scan lines and return start-of-line `#` comments (with the leading `#` and
61
+ * any leading whitespace stripped). Inline/trailing `#` after an assignment is
62
+ * never extracted.
63
+ */
64
+ function scanComments(text) {
65
+ const comments = [];
66
+ for (const line of text.split(/\r?\n/)) {
67
+ const trimmed = line.trimStart();
68
+ if (trimmed.startsWith("#")) {
69
+ comments.push(trimmed.slice(1).trimStart());
70
+ }
71
+ }
72
+ return comments;
73
+ }
74
+ /**
75
+ * Read and return ONLY non-secret metadata (keys + start-of-line comments).
76
+ *
77
+ * The function reads the whole file into memory (same as any dotenv parser)
78
+ * but deliberately does not parse values — the LHS-only regex scanners above
79
+ * ensure no value content is retained or returned. The guarantee is that
80
+ * values never leave this function.
81
+ */
82
+ export function listKeys(envPath) {
83
+ if (!fs.existsSync(envPath))
84
+ return { keys: [], comments: [] };
85
+ const text = fs.readFileSync(envPath, "utf8");
86
+ return { keys: scanKeys(text), comments: scanComments(text) };
87
+ }
88
+ /**
89
+ * Return structured `entries` pairing each key with the nearest preceding
90
+ * comment line (if any). This is an easier-to-consume shape than the parallel
91
+ * `keys[]` + `comments[]` of `listKeys` (QA #35).
92
+ *
93
+ * Values are never included — the same privacy guarantee as `listKeys`.
94
+ */
95
+ export function listEntries(envPath) {
96
+ if (!fs.existsSync(envPath))
97
+ return [];
98
+ const text = fs.readFileSync(envPath, "utf8");
99
+ const lines = text.split(/\r?\n/);
100
+ const seen = new Set();
101
+ const entries = [];
102
+ let pendingComment;
103
+ for (const line of lines) {
104
+ const trimmed = line.trimStart();
105
+ if (trimmed.startsWith("#")) {
106
+ // Capture the most recent comment before a key
107
+ pendingComment = trimmed.slice(1).trimStart() || undefined;
108
+ continue;
109
+ }
110
+ const m = line.match(ASSIGN_RE);
111
+ if (m) {
112
+ const key = m[1];
113
+ if (!seen.has(key)) {
114
+ seen.add(key);
115
+ const entry = { key };
116
+ if (pendingComment)
117
+ entry.comment = pendingComment;
118
+ entries.push(entry);
119
+ }
120
+ pendingComment = undefined;
121
+ }
122
+ else {
123
+ // Any non-comment, non-assignment line (including blank lines)
124
+ // breaks "nearest preceding comment line" association.
125
+ pendingComment = undefined;
126
+ }
127
+ }
128
+ return entries;
129
+ }
130
+ /**
131
+ * Read all KEY=value pairs from an env file. Intended for programmatic callers
132
+ * that need to inject values into a process environment. Callers MUST NOT write
133
+ * the returned values to stdout or any logged output.
134
+ *
135
+ * Value parsing (quoting, escapes, multi-line, etc.) is delegated to dotenv.
136
+ */
137
+ export function loadEnv(envPath) {
138
+ if (!fs.existsSync(envPath))
139
+ return {};
140
+ const buf = fs.readFileSync(envPath);
141
+ return dotenv.parse(buf);
142
+ }
143
+ /**
144
+ * Load an env file and assign its values into `target` (defaults to
145
+ * `process.env`). Returns the list of keys that were set so the caller can
146
+ * log/observe without touching values.
147
+ *
148
+ * Existing keys in `target` are overwritten — callers who want to preserve
149
+ * pre-existing environment variables should filter before calling.
150
+ */
151
+ export function injectIntoEnv(envPath, target = process.env) {
152
+ const env = loadEnv(envPath);
153
+ for (const [key, value] of Object.entries(env)) {
154
+ target[key] = value;
155
+ }
156
+ return Object.keys(env);
157
+ }
158
+ /**
159
+ * Serialise an env file's values as a POSIX shell script of `export KEY='value'`
160
+ * lines, with single-quote escaping (`'\''`). Every line is an assignment of a
161
+ * literal string — there is no expansion, command substitution, or
162
+ * non-assignment content, so `eval`-ing the output is safe regardless of what
163
+ * the source file contains.
164
+ *
165
+ * This is the trust boundary for shell loading: a raw `.env` may contain
166
+ * `X=$(rm -rf ~)`, which would execute if `source`d directly, but dotenv parses
167
+ * it to the literal string `$(rm -rf ~)` and we re-emit it single-quoted. This
168
+ * backs `akm env export <ref> --out <file>` (file-only; never printed to stdout).
169
+ */
170
+ export function buildShellExportScript(envPath) {
171
+ const env = loadEnv(envPath);
172
+ const lines = [];
173
+ for (const [key, value] of Object.entries(env)) {
174
+ // Defence in depth: dotenv already validates key shape, but reject any
175
+ // key we wouldn't be able to export safely.
176
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
177
+ continue;
178
+ const escaped = value.replace(/'/g, "'\\''");
179
+ lines.push(`export ${key}='${escaped}'`);
180
+ }
181
+ return lines.length > 0 ? `${lines.join("\n")}\n` : "";
182
+ }
183
+ /** Create an empty env file (does nothing if it already exists). */
184
+ export function createEnv(envPath) {
185
+ ensureParentDir(envPath);
186
+ if (fs.existsSync(envPath))
187
+ return;
188
+ writeFileAtomic(envPath, "", 0o600);
189
+ }
190
+ /**
191
+ * Write (create or overwrite) an env file with the given text content,
192
+ * atomically at mode 0600. Used to ingest an existing `.env` file
193
+ * (`env create --from-file` / `--from-stdin`).
194
+ */
195
+ export function writeEnv(envPath, content) {
196
+ ensureParentDir(envPath);
197
+ writeFileAtomic(envPath, content, 0o600);
198
+ }
199
+ /** Remove an env file (and its `.sensitive` marker, if present). Returns true if it existed. */
200
+ export function removeEnv(envPath) {
201
+ if (!fs.existsSync(envPath))
202
+ return false;
203
+ fs.rmSync(envPath);
204
+ const marker = `${envPath}.sensitive`;
205
+ if (fs.existsSync(marker))
206
+ fs.rmSync(marker);
207
+ return true;
208
+ }
209
+ function ensureParentDir(filePath) {
210
+ const dir = path.dirname(filePath);
211
+ if (!fs.existsSync(dir))
212
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
213
+ }
@@ -1,3 +1,6 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
1
4
  import fs from "node:fs";
2
5
  import path from "node:path";
3
6
  import { writeFileAtomic } from "../core/common";
@@ -1,3 +1,6 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
1
4
  /**
2
5
  * `akm events list` and `akm events tail` (#204).
3
6
  *
@@ -0,0 +1,127 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+ /**
5
+ * CLI surface for `akm extract`.
6
+ *
7
+ * Examples:
8
+ * akm extract --type claude-code --session-id <id>
9
+ * akm extract --type claude-code --since 24h
10
+ * akm extract --type opencode --since 7d --dry-run
11
+ * akm extract --auto # iterate all available harnesses
12
+ * akm extract --type claude-code --location /custom/path --session-id <id>
13
+ *
14
+ * Output is the AkmExtractResult JSON envelope (or an aggregated one when
15
+ * `--auto` runs multiple harnesses).
16
+ */
17
+ import { defineCommand } from "citty";
18
+ import { output, runWithJsonErrors } from "../cli/shared";
19
+ import { UsageError } from "../core/errors";
20
+ import { getAvailableHarnesses } from "../integrations/session-logs";
21
+ import { akmExtract } from "./extract";
22
+ export const extractCommand = defineCommand({
23
+ meta: {
24
+ name: "extract",
25
+ description: "Extract durable insights from native session files (claude-code, opencode) and queue them as proposals. Replaces the legacy session-checkpoint hook.",
26
+ },
27
+ args: {
28
+ type: {
29
+ type: "string",
30
+ description: "Harness name (claude-code, opencode). Required unless --auto.",
31
+ },
32
+ "session-id": {
33
+ type: "string",
34
+ description: "Process only this session ID. When absent, discover sessions via --since.",
35
+ },
36
+ location: {
37
+ type: "string",
38
+ description: "Override the harness's default session-discovery location.",
39
+ },
40
+ since: {
41
+ type: "string",
42
+ description: "Discovery cutoff. ISO timestamp or duration (24h, 7d, 30m). Default 24h.",
43
+ },
44
+ auto: {
45
+ type: "boolean",
46
+ description: "Iterate every available harness with default --since. Mutually exclusive with --type.",
47
+ default: false,
48
+ },
49
+ "dry-run": {
50
+ type: "boolean",
51
+ description: "Show candidates without queuing proposals.",
52
+ default: false,
53
+ },
54
+ force: {
55
+ type: "boolean",
56
+ description: "Re-process sessions even if they were already extracted and have no new events. Default: skip already-seen sessions.",
57
+ default: false,
58
+ },
59
+ "timeout-ms": {
60
+ type: "string",
61
+ description: "Per-session LLM timeout in ms (default 60000).",
62
+ },
63
+ },
64
+ async run({ args }) {
65
+ await runWithJsonErrors(async () => {
66
+ const type = typeof args.type === "string" ? args.type.trim() : "";
67
+ const sessionId = typeof args["session-id"] === "string" ? args["session-id"].trim() : "";
68
+ const location = typeof args.location === "string" ? args.location.trim() : "";
69
+ const since = typeof args.since === "string" ? args.since.trim() : "";
70
+ const auto = args.auto === true;
71
+ const dryRun = args["dry-run"] === true;
72
+ const force = args.force === true;
73
+ const timeoutMs = typeof args["timeout-ms"] === "string" && args["timeout-ms"] !== ""
74
+ ? Number.parseInt(args["timeout-ms"], 10)
75
+ : undefined;
76
+ if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
77
+ throw new UsageError(`--timeout-ms must be a positive integer (got "${args["timeout-ms"]}").`, "INVALID_FLAG_VALUE");
78
+ }
79
+ if (auto && type) {
80
+ throw new UsageError("--auto and --type are mutually exclusive. Pick one.", "INVALID_FLAG_VALUE");
81
+ }
82
+ if (!auto && !type) {
83
+ throw new UsageError("--type is required (or pass --auto to try every available harness).", "MISSING_REQUIRED_ARGUMENT");
84
+ }
85
+ const commonOptions = {
86
+ ...(sessionId ? { sessionId } : {}),
87
+ ...(location ? { location } : {}),
88
+ ...(since ? { since } : {}),
89
+ dryRun,
90
+ force,
91
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
92
+ };
93
+ if (auto) {
94
+ const harnesses = getAvailableHarnesses();
95
+ if (harnesses.length === 0) {
96
+ output("extract", {
97
+ schemaVersion: 1,
98
+ ok: false,
99
+ shape: "extract-auto-result",
100
+ warnings: ["no available harnesses found on this machine"],
101
+ results: [],
102
+ });
103
+ return;
104
+ }
105
+ const results = [];
106
+ for (const h of harnesses) {
107
+ const result = await akmExtract({ type: h.name, ...commonOptions });
108
+ results.push(result);
109
+ }
110
+ const ok = results.every((r) => r.ok);
111
+ const totalProposals = results.reduce((sum, r) => sum + r.proposals.length, 0);
112
+ output("extract", {
113
+ schemaVersion: 1,
114
+ ok,
115
+ shape: "extract-auto-result",
116
+ dryRun,
117
+ harnessesProcessed: results.length,
118
+ totalProposals,
119
+ results,
120
+ });
121
+ return;
122
+ }
123
+ const result = await akmExtract({ type, ...commonOptions });
124
+ output("extract", result);
125
+ });
126
+ },
127
+ });
@@ -0,0 +1,217 @@
1
+ // This Source Code Form is subject to the terms of the Mozilla Public
2
+ // License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
+ /**
5
+ * Prompt + schema for `akm extract <session>`.
6
+ *
7
+ * Mirrors the REFLECT_JSON_SCHEMA pattern: a strict JSON Schema describing
8
+ * the LLM output, plus a {@link buildExtractPrompt} helper that interpolates
9
+ * session data into the markdown template loaded from
10
+ * `src/assets/prompts/extract-session.md`.
11
+ *
12
+ * The schema is intentionally strict — providers with `supportsJsonSchema:
13
+ * true` enforce shape upstream, so the parser only has to handle the
14
+ * happy path. `additionalProperties: false` means any hallucinated keys
15
+ * the model emits get dropped before we parse.
16
+ */
17
+ import promptTemplate from "../assets/prompts/extract-session.md" with { type: "text" };
18
+ /**
19
+ * JSON Schema for the structured extract output. Passed to `chatCompletion`
20
+ * when the configured LLM connection has `supportsJsonSchema: true`.
21
+ *
22
+ * Shape:
23
+ * {
24
+ * "candidates": [{type, name, description, when_to_use?, body, confidence, evidence}, ...],
25
+ * "rationale_if_empty"?: string
26
+ * }
27
+ *
28
+ * `additionalProperties: false` at each level so any hallucinated keys are
29
+ * dropped before parsing.
30
+ */
31
+ export const EXTRACT_JSON_SCHEMA = {
32
+ type: "object",
33
+ required: ["candidates"],
34
+ additionalProperties: false,
35
+ properties: {
36
+ candidates: {
37
+ type: "array",
38
+ description: "Zero or more durable-insight candidates extracted from the session.",
39
+ items: {
40
+ type: "object",
41
+ required: ["type", "name", "description", "body", "confidence", "evidence"],
42
+ additionalProperties: false,
43
+ properties: {
44
+ type: {
45
+ type: "string",
46
+ enum: ["memory", "lesson", "knowledge"],
47
+ description: "Asset type the candidate would land as.",
48
+ },
49
+ name: {
50
+ type: "string",
51
+ description: "Kebab-case slug for the new asset.",
52
+ pattern: "^[a-z0-9][a-z0-9-]*[a-z0-9]$",
53
+ },
54
+ description: {
55
+ type: "string",
56
+ minLength: 20,
57
+ maxLength: 400,
58
+ description: "One-sentence summary of the candidate.",
59
+ },
60
+ when_to_use: {
61
+ type: "string",
62
+ minLength: 15,
63
+ maxLength: 400,
64
+ description: "Trigger sentence for the candidate; REQUIRED when type=lesson.",
65
+ },
66
+ body: {
67
+ type: "string",
68
+ minLength: 50,
69
+ description: "Markdown body of the candidate asset.",
70
+ },
71
+ confidence: {
72
+ type: "number",
73
+ minimum: 0,
74
+ maximum: 1,
75
+ description: "Self-rated confidence in [0, 1] that this candidate is a real durable insight.",
76
+ },
77
+ evidence: {
78
+ type: "string",
79
+ minLength: 5,
80
+ description: "One-line pointer to the moment in the session that supports this candidate.",
81
+ },
82
+ },
83
+ },
84
+ },
85
+ rationale_if_empty: {
86
+ type: "string",
87
+ minLength: 10,
88
+ description: "Required when `candidates` is empty — explains why nothing rose to durable-insight level.",
89
+ },
90
+ },
91
+ };
92
+ /**
93
+ * Format inline refs as a bullet list for the "Already preserved" section.
94
+ * If empty, returns a sentinel string so the LLM knows the agent saved
95
+ * nothing inline.
96
+ */
97
+ function formatAlreadyPreserved(inlineRefs) {
98
+ if (inlineRefs.length === 0) {
99
+ return "(none — the agent did not call `akm remember` or `akm feedback` during this session)";
100
+ }
101
+ return inlineRefs
102
+ .map((ref) => {
103
+ const prefix = ref.kind === "remember" ? "- remember:" : `- feedback ${ref.ref ?? "<ref>"}:`;
104
+ const body = ref.text.trim().slice(0, 200);
105
+ return `${prefix} ${body}${ref.text.length > 200 ? "…" : ""}`;
106
+ })
107
+ .join("\n");
108
+ }
109
+ /**
110
+ * Format pre-filtered events as a transcript snippet. Each event becomes:
111
+ * [<role> @ <iso>] <text>
112
+ * Events are already truncated/cleaned by the pre-filter; this is purely
113
+ * a render step.
114
+ */
115
+ function formatTranscript(events) {
116
+ if (events.length === 0)
117
+ return "(empty — pre-filter removed all events as noise)";
118
+ return events
119
+ .map((e) => {
120
+ const tsLabel = e.ts ? new Date(e.ts).toISOString() : "unknown-ts";
121
+ const roleLabel = e.role ?? "unknown";
122
+ return `[${roleLabel} @ ${tsLabel}] ${e.text}`;
123
+ })
124
+ .join("\n\n");
125
+ }
126
+ /**
127
+ * Build the user-prompt body for the extract LLM call by interpolating
128
+ * session metadata, already-preserved refs, and the filtered transcript
129
+ * into the template.
130
+ */
131
+ export function buildExtractPrompt(input) {
132
+ const ref = input.data.ref;
133
+ const startedAt = ref.startedAt ? new Date(ref.startedAt).toISOString() : "unknown";
134
+ const endedAt = ref.endedAt ? new Date(ref.endedAt).toISOString() : "unknown";
135
+ return promptTemplate
136
+ .replace("{{HARNESS}}", ref.harness)
137
+ .replace("{{TITLE}}", ref.title ?? "(no title)")
138
+ .replace("{{STARTED_AT}}", startedAt)
139
+ .replace("{{ENDED_AT}}", endedAt)
140
+ .replace("{{PROJECT_HINT}}", ref.projectHint ?? "(no project hint)")
141
+ .replace("{{ALREADY_PRESERVED}}", formatAlreadyPreserved(input.inlineRefs))
142
+ .replace("{{TRANSCRIPT}}", formatTranscript(input.events));
143
+ }
144
+ /**
145
+ * Parse the LLM's JSON response into a structured {@link ExtractPayload}.
146
+ * Defensive — drops candidates that violate the shape rather than failing
147
+ * the whole call. Returns the empty-candidates payload when nothing parses.
148
+ */
149
+ export function parseExtractPayload(stdout) {
150
+ if (!stdout || stdout.trim().length === 0) {
151
+ return { candidates: [], rationale_if_empty: "LLM returned empty response" };
152
+ }
153
+ let parsed;
154
+ try {
155
+ parsed = JSON.parse(stdout);
156
+ }
157
+ catch {
158
+ // Tolerate prose preamble/postamble by extracting the first balanced
159
+ // top-level JSON object.
160
+ const start = stdout.indexOf("{");
161
+ const end = stdout.lastIndexOf("}");
162
+ if (start === -1 || end <= start) {
163
+ return { candidates: [], rationale_if_empty: `LLM response was not parseable JSON` };
164
+ }
165
+ try {
166
+ parsed = JSON.parse(stdout.slice(start, end + 1));
167
+ }
168
+ catch {
169
+ return { candidates: [], rationale_if_empty: `LLM response was not parseable JSON` };
170
+ }
171
+ }
172
+ if (!parsed || typeof parsed !== "object") {
173
+ return { candidates: [], rationale_if_empty: "LLM response was not an object" };
174
+ }
175
+ const obj = parsed;
176
+ const rawCandidates = Array.isArray(obj.candidates) ? obj.candidates : [];
177
+ const candidates = [];
178
+ for (const raw of rawCandidates) {
179
+ if (!raw || typeof raw !== "object")
180
+ continue;
181
+ const c = raw;
182
+ const type = c.type;
183
+ if (type !== "memory" && type !== "lesson" && type !== "knowledge")
184
+ continue;
185
+ if (typeof c.name !== "string" || !/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(c.name))
186
+ continue;
187
+ if (typeof c.description !== "string" || c.description.trim().length < 20)
188
+ continue;
189
+ if (typeof c.body !== "string" || c.body.trim().length < 50)
190
+ continue;
191
+ if (typeof c.confidence !== "number" || !Number.isFinite(c.confidence))
192
+ continue;
193
+ if (typeof c.evidence !== "string" || c.evidence.trim().length < 5)
194
+ continue;
195
+ if (type === "lesson") {
196
+ if (typeof c.when_to_use !== "string" || c.when_to_use.trim().length < 15)
197
+ continue;
198
+ }
199
+ const confidence = Math.max(0, Math.min(1, c.confidence));
200
+ const candidate = {
201
+ type,
202
+ name: c.name,
203
+ description: c.description.trim(),
204
+ body: c.body,
205
+ confidence,
206
+ evidence: c.evidence.trim(),
207
+ };
208
+ if (typeof c.when_to_use === "string")
209
+ candidate.when_to_use = c.when_to_use.trim();
210
+ candidates.push(candidate);
211
+ }
212
+ const result = { candidates };
213
+ if (typeof obj.rationale_if_empty === "string") {
214
+ result.rationale_if_empty = obj.rationale_if_empty.trim();
215
+ }
216
+ return result;
217
+ }