akm-cli 0.10.261130-beta.3 → 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 (60) hide show
  1. package/CHANGELOG.md +14 -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/health/improve-metrics.js +8 -0
  12. package/dist/commands/health/scheduler-binary.js +13 -1
  13. package/dist/commands/improve/consolidate/pair-pass.js +26 -19
  14. package/dist/commands/improve/distill.js +6 -3
  15. package/dist/commands/improve/loop-stages.js +2 -2
  16. package/dist/commands/improve/reflect.js +3 -3
  17. package/dist/commands/improve/stage.js +46 -16
  18. package/dist/commands/lint/env-key-rules.js +1 -1
  19. package/dist/commands/proposal/proposal.js +1 -0
  20. package/dist/commands/proposal/repository.js +164 -69
  21. package/dist/commands/run-cli.js +13 -4
  22. package/dist/commands/sources/installed-stashes.js +37 -7
  23. package/dist/commands/sources/self-update.js +29 -17
  24. package/dist/commands/tasks/tasks.js +56 -9
  25. package/dist/core/adapter/adapters/akm-lint.js +1 -1
  26. package/dist/core/asset/lint-text.js +18 -2
  27. package/dist/core/config/experimental.js +6 -0
  28. package/dist/core/config/schema/experimental.js +6 -0
  29. package/dist/core/redaction.js +10 -0
  30. package/dist/core/type-presentation.js +2 -2
  31. package/dist/integrations/agent/prompts.js +3 -3
  32. package/dist/output/format-exempt.js +2 -0
  33. package/dist/output/renderers.js +2 -2
  34. package/dist/output/shapes/helpers.js +1 -0
  35. package/dist/output/text/proposal-format.js +4 -1
  36. package/dist/scripts/akm-migrate-node.js +23 -5
  37. package/dist/scripts/akm-migrate.js +23 -5
  38. package/dist/tasks/prepare/prepare-support.js +1 -1
  39. package/dist/tasks/resolve-akm-bin.js +12 -5
  40. package/dist/tasks/run/attempt-lifecycle.js +9 -6
  41. package/dist/tasks/run/load-task.js +1 -1
  42. package/dist/tasks/run/run-task.js +31 -11
  43. package/dist/tasks/scheduler-sync.js +1 -1
  44. package/dist/workspace/documents.js +5 -7
  45. package/docs/architecture/akm-core-principles.md +5 -0
  46. package/docs/architecture/architecture.md +1 -1
  47. package/docs/architecture/internals/health-advisories.md +1 -1
  48. package/docs/architecture/internals/improve-workflow.md +1 -1
  49. package/docs/guides/author-bundles.md +1 -1
  50. package/docs/migration/v0.10-to-v0.11.md +17 -1
  51. package/docs/reference/asset-types.md +2 -2
  52. package/docs/reference/cli.md +106 -25
  53. package/docs/reference/configuration.md +5 -1
  54. package/docs/reference/data-and-telemetry.md +2 -2
  55. package/docs/reference/env-and-secrets.md +35 -23
  56. package/docs/reference/tasks.md +18 -1
  57. package/docs/reference/workflow-schema.md +2 -2
  58. package/docs/reference/workspace.md +8 -1
  59. package/package.json +1 -1
  60. 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,8 +52,20 @@ 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
 
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).
62
+ - Accepting an enabled task's retirement reconciles its host-local activation before archiving. A refused retirement leaves the task enabled as it was, another task's sync failure or an unreadable native scheduler is a warning, and reverting does not reactivate it (#1705).
63
+ - Failed scheduled source resolution or preparation records a typed failure with an unknown target in task history, without dispatching the task body. Interactive preflight remains non-mutating (#1711).
64
+ - Consolidation reports same-run retirement conflicts as deferrals, counts parsed verdicts accurately, and keeps deferred pairs eligible for later runs. Health separates deferrals from failures and reports unknown deferral totals for older records (#1706).
65
+ - Stale-path lint treats fenced code as documentation examples. Current paths in prose and frontmatter remain checked, with bundle-level `lint.skip` suppression (#1707).
66
+ - Writable Git bundle updates publish the fetched upstream tracking revision alongside the verified checkout update, preserving local work and concurrent tracking changes; a refused fast-forward restores the tracking revision (#1709).
67
+ - Scheduler version advice recommends rebinding only when the scheduled CLI is older; a newer scheduled CLI directs the caller to update instead (#1710).
68
+
55
69
  - `akm upgrade --channel <channel>` no longer exits 1 when every installed plugin already follows that channel and one update is `deferred` (OpenCode is running) or `skipped`: the entry reports it, as in an upgrade with no `--channel`. It exited 1 on every such run, so AKM Desktop's Update, which always names the channel, failed whenever OpenCode was open. A plugin left on the other channel still makes the switch exit 1. When akm exits 1 without a failed step, AKM Desktop now shows what akm reported as not done (akm's message and each deferred or skipped plugin with its reason) instead of "AKM's upgrade exited with an error."
56
70
  - AKM Desktop's asset page says why its usage and proposal read failed instead of only that it is unavailable. The Software page's hold on Update no longer guesses from the shape of a version whether Desktop's channel will offer that release.
57
71
  - AKM Desktop's Activity views show what akm reports and say when akm reported nothing. `assets.searchMisses` and `activity.retrievalTrend` return `available: false` with the reason when `state.db` is absent or needs a migration, and the Runs, Usage and search-gap views and the Library map's searches that found nothing say so instead of "No runs recorded" or "No searches"; `activity.overview` names it in `errors.state`. `activity.pulse`, `assets.improvement` and `activity.improveImpact` report an unresolvable bundle directory instead of reading it as no proposals. Needs attention counts every failed task run from akm's full count, not the pulse's three-row preview; the Usage summary calls the proposals counted in its window "updated in this window" instead of "pending"; Repeated search gaps lists the queries akm marks `repeated`.
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
+ });
@@ -108,6 +108,7 @@ export function emptyImproveMetrics() {
108
108
  totalChunks: 0,
109
109
  pairsJudged: 0,
110
110
  failedPairs: 0,
111
+ deferredPairs: 0,
111
112
  durationMs: 0,
112
113
  },
113
114
  memoryInference: {
@@ -233,6 +234,9 @@ function projectRunMetrics(result) {
233
234
  if (pairPass) {
234
235
  cons.pairsJudged += toFiniteNumber(pairPass.pairsJudged);
235
236
  cons.failedPairs += toFiniteNumber(pairPass.failedJudgments);
237
+ const deferred = pairPass.deferredJudgments;
238
+ cons.deferredPairs =
239
+ typeof deferred === "number" && Number.isSafeInteger(deferred) && deferred >= 0 ? deferred : null;
236
240
  }
237
241
  }
238
242
  const memoryInference = result.memoryInference;
@@ -291,6 +295,10 @@ function mergeImproveMetrics(dst, src) {
291
295
  dst.consolidation.totalChunks += src.consolidation.totalChunks;
292
296
  dst.consolidation.pairsJudged += src.consolidation.pairsJudged;
293
297
  dst.consolidation.failedPairs += src.consolidation.failedPairs;
298
+ dst.consolidation.deferredPairs =
299
+ dst.consolidation.deferredPairs === null || src.consolidation.deferredPairs === null
300
+ ? null
301
+ : dst.consolidation.deferredPairs + src.consolidation.deferredPairs;
294
302
  dst.consolidation.durationMs += src.consolidation.durationMs;
295
303
  dst.memoryInference.considered += src.memoryInference.considered;
296
304
  dst.memoryInference.freshAttempts += src.memoryInference.freshAttempts;
@@ -21,6 +21,8 @@
21
21
  * a second crontab/launchd/schtasks text parser.
22
22
  */
23
23
  import { spawnSync } from "node:child_process";
24
+ import { isExactSemver } from "../../registry/semver.js";
25
+ import { semverOrder } from "../../runtime.js";
24
26
  import { selectBackend } from "../../tasks/backends/index.js";
25
27
  import { pkgVersion } from "../../version.js";
26
28
  /**
@@ -118,12 +120,22 @@ export async function collectSchedulerBinaryAdvisory(probe, deps = {}) {
118
120
  evidence: { binding, scheduledVersion, cliVersion },
119
121
  };
120
122
  }
123
+ const order = isExactSemver(scheduledVersion) && isExactSemver(cliVersion)
124
+ ? semverOrder(scheduledVersion, cliVersion)
125
+ : undefined;
126
+ const advice = order === -1
127
+ ? " — run `akm doctor scheduler sync --rebind` to rebind the schedule."
128
+ : order === 1
129
+ ? "; the scheduled CLI is newer. Update the calling CLI or plugin, then run health again."
130
+ : order === 0
131
+ ? "; the versions have equal semantic precedence. Inspect both installations before deciding whether to rebind."
132
+ : "; version ordering is unknown. Inspect both installations before deciding whether to rebind.";
121
133
  return {
122
134
  name: "scheduler-binary",
123
135
  kind: "deterministic",
124
136
  status: "warn",
125
137
  confidence: "high",
126
- message: `Scheduled tasks are bound to akm v${scheduledVersion}, but the running CLI is v${cliVersion} — run \`akm doctor scheduler sync --rebind\` to rebind the schedule.`,
138
+ message: `Scheduled tasks are bound to akm v${scheduledVersion}, but the running CLI is v${cliVersion}${advice}`,
127
139
  evidence: { binding, scheduledVersion, cliVersion },
128
140
  };
129
141
  }
@@ -735,13 +735,10 @@ async function judgeOne(ctx, candidate) {
735
735
  // durable half).
736
736
  const retiredKey = stripBundle(retired.asset.ref);
737
737
  const successorKey = stripBundle(successor.asset.ref);
738
- // A retire-worthy verdict the same-run
739
- // chain guard drops is not a settled "no action" — a LATER run, once the
740
- // conflicting retirement has been reviewed, may well mint it. Counted as
741
- // failed so its initiator gets no row (real data: night 1 alone judged 177
742
- // duplicate verdicts into only 59 proposals — 118 silently abandoned).
738
+ // The verdict is valid, but the conflicting proposal must resolve before
739
+ // this retirement can proceed. Leave its initiator eligible for a later run.
743
740
  if (ctx.retiredThisRun.has(retiredKey) || ctx.retiredThisRun.has(successorKey)) {
744
- return failedPair("other", "a note in this pair was already retired earlier in this run");
741
+ return { deferred: "same_run_retirement" };
745
742
  }
746
743
  ctx.retiredThisRun.add(retiredKey);
747
744
  ctx.retiredThisRun.add(successorKey);
@@ -821,7 +818,7 @@ async function judgeOne(ctx, candidate) {
821
818
  catch (error) {
822
819
  ctx.warnings.push(`Pair pass: could not mint a retire proposal for ${retired.asset.ref}: ${error instanceof Error ? error.message : String(error)}`);
823
820
  // A mint failure is transient (a lock, a disk error, a
824
- // validation hiccup) — treated the same as a same-run drop, so no row is
821
+ // validation hiccup) — no row is
825
822
  // written and the pair is retried next run instead of abandoned.
826
823
  return failedPair("other", error instanceof Error ? error.message : String(error));
827
824
  }
@@ -851,6 +848,7 @@ seams = {}) {
851
848
  labelCounts: emptyLabelCounts(),
852
849
  retired: [],
853
850
  failedJudgments: 0,
851
+ deferredJudgments: 0,
854
852
  };
855
853
  const llmRunner = opts.llmRunner ?? undefined;
856
854
  if (!bundleId || !llmRunner)
@@ -958,27 +956,31 @@ seams = {}) {
958
956
  continuitySearch: seams.continuitySearch ?? createContinuitySearch(stashDir, config),
959
957
  };
960
958
  const failures = [];
961
- // An initiator with any failed (or never-sent) judge call
962
- // gets no ledger row — a failure attempted nothing conclusive, so writing
963
- // one would mean the pair is never retried.
964
- const failedInitiators = new Set();
959
+ const deferrals = [];
960
+ // Failed or deferred pairs get no ledger row: their work is still unsettled.
961
+ const unsettledInitiators = new Set();
965
962
  if (judgeable.length > 0) {
966
963
  const results = await concurrentMap(judgeable, (candidate) => judgeOne(ctx, candidate), (llmRunner.kind === "connection" ? llmRunner.concurrency : undefined) ?? 1, { signal: opts.signal });
967
964
  results.forEach((r, idx) => {
968
965
  // `concurrentMap` leaves an entry `undefined` for a call an aborted run never sent at all: that pair did not
969
966
  // settle either, so it is counted as cancelled rather than as a clean "no action" verdict.
970
967
  const failure = r === undefined ? { kind: "cancelled", reason: "not sent: the run was cancelled" } : r.failure;
971
- if (!failure)
968
+ const deferred = r?.deferred;
969
+ if (!failure && !deferred)
972
970
  return;
973
971
  const candidate = judgeable[idx];
974
- failedInitiators.add(candidate.initiator.ref);
975
- failures.push({ initiator: candidate.initiator.ref, other: candidate.other.ref, ...failure });
972
+ unsettledInitiators.add(candidate.initiator.ref);
973
+ const pair = { initiator: candidate.initiator.ref, other: candidate.other.ref };
974
+ if (failure)
975
+ failures.push({ ...pair, ...failure });
976
+ if (deferred)
977
+ deferrals.push({ ...pair, reason: deferred });
976
978
  });
977
979
  }
978
980
  // S1: a ledger row is written for an initiator only once ALL of its OWN
979
981
  // candidates were admitted (whole-initiator admission above makes this a
980
982
  // simple membership check: judgeable either has every one of an
981
- // initiator's candidates, or none of them) and none of them failed
983
+ // initiator's candidates, or none of them) and none failed or were deferred
982
984
  // — including an initiator with zero candidates, which
983
985
  // trivially satisfies both. One left out by the cap or a pending-proposal
984
986
  // collision gets no row at all, so the next run reconsiders it rather
@@ -995,7 +997,7 @@ seams = {}) {
995
997
  return true;
996
998
  if (!admittedRefs.has(i.ref))
997
999
  return false;
998
- return !failedInitiators.has(i.ref);
1000
+ return !unsettledInitiators.has(i.ref);
999
1001
  })
1000
1002
  .map((i) => ({
1001
1003
  stashDir,
@@ -1006,6 +1008,10 @@ seams = {}) {
1006
1008
  }));
1007
1009
  recordLedgerAttempt({ proposalsCtx: opts.proposalsCtx }, ledgerInputs);
1008
1010
  }
1011
+ const deferredJudgments = deferrals.length;
1012
+ if (deferredJudgments > 0) {
1013
+ warnings.push(`Pair pass: ${deferredJudgments} retire decisions deferred because a note is already reserved for retirement in this run; these pairs remain eligible for later runs.`);
1014
+ }
1009
1015
  const failedJudgments = failures.length;
1010
1016
  const failureKinds = {};
1011
1017
  for (const { kind } of failures)
@@ -1020,12 +1026,13 @@ seams = {}) {
1020
1026
  initiators: initiators.length,
1021
1027
  initiatorsBacklog,
1022
1028
  pairsConsidered: candidates.length,
1023
- // Parsed verdicts only — judgeable.length counted pairs that
1024
- // were admitted, not pairs a verdict actually came back for.
1025
- pairsJudged: judgeable.length - failedJudgments,
1029
+ // Count the judge's parsed verdicts, including decisions deferred or failing after the verdict.
1030
+ pairsJudged: Object.values(ctx.labelCounts).reduce((sum, count) => sum + count, 0),
1026
1031
  labelCounts: ctx.labelCounts,
1027
1032
  retired: ctx.retired,
1028
1033
  failedJudgments,
1034
+ deferredJudgments,
1035
+ ...(deferredJudgments > 0 ? { deferrals: deferrals.slice(0, PAIR_FAILURES_REPORTED_MAX) } : {}),
1029
1036
  ...(failedJudgments > 0 ? { failureKinds, failures: failures.slice(0, PAIR_FAILURES_REPORTED_MAX) } : {}),
1030
1037
  };
1031
1038
  }
@@ -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,