akm-cli 0.8.0-rc2 → 0.8.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 (295) hide show
  1. package/{.github/CHANGELOG.md → CHANGELOG.md} +191 -3
  2. package/README.md +22 -6
  3. package/SECURITY.md +93 -0
  4. package/dist/cli/config-migrate.js +144 -0
  5. package/dist/cli/config-validate.js +39 -0
  6. package/dist/cli/confirm.js +73 -0
  7. package/dist/cli/parse-args.js +93 -3
  8. package/dist/cli/shared.js +129 -0
  9. package/dist/cli.js +2141 -1268
  10. package/dist/commands/add-cli.js +279 -0
  11. package/dist/commands/agent-dispatch.js +20 -12
  12. package/dist/commands/agent-support.js +11 -5
  13. package/dist/commands/completions.js +3 -0
  14. package/dist/commands/config-cli.js +129 -517
  15. package/dist/commands/consolidate.js +1533 -144
  16. package/dist/commands/curate.js +44 -3
  17. package/dist/commands/db-cli.js +23 -0
  18. package/dist/commands/distill-promotion-policy.js +5 -3
  19. package/dist/commands/distill.js +906 -100
  20. package/dist/commands/env.js +213 -0
  21. package/dist/commands/eval-cases.js +3 -0
  22. package/dist/commands/events.js +3 -0
  23. package/dist/commands/extract-cli.js +127 -0
  24. package/dist/commands/extract-prompt.js +204 -0
  25. package/dist/commands/extract.js +477 -0
  26. package/dist/commands/feedback-cli.js +331 -0
  27. package/dist/commands/graph.js +260 -5
  28. package/dist/commands/health.js +977 -51
  29. package/dist/commands/help/help-accept.md +6 -3
  30. package/dist/commands/help/help-improve.md +36 -8
  31. package/dist/commands/help/help-proposals.md +7 -4
  32. package/dist/commands/help/help-reject.md +5 -2
  33. package/dist/commands/history.js +51 -16
  34. package/dist/commands/improve-auto-accept.js +97 -0
  35. package/dist/commands/improve-cli.js +236 -0
  36. package/dist/commands/improve-profiles.js +184 -0
  37. package/dist/commands/improve-result-file.js +167 -0
  38. package/dist/commands/improve.js +1725 -332
  39. package/dist/commands/info.js +3 -0
  40. package/dist/commands/init.js +49 -1
  41. package/dist/commands/installed-stashes.js +6 -23
  42. package/dist/commands/knowledge.js +3 -0
  43. package/dist/commands/lint/agent-linter.js +3 -0
  44. package/dist/commands/lint/base-linter.js +199 -5
  45. package/dist/commands/lint/command-linter.js +3 -0
  46. package/dist/commands/lint/default-linter.js +3 -0
  47. package/dist/commands/lint/env-key-rules.js +154 -0
  48. package/dist/commands/lint/index.js +92 -3
  49. package/dist/commands/lint/knowledge-linter.js +3 -0
  50. package/dist/commands/lint/markdown-insertion.js +343 -0
  51. package/dist/commands/lint/memory-linter.js +3 -0
  52. package/dist/commands/lint/registry.js +3 -0
  53. package/dist/commands/lint/skill-linter.js +3 -0
  54. package/dist/commands/lint/task-linter.js +15 -12
  55. package/dist/commands/lint/types.js +3 -0
  56. package/dist/commands/lint/workflow-linter.js +3 -0
  57. package/dist/commands/lint.js +3 -0
  58. package/dist/commands/migration-help.js +5 -2
  59. package/dist/commands/proposal-drain-policies.js +128 -0
  60. package/dist/commands/proposal-drain.js +477 -0
  61. package/dist/commands/proposal.js +60 -6
  62. package/dist/commands/propose.js +24 -19
  63. package/dist/commands/reflect.js +1004 -94
  64. package/dist/commands/registry-cli.js +150 -0
  65. package/dist/commands/registry-search.js +3 -0
  66. package/dist/commands/remember-cli.js +257 -0
  67. package/dist/commands/remember.js +15 -6
  68. package/dist/commands/schema-repair.js +88 -15
  69. package/dist/commands/search.js +99 -14
  70. package/dist/commands/secret.js +173 -0
  71. package/dist/commands/self-update.js +3 -0
  72. package/dist/commands/show.js +32 -13
  73. package/dist/commands/source-add.js +7 -35
  74. package/dist/commands/source-clone.js +3 -0
  75. package/dist/commands/source-manage.js +3 -0
  76. package/dist/commands/tasks.js +161 -95
  77. package/dist/commands/url-checker.js +3 -0
  78. package/dist/core/action-contributors.js +3 -0
  79. package/dist/core/asset-ref.js +13 -2
  80. package/dist/core/asset-registry.js +9 -2
  81. package/dist/core/asset-serialize.js +88 -0
  82. package/dist/core/asset-spec.js +61 -5
  83. package/dist/core/common.js +93 -5
  84. package/dist/core/concurrent.js +3 -0
  85. package/dist/core/config-io.js +347 -0
  86. package/dist/core/config-migration.js +622 -0
  87. package/dist/core/config-schema.js +558 -0
  88. package/dist/core/config-sources.js +108 -0
  89. package/dist/core/config-types.js +4 -0
  90. package/dist/core/config-walker.js +337 -0
  91. package/dist/core/config.js +366 -1077
  92. package/dist/core/errors.js +42 -20
  93. package/dist/core/events.js +31 -25
  94. package/dist/core/file-lock.js +104 -0
  95. package/dist/core/frontmatter.js +75 -10
  96. package/dist/core/lesson-lint.js +3 -0
  97. package/dist/core/markdown.js +3 -0
  98. package/dist/core/memory-belief.js +62 -0
  99. package/dist/core/memory-contradiction-detect.js +274 -0
  100. package/dist/core/memory-improve.js +142 -14
  101. package/dist/core/parse.js +3 -0
  102. package/dist/core/paths.js +218 -50
  103. package/dist/core/proposal-quality-validators.js +380 -0
  104. package/dist/core/proposal-validators.js +11 -3
  105. package/dist/core/proposals.js +464 -5
  106. package/dist/core/state-db.js +349 -56
  107. package/dist/core/text-truncation.js +107 -0
  108. package/dist/core/time.js +3 -0
  109. package/dist/core/tty.js +59 -0
  110. package/dist/core/warn.js +7 -2
  111. package/dist/core/write-source.js +12 -0
  112. package/dist/indexer/db-backup.js +391 -0
  113. package/dist/indexer/db-search.js +136 -28
  114. package/dist/indexer/db.js +661 -166
  115. package/dist/indexer/ensure-index.js +3 -0
  116. package/dist/indexer/file-context.js +3 -0
  117. package/dist/indexer/graph-boost.js +162 -40
  118. package/dist/indexer/graph-db.js +241 -51
  119. package/dist/indexer/graph-dedup.js +3 -7
  120. package/dist/indexer/graph-extraction.js +242 -149
  121. package/dist/indexer/index-context.js +3 -9
  122. package/dist/indexer/indexer.js +84 -14
  123. package/dist/indexer/llm-cache.js +24 -19
  124. package/dist/indexer/manifest.js +3 -0
  125. package/dist/indexer/matchers.js +184 -11
  126. package/dist/indexer/memory-inference.js +94 -50
  127. package/dist/indexer/metadata-contributors.js +3 -0
  128. package/dist/indexer/metadata.js +110 -50
  129. package/dist/indexer/path-resolver.js +3 -0
  130. package/dist/indexer/project-context.js +192 -0
  131. package/dist/indexer/ranking-contributors.js +134 -7
  132. package/dist/indexer/ranking.js +8 -1
  133. package/dist/indexer/search-fields.js +5 -9
  134. package/dist/indexer/search-hit-enrichers.js +91 -2
  135. package/dist/indexer/search-source.js +20 -1
  136. package/dist/indexer/semantic-status.js +4 -1
  137. package/dist/indexer/staleness-detect.js +447 -0
  138. package/dist/indexer/usage-events.js +12 -9
  139. package/dist/indexer/walker.js +3 -0
  140. package/dist/integrations/agent/builders.js +135 -0
  141. package/dist/integrations/agent/config.js +121 -401
  142. package/dist/integrations/agent/detect.js +3 -0
  143. package/dist/integrations/agent/index.js +6 -14
  144. package/dist/integrations/agent/model-aliases.js +55 -0
  145. package/dist/integrations/agent/profiles.js +3 -0
  146. package/dist/integrations/agent/prompts.js +137 -8
  147. package/dist/integrations/agent/runner.js +208 -0
  148. package/dist/integrations/agent/sdk-runner.js +8 -2
  149. package/dist/integrations/agent/spawn.js +54 -14
  150. package/dist/integrations/github.js +3 -0
  151. package/dist/integrations/lockfile.js +22 -51
  152. package/dist/integrations/session-logs/index.js +4 -0
  153. package/dist/integrations/session-logs/inline-refs.js +35 -0
  154. package/dist/integrations/session-logs/pre-filter.js +152 -0
  155. package/dist/integrations/session-logs/providers/claude-code.js +226 -0
  156. package/dist/integrations/session-logs/providers/opencode.js +231 -25
  157. package/dist/integrations/session-logs/types.js +3 -0
  158. package/dist/llm/call-ai.js +14 -26
  159. package/dist/llm/client.js +16 -2
  160. package/dist/llm/embedder.js +20 -29
  161. package/dist/llm/embedders/cache.js +3 -7
  162. package/dist/llm/embedders/local.js +42 -1
  163. package/dist/llm/embedders/remote.js +20 -8
  164. package/dist/llm/embedders/types.js +3 -7
  165. package/dist/llm/feature-gate.js +92 -56
  166. package/dist/llm/graph-extract.js +401 -30
  167. package/dist/llm/index-passes.js +44 -29
  168. package/dist/llm/memory-infer.js +30 -2
  169. package/dist/llm/metadata-enhance.js +3 -7
  170. package/dist/llm/prompts/extract-session.md +80 -0
  171. package/dist/llm/prompts/graph-extract-user-prompt.md +24 -1
  172. package/dist/output/cli-hints-full.md +60 -32
  173. package/dist/output/cli-hints-short.md +10 -7
  174. package/dist/output/cli-hints.js +5 -2
  175. package/dist/output/context.js +60 -8
  176. package/dist/output/renderers.js +170 -194
  177. package/dist/output/shapes/curate.js +56 -0
  178. package/dist/output/shapes/distill.js +10 -0
  179. package/dist/output/shapes/env-list.js +19 -0
  180. package/dist/output/shapes/events.js +11 -0
  181. package/dist/output/shapes/helpers.js +424 -0
  182. package/dist/output/shapes/history.js +7 -0
  183. package/dist/output/shapes/passthrough.js +105 -0
  184. package/dist/output/shapes/proposal-accept.js +7 -0
  185. package/dist/output/shapes/proposal-diff.js +7 -0
  186. package/dist/output/shapes/proposal-list.js +7 -0
  187. package/dist/output/shapes/proposal-producer.js +11 -0
  188. package/dist/output/shapes/proposal-reject.js +7 -0
  189. package/dist/output/shapes/proposal-show.js +7 -0
  190. package/dist/output/shapes/registry-search.js +6 -0
  191. package/dist/output/shapes/registry.js +30 -0
  192. package/dist/output/shapes/search.js +6 -0
  193. package/dist/output/shapes/secret-list.js +19 -0
  194. package/dist/output/shapes/show.js +6 -0
  195. package/dist/output/shapes/vault-list.js +19 -0
  196. package/dist/output/shapes.js +51 -549
  197. package/dist/output/text/add.js +6 -0
  198. package/dist/output/text/clone.js +6 -0
  199. package/dist/output/text/config.js +6 -0
  200. package/dist/output/text/curate.js +6 -0
  201. package/dist/output/text/distill.js +7 -0
  202. package/dist/output/text/enable-disable.js +7 -0
  203. package/dist/output/text/events.js +10 -0
  204. package/dist/output/text/feedback.js +6 -0
  205. package/dist/output/text/helpers.js +1059 -0
  206. package/dist/output/text/history.js +7 -0
  207. package/dist/output/text/import.js +6 -0
  208. package/dist/output/text/index.js +6 -0
  209. package/dist/output/text/info.js +6 -0
  210. package/dist/output/text/init.js +6 -0
  211. package/dist/output/text/list.js +6 -0
  212. package/dist/output/text/proposal-producer.js +8 -0
  213. package/dist/output/text/proposal.js +12 -0
  214. package/dist/output/text/registry-commands.js +11 -0
  215. package/dist/output/text/registry.js +30 -0
  216. package/dist/output/text/remember.js +6 -0
  217. package/dist/output/text/remove.js +6 -0
  218. package/dist/output/text/save.js +6 -0
  219. package/dist/output/text/search.js +6 -0
  220. package/dist/output/text/show.js +6 -0
  221. package/dist/output/text/update.js +6 -0
  222. package/dist/output/text/upgrade.js +6 -0
  223. package/dist/output/text/vault.js +16 -0
  224. package/dist/output/text/wiki.js +15 -0
  225. package/dist/output/text/workflow.js +14 -0
  226. package/dist/output/text.js +44 -1329
  227. package/dist/registry/build-index.js +3 -0
  228. package/dist/registry/create-provider-registry.js +3 -0
  229. package/dist/registry/factory.js +4 -1
  230. package/dist/registry/origin-resolve.js +3 -0
  231. package/dist/registry/providers/index.js +3 -0
  232. package/dist/registry/providers/skills-sh.js +11 -2
  233. package/dist/registry/providers/static-index.js +10 -1
  234. package/dist/registry/providers/types.js +3 -24
  235. package/dist/registry/resolve.js +11 -16
  236. package/dist/registry/types.js +3 -0
  237. package/dist/scripts/migrate-storage.js +17767 -0
  238. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +9031 -0
  239. package/dist/scripts/migrations/v16-to-v17.js +141 -0
  240. package/dist/setup/detect.js +3 -0
  241. package/dist/setup/ripgrep-install.js +3 -0
  242. package/dist/setup/ripgrep-resolve.js +3 -0
  243. package/dist/setup/setup.js +306 -67
  244. package/dist/setup/steps.js +3 -15
  245. package/dist/sources/include.js +3 -0
  246. package/dist/sources/provider-factory.js +3 -11
  247. package/dist/sources/provider.js +3 -20
  248. package/dist/sources/providers/filesystem.js +19 -23
  249. package/dist/sources/providers/git.js +171 -21
  250. package/dist/sources/providers/index.js +3 -0
  251. package/dist/sources/providers/install-types.js +3 -13
  252. package/dist/sources/providers/npm.js +3 -4
  253. package/dist/sources/providers/provider-utils.js +3 -0
  254. package/dist/sources/providers/sync-from-ref.js +3 -11
  255. package/dist/sources/providers/tar-utils.js +3 -0
  256. package/dist/sources/providers/website.js +18 -22
  257. package/dist/sources/resolve.js +3 -0
  258. package/dist/sources/types.js +3 -0
  259. package/dist/sources/website-ingest.js +3 -0
  260. package/dist/tasks/backends/cron.js +3 -0
  261. package/dist/tasks/backends/exec-utils.js +3 -0
  262. package/dist/tasks/backends/index.js +3 -11
  263. package/dist/tasks/backends/launchd.js +3 -0
  264. package/dist/tasks/backends/schtasks.js +3 -0
  265. package/dist/tasks/parser.js +51 -38
  266. package/dist/tasks/resolveAkmBin.js +3 -0
  267. package/dist/tasks/runner.js +35 -9
  268. package/dist/tasks/schedule.js +20 -1
  269. package/dist/tasks/schema.js +5 -3
  270. package/dist/tasks/validator.js +6 -3
  271. package/dist/version.js +3 -0
  272. package/dist/wiki/wiki-templates.js +3 -0
  273. package/dist/wiki/wiki.js +3 -0
  274. package/dist/workflows/authoring.js +3 -0
  275. package/dist/workflows/cli.js +3 -0
  276. package/dist/workflows/db.js +140 -10
  277. package/dist/workflows/document-cache.js +3 -10
  278. package/dist/workflows/parser.js +3 -0
  279. package/dist/workflows/renderer.js +3 -0
  280. package/dist/workflows/runs.js +18 -1
  281. package/dist/workflows/schema.js +3 -0
  282. package/dist/workflows/scope-key.js +3 -0
  283. package/dist/workflows/validator.js +5 -9
  284. package/docs/README.md +7 -2
  285. package/docs/data-and-telemetry.md +225 -0
  286. package/docs/migration/release-notes/0.7.5.md +2 -2
  287. package/docs/migration/release-notes/0.8.0.md +57 -5
  288. package/docs/migration/v0.7-to-v0.8.md +1378 -0
  289. package/package.json +28 -11
  290. package/.github/LICENSE +0 -374
  291. package/dist/commands/install-audit.js +0 -385
  292. package/dist/commands/vault.js +0 -310
  293. package/dist/indexer/match-contributors.js +0 -141
  294. package/dist/integrations/agent/pipeline.js +0 -39
  295. package/dist/integrations/agent/runners.js +0 -31
@@ -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,204 @@
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
+ import promptTemplate from "../llm/prompts/extract-session.md" with { type: "text" };
5
+ /**
6
+ * JSON Schema for the structured extract output. Passed to `chatCompletion`
7
+ * when the configured LLM connection has `supportsJsonSchema: true`.
8
+ *
9
+ * Shape:
10
+ * {
11
+ * "candidates": [{type, name, description, when_to_use?, body, confidence, evidence}, ...],
12
+ * "rationale_if_empty"?: string
13
+ * }
14
+ *
15
+ * `additionalProperties: false` at each level so any hallucinated keys are
16
+ * dropped before parsing.
17
+ */
18
+ export const EXTRACT_JSON_SCHEMA = {
19
+ type: "object",
20
+ required: ["candidates"],
21
+ additionalProperties: false,
22
+ properties: {
23
+ candidates: {
24
+ type: "array",
25
+ description: "Zero or more durable-insight candidates extracted from the session.",
26
+ items: {
27
+ type: "object",
28
+ required: ["type", "name", "description", "body", "confidence", "evidence"],
29
+ additionalProperties: false,
30
+ properties: {
31
+ type: {
32
+ type: "string",
33
+ enum: ["memory", "lesson", "knowledge"],
34
+ description: "Asset type the candidate would land as.",
35
+ },
36
+ name: {
37
+ type: "string",
38
+ description: "Kebab-case slug for the new asset.",
39
+ pattern: "^[a-z0-9][a-z0-9-]*[a-z0-9]$",
40
+ },
41
+ description: {
42
+ type: "string",
43
+ minLength: 20,
44
+ maxLength: 400,
45
+ description: "One-sentence summary of the candidate.",
46
+ },
47
+ when_to_use: {
48
+ type: "string",
49
+ minLength: 15,
50
+ maxLength: 400,
51
+ description: "Trigger sentence for the candidate; REQUIRED when type=lesson.",
52
+ },
53
+ body: {
54
+ type: "string",
55
+ minLength: 50,
56
+ description: "Markdown body of the candidate asset.",
57
+ },
58
+ confidence: {
59
+ type: "number",
60
+ minimum: 0,
61
+ maximum: 1,
62
+ description: "Self-rated confidence in [0, 1] that this candidate is a real durable insight.",
63
+ },
64
+ evidence: {
65
+ type: "string",
66
+ minLength: 5,
67
+ description: "One-line pointer to the moment in the session that supports this candidate.",
68
+ },
69
+ },
70
+ },
71
+ },
72
+ rationale_if_empty: {
73
+ type: "string",
74
+ minLength: 10,
75
+ description: "Required when `candidates` is empty — explains why nothing rose to durable-insight level.",
76
+ },
77
+ },
78
+ };
79
+ /**
80
+ * Format inline refs as a bullet list for the "Already preserved" section.
81
+ * If empty, returns a sentinel string so the LLM knows the agent saved
82
+ * nothing inline.
83
+ */
84
+ function formatAlreadyPreserved(inlineRefs) {
85
+ if (inlineRefs.length === 0) {
86
+ return "(none — the agent did not call `akm remember` or `akm feedback` during this session)";
87
+ }
88
+ return inlineRefs
89
+ .map((ref) => {
90
+ const prefix = ref.kind === "remember" ? "- remember:" : `- feedback ${ref.ref ?? "<ref>"}:`;
91
+ const body = ref.text.trim().slice(0, 200);
92
+ return `${prefix} ${body}${ref.text.length > 200 ? "…" : ""}`;
93
+ })
94
+ .join("\n");
95
+ }
96
+ /**
97
+ * Format pre-filtered events as a transcript snippet. Each event becomes:
98
+ * [<role> @ <iso>] <text>
99
+ * Events are already truncated/cleaned by the pre-filter; this is purely
100
+ * a render step.
101
+ */
102
+ function formatTranscript(events) {
103
+ if (events.length === 0)
104
+ return "(empty — pre-filter removed all events as noise)";
105
+ return events
106
+ .map((e) => {
107
+ const tsLabel = e.ts ? new Date(e.ts).toISOString() : "unknown-ts";
108
+ const roleLabel = e.role ?? "unknown";
109
+ return `[${roleLabel} @ ${tsLabel}] ${e.text}`;
110
+ })
111
+ .join("\n\n");
112
+ }
113
+ /**
114
+ * Build the user-prompt body for the extract LLM call by interpolating
115
+ * session metadata, already-preserved refs, and the filtered transcript
116
+ * into the template.
117
+ */
118
+ export function buildExtractPrompt(input) {
119
+ const ref = input.data.ref;
120
+ const startedAt = ref.startedAt ? new Date(ref.startedAt).toISOString() : "unknown";
121
+ const endedAt = ref.endedAt ? new Date(ref.endedAt).toISOString() : "unknown";
122
+ return promptTemplate
123
+ .replace("{{HARNESS}}", ref.harness)
124
+ .replace("{{TITLE}}", ref.title ?? "(no title)")
125
+ .replace("{{STARTED_AT}}", startedAt)
126
+ .replace("{{ENDED_AT}}", endedAt)
127
+ .replace("{{PROJECT_HINT}}", ref.projectHint ?? "(no project hint)")
128
+ .replace("{{ALREADY_PRESERVED}}", formatAlreadyPreserved(input.inlineRefs))
129
+ .replace("{{TRANSCRIPT}}", formatTranscript(input.events));
130
+ }
131
+ /**
132
+ * Parse the LLM's JSON response into a structured {@link ExtractPayload}.
133
+ * Defensive — drops candidates that violate the shape rather than failing
134
+ * the whole call. Returns the empty-candidates payload when nothing parses.
135
+ */
136
+ export function parseExtractPayload(stdout) {
137
+ if (!stdout || stdout.trim().length === 0) {
138
+ return { candidates: [], rationale_if_empty: "LLM returned empty response" };
139
+ }
140
+ let parsed;
141
+ try {
142
+ parsed = JSON.parse(stdout);
143
+ }
144
+ catch {
145
+ // Tolerate prose preamble/postamble by extracting the first balanced
146
+ // top-level JSON object.
147
+ const start = stdout.indexOf("{");
148
+ const end = stdout.lastIndexOf("}");
149
+ if (start === -1 || end <= start) {
150
+ return { candidates: [], rationale_if_empty: `LLM response was not parseable JSON` };
151
+ }
152
+ try {
153
+ parsed = JSON.parse(stdout.slice(start, end + 1));
154
+ }
155
+ catch {
156
+ return { candidates: [], rationale_if_empty: `LLM response was not parseable JSON` };
157
+ }
158
+ }
159
+ if (!parsed || typeof parsed !== "object") {
160
+ return { candidates: [], rationale_if_empty: "LLM response was not an object" };
161
+ }
162
+ const obj = parsed;
163
+ const rawCandidates = Array.isArray(obj.candidates) ? obj.candidates : [];
164
+ const candidates = [];
165
+ for (const raw of rawCandidates) {
166
+ if (!raw || typeof raw !== "object")
167
+ continue;
168
+ const c = raw;
169
+ const type = c.type;
170
+ if (type !== "memory" && type !== "lesson" && type !== "knowledge")
171
+ continue;
172
+ if (typeof c.name !== "string" || !/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(c.name))
173
+ continue;
174
+ if (typeof c.description !== "string" || c.description.trim().length < 20)
175
+ continue;
176
+ if (typeof c.body !== "string" || c.body.trim().length < 50)
177
+ continue;
178
+ if (typeof c.confidence !== "number" || !Number.isFinite(c.confidence))
179
+ continue;
180
+ if (typeof c.evidence !== "string" || c.evidence.trim().length < 5)
181
+ continue;
182
+ if (type === "lesson") {
183
+ if (typeof c.when_to_use !== "string" || c.when_to_use.trim().length < 15)
184
+ continue;
185
+ }
186
+ const confidence = Math.max(0, Math.min(1, c.confidence));
187
+ const candidate = {
188
+ type,
189
+ name: c.name,
190
+ description: c.description.trim(),
191
+ body: c.body,
192
+ confidence,
193
+ evidence: c.evidence.trim(),
194
+ };
195
+ if (typeof c.when_to_use === "string")
196
+ candidate.when_to_use = c.when_to_use.trim();
197
+ candidates.push(candidate);
198
+ }
199
+ const result = { candidates };
200
+ if (typeof obj.rationale_if_empty === "string") {
201
+ result.rationale_if_empty = obj.rationale_if_empty.trim();
202
+ }
203
+ return result;
204
+ }