akm-cli 0.7.4 → 0.8.0-rc.10

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 (300) hide show
  1. package/CHANGELOG.md +224 -1
  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 +133 -0
  8. package/dist/cli/shared.js +129 -0
  9. package/dist/cli.js +2631 -1440
  10. package/dist/commands/add-cli.js +279 -0
  11. package/dist/commands/agent-dispatch.js +110 -0
  12. package/dist/commands/agent-support.js +68 -0
  13. package/dist/commands/completions.js +3 -0
  14. package/dist/commands/config-cli.js +130 -534
  15. package/dist/commands/consolidate.js +2122 -0
  16. package/dist/commands/curate.js +45 -3
  17. package/dist/commands/db-cli.js +23 -0
  18. package/dist/commands/distill-promotion-policy.js +660 -0
  19. package/dist/commands/distill.js +1081 -73
  20. package/dist/commands/env.js +213 -0
  21. package/dist/commands/eval-cases.js +43 -0
  22. package/dist/commands/events.js +15 -24
  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 +477 -0
  28. package/dist/commands/health.js +1302 -0
  29. package/dist/commands/help/help-accept.md +12 -0
  30. package/dist/commands/help/help-improve.md +69 -0
  31. package/dist/commands/help/help-proposals.md +18 -0
  32. package/dist/commands/help/help-propose.md +17 -0
  33. package/dist/commands/help/help-reject.md +11 -0
  34. package/dist/commands/history.js +54 -46
  35. package/dist/commands/improve-auto-accept.js +97 -0
  36. package/dist/commands/improve-cli.js +217 -0
  37. package/dist/commands/improve-profiles.js +166 -0
  38. package/dist/commands/improve-result-file.js +167 -0
  39. package/dist/commands/improve.js +2373 -0
  40. package/dist/commands/info.js +5 -2
  41. package/dist/commands/init.js +50 -2
  42. package/dist/commands/installed-stashes.js +102 -139
  43. package/dist/commands/knowledge.js +136 -0
  44. package/dist/commands/lint/agent-linter.js +49 -0
  45. package/dist/commands/lint/base-linter.js +479 -0
  46. package/dist/commands/lint/command-linter.js +49 -0
  47. package/dist/commands/lint/default-linter.js +16 -0
  48. package/dist/commands/lint/env-key-rules.js +154 -0
  49. package/dist/commands/lint/index.js +196 -0
  50. package/dist/commands/lint/knowledge-linter.js +16 -0
  51. package/dist/commands/lint/markdown-insertion.js +343 -0
  52. package/dist/commands/lint/memory-linter.js +61 -0
  53. package/dist/commands/lint/registry.js +36 -0
  54. package/dist/commands/lint/skill-linter.js +45 -0
  55. package/dist/commands/lint/task-linter.js +50 -0
  56. package/dist/commands/lint/types.js +4 -0
  57. package/dist/commands/lint/workflow-linter.js +56 -0
  58. package/dist/commands/lint.js +4 -0
  59. package/dist/commands/migration-help.js +3 -0
  60. package/dist/commands/proposal.js +67 -12
  61. package/dist/commands/propose.js +120 -45
  62. package/dist/commands/reflect.js +1104 -60
  63. package/dist/commands/registry-cli.js +150 -0
  64. package/dist/commands/registry-search.js +5 -2
  65. package/dist/commands/remember-cli.js +257 -0
  66. package/dist/commands/remember.js +70 -7
  67. package/dist/commands/schema-repair.js +203 -0
  68. package/dist/commands/search.js +115 -14
  69. package/dist/commands/secret.js +173 -0
  70. package/dist/commands/self-update.js +3 -0
  71. package/dist/commands/show.js +158 -60
  72. package/dist/commands/source-add.js +17 -45
  73. package/dist/commands/source-clone.js +3 -0
  74. package/dist/commands/source-manage.js +14 -19
  75. package/dist/commands/tasks.js +437 -0
  76. package/dist/commands/url-checker.js +42 -0
  77. package/dist/core/action-contributors.js +28 -0
  78. package/dist/core/asset-ref.js +17 -2
  79. package/dist/core/asset-registry.js +12 -17
  80. package/dist/core/asset-serialize.js +88 -0
  81. package/dist/core/asset-spec.js +67 -1
  82. package/dist/core/common.js +182 -0
  83. package/dist/core/concurrent.js +25 -0
  84. package/dist/core/config-io.js +347 -0
  85. package/dist/core/config-migration.js +622 -0
  86. package/dist/core/config-schema.js +534 -0
  87. package/dist/core/config-sources.js +108 -0
  88. package/dist/core/config-types.js +4 -0
  89. package/dist/core/config-walker.js +337 -0
  90. package/dist/core/config.js +364 -968
  91. package/dist/core/errors.js +42 -20
  92. package/dist/core/events.js +105 -135
  93. package/dist/core/file-lock.js +104 -0
  94. package/dist/core/frontmatter.js +75 -8
  95. package/dist/core/lesson-lint.js +3 -0
  96. package/dist/core/markdown.js +20 -0
  97. package/dist/core/memory-belief.js +62 -0
  98. package/dist/core/memory-contradiction-detect.js +274 -0
  99. package/dist/core/memory-improve.js +806 -0
  100. package/dist/core/parse.js +158 -0
  101. package/dist/core/paths.js +280 -14
  102. package/dist/core/proposal-quality-validators.js +380 -0
  103. package/dist/core/proposal-validators.js +69 -0
  104. package/dist/core/proposals.js +512 -42
  105. package/dist/core/state-db.js +1068 -0
  106. package/dist/core/text-truncation.js +107 -0
  107. package/dist/core/time.js +54 -0
  108. package/dist/core/tty.js +59 -0
  109. package/dist/core/warn.js +64 -1
  110. package/dist/core/write-source.js +3 -0
  111. package/dist/indexer/db-backup.js +391 -0
  112. package/dist/indexer/db-search.js +198 -489
  113. package/dist/indexer/db.js +990 -108
  114. package/dist/indexer/ensure-index.js +136 -0
  115. package/dist/indexer/file-context.js +3 -0
  116. package/dist/indexer/graph-boost.js +376 -101
  117. package/dist/indexer/graph-db.js +391 -0
  118. package/dist/indexer/graph-dedup.js +95 -0
  119. package/dist/indexer/graph-extraction.js +550 -114
  120. package/dist/indexer/index-context.js +4 -0
  121. package/dist/indexer/indexer.js +547 -309
  122. package/dist/indexer/llm-cache.js +52 -0
  123. package/dist/indexer/manifest.js +3 -0
  124. package/dist/indexer/matchers.js +167 -160
  125. package/dist/indexer/memory-inference.js +152 -74
  126. package/dist/indexer/metadata-contributors.js +29 -0
  127. package/dist/indexer/metadata.js +275 -196
  128. package/dist/indexer/path-resolver.js +92 -0
  129. package/dist/indexer/project-context.js +192 -0
  130. package/dist/indexer/ranking-contributors.js +331 -0
  131. package/dist/indexer/ranking.js +81 -0
  132. package/dist/indexer/search-fields.js +5 -9
  133. package/dist/indexer/search-hit-enrichers.js +111 -0
  134. package/dist/indexer/search-source.js +44 -10
  135. package/dist/indexer/semantic-status.js +6 -17
  136. package/dist/indexer/staleness-detect.js +447 -0
  137. package/dist/indexer/usage-events.js +12 -9
  138. package/dist/indexer/walker.js +28 -0
  139. package/dist/integrations/agent/builders.js +135 -0
  140. package/dist/integrations/agent/config.js +122 -230
  141. package/dist/integrations/agent/detect.js +3 -0
  142. package/dist/integrations/agent/index.js +7 -13
  143. package/dist/integrations/agent/model-aliases.js +55 -0
  144. package/dist/integrations/agent/profiles.js +70 -5
  145. package/dist/integrations/agent/prompts.js +250 -36
  146. package/dist/integrations/agent/runner.js +151 -0
  147. package/dist/integrations/agent/sdk-runner.js +126 -0
  148. package/dist/integrations/agent/spawn.js +183 -35
  149. package/dist/integrations/github.js +3 -0
  150. package/dist/integrations/lockfile.js +32 -69
  151. package/dist/integrations/session-logs/index.js +69 -0
  152. package/dist/integrations/session-logs/inline-refs.js +35 -0
  153. package/dist/integrations/session-logs/pre-filter.js +152 -0
  154. package/dist/integrations/session-logs/providers/claude-code.js +282 -0
  155. package/dist/integrations/session-logs/providers/opencode.js +258 -0
  156. package/dist/integrations/session-logs/types.js +4 -0
  157. package/dist/llm/call-ai.js +62 -0
  158. package/dist/llm/client.js +79 -88
  159. package/dist/llm/embedder.js +20 -29
  160. package/dist/llm/embedders/cache.js +3 -7
  161. package/dist/llm/embedders/local.js +42 -1
  162. package/dist/llm/embedders/remote.js +20 -8
  163. package/dist/llm/embedders/types.js +3 -7
  164. package/dist/llm/feature-gate.js +95 -48
  165. package/dist/llm/graph-extract.js +676 -72
  166. package/dist/llm/index-passes.js +44 -29
  167. package/dist/llm/memory-infer.js +80 -71
  168. package/dist/llm/metadata-enhance.js +42 -29
  169. package/dist/llm/prompts/extract-session.md +80 -0
  170. package/dist/llm/prompts/graph-extract-user-prompt.md +35 -0
  171. package/dist/output/cli-hints-full.md +292 -0
  172. package/dist/output/cli-hints-short.md +66 -0
  173. package/dist/output/cli-hints.js +7 -311
  174. package/dist/output/context.js +60 -8
  175. package/dist/output/renderers.js +306 -258
  176. package/dist/output/shapes/curate.js +56 -0
  177. package/dist/output/shapes/distill.js +10 -0
  178. package/dist/output/shapes/env-list.js +19 -0
  179. package/dist/output/shapes/events.js +11 -0
  180. package/dist/output/shapes/helpers.js +424 -0
  181. package/dist/output/shapes/history.js +7 -0
  182. package/dist/output/shapes/passthrough.js +102 -0
  183. package/dist/output/shapes/proposal-accept.js +7 -0
  184. package/dist/output/shapes/proposal-diff.js +7 -0
  185. package/dist/output/shapes/proposal-list.js +7 -0
  186. package/dist/output/shapes/proposal-producer.js +11 -0
  187. package/dist/output/shapes/proposal-reject.js +7 -0
  188. package/dist/output/shapes/proposal-show.js +7 -0
  189. package/dist/output/shapes/registry-search.js +6 -0
  190. package/dist/output/shapes/registry.js +30 -0
  191. package/dist/output/shapes/search.js +6 -0
  192. package/dist/output/shapes/secret-list.js +19 -0
  193. package/dist/output/shapes/show.js +6 -0
  194. package/dist/output/shapes/vault-list.js +19 -0
  195. package/dist/output/shapes.js +51 -511
  196. package/dist/output/text/add.js +6 -0
  197. package/dist/output/text/clone.js +6 -0
  198. package/dist/output/text/config.js +6 -0
  199. package/dist/output/text/curate.js +6 -0
  200. package/dist/output/text/distill.js +7 -0
  201. package/dist/output/text/enable-disable.js +7 -0
  202. package/dist/output/text/events.js +10 -0
  203. package/dist/output/text/feedback.js +6 -0
  204. package/dist/output/text/helpers.js +1039 -0
  205. package/dist/output/text/history.js +7 -0
  206. package/dist/output/text/import.js +6 -0
  207. package/dist/output/text/index.js +6 -0
  208. package/dist/output/text/info.js +6 -0
  209. package/dist/output/text/init.js +6 -0
  210. package/dist/output/text/list.js +6 -0
  211. package/dist/output/text/proposal-producer.js +8 -0
  212. package/dist/output/text/proposal.js +11 -0
  213. package/dist/output/text/registry-commands.js +11 -0
  214. package/dist/output/text/registry.js +30 -0
  215. package/dist/output/text/remember.js +6 -0
  216. package/dist/output/text/remove.js +6 -0
  217. package/dist/output/text/save.js +6 -0
  218. package/dist/output/text/search.js +6 -0
  219. package/dist/output/text/show.js +6 -0
  220. package/dist/output/text/update.js +6 -0
  221. package/dist/output/text/upgrade.js +6 -0
  222. package/dist/output/text/vault.js +16 -0
  223. package/dist/output/text/wiki.js +15 -0
  224. package/dist/output/text/workflow.js +14 -0
  225. package/dist/output/text.js +44 -1093
  226. package/dist/registry/build-index.js +3 -0
  227. package/dist/registry/create-provider-registry.js +3 -0
  228. package/dist/registry/factory.js +4 -1
  229. package/dist/registry/origin-resolve.js +3 -0
  230. package/dist/registry/providers/index.js +3 -0
  231. package/dist/registry/providers/skills-sh.js +71 -50
  232. package/dist/registry/providers/static-index.js +53 -48
  233. package/dist/registry/providers/types.js +3 -24
  234. package/dist/registry/resolve.js +11 -16
  235. package/dist/registry/types.js +3 -0
  236. package/dist/scripts/migrate-storage.js +17750 -0
  237. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +9031 -0
  238. package/dist/scripts/migrations/v16-to-v17.js +141 -0
  239. package/dist/setup/detect.js +3 -0
  240. package/dist/setup/ripgrep-install.js +3 -0
  241. package/dist/setup/ripgrep-resolve.js +3 -0
  242. package/dist/setup/setup.js +775 -37
  243. package/dist/setup/steps.js +3 -15
  244. package/dist/sources/include.js +3 -0
  245. package/dist/sources/provider-factory.js +5 -12
  246. package/dist/sources/provider.js +3 -20
  247. package/dist/sources/providers/filesystem.js +19 -23
  248. package/dist/sources/providers/git.js +179 -20
  249. package/dist/sources/providers/index.js +3 -0
  250. package/dist/sources/providers/install-types.js +3 -13
  251. package/dist/sources/providers/npm.js +3 -4
  252. package/dist/sources/providers/provider-utils.js +3 -0
  253. package/dist/sources/providers/sync-from-ref.js +3 -11
  254. package/dist/sources/providers/tar-utils.js +3 -0
  255. package/dist/sources/providers/website.js +18 -22
  256. package/dist/sources/resolve.js +3 -0
  257. package/dist/sources/types.js +3 -0
  258. package/dist/sources/website-ingest.js +7 -0
  259. package/dist/tasks/backends/cron.js +203 -0
  260. package/dist/tasks/backends/exec-utils.js +28 -0
  261. package/dist/tasks/backends/index.js +24 -0
  262. package/dist/tasks/backends/launchd-template.xml +19 -0
  263. package/dist/tasks/backends/launchd.js +187 -0
  264. package/dist/tasks/backends/schtasks-template.xml +29 -0
  265. package/dist/tasks/backends/schtasks.js +215 -0
  266. package/dist/tasks/parser.js +211 -0
  267. package/dist/tasks/resolveAkmBin.js +87 -0
  268. package/dist/tasks/runner.js +458 -0
  269. package/dist/tasks/schedule.js +227 -0
  270. package/dist/tasks/schema.js +15 -0
  271. package/dist/tasks/validator.js +62 -0
  272. package/dist/version.js +3 -0
  273. package/dist/wiki/index-template.md +12 -0
  274. package/dist/wiki/ingest-workflow-template.md +54 -0
  275. package/dist/wiki/log-template.md +8 -0
  276. package/dist/wiki/schema-template.md +61 -0
  277. package/dist/wiki/wiki-templates.js +15 -0
  278. package/dist/wiki/wiki.js +13 -61
  279. package/dist/workflows/authoring.js +8 -25
  280. package/dist/workflows/cli.js +3 -0
  281. package/dist/workflows/db.js +141 -2
  282. package/dist/workflows/document-cache.js +3 -10
  283. package/dist/workflows/parser.js +3 -0
  284. package/dist/workflows/renderer.js +11 -3
  285. package/dist/workflows/runs.js +91 -89
  286. package/dist/workflows/schema.js +3 -0
  287. package/dist/workflows/scope-key.js +79 -0
  288. package/dist/workflows/validator.js +4 -8
  289. package/dist/workflows/workflow-template.md +24 -0
  290. package/docs/README.md +10 -2
  291. package/docs/data-and-telemetry.md +225 -0
  292. package/docs/migration/release-notes/0.7.0.md +1 -1
  293. package/docs/migration/release-notes/0.7.4.md +1 -1
  294. package/docs/migration/release-notes/0.7.5.md +20 -0
  295. package/docs/migration/release-notes/0.8.0.md +48 -0
  296. package/docs/migration/v0.7-to-v0.8.md +1307 -0
  297. package/package.json +29 -11
  298. package/dist/commands/install-audit.js +0 -381
  299. package/dist/commands/vault.js +0 -333
  300. package/dist/templates/wiki-templates.js +0 -100
@@ -0,0 +1,150 @@
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 { defineCommand } from "citty";
5
+ import { parsePositiveIntFlag } from "../cli/parse-args";
6
+ import { output, runWithJsonErrors } from "../cli/shared";
7
+ import { DEFAULT_CONFIG, loadUserConfig, saveConfig } from "../core/config";
8
+ import { UsageError } from "../core/errors";
9
+ import { warn } from "../core/warn";
10
+ import { getHyphenatedArg, getHyphenatedBoolean } from "../output/context";
11
+ import { buildRegistryIndex, writeRegistryIndex } from "../registry/build-index";
12
+ import { searchRegistry } from "./registry-search";
13
+ export const registryCommand = defineCommand({
14
+ meta: { name: "registry", description: "Manage stash registries" },
15
+ subCommands: {
16
+ list: defineCommand({
17
+ meta: { name: "list", description: "List configured registries" },
18
+ run() {
19
+ return runWithJsonErrors(() => {
20
+ const config = loadUserConfig();
21
+ const registries = config.registries ?? DEFAULT_CONFIG.registries;
22
+ output("registry-list", { registries });
23
+ });
24
+ },
25
+ }),
26
+ add: defineCommand({
27
+ meta: { name: "add", description: "Add a registry by URL" },
28
+ args: {
29
+ url: { type: "positional", description: "Registry index URL", required: true },
30
+ name: { type: "string", description: "Human-friendly name for the registry" },
31
+ provider: { type: "string", description: "Provider type (e.g. static-index, skills-sh)" },
32
+ options: { type: "string", description: 'Provider options as JSON (e.g. \'{"apiKey":"key"}\').' },
33
+ "allow-insecure": {
34
+ type: "boolean",
35
+ description: "Allow a plain HTTP registry URL (otherwise rejected)",
36
+ default: false,
37
+ },
38
+ },
39
+ run({ args }) {
40
+ return runWithJsonErrors(() => {
41
+ if (!args.url.startsWith("http")) {
42
+ throw new UsageError("Registry URL must start with http:// or https://");
43
+ }
44
+ if (args.url.startsWith("http://")) {
45
+ const allowInsecure = getHyphenatedBoolean(args, "allow-insecure");
46
+ if (!allowInsecure) {
47
+ throw new UsageError("Registry URL uses plain HTTP (not HTTPS). An on-path attacker could substitute a malicious index. " +
48
+ "Use https:// or pass --allow-insecure if you have explicitly accepted the risk.");
49
+ }
50
+ warn("Warning: registry URL uses plain HTTP (not HTTPS). --allow-insecure was set; an on-path attacker could substitute a malicious index.");
51
+ }
52
+ const config = loadUserConfig();
53
+ const registries = [...(config.registries ?? [])];
54
+ // Deduplicate by URL
55
+ if (registries.some((r) => r.url === args.url)) {
56
+ output("registry-add", { registries, added: false, message: "Registry URL already configured" });
57
+ return;
58
+ }
59
+ const entry = { url: args.url };
60
+ if (args.name)
61
+ entry.name = args.name;
62
+ if (args.provider)
63
+ entry.provider = args.provider;
64
+ if (args.options) {
65
+ try {
66
+ entry.options = JSON.parse(args.options);
67
+ }
68
+ catch {
69
+ throw new UsageError("--options must be valid JSON");
70
+ }
71
+ }
72
+ registries.push(entry);
73
+ saveConfig({ ...config, registries });
74
+ output("registry-add", { registries, added: true });
75
+ });
76
+ },
77
+ }),
78
+ remove: defineCommand({
79
+ meta: { name: "remove", description: "Remove a registry by URL or name" },
80
+ args: {
81
+ target: { type: "positional", description: "Registry URL or name to remove", required: true },
82
+ yes: { type: "boolean", alias: "y", description: "Skip confirmation prompt", default: false },
83
+ },
84
+ run({ args }) {
85
+ return runWithJsonErrors(async () => {
86
+ const config = loadUserConfig();
87
+ const registries = [...(config.registries ?? [])];
88
+ const idx = registries.findIndex((r) => r.url === args.target || r.name === args.target);
89
+ if (idx === -1) {
90
+ output("registry-remove", { registries, removed: false, message: "No matching registry found" });
91
+ return;
92
+ }
93
+ const { confirmDestructive } = await import("../cli/confirm.js");
94
+ const confirmed = await confirmDestructive(`Remove registry "${args.target}"? This cannot be undone.`, {
95
+ yes: args.yes === true,
96
+ });
97
+ if (!confirmed) {
98
+ process.stderr.write("Aborted.\n");
99
+ return;
100
+ }
101
+ const removed = registries.splice(idx, 1)[0];
102
+ saveConfig({ ...config, registries });
103
+ output("registry-remove", { registries, removed: true, entry: removed });
104
+ });
105
+ },
106
+ }),
107
+ search: defineCommand({
108
+ meta: { name: "search", description: "Search enabled registries for stashes" },
109
+ args: {
110
+ query: { type: "positional", description: "Search query", required: true },
111
+ limit: { type: "string", description: "Maximum number of results" },
112
+ assets: { type: "boolean", description: "Include asset-level search results", default: false },
113
+ },
114
+ async run({ args }) {
115
+ await runWithJsonErrors(async () => {
116
+ const limitRaw = parsePositiveIntFlag(args.limit ?? undefined);
117
+ const result = await searchRegistry(args.query, { limit: limitRaw, includeAssets: args.assets });
118
+ output("registry-search", result);
119
+ });
120
+ },
121
+ }),
122
+ "build-index": defineCommand({
123
+ meta: { name: "build-index", description: "Build a v2 registry index from discovery and manual entries" },
124
+ args: {
125
+ out: { type: "string", description: "Output path for the generated index" },
126
+ manual: { type: "string", description: "Manual entries JSON file" },
127
+ "npm-registry": { type: "string", description: "Override npm registry base URL" },
128
+ "github-api": { type: "string", description: "Override GitHub API base URL" },
129
+ },
130
+ async run({ args }) {
131
+ await runWithJsonErrors(async () => {
132
+ const result = await buildRegistryIndex({
133
+ manualEntriesPath: args.manual,
134
+ npmRegistryBase: getHyphenatedArg(args, "npm-registry"),
135
+ githubApiBase: getHyphenatedArg(args, "github-api"),
136
+ });
137
+ const outPath = writeRegistryIndex(result.index, args.out);
138
+ output("registry-build-index", {
139
+ outPath,
140
+ version: result.index.version,
141
+ updatedAt: result.index.updatedAt,
142
+ totalKits: result.counts.total,
143
+ counts: result.counts,
144
+ manualEntriesPath: result.paths.manualEntriesPath,
145
+ });
146
+ });
147
+ },
148
+ }),
149
+ },
150
+ });
@@ -1,5 +1,8 @@
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 { toErrorMessage } from "../core/common";
2
- import { DEFAULT_CONFIG, loadConfig } from "../core/config";
5
+ import { DEFAULT_CONFIG } from "../core/config";
3
6
  import { warn } from "../core/warn";
4
7
  import { resolveProviderFactory } from "../registry/factory";
5
8
  // ── Eagerly import providers to trigger self-registration ───────────────────
@@ -133,7 +136,7 @@ export function resolveRegistries(configRegistries) {
133
136
  }
134
137
  return entries;
135
138
  }
136
- const registries = configRegistries ?? loadConfig().registries ?? DEFAULT_CONFIG.registries ?? [];
139
+ const registries = configRegistries ?? DEFAULT_CONFIG.registries ?? [];
137
140
  return registries.filter((r) => r.enabled !== false);
138
141
  }
139
142
  // ── Provider resolution ─────────────────────────────────────────────────────
@@ -0,0 +1,257 @@
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 { defineCommand } from "citty";
5
+ import { output, parseAllFlagValues, runWithJsonErrors } from "../cli/shared";
6
+ import { UsageError } from "../core/errors";
7
+ import { appendEvent } from "../core/events";
8
+ import { inferAssetName, writeMarkdownAsset } from "./knowledge";
9
+ import { buildMemoryFrontmatter, parseDuration, readMemoryContent, resolveRememberContentArg, runAutoHeuristics, runLlmEnrich, } from "./remember";
10
+ import { akmSearch } from "./search";
11
+ // ── Helper: similar memory search ────────────────────────────────────────────
12
+ /**
13
+ * Best-effort top-3 similar memory search for `--show-similar`.
14
+ * Scoped to memory: type; excludes the just-written ref.
15
+ */
16
+ async function fetchSimilarMemories(query, excludeRef) {
17
+ try {
18
+ const result = await akmSearch({ query, type: "memory", limit: 4 });
19
+ return (result.hits ?? [])
20
+ .filter((h) => "ref" in h && h.ref !== excludeRef)
21
+ .slice(0, 3)
22
+ .map((h) => ({ ref: h.ref, ...(h.name ? { title: h.name } : {}) }));
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ }
28
+ // ── Command definition ────────────────────────────────────────────────────────
29
+ export const rememberCommand = defineCommand({
30
+ meta: {
31
+ name: "remember",
32
+ description: "Record a memory in the default stash",
33
+ },
34
+ args: {
35
+ content: {
36
+ type: "positional",
37
+ description: "Memory content. Omit to read markdown from stdin.",
38
+ required: false,
39
+ },
40
+ name: {
41
+ type: "string",
42
+ description: "Memory name (defaults to a slug from the content)",
43
+ },
44
+ force: {
45
+ type: "boolean",
46
+ description: "Overwrite an existing memory with the same name",
47
+ default: false,
48
+ },
49
+ description: {
50
+ type: "string",
51
+ description: "Short description written to frontmatter (persisted as the memory's description field)",
52
+ },
53
+ tag: {
54
+ type: "string",
55
+ description: "Tag to add to the memory (repeatable: --tag foo --tag bar)",
56
+ },
57
+ expires: {
58
+ type: "string",
59
+ description: "Expiry duration shorthand (e.g. 30d, 12h, 6m). Resolved to an ISO date.",
60
+ },
61
+ source: {
62
+ type: "string",
63
+ description: "Source reference (URL, asset ref, file path, or any free-form string)",
64
+ },
65
+ auto: {
66
+ type: "boolean",
67
+ description: "Apply heuristic tagging (code, subjective, source, observed_at) from the body",
68
+ default: false,
69
+ },
70
+ enrich: {
71
+ type: "boolean",
72
+ description: "Call the configured LLM to propose tags and description (requires LLM config)",
73
+ default: false,
74
+ },
75
+ target: {
76
+ type: "string",
77
+ description: "Override the write destination. Accepts a source name from your config; falls back to defaultWriteTarget then the working stash.",
78
+ },
79
+ user: {
80
+ type: "string",
81
+ description: "Scope this memory to a user id (persisted as `scope_user` frontmatter)",
82
+ },
83
+ agent: {
84
+ type: "string",
85
+ description: "Scope this memory to an agent id (persisted as `scope_agent` frontmatter)",
86
+ },
87
+ run: {
88
+ type: "string",
89
+ description: "Scope this memory to a run id (persisted as `scope_run` frontmatter)",
90
+ },
91
+ channel: {
92
+ type: "string",
93
+ description: "Scope this memory to a channel name (persisted as `scope_channel` frontmatter)",
94
+ },
95
+ showSimilar: {
96
+ type: "boolean",
97
+ description: "Return top-3 similar existing memories in output (opt-in)",
98
+ },
99
+ },
100
+ async run({ args }) {
101
+ return runWithJsonErrors(async () => {
102
+ const body = readMemoryContent(resolveRememberContentArg(args.content));
103
+ // Determine if the user has requested any structured metadata mode.
104
+ // Collect all --tag occurrences directly from process.argv because citty
105
+ // only exposes the last value for repeated string flags.
106
+ const rawTags = parseAllFlagValues("--tag");
107
+ // Collect scope flags. Scope alone counts as structured metadata so we
108
+ // emit frontmatter, but it does NOT trigger the "tags required" check —
109
+ // memory + scope (no tags) is a valid combination for multi-tenant use.
110
+ const scopeFields = {};
111
+ if (typeof args.user === "string" && args.user.trim())
112
+ scopeFields.user = args.user.trim();
113
+ if (typeof args.agent === "string" && args.agent.trim())
114
+ scopeFields.agent = args.agent.trim();
115
+ if (typeof args.run === "string" && args.run.trim())
116
+ scopeFields.run = args.run.trim();
117
+ if (typeof args.channel === "string" && args.channel.trim())
118
+ scopeFields.channel = args.channel.trim();
119
+ const hasScope = Object.keys(scopeFields).length > 0;
120
+ const hasTagRequiringArgs = rawTags.length > 0 || !!args.expires || !!args.source || !!args.description;
121
+ const hasStructuredArgs = hasTagRequiringArgs || hasScope || args.auto;
122
+ if (!hasStructuredArgs) {
123
+ // Phase 1B / Rec 7: even the zero-flag hot-path emits
124
+ // `captureMode: hot` + `beliefState: asserted` so user-supplied
125
+ // memories outrank background-derived ones during ranking.
126
+ const frontmatterBlock = buildMemoryFrontmatter({
127
+ captureMode: "hot",
128
+ beliefState: "asserted",
129
+ });
130
+ const contentWithFrontmatter = `${frontmatterBlock}\n${body}`;
131
+ // Derive the asset slug from the body (not the frontmatter block);
132
+ // otherwise inferAssetName would key off the leading `---` delimiter.
133
+ const result = await writeMarkdownAsset({
134
+ type: "memory",
135
+ content: contentWithFrontmatter,
136
+ name: args.name,
137
+ fallbackPrefix: "memory",
138
+ preferredName: inferAssetName(body, "memory"),
139
+ force: args.force,
140
+ target: args.target,
141
+ });
142
+ appendEvent({
143
+ eventType: "remember",
144
+ ref: result.ref,
145
+ metadata: { path: result.path, force: args.force === true },
146
+ });
147
+ if (args.showSimilar) {
148
+ const similar = await fetchSimilarMemories(body.slice(0, 500), result.ref);
149
+ output("remember", { ok: true, ...result, similar });
150
+ }
151
+ else {
152
+ output("remember", { ok: true, ...result });
153
+ }
154
+ return;
155
+ }
156
+ // ── Accumulate metadata from all three modes ──────────────────────────
157
+ // Start with CLI args (Mode 1: always)
158
+ const tags = [...rawTags];
159
+ // --description is persisted as-is; LLM enrichment may fill it if absent.
160
+ let description = args.description || undefined;
161
+ let source = args.source;
162
+ let observed_at;
163
+ let expires;
164
+ let subjective;
165
+ // Resolve --expires to an ISO date string
166
+ if (args.expires) {
167
+ const durationMs = parseDuration(args.expires);
168
+ const expiresDate = new Date(Date.now() + durationMs);
169
+ expires = expiresDate.toISOString().slice(0, 10);
170
+ }
171
+ // Mode 2: --auto heuristics
172
+ if (args.auto) {
173
+ const auto = runAutoHeuristics(body);
174
+ for (const t of auto.tags) {
175
+ if (!tags.includes(t))
176
+ tags.push(t);
177
+ }
178
+ if (!source && auto.source)
179
+ source = auto.source;
180
+ if (!observed_at && auto.observed_at)
181
+ observed_at = auto.observed_at;
182
+ if (!subjective && auto.subjective)
183
+ subjective = auto.subjective;
184
+ }
185
+ // Mode 3: --enrich LLM (fail-soft)
186
+ if (args.enrich) {
187
+ const enriched = await runLlmEnrich(body);
188
+ for (const t of enriched.tags) {
189
+ if (!tags.includes(t))
190
+ tags.push(t);
191
+ }
192
+ if (!description && enriched.description)
193
+ description = enriched.description;
194
+ if (!observed_at && enriched.observed_at)
195
+ observed_at = enriched.observed_at;
196
+ }
197
+ // ── Required-field check (before any write) ───────────────────────────
198
+ // Tags remain required when the user explicitly asked for tag-bearing
199
+ // metadata (--tag / --enrich / --description / --source / --expires).
200
+ // `--auto` alone is allowed even when its heuristics derive zero tags.
201
+ // Scope-only writes (`akm remember "..." --user u1`) also skip this
202
+ // check — scope is independent metadata and a memory with only scope is
203
+ // valid.
204
+ const missing = [];
205
+ if (hasTagRequiringArgs && tags.length === 0)
206
+ missing.push("tags");
207
+ if (missing.length > 0) {
208
+ throw new UsageError(`Memory is missing required frontmatter field(s): ${missing.join(", ")}. ` +
209
+ "Provide them via --tag <value>, --auto (heuristics), or --enrich (LLM).");
210
+ }
211
+ // ── Build frontmatter and write ───────────────────────────────────────
212
+ // Phase 1B / Rec 7: the hot-path CLI write always marks the memory as
213
+ // `captureMode: hot` and `beliefState: asserted`. Ranking applies a
214
+ // hot-capture boost so user-supplied memories outrank otherwise-equal
215
+ // background-derived ones.
216
+ const frontmatterBlock = buildMemoryFrontmatter({
217
+ description,
218
+ tags,
219
+ source,
220
+ observed_at,
221
+ expires,
222
+ subjective,
223
+ captureMode: "hot",
224
+ beliefState: "asserted",
225
+ ...(hasScope ? { scope: scopeFields } : {}),
226
+ });
227
+ const contentWithFrontmatter = `${frontmatterBlock}\n${body}`;
228
+ const result = await writeMarkdownAsset({
229
+ type: "memory",
230
+ content: contentWithFrontmatter,
231
+ name: args.name,
232
+ fallbackPrefix: "memory",
233
+ force: args.force,
234
+ target: args.target,
235
+ });
236
+ appendEvent({
237
+ eventType: "remember",
238
+ ref: result.ref,
239
+ metadata: {
240
+ path: result.path,
241
+ force: args.force === true,
242
+ tagCount: tags.length,
243
+ enriched: args.enrich === true,
244
+ auto: args.auto === true,
245
+ ...(hasScope ? { scope: scopeFields } : {}),
246
+ },
247
+ });
248
+ if (args.showSimilar) {
249
+ const similar = await fetchSimilarMemories((body ?? args.content ?? "").slice(0, 500), result.ref);
250
+ output("remember", { ok: true, ...result, similar });
251
+ }
252
+ else {
253
+ output("remember", { ok: true, ...result });
254
+ }
255
+ });
256
+ },
257
+ });
@@ -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
  * Memory-specific helpers for `akm remember`.
3
6
  *
@@ -5,12 +8,13 @@
5
8
  * heuristic derivation, LLM enrichment) is testable in isolation and the
6
9
  * CLI entry point stays focused on argument parsing + output routing.
7
10
  */
8
- import { stringify as yamlStringify } from "yaml";
11
+ import { serializeFrontmatter } from "../core/asset-serialize";
9
12
  import { toErrorMessage, tryReadStdinText } from "../core/common";
10
- import { loadConfig } from "../core/config";
13
+ import { getDefaultLlmConfig, loadConfig } from "../core/config";
11
14
  import { UsageError } from "../core/errors";
12
15
  import { warn } from "../core/warn";
13
16
  import { SCOPE_KEYS } from "../indexer/metadata";
17
+ import { parseFlagValue } from "../output/context";
14
18
  /**
15
19
  * Parse a shorthand duration string to a number of milliseconds.
16
20
  * Supports: `30d` (days), `12h` (hours), `6m` (months, approximated as 30d).
@@ -53,6 +57,12 @@ export function buildMemoryFrontmatter(fields) {
53
57
  obj.expires = fields.expires;
54
58
  if (fields.subjective)
55
59
  obj.subjective = true;
60
+ if (fields.captureMode === "hot" || fields.captureMode === "background") {
61
+ obj.captureMode = fields.captureMode;
62
+ }
63
+ if (typeof fields.beliefState === "string" && fields.beliefState.trim()) {
64
+ obj.beliefState = fields.beliefState.trim();
65
+ }
56
66
  // Scope keys are emitted as flat top-level keys (`scope_user`, …) so the
57
67
  // existing one-level frontmatter parser can read them without nesting.
58
68
  // A scope object with no populated values is dropped.
@@ -68,7 +78,7 @@ export function buildMemoryFrontmatter(fields) {
68
78
  // produce `---\n{}\n---` (the YAML serializer's empty-object form).
69
79
  if (Object.keys(obj).length === 0)
70
80
  return "---\n---";
71
- const serialized = yamlStringify(obj).trimEnd();
81
+ const serialized = serializeFrontmatter(obj);
72
82
  return `---\n${serialized}\n---`;
73
83
  }
74
84
  /**
@@ -133,12 +143,12 @@ const LLM_ENRICH_TIMEOUT_MS = 10_000;
133
143
  */
134
144
  export async function runLlmEnrich(body) {
135
145
  const config = loadConfig();
136
- if (!config.llm) {
137
- warn("Warning: --enrich requires an LLM to be configured. Run `akm config set llm` to configure one.");
146
+ const llmConfig = getDefaultLlmConfig(config);
147
+ if (!llmConfig) {
148
+ warn("Warning: --enrich requires an LLM to be configured. Run `akm setup` to configure one.");
138
149
  return { tags: [] };
139
150
  }
140
- const llmConfig = config.llm;
141
- const { chatCompletion, parseJsonResponse } = await import("../llm/client");
151
+ const { chatCompletion, parseEmbeddedJsonResponse: parseJsonResponse } = await import("../llm/client");
142
152
  const prompt = `You are a memory tagger for a developer knowledge base.
143
153
  Given the memory text below, return ONLY a JSON object with these fields:
144
154
  - "tags": array of 1-5 short lowercase keyword tags
@@ -188,3 +198,56 @@ Return ONLY the JSON object, no prose, no markdown fences.`;
188
198
  return { tags: [] };
189
199
  }
190
200
  }
201
+ // ── Content-arg disambiguation ───────────────────────────────────────────────
202
+ /**
203
+ * Guard against citty consuming a global flag value as the `content` positional.
204
+ *
205
+ * When the user runs `akm remember --format json` without a content argument,
206
+ * citty may assign `"json"` to the `content` positional because of how it
207
+ * handles flag order. This helper detects that case and returns `undefined`
208
+ * so `readMemoryContent` falls through to stdin.
209
+ */
210
+ export function resolveRememberContentArg(content) {
211
+ if (content === undefined)
212
+ return undefined;
213
+ const parsedFormat = parseFlagValue(process.argv, "--format");
214
+ if (parsedFormat !== undefined &&
215
+ content === parsedFormat &&
216
+ wasRememberFlagValueConsumedAsContent(content, parsedFormat, "--format")) {
217
+ return undefined;
218
+ }
219
+ const parsedDetail = parseFlagValue(process.argv, "--detail");
220
+ if (parsedDetail !== undefined &&
221
+ content === parsedDetail &&
222
+ wasRememberFlagValueConsumedAsContent(content, parsedDetail, "--detail")) {
223
+ return undefined;
224
+ }
225
+ return content;
226
+ }
227
+ function wasRememberFlagValueConsumedAsContent(content, flagValue, flagName) {
228
+ const argv = process.argv.slice(2);
229
+ const rememberIndex = argv.indexOf("remember");
230
+ const tokens = rememberIndex >= 0 ? argv.slice(rememberIndex + 1) : argv;
231
+ let flagIndex = -1;
232
+ let flagConsumesNextToken = false;
233
+ for (let i = 0; i < tokens.length; i += 1) {
234
+ const token = tokens[i];
235
+ if (token === flagName) {
236
+ flagIndex = i;
237
+ flagConsumesNextToken = true;
238
+ break;
239
+ }
240
+ if (token === `${flagName}=${flagValue}`) {
241
+ flagIndex = i;
242
+ break;
243
+ }
244
+ }
245
+ if (flagIndex === -1)
246
+ return false;
247
+ if (tokens.slice(0, flagIndex).includes(content))
248
+ return false;
249
+ const firstTokenAfterFlag = flagIndex + (flagConsumesNextToken ? 2 : 1);
250
+ if (tokens.slice(firstTokenAfterFlag).includes(content))
251
+ return false;
252
+ return true;
253
+ }