akm-cli 0.10.261130-beta.4 → 0.10.261130-beta.5

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 (39) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/STABILITY.md +6 -5
  3. package/dist/assets/hints/cli-hints-full.md +6 -4
  4. package/dist/assets/hints/cli-hints-short.md +1 -1
  5. package/dist/cli/deprecations.js +5 -1
  6. package/dist/cli.js +3 -1
  7. package/dist/commands/env/env-cli.js +6 -6
  8. package/dist/commands/env/injection.js +90 -0
  9. package/dist/commands/env/secret-cli.js +2 -2
  10. package/dist/commands/exec-cli.js +44 -0
  11. package/dist/commands/improve/distill.js +6 -3
  12. package/dist/commands/improve/loop-stages.js +2 -2
  13. package/dist/commands/improve/reflect.js +3 -3
  14. package/dist/commands/improve/stage.js +46 -16
  15. package/dist/commands/lint/env-key-rules.js +1 -1
  16. package/dist/commands/run-cli.js +13 -4
  17. package/dist/core/adapter/adapters/akm-lint.js +1 -1
  18. package/dist/core/config/experimental.js +6 -0
  19. package/dist/core/config/schema/experimental.js +6 -0
  20. package/dist/core/redaction.js +10 -0
  21. package/dist/core/type-presentation.js +2 -2
  22. package/dist/integrations/agent/prompts.js +3 -3
  23. package/dist/output/format-exempt.js +2 -0
  24. package/dist/output/renderers.js +2 -2
  25. package/dist/scripts/akm-migrate-node.js +6 -4
  26. package/dist/scripts/akm-migrate.js +6 -4
  27. package/dist/tasks/prepare/prepare-support.js +1 -1
  28. package/docs/architecture/architecture.md +1 -1
  29. package/docs/guides/author-bundles.md +1 -1
  30. package/docs/migration/v0.10-to-v0.11.md +17 -1
  31. package/docs/reference/asset-types.md +2 -2
  32. package/docs/reference/cli.md +88 -19
  33. package/docs/reference/configuration.md +5 -1
  34. package/docs/reference/data-and-telemetry.md +2 -2
  35. package/docs/reference/env-and-secrets.md +35 -23
  36. package/docs/reference/tasks.md +1 -1
  37. package/docs/reference/workflow-schema.md +2 -2
  38. package/package.json +1 -1
  39. package/schemas/akm-config.json +6 -0
package/CHANGELOG.md CHANGED
@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
9
  ### Added
10
10
 
11
+ - `akm run` takes repeatable `--env <env-ref>` and `--secret <secret-ref>:<VAR>`, which inject env assets and secrets into the agent, command, task or workflow it runs. The secrets injected this way are scrubbed from the output akm captures. The names are reserved: a task input or workflow parameter called `env` or `secret` cannot be passed through `akm run`.
12
+ - `akm exec [--env <ref>]... [--secret <ref>:<VAR>]... -- <command>` runs any command with the same injection, with `--clean` and `--inherit`. Experimental, and off until `experimental.exec` is `true` in config.
11
13
  - A file or folder renamed or moved on disk is the same asset. `akm index` (full or incremental) pairs an entry whose file is gone with the new file of the same content, in the same bundle or another, and carries its history to the new ref: the index row (vector, links and utility stay, nothing is embedded again), the `state.db` rows keyed by the old ref (usage, feedback, proposals, events, improve ledger, salience, outcome, task and workflow history) and cached model results. Files that share a content hash pair by file name one to one; anything ambiguous is indexed as new and named in a warning, and a file edited as well as moved is a new asset. The result's `moves` (`{ moved: [{ from, to }], unpaired }`) is present when a file was paired or could not be, and each move is recorded as a `moved` event. There is no move command: `mv` or a file manager is the move.
12
14
  - `akm lint` reports a link to a moved ref as a `missing-ref` carrying `movedFrom` and `movedTo`, and `--fix` rewrites it (frontmatter and prose, not code fences). A `missing-ref` with no recorded move is reported as before and never rewritten. `akm-cli/workspace`: `assets.movedLinks` lists, per akm bundle, the links that name an old ref, and `assets.updateMovedLinks` rewrites exactly those in one writable bundle (the same lint pass).
13
15
  - `akm-cli/workspace`: what may be done to a file or folder. `assets.bundleFiles` entries and `assets.show` carry `actions` (`read`, `edit`, `move` for rename or move, `copy`, `retire`, `delete`), each `{ allowed: true }` or `{ allowed: false, reason }`, computed from the checks the operations run: the read-only sentence for a bundle that is read-only (reading, editing, moving and deleting are plain file operations, so a writable bundle of any adapter still takes them), the write path's adapter sentence for retiring or making a typed asset in a bundle of another adapter, env and secret files, the managed `.git/` and `.akm/` folders, a skill that moves as its folder, a file that is not text (or cannot be opened, with the cause), the retire guard, and an asset that is retired rather than deleted. `assets.bundleFiles` also reports `newFile` for the folder shown.
@@ -50,6 +52,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
50
52
 
51
53
  - AKM Desktop's Source history no longer shows a "Made by" badge or filter, and the commit entries of `akm-cli/workspace` `proposals.recentChanges` and `assets.history` no longer carry `origin`: it was judged from the commit subject, so a hand-written "Remember to rotate the key" read as akm's. Each commit shows its own author, date and subject; akm's commit messages are unchanged.
52
54
 
55
+ ### Deprecated
56
+
57
+ - `akm env run` and `akm secret run`: use `akm exec` (turn it on with `experimental.exec`). Both still work, print a deprecation notice and are removed in 0.11. `env run --only` and `--except` have no `exec` form.
58
+
53
59
  ### Fixed
54
60
 
55
61
  - Package-local plugin CLIs invoked directly with Bun no longer default to an npm-global upgrade when npm ownership is unproven; the `npm` on PATH proves a global install when no launching Node does (#1708).
package/STABILITY.md CHANGED
@@ -149,11 +149,12 @@ check the [migration guide](docs/migration/v0.10-to-v0.11.md) for availability.
149
149
  | `akm env list` | Stable | Read-and-inject surface. |
150
150
  | `akm env path` | Stable | Read-and-inject surface. |
151
151
  | `akm env export` | Stable | Read-and-inject surface. |
152
- | `akm env run` | Stable | Read-and-inject surface. `--allow-dangerous-env-keys` is Deprecated, no effect: accepted through 0.10 and a usage error in 0.11, so drop it; prints a notice since 0.10.261122. |
152
+ | `akm exec` | Experimental | First in 0.10.261130. Off until `experimental.exec` is `true` in config; otherwise it refuses with a config error (exit 78) and runs nothing. Runs any command with repeatable `--env <ref>` and `--secret <ref>:<VAR>` injected; `akm run` takes the same two flags for an akm asset. Child-process passthrough, exempt from `--format`. |
153
+ | `akm env run` | Deprecated | Removed in 0.11: use `akm exec --env <ref> -- <command>`. Read-and-inject surface. `--allow-dangerous-env-keys` is Deprecated, no effect: accepted through 0.10 and a usage error in 0.11, so drop it; prints a notice since 0.10.261122. |
153
154
  | `akm env create` | Experimental | Write verb. |
154
155
  | `akm env remove` | Experimental | Write verb. |
155
156
  | `akm secret list` | Stable | Read-and-inject surface. |
156
- | `akm secret run` | Stable | Read-and-inject surface. |
157
+ | `akm secret run` | Deprecated | Removed in 0.11: use `akm exec --secret <ref>:<VAR> -- <command>`. Read-and-inject surface. |
157
158
  | `akm secret set` | Experimental | Write verb. |
158
159
  | `akm secret remove` | Experimental | Write verb; restored in 0.10 after its 0.9.0 removal. |
159
160
 
@@ -405,7 +406,7 @@ available as JSON), never on the format alone.
405
406
  `--detail` is `brief|normal|full` (verbosity) or `agent` (the projection of
406
407
  `search`, `curate` and `show`; see Agent-oriented output below). A small set of commands is **format-exempt** because their
407
408
  output is not a result envelope at all: `completions` (shell script source),
408
- child-process passthrough in `env run` / `secret run`, a bare-path payload
409
+ child-process passthrough in `exec`, `env run` / `secret run`, a bare-path payload
409
410
  from `env path` and `config path`, and document payloads from `hints` and `help`
410
411
  (bare and `help migrate`). The set is declared in
411
412
  `src/output/format-exempt.ts`, and
@@ -793,8 +794,8 @@ not additional public support statuses.
793
794
 
794
795
  An `env` asset holds a whole `.env` group; a `secret` holds a single sensitive
795
796
  value. Env key names are discoverable. Values are never written to stdout, the index, or
796
- structured output; the safe injection path is `akm env run <name> --
797
- <command>` (or `akm secret run <name> <VAR> -- …`). The `env` / `secret`
797
+ structured output; the safe injection path is `akm exec --env <ref> --
798
+ <command>` (or `akm exec --secret <ref>:<VAR> -- …`). The `env` / `secret`
798
799
  **write** verbs (`env create`, `env remove`, `secret set`, `secret remove`) are Experimental; the
799
800
  `list` / `path` / `run` / `export` read-and-inject surface is Stable.
800
801
 
@@ -159,8 +159,9 @@ akm env create env/prod # Create an empty env file
159
159
  akm env create env/prod --from-file ./.env # Ingest an existing .env
160
160
  akm env list # List all env files across bundles with key names
161
161
  akm show env/prod # Inspect key names (never values or comments)
162
- akm env run env/prod -- ./deploy.sh # Run a command with the whole .env injected (the safe path)
163
- akm env run env/prod -- $SHELL # Open an interactive shell with values injected
162
+ akm exec --env env/prod -- ./deploy.sh # Run a command with the whole .env injected (Experimental: needs experimental.exec true)
163
+ akm exec --env env/prod -- $SHELL # Open an interactive shell with values injected
164
+ akm run <ref> --env env/prod # Run an akm asset with it injected (repeatable)
164
165
  akm env export env/prod --out ./env.sh # Write a sourceable script to a file (mode 0600)
165
166
  akm env path env/prod --quiet # Print the raw file path (for Docker `_FILE` / `--env-file`)
166
167
  akm env remove env/prod # Delete the env file
@@ -175,7 +176,8 @@ the value; only the name is ever surfaced.
175
176
  ```sh
176
177
  printf '%s' "$TOKEN" | akm secret set secrets/deploy-token # Store a single value
177
178
  akm secret list # List secrets (names only)
178
- akm secret run secrets/deploy-token GITHUB_TOKEN -- gh release create v1.0.0 # Inject into one env var
179
+ akm exec --secret secrets/deploy-token:GITHUB_TOKEN -- gh release create v1.0.0 # Inject into one env var
180
+ akm run <ref> --secret secrets/deploy-token:GITHUB_TOKEN # The same for an akm asset; scrubbed from captured output
179
181
  ```
180
182
 
181
183
  ## Workflows (Deprecated)
@@ -480,7 +482,7 @@ envelope is the preferred signal for agents parsing output programmatically;
480
482
  the exit code is the preferred signal for shell scripts. Passthrough surfaces
481
483
  below preserve the child's own streams and status instead.
482
484
 
483
- `env run`, `secret run`, and `migrate` are process passthroughs and preserve
485
+ `exec`, `env run`, `secret run`, and `migrate` are process passthroughs and preserve
484
486
  the spawned process's exact status. `akm run` on a task preserves configuration failures
485
487
  as exit 78; successful task results exit 0 and other failures exit 1, while a
486
488
  command child's exact status remains in `result.detail.exitCode`. `agent` maps
@@ -14,7 +14,7 @@ akm rules # The rules that apply here, in full
14
14
  akm run <ref> # Run an agent, command, task or workflow asset
15
15
  akm doctor # Health checks; `doctor metrics|info|log` report
16
16
  akm help <command> # A command's options
17
- akm env run <ref> -- <cmd> # Inject an env asset's values (secrets: akm secret run <ref> <VAR> -- <cmd>)
17
+ akm exec --env <ref> -- <cmd> # Inject an env asset's values (secrets: --secret <ref>:<VAR>; same flags on akm run). Needs experimental.exec
18
18
  ```
19
19
 
20
20
  For a large document, `akm show <ref> --outline` returns its outline (`toc`, no body); `akm show <ref>#<slug>` reads one section.
@@ -40,6 +40,11 @@ const DEPRECATIONS = [
40
40
  path: ["workflow", sub],
41
41
  note: WORKFLOWS_NOTE,
42
42
  })),
43
+ { path: ["env", "run"], use: "`akm exec --env <ref> -- <command>` (Experimental: set `experimental.exec` to true)" },
44
+ {
45
+ path: ["secret", "run"],
46
+ use: "`akm exec --secret <ref>:<VAR> -- <command>` (Experimental: set `experimental.exec` to true)",
47
+ },
43
48
  { path: ["agent"], needsRef: true, use: "`akm run <ref>`" },
44
49
  { path: ["command", "run"], use: "`akm run <ref>`" },
45
50
  { path: ["command"], needsRef: true, use: "`akm run <ref>`" },
@@ -82,7 +87,6 @@ const DEPRECATIONS = [
82
87
  ...[
83
88
  ["bundle", "add"],
84
89
  ["bundle", "update"],
85
- ["env", "run"],
86
90
  ].map((path) => ({
87
91
  path,
88
92
  flag: "--allow-dangerous-env-keys",
package/dist/cli.js CHANGED
@@ -88,6 +88,7 @@ import { closestMatch } from "./core/closest-match.js";
88
88
  import { trackStdioReaderGone } from "./core/stdio-reader-gone.js";
89
89
  import "./commands/health/renderers.js";
90
90
  import "./commands/metrics/md-report.js";
91
+ import { execCommand } from "./commands/exec-cli.js";
91
92
  import { parseWindowSpec } from "./commands/health/windows.js";
92
93
  import { doctorPromptCommand, improveCommand } from "./commands/improve/improve-cli.js";
93
94
  import { judgeCommand } from "./commands/judge-cli.js";
@@ -608,6 +609,7 @@ const commands = {
608
609
  show: showCommand,
609
610
  rules: rulesCommand,
610
611
  run: runAssetCommand,
612
+ exec: execCommand,
611
613
  workflow: workflowCommand,
612
614
  remember: rememberCommand,
613
615
  import: importKnowledgeCommand,
@@ -935,7 +937,7 @@ const HELP_SECTIONS = [
935
937
  title: "ASSETS",
936
938
  commands: ["import", "clone", "bundle", "env", "secret", "sync", "proposal"],
937
939
  },
938
- { title: "AUTOMATION", commands: ["improve", "judge", "agent", "command", "workflow", "task"] },
940
+ { title: "AUTOMATION", commands: ["run", "exec", "improve", "judge", "agent", "command", "workflow", "task"] },
939
941
  {
940
942
  title: "SYSTEM",
941
943
  commands: [
@@ -116,7 +116,7 @@ const envCreateCommand = defineJsonCommand({
116
116
  const envPathCommand = defineJsonCommand({
117
117
  meta: {
118
118
  name: "path",
119
- description: "Print the absolute env file path (Docker `_FILE` convention / `--env-file`). To inject values, use `akm env run <ref> -- <cmd>` — do NOT `source` the raw file.",
119
+ description: "Print the absolute env file path (Docker `_FILE` convention / `--env-file`). To inject values, use `akm exec --env <ref> -- <cmd>` — do NOT `source` the raw file.",
120
120
  },
121
121
  args: {
122
122
  ref: { type: "positional", description: "Env ref", required: true },
@@ -129,7 +129,7 @@ const envPathCommand = defineJsonCommand({
129
129
  // suppressed with --quiet for the legitimate `_FILE` / `--env-file` use.
130
130
  if (args.quiet !== true) {
131
131
  process.stderr.write(`warning: this is the raw file path. Do NOT \`source\` it (shell substitutions in the file would execute).\n` +
132
- ` To inject values run: akm env run ${args.ref} -- <command>\n`);
132
+ ` To inject values run: akm exec --env ${args.ref} -- <command>\n`);
133
133
  }
134
134
  // F3/B3: this stdout write IS the payload — a bare absolute path for
135
135
  // shell substitution (`$(akm env path <ref>)`, Docker `_FILE` /
@@ -153,7 +153,7 @@ const envPathCommand = defineJsonCommand({
153
153
  const envExportCommand = defineJsonCommand({
154
154
  meta: {
155
155
  name: "export",
156
- description: "Write safe `export KEY='value'` lines to a file (mode 0600) for `source`-ing — requires --out <path>. Values are re-serialised single-quoted so a raw `.env` cannot execute on load, and are NEVER printed to stdout. To use values directly, prefer `akm env run <ref> -- <command>`.",
156
+ description: "Write safe `export KEY='value'` lines to a file (mode 0600) for `source`-ing — requires --out <path>. Values are re-serialised single-quoted so a raw `.env` cannot execute on load, and are NEVER printed to stdout. To use values directly, prefer `akm exec --env <ref> -- <command>`.",
157
157
  },
158
158
  args: {
159
159
  ref: { type: "positional", description: "Env ref", required: true },
@@ -163,7 +163,7 @@ const envExportCommand = defineJsonCommand({
163
163
  const outPath = args.out;
164
164
  if (!outPath) {
165
165
  throw new UsageError("`akm env export` writes to a file — pass --out <path>.\n" +
166
- " To use values directly, run `akm env run <ref> -- <command>` (or `-- $SHELL` for an interactive\n" +
166
+ " To use values directly, run `akm exec --env <ref> -- <command>` (or `-- $SHELL` for an interactive\n" +
167
167
  " session). export never prints values to stdout, to avoid leaking them into a captured context.", "MISSING_REQUIRED_ARGUMENT");
168
168
  }
169
169
  const { conceptId, absPath, source } = resolveEnvPath(args.ref);
@@ -203,7 +203,7 @@ async function runEnvInjected(target, opts) {
203
203
  }
204
204
  if (baseExists) {
205
205
  throw new UsageError(`'akm env run' injects the whole file; the single-key '<ref>/${maybeKey}' form was removed.\n` +
206
- ` For one value use a secret: \`akm secret run secrets/${maybeKey} ${maybeKey} -- <command>\`.`, "INVALID_FLAG_VALUE");
206
+ ` For one value use a secret: \`akm exec --secret secrets/${maybeKey}:${maybeKey} -- <command>\`.`, "INVALID_FLAG_VALUE");
207
207
  }
208
208
  }
209
209
  }
@@ -266,7 +266,7 @@ const envRunCommand = defineJsonCommand({
266
266
  name: "run",
267
267
  description:
268
268
  // biome-ignore lint/suspicious/noTemplateCurlyInString: literal `${ref}` token syntax documented for users, not interpolation
269
- "Run a command with the env file injected into its environment: `akm env run <ref> -- <command>`. Use `-- $SHELL` for an interactive session. Restrict which variables are injected with --only / --except. Values may embed `${ref}` tokens, replaced at run time: a `${secrets/NAME}` (or `${bundle//secrets/NAME}`) token with the secret's value, any other asset ref with its absolute path. Pass --clean to start the child with a minimal inherited environment instead of the full parent environment.",
269
+ "Deprecated; use `akm exec --env <ref> -- <command>`; removed in 0.11. Run a command with the env file injected into its environment: `akm env run <ref> -- <command>`. Use `-- $SHELL` for an interactive session. Restrict which variables are injected with --only / --except. Values may embed `${ref}` tokens, replaced at run time: a `${secrets/NAME}` (or `${bundle//secrets/NAME}`) token with the secret's value, any other asset ref with its absolute path. Pass --clean to start the child with a minimal inherited environment instead of the full parent environment.",
270
270
  },
271
271
  args: {
272
272
  target: { type: "positional", description: "Env ref", required: true },
@@ -0,0 +1,90 @@
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
+ * The repeatable `--env <ref>` and `--secret <ref>:<VAR>` flags of `akm run`
6
+ * and `akm exec`: what they resolve to, and the one child spawn `akm exec`
7
+ * makes. Env assets apply in the order given, then secrets over them; a later
8
+ * flag wins over an earlier one for the same variable. Resolution keeps every
9
+ * invariant of `resolveEnvBinding` (nothing is injected when a ref is missing;
10
+ * audit events carry names only).
11
+ */
12
+ import { spawnSync } from "node:child_process";
13
+ import { getParsedInvocation } from "../../cli/invocation.js";
14
+ import { makeSecretRef, resolveSecretPath } from "../../core/env-secret-ref.js";
15
+ import { ConfigError, NotFoundError, UsageError } from "../../core/errors.js";
16
+ import { appendEvent } from "../../core/events.js";
17
+ import { readValue } from "../../core/secret-value.js";
18
+ import { resolveEnvBinding } from "./env-binding.js";
19
+ export const INJECTION_ARGS = {
20
+ env: {
21
+ type: "string",
22
+ description: "Inject every variable of this env asset (`[bundle//]env/<name>`); repeatable",
23
+ },
24
+ secret: {
25
+ type: "string",
26
+ description: "Inject a secret's value as a variable: `<secret-ref>:<VAR>`; repeatable",
27
+ },
28
+ };
29
+ const INJECTION_FLAGS = ["--env", "--secret"];
30
+ /** Resolve this invocation's `--env` and `--secret` flags. */
31
+ export function resolveInjections() {
32
+ const invocation = getParsedInvocation();
33
+ const values = {};
34
+ const secretValues = [];
35
+ // Parse every secret spec first, so a malformed one fails before any ref is read or audited.
36
+ const secrets = invocation.getAllFlagValues("--secret").map((spec) => {
37
+ const colon = spec.lastIndexOf(":");
38
+ const varName = spec.slice(colon + 1);
39
+ if (colon <= 0 || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(varName)) {
40
+ throw new UsageError(`--secret takes <secret-ref>:<VAR>, for example secrets/deploy-token:GITHUB_TOKEN; got ${JSON.stringify(spec)}.`, "INVALID_FLAG_VALUE");
41
+ }
42
+ return { ref: spec.slice(0, colon), varName };
43
+ });
44
+ for (const ref of invocation.getAllFlagValues("--env")) {
45
+ const binding = resolveEnvBinding(ref);
46
+ Object.assign(values, binding.values);
47
+ secretValues.push(...binding.secretValues);
48
+ }
49
+ for (const { ref, varName } of secrets) {
50
+ const { conceptId, absPath, source } = resolveSecretPath(ref);
51
+ const value = readValue(absPath);
52
+ values[varName] = value;
53
+ secretValues.push(value);
54
+ appendEvent({ eventType: "secret_access", ref: makeSecretRef(conceptId, source), metadata: { var: varName } });
55
+ }
56
+ return { values, secretValues };
57
+ }
58
+ /** `rawArgs` without the injection flags and their values; a `--` tail is kept as it is. */
59
+ export function withoutInjectionFlags(rawArgs) {
60
+ const kept = [];
61
+ for (let i = 0; i < rawArgs.length; i++) {
62
+ const arg = rawArgs[i];
63
+ if (arg === "--")
64
+ return [...kept, ...rawArgs.slice(i)];
65
+ if (INJECTION_FLAGS.includes(arg))
66
+ i++;
67
+ else if (!INJECTION_FLAGS.some((flag) => arg.startsWith(`${flag}=`)))
68
+ kept.push(arg);
69
+ }
70
+ return kept;
71
+ }
72
+ /**
73
+ * Run `command` with `env`, on this terminal, and exit with its status. Never
74
+ * through a shell; the child's own output is not akm's and is not scrubbed.
75
+ */
76
+ export function runChild(command, env) {
77
+ const result = spawnSync(command[0], command.slice(1), { stdio: "inherit", env });
78
+ if (result.error) {
79
+ const code = result.error.code;
80
+ if (code === "ENOENT") {
81
+ throw new NotFoundError(`Command not found: ${command[0]}`, "FILE_NOT_FOUND", `Install '${command[0]}' or add its directory to PATH.`);
82
+ }
83
+ if (code === "EACCES") {
84
+ throw new ConfigError(`Command not executable: ${command[0]}`, "STASH_DIR_UNREADABLE", `Add execute permission ('chmod +x ${command[0]}') or invoke via an interpreter.`);
85
+ }
86
+ throw result.error;
87
+ }
88
+ // Not `process.exit`: the CLI's own cleanup still runs before the process ends with the child's status.
89
+ process.exitCode = result.status ?? 0;
90
+ }
@@ -148,7 +148,7 @@ const secretSetCommand = defineJsonCommand({
148
148
  const secretRunCommand = defineJsonCommand({
149
149
  meta: {
150
150
  name: "run",
151
- description: "Run a command with a secret's value injected into an env var: `akm secret run <ref> <VAR> -- <command>`. The value is set as $VAR in the child process only. Pass --clean to start the child with a minimal inherited environment instead of the full parent environment.",
151
+ description: "Deprecated; use `akm exec --secret <ref>:<VAR> -- <command>`; removed in 0.11. Run a command with a secret's value injected into an env var: `akm secret run <ref> <VAR> -- <command>`. The value is set as $VAR in the child process only. Pass --clean to start the child with a minimal inherited environment instead of the full parent environment.",
152
152
  },
153
153
  args: {
154
154
  ref: { type: "positional", description: "Secret ref", required: true },
@@ -244,7 +244,7 @@ export const secretCommand = defineGroupCommand({
244
244
  meta: {
245
245
  name: "secret",
246
246
  description: "Manage secrets — one standalone sensitive value per file (an API token, a PEM private key, a TLS cert).\n\n" +
247
- "Names are visible; the file contents are the value and never appear in structured output. For a group of related configuration loaded together, use `akm env`. A secret's file lives at `<bundle>/secrets/<name>` (`akm bundle list` shows bundle roots); consume its value without writing it anywhere via `akm secret run <ref> <VAR> -- <command>`.",
247
+ "Names are visible; the file contents are the value and never appear in structured output. For a group of related configuration loaded together, use `akm env`. A secret's file lives at `<bundle>/secrets/<name>` (`akm bundle list` shows bundle roots); consume its value without writing it anywhere via `akm exec --secret <ref>:<VAR> -- <command>`.",
248
248
  },
249
249
  subCommands: {
250
250
  list: secretListCommand,
@@ -0,0 +1,44 @@
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 { getParsedInvocation } from "../cli/invocation.js";
5
+ import { defineJsonCommand } from "../cli/shared.js";
6
+ import { loadConfig } from "../core/config/config.js";
7
+ import { EXEC_CONFIG_KEY, isExecEnabled } from "../core/config/experimental.js";
8
+ import { ConfigError, UsageError } from "../core/errors.js";
9
+ import { buildChildEnv } from "./env/child-env.js";
10
+ import { INJECTION_ARGS, resolveInjections, runChild } from "./env/injection.js";
11
+ /** `akm exec`: any program, with env assets and secrets injected. Experimental and off by default. `akm run` is the same for an akm asset. */
12
+ export const execCommand = defineJsonCommand({
13
+ meta: {
14
+ name: "exec",
15
+ description: "Experimental, off until `experimental.exec` is true in config. Run any command with env assets and secrets injected into its environment: `akm exec [--env <ref>]... [--secret <ref>:<VAR>]... -- <command>`. Use `-- $SHELL` for an interactive session. The command's own output is not scrubbed. Pass --clean to start it with a minimal inherited environment. To run an akm asset, use `akm run <ref>`.",
16
+ },
17
+ args: {
18
+ ...INJECTION_ARGS,
19
+ clean: {
20
+ type: "boolean",
21
+ description: "Start the child with a minimal inherited environment",
22
+ default: false,
23
+ },
24
+ inherit: {
25
+ type: "string",
26
+ description: "With --clean, also inherit these parent env vars (comma-separated)",
27
+ },
28
+ },
29
+ async run({ args }) {
30
+ if (!isExecEnabled(loadConfig())) {
31
+ throw new ConfigError(`akm exec is Experimental and is off. Set ${EXEC_CONFIG_KEY} to true to use it.`, "INVALID_CONFIG_FILE", `Run \`akm config set ${EXEC_CONFIG_KEY} true\`. To run an akm asset with env assets and secrets injected, use \`akm run <ref> --env <ref> --secret <ref>:<VAR>\`.`);
32
+ }
33
+ const command = getParsedInvocation().passthroughArgs();
34
+ if (command.length === 0) {
35
+ throw new UsageError("Missing command. Usage: akm exec [--env <ref>]... [--secret <ref>:<VAR>]... -- <command>");
36
+ }
37
+ const env = buildChildEnv(process.env, {
38
+ clean: args.clean === true,
39
+ inherit: (args.inherit ?? "").split(/[,\s]+/).filter(Boolean),
40
+ });
41
+ Object.assign(env, resolveInjections().values);
42
+ runChild(command, env);
43
+ },
44
+ });
@@ -263,8 +263,8 @@ export function buildDistillPrompt(input) {
263
263
  }
264
264
  }
265
265
  if (input.rejectedProposals && input.rejectedProposals.length > 0) {
266
- lines.push("", "Previously rejected proposals for this ref (Reflexion context):", "The following proposals were already reviewed and rejected. " +
267
- "Your new proposal MUST differ meaningfully in approach, framing, or evidence.");
266
+ lines.push("", "Previously rejected proposals for this ref (Reflexion context):", "Previous attempts were refused for the reasons below. Avoid repeating the same mistake. " +
267
+ "If the evidence has changed, judge the lesson against the current source and feedback.");
268
268
  for (const rp of input.rejectedProposals) {
269
269
  lines.push(`- Rejection reason: ${rp.reason}`);
270
270
  if (rp.contentPreview)
@@ -1096,7 +1096,10 @@ function readDistillFeedback(run) {
1096
1096
  }
1097
1097
  /** System + user prompt: rejected-proposal context, optional CLS neighbours, stash standards. */
1098
1098
  async function buildDistillMessages(run, feedback, kind) {
1099
- const rejectedProposals = rejectedProposalContext(run.stash, run.inputRef, run.options.ctx, run.options.eventsCtx);
1099
+ const rejectedProposals = rejectedProposalContext(run.stash, run.inputRef, run.options.ctx, run.options.eventsCtx, {
1100
+ source: "distill",
1101
+ ref: run.ledgerRef,
1102
+ });
1100
1103
  // CLS interleaving (default on): show the related lessons, knowledge notes and skills, so the writer neither repeats nor overwrites them.
1101
1104
  const cls = getImproveProcessConfig("distill", run.profile)?.cls ?? {};
1102
1105
  let clsContext = "";
@@ -172,8 +172,8 @@ async function runLoopReflectPass(planned, env, tally) {
172
172
  : "reflect-failed",
173
173
  result,
174
174
  });
175
- // A quality rejection recorded itself, and the judge's text is no lesson for
176
- // the next prompt; skips revisit on the `unchanged` cadence. A transient
175
+ // A quality rejection recorded itself for that input, not the shared recent
176
+ // errors sent to other refs; skips revisit on the `unchanged` cadence. A transient
177
177
  // failure (transport, parse, timeout, budget abort, crash) is not a verdict
178
178
  // on the asset and writes no row, like distill: a `failed` row would advance
179
179
  // the ledger cursor and consume the feedback that planned the ref. Only a
@@ -42,7 +42,7 @@ import { CHARS_PER_TOKEN, DEFAULT_CONTEXT_LENGTH_TOKENS } from "./consolidate/ch
42
42
  import { contentHash } from "./content-hash.js";
43
43
  import { findAssetFilePath } from "./eligibility.js";
44
44
  import { resolveImproveExecution } from "./execution.js";
45
- import { recordLedgerAttempt } from "./ledger.js";
45
+ import { recordLedgerAttempt, stateKey } from "./ledger.js";
46
46
  import { bodyHasH1, classifyReflectChange, findReflectDefect, splitFrontmatter, } from "./reflect-noise.js";
47
47
  import { callStageOnce, errMessage, mintProposal, rejectedProposalContext, resolveQualityGateJudge, runReflectQualityJudge, } from "./stage.js";
48
48
  const MAX_FEEDBACK_LINES = 10;
@@ -639,7 +639,7 @@ function gatherReflectPromptSources(options, stash, parsedRef, assetContent) {
639
639
  return {
640
640
  feedback: readRecentFeedback(options.ref ? (options.itemRef ?? options.ref) : undefined, options.eventsCtx, assetContent),
641
641
  schemaHints: buildSchemaHints(parsedRef?.type ?? "", assetContent),
642
- rejectedProposals: rejectedProposalContext(stash, options.ref, options.ctx, options.eventsCtx),
642
+ rejectedProposals: rejectedProposalContext(stash, options.ref, options.ctx, options.eventsCtx, options.ref ? { source: "reflect", ref: stateKey(options.ref, options.itemRef) } : undefined),
643
643
  standardsContext: resolveStandardsContext(parsedRef?.type, stash),
644
644
  };
645
645
  }
@@ -723,7 +723,7 @@ async function finalizeReflectProposal(args) {
723
723
  if (options.ref) {
724
724
  recordLedgerAttempt({ proposalsCtx: options.ctx, eventsCtx: options.eventsCtx }, {
725
725
  stashDir: run.stash,
726
- ref: options.itemRef ?? options.ref,
726
+ ref: stateKey(options.ref, options.itemRef),
727
727
  source: "reflect",
728
728
  outcome: "quality_rejected",
729
729
  detail,
@@ -16,9 +16,12 @@ import { warn } from "../../core/warn.js";
16
16
  import { isRefused, structuredLoop } from "../../llm/structured.js";
17
17
  import { callStructured } from "../../llm/structured-call.js";
18
18
  import { currentLlmStage, withLlmStage } from "../../llm/usage-telemetry.js";
19
+ import { getImproveLedgerRow } from "../../storage/repositories/improve-ledger-repository.js";
20
+ import { getStateProposal } from "../../storage/repositories/proposals-repository.js";
19
21
  import { isProceduralRejection } from "../proposal/proposal-types.js";
20
22
  import { createProposal, listProposalsReadOnly, proposalContentHash, recordGateDecision, } from "../proposal/repository.js";
21
23
  import { resolveImproveExecution } from "./execution.js";
24
+ import { readLedgerDb } from "./ledger.js";
22
25
  /** Normalize an unknown thrown value to a message. */
23
26
  export function errMessage(e) {
24
27
  return e instanceof Error ? e.message : String(e);
@@ -98,25 +101,52 @@ export function attributeStage(plan, process, fn) {
98
101
  /** How many prior rejected proposals are shown to the model as "don't repeat this". */
99
102
  export const MAX_REJECTED_PROPOSALS = 3;
100
103
  /**
101
- * Reflexion context: the newest reviewer rejections for `ref`. Procedural
102
- * refusals (expiry, stale target, missing asset) are not judgements on the
103
- * content and are left out. Reads never create state.db, and an improve run's
104
- * live connection (`eventsCtx.db`) is read through, not copied.
104
+ * The newest content rejections for this input. A guard can reject before
105
+ * minting, and a distill proposal targets its output, not its input; the
106
+ * exact input's last ledger attempt covers both. Procedural refusals do not
107
+ * judge content. Read through the live connection or open one read snapshot.
105
108
  */
106
- export function rejectedProposalContext(stash, ref, ctx, eventsCtx) {
109
+ export function rejectedProposalContext(stash, ref, ctx, eventsCtx, attempt) {
107
110
  if (!ref)
108
111
  return [];
109
- const proposalsCtx = eventsCtx?.db ? { ...ctx, db: eventsCtx.db } : ctx;
110
- return listProposalsReadOnly(stash, { ref, status: "rejected", includeArchive: true }, proposalsCtx)
111
- .filter((p) => !isProceduralRejection(p))
112
- .sort((a, b) => new Date(b.updatedAt ?? 0).getTime() - new Date(a.updatedAt ?? 0).getTime())
113
- .slice(0, MAX_REJECTED_PROPOSALS)
114
- .map((p) => ({
115
- ref: p.ref,
116
- reason: p.review?.reason ?? "no reason given",
117
- // `payload.content` is populated on every row, including legacy ones.
118
- contentPreview: p.payload.content.slice(0, 500),
119
- }));
112
+ const db = eventsCtx?.db ?? ctx?.db;
113
+ return (readLedgerDb({ proposalsCtx: ctx, eventsCtx: db ? { ...eventsCtx, db } : eventsCtx, readOnly: true }, (db) => {
114
+ const proposals = listProposalsReadOnly(stash, { ref, status: "rejected", includeArchive: true }, { ...ctx, db });
115
+ const history = [];
116
+ try {
117
+ const latest = attempt ? getImproveLedgerRow(db, stash, attempt.ref, attempt.source) : undefined;
118
+ if (latest?.outcome === "quality_rejected" && latest.detail) {
119
+ history.push({ at: latest.lastAttemptAt, entry: { ref, reason: latest.detail } });
120
+ }
121
+ else if (latest?.outcome === "rejected" &&
122
+ latest.proposalId &&
123
+ !proposals.some((p) => p.id === latest.proposalId)) {
124
+ const linked = getStateProposal(db, latest.proposalId, stash);
125
+ if (linked?.status === "rejected")
126
+ proposals.push(linked);
127
+ }
128
+ }
129
+ catch (error) {
130
+ // A read-only preview may open a database that predates the ledger.
131
+ warn(`[improve] ledger read failed: ${errMessage(error)}`);
132
+ }
133
+ for (const proposal of proposals) {
134
+ if (isProceduralRejection(proposal))
135
+ continue;
136
+ history.push({
137
+ at: proposal.updatedAt,
138
+ entry: {
139
+ ref: proposal.ref,
140
+ reason: proposal.review?.reason ?? "no reason given",
141
+ contentPreview: proposal.payload.content.slice(0, 500),
142
+ },
143
+ });
144
+ }
145
+ return history
146
+ .sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime())
147
+ .slice(0, MAX_REJECTED_PROPOSALS)
148
+ .map(({ entry }) => entry);
149
+ }) ?? []);
120
150
  }
121
151
  // ── Mint ─────────────────────────────────────────────────────────────────────
122
152
  /**
@@ -168,7 +168,7 @@ export function checkEnvForDangerousKeys(envPath, relPath, envRef) {
168
168
  issues.push({
169
169
  file: relPath,
170
170
  issue: "dangerous-env-key",
171
- detail: `Env key \`${key}\` can be used to hijack process execution when injected via \`akm env run\`. Ref: ${envRef}. Review this file before running \`akm env run\` commands against untrusted stashes. (suppress with: ${SUPPRESSION_COMMENT} on previous line)`,
171
+ detail: `Env key \`${key}\` can be used to hijack process execution when injected via \`akm exec --env\`. Ref: ${envRef}. Review this file before running \`akm exec --env\` commands against untrusted stashes. (suppress with: ${SUPPRESSION_COMMENT} on previous line)`,
172
172
  fixed: false,
173
173
  });
174
174
  }
@@ -11,12 +11,14 @@ import { adapterForId } from "../core/adapter/registry.js";
11
11
  import { makeBundleRef, parseBundleRef } from "../core/asset/asset-ref.js";
12
12
  import { loadConfig } from "../core/config/config.js";
13
13
  import { NotFoundError, UsageError } from "../core/errors.js";
14
+ import { registerInjectedSecretValues } from "../core/redaction.js";
14
15
  import { resolveConceptOwner } from "../indexer/lookup/adapter-concept-owner.js";
15
16
  import { resolveSourceEntries } from "../indexer/search/search-source.js";
16
17
  import { buildFileContext } from "../indexer/walk/file-context.js";
17
18
  import { resolveWorkflowRunTarget } from "../workflows/runtime/runs.js";
18
19
  import { agentCommand } from "./agent/contribute-cli.js";
19
20
  import { commandRunCommand } from "./command/command-cli.js";
21
+ import { INJECTION_ARGS, resolveInjections, withoutInjectionFlags } from "./env/injection.js";
20
22
  import { tasksRunCommand } from "./tasks/tasks-cli.js";
21
23
  import { workflowRunCommand } from "./workflow-cli.js";
22
24
  const EXECUTORS = {
@@ -36,6 +38,8 @@ for (const executor of Object.values(EXECUTORS)) {
36
38
  }
37
39
  delete args.new;
38
40
  delete args.config;
41
+ // `run`'s own: resolved here and taken off the line before the executor sees it.
42
+ Object.assign(args, INJECTION_ARGS);
39
43
  args.ref = {
40
44
  type: "positional",
41
45
  description: "Agent, command, task or workflow ref; or an existing workflow run id",
@@ -45,7 +49,7 @@ export const runAssetCommand = defineJsonCommand({
45
49
  configFile: false,
46
50
  meta: {
47
51
  name: "run",
48
- description: "Run an agent (--prompt/--prompt-stdin), command (--arguments), task (declared input flags), or workflow (declared parameter flags). Existing workflow run ids continue their frozen run. Other workflow lifecycle operations remain under akm workflow.",
52
+ description: "Run an agent (--prompt/--prompt-stdin), command (--arguments), task (declared input flags), or workflow (declared parameter flags). Repeatable --env <ref> and --secret <ref>:<VAR> inject env assets and secrets into the run. Existing workflow run ids continue their frozen run. Other workflow lifecycle operations remain under akm workflow. To run any other program, use `akm exec`.",
49
53
  },
50
54
  args,
51
55
  async run({ args: parsed, rawArgs }) {
@@ -84,9 +88,9 @@ export const runAssetCommand = defineJsonCommand({
84
88
  const executor = EXECUTORS[type];
85
89
  // Preserve raw input spellings and values; replace only the positional ref
86
90
  // with its qualified owner so another bundle cannot retarget a task.
87
- const forwarded = [...rawArgs];
88
- const refIndex = findCittyTopLevelCommandIndex(rawArgs, args);
89
- forwarded[refIndex] = target;
91
+ const positioned = [...rawArgs];
92
+ positioned[findCittyTopLevelCommandIndex(rawArgs, args)] = target;
93
+ const forwarded = withoutInjectionFlags(positioned);
90
94
  if (type === "workflow" &&
91
95
  rawArgs
92
96
  .slice(0, rawArgs.indexOf("--") === -1 ? undefined : rawArgs.indexOf("--"))
@@ -106,6 +110,11 @@ export const runAssetCommand = defineJsonCommand({
106
110
  throw new UsageError(`akm run ${ref} does not accept extra positional arguments or --. Use ${type === "agent" ? "--prompt or --prompt-stdin" : "--arguments"} for its input.`, "INVALID_FLAG_VALUE");
107
111
  }
108
112
  }
113
+ // Every process an executor starts inherits akm's environment, so the injected variables go there, and
114
+ // the secrets among them join what each executor scrubs from the output it captures.
115
+ const injected = resolveInjections();
116
+ Object.assign(process.env, injected.values);
117
+ registerInjectedSecretValues(injected.secretValues);
109
118
  await runCommand(executor.command, { rawArgs: forwarded });
110
119
  },
111
120
  });
@@ -165,7 +165,7 @@ export function dangerousEnvKeyDiagnostics(type, relPath, raw) {
165
165
  diagnostics.push({
166
166
  file: relPath,
167
167
  issue: "dangerous-env-key",
168
- detail: `Env key \`${key}\` can be used to hijack process execution when injected via \`akm env run\`. Ref: ${ref}. Review this file before running \`akm env run\` commands against untrusted stashes. (suppress with: ${SUPPRESSION_COMMENT} on previous line)`,
168
+ detail: `Env key \`${key}\` can be used to hijack process execution when injected via \`akm exec --env\`. Ref: ${ref}. Review this file before running \`akm exec --env\` commands against untrusted stashes. (suppress with: ${SUPPRESSION_COMMENT} on previous line)`,
169
169
  fixed: false,
170
170
  });
171
171
  }
@@ -19,3 +19,9 @@ export function isImproveAutonomyEnabled(config) {
19
19
  * health advisory, and those three must name the same key as the schema.
20
20
  */
21
21
  export const IMPROVE_AUTONOMY_CONFIG_KEY = "experimental.improveAutonomy";
22
+ /** True only when the user has explicitly turned `akm exec` on. */
23
+ export function isExecEnabled(config) {
24
+ return config?.experimental?.exec === true;
25
+ }
26
+ /** The config key that turns `akm exec` on; the refusal and the docs name the same one. */
27
+ export const EXEC_CONFIG_KEY = "experimental.exec";
@@ -29,6 +29,12 @@ export const ExperimentalConfigSchema = z
29
29
  * purpose, and it has its own `sync.push: false` / `--no-push` controls.
30
30
  */
31
31
  improveAutonomy: z.boolean().optional(),
32
+ /**
33
+ * Allow `akm exec`: any command, run with env assets and secrets injected.
34
+ *
35
+ * OFF by default. `akm run --env/--secret`, which injects into an akm asset's run, is not gated.
36
+ */
37
+ exec: z.boolean().optional(),
32
38
  /**
33
39
  * The research learning controls, under the paths `improve.*` has for them. `strategies` is
34
40
  * `improve.strategies` (custom strategies, process `enabled`, `allowedTypes`, quality-gate toggles, reflect