akm-cli 0.9.0-rc.0 → 0.9.0-rc.2

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 (262) hide show
  1. package/CHANGELOG.md +339 -2
  2. package/SECURITY.md +23 -24
  3. package/dist/assets/help/help-improve.md +10 -10
  4. package/dist/assets/hints/cli-hints-full.md +44 -10
  5. package/dist/assets/hints/cli-hints-short.md +6 -2
  6. package/dist/assets/{profiles → improve-strategies}/default.json +1 -0
  7. package/dist/assets/{profiles → improve-strategies}/graph-refresh.json +1 -1
  8. package/dist/assets/{profiles → improve-strategies}/proactive-maintenance.json +2 -3
  9. package/dist/assets/{profiles → improve-strategies}/reflect-distill.json +3 -4
  10. package/dist/assets/prompts/workflow-unit-preamble.md +26 -0
  11. package/dist/assets/stash-skeleton/README.md +28 -0
  12. package/dist/assets/stash-skeleton/facts/conventions/assets/agent.md +6 -0
  13. package/dist/assets/stash-skeleton/facts/conventions/assets/command.md +6 -0
  14. package/dist/assets/stash-skeleton/facts/conventions/assets/fact.md +12 -1
  15. package/dist/assets/stash-skeleton/facts/conventions/assets/knowledge.md +11 -1
  16. package/dist/assets/stash-skeleton/facts/conventions/assets/lesson.md +6 -0
  17. package/dist/assets/stash-skeleton/facts/conventions/assets/memory.md +9 -0
  18. package/dist/assets/stash-skeleton/facts/conventions/assets/script.md +7 -0
  19. package/dist/assets/stash-skeleton/facts/conventions/assets/skill.md +7 -0
  20. package/dist/assets/stash-skeleton/facts/conventions/assets/workflow.md +6 -0
  21. package/dist/assets/stash-skeleton/facts/conventions/backlinks.md +98 -0
  22. package/dist/assets/stash-skeleton/facts/conventions/domains.md +63 -0
  23. package/dist/assets/stash-skeleton/facts/conventions/organization.md +127 -0
  24. package/dist/assets/tasks/core/backup.yml +1 -0
  25. package/dist/assets/tasks/core/extract.yml +1 -0
  26. package/dist/assets/tasks/core/improve.yml +1 -0
  27. package/dist/assets/tasks/core/index-refresh.yml +1 -0
  28. package/dist/assets/tasks/core/sync.yml +1 -0
  29. package/dist/assets/tasks/core/version-check.yml +1 -0
  30. package/dist/assets/tasks/graph-refresh-weekly.yml +4 -4
  31. package/dist/assets/templates/html/health.html +5 -1
  32. package/dist/cli/config-migrate.js +31 -138
  33. package/dist/cli/config-validate.js +10 -8
  34. package/dist/cli.js +48 -14
  35. package/dist/commands/agent/agent-dispatch.js +17 -16
  36. package/dist/commands/agent/agent-support.js +0 -24
  37. package/dist/commands/agent/contribute-cli.js +5 -15
  38. package/dist/commands/backup-cli.js +54 -0
  39. package/dist/commands/config-cli.js +45 -159
  40. package/dist/commands/env/env-binding.js +95 -0
  41. package/dist/commands/env/env-cli.js +8 -65
  42. package/dist/commands/env/secret.js +8 -5
  43. package/dist/commands/health/checks.js +130 -83
  44. package/dist/commands/health/html-report.js +4 -0
  45. package/dist/commands/health/improve-metrics.js +30 -32
  46. package/dist/commands/health/llm-usage.js +19 -19
  47. package/dist/commands/health/md-report.js +4 -0
  48. package/dist/commands/health/metrics.js +2 -1
  49. package/dist/commands/health/surfaces.js +5 -4
  50. package/dist/commands/health.js +1 -1
  51. package/dist/commands/improve/consolidate/chunking.js +2 -2
  52. package/dist/commands/improve/consolidate.js +28 -25
  53. package/dist/commands/improve/distill/promote-memory.js +5 -12
  54. package/dist/commands/improve/distill/quality-gate.js +5 -7
  55. package/dist/commands/improve/distill.js +16 -5
  56. package/dist/commands/improve/eligibility.js +22 -12
  57. package/dist/commands/improve/extract-cli.js +47 -19
  58. package/dist/commands/improve/extract.js +110 -62
  59. package/dist/commands/improve/improve-cli.js +38 -16
  60. package/dist/commands/improve/improve-result-file.js +30 -24
  61. package/dist/commands/improve/improve-strategies.js +137 -0
  62. package/dist/commands/improve/improve.js +60 -30
  63. package/dist/commands/improve/locks.js +66 -45
  64. package/dist/commands/improve/loop-stages.js +75 -33
  65. package/dist/commands/improve/memory/memory-belief.js +79 -7
  66. package/dist/commands/improve/memory/memory-contradiction-detect.js +12 -4
  67. package/dist/commands/improve/preparation.js +71 -73
  68. package/dist/commands/improve/procedural.js +3 -2
  69. package/dist/commands/improve/recombine.js +2 -1
  70. package/dist/commands/improve/reflect.js +119 -214
  71. package/dist/commands/improve/shared.js +11 -5
  72. package/dist/commands/lint/base-linter.js +152 -42
  73. package/dist/commands/mv-cli.js +809 -0
  74. package/dist/commands/proposal/proposal-cli.js +18 -8
  75. package/dist/commands/proposal/propose.js +64 -69
  76. package/dist/commands/read/knowledge.js +436 -4
  77. package/dist/commands/read/remember-cli.js +39 -2
  78. package/dist/commands/read/search-cli.js +6 -1
  79. package/dist/commands/registry-cli.js +29 -14
  80. package/dist/commands/remember.js +2 -0
  81. package/dist/commands/sources/init.js +13 -14
  82. package/dist/commands/sources/migration-help.js +7 -4
  83. package/dist/commands/sources/schema-repair.js +2 -4
  84. package/dist/commands/sources/source-add.js +62 -73
  85. package/dist/commands/sources/source-manage.js +50 -46
  86. package/dist/commands/sources/stash-cli.js +41 -4
  87. package/dist/commands/tasks/default-tasks.js +12 -12
  88. package/dist/commands/tasks/tasks-cli.js +7 -3
  89. package/dist/commands/tasks/tasks.js +113 -18
  90. package/dist/commands/wiki-cli.js +9 -10
  91. package/dist/commands/workflow-cli.js +276 -12
  92. package/dist/core/asset/asset-spec.js +58 -1
  93. package/dist/core/asset/frontmatter.js +12 -2
  94. package/dist/core/common.js +5 -3
  95. package/dist/core/config/config-io.js +28 -17
  96. package/dist/core/config/config-schema.js +379 -66
  97. package/dist/core/config/config-types.js +3 -3
  98. package/dist/core/config/config-version.js +29 -0
  99. package/dist/core/config/config-walker.js +98 -27
  100. package/dist/core/config/config.js +132 -266
  101. package/dist/core/config/deep-merge.js +41 -0
  102. package/dist/core/config/engine-semantics.js +32 -0
  103. package/dist/core/errors.js +2 -2
  104. package/dist/core/extra-params.js +61 -0
  105. package/dist/core/file-lock.js +201 -56
  106. package/dist/core/improve-result.js +178 -0
  107. package/dist/core/json-schema.js +142 -0
  108. package/dist/core/maintenance-barrier.js +119 -0
  109. package/dist/core/migration-backup.js +416 -0
  110. package/dist/core/paths.js +3 -0
  111. package/dist/core/redaction.js +358 -0
  112. package/dist/core/state/migrations.js +17 -2
  113. package/dist/core/state-db.js +44 -1
  114. package/dist/indexer/db/db.js +118 -2
  115. package/dist/indexer/graph/graph-extraction.js +28 -16
  116. package/dist/indexer/index-writer-lock.js +31 -24
  117. package/dist/indexer/index-written-assets.js +15 -6
  118. package/dist/indexer/indexer.js +47 -2
  119. package/dist/indexer/passes/memory-inference.js +10 -6
  120. package/dist/indexer/passes/metadata.js +250 -0
  121. package/dist/indexer/search/db-search.js +111 -44
  122. package/dist/indexer/search/fts-query.js +41 -0
  123. package/dist/indexer/search/ranking-contributors.js +48 -0
  124. package/dist/indexer/search/ranking.js +36 -23
  125. package/dist/indexer/search/search-fields.js +11 -1
  126. package/dist/indexer/walk/matchers.js +39 -0
  127. package/dist/integrations/agent/builder-shared.js +7 -0
  128. package/dist/integrations/agent/builders.js +5 -50
  129. package/dist/integrations/agent/config.js +3 -143
  130. package/dist/integrations/agent/detect.js +17 -2
  131. package/dist/integrations/agent/engine-resolution.js +202 -0
  132. package/dist/integrations/agent/index.js +1 -2
  133. package/dist/integrations/agent/model-aliases.js +16 -2
  134. package/dist/integrations/agent/profiles.js +36 -62
  135. package/dist/integrations/agent/runner-dispatch.js +91 -4
  136. package/dist/integrations/agent/runner.js +76 -207
  137. package/dist/integrations/agent/spawn.js +141 -20
  138. package/dist/integrations/harnesses/aider/agent-builder.js +112 -0
  139. package/dist/integrations/harnesses/aider/index.js +57 -0
  140. package/dist/integrations/harnesses/aider/result-extractor.js +53 -0
  141. package/dist/integrations/harnesses/amazonq/agent-builder.js +152 -0
  142. package/dist/integrations/harnesses/amazonq/index.js +58 -0
  143. package/dist/integrations/harnesses/amazonq/result-extractor.js +48 -0
  144. package/dist/integrations/harnesses/claude/agent-builder.js +46 -8
  145. package/dist/integrations/harnesses/claude/index.js +25 -25
  146. package/dist/integrations/harnesses/claude/result-extractor.js +52 -0
  147. package/dist/integrations/harnesses/codex/agent-builder.js +136 -0
  148. package/dist/integrations/harnesses/codex/index.js +62 -0
  149. package/dist/integrations/harnesses/codex/result-extractor.js +73 -0
  150. package/dist/integrations/harnesses/copilot/agent-builder.js +121 -0
  151. package/dist/integrations/harnesses/copilot/index.js +59 -0
  152. package/dist/integrations/harnesses/copilot/result-extractor.js +151 -0
  153. package/dist/integrations/harnesses/gemini/agent-builder.js +120 -0
  154. package/dist/integrations/harnesses/gemini/index.js +59 -0
  155. package/dist/integrations/harnesses/gemini/result-extractor.js +121 -0
  156. package/dist/integrations/harnesses/index.js +27 -28
  157. package/dist/integrations/harnesses/opencode/agent-builder.js +2 -3
  158. package/dist/integrations/harnesses/opencode/index.js +15 -22
  159. package/dist/integrations/harnesses/opencode-sdk/harness.js +60 -0
  160. package/dist/integrations/harnesses/opencode-sdk/index.js +8 -32
  161. package/dist/integrations/harnesses/opencode-sdk/sdk-runner.js +681 -108
  162. package/dist/integrations/harnesses/openhands/agent-builder.js +125 -0
  163. package/dist/integrations/harnesses/openhands/index.js +57 -0
  164. package/dist/integrations/harnesses/openhands/result-extractor.js +103 -0
  165. package/dist/integrations/harnesses/pi/agent-builder.js +103 -0
  166. package/dist/integrations/harnesses/pi/index.js +57 -0
  167. package/dist/integrations/harnesses/pi/result-extractor.js +135 -0
  168. package/dist/integrations/harnesses/types.js +8 -32
  169. package/dist/integrations/lockfile.js +32 -21
  170. package/dist/integrations/session-logs/index.js +24 -11
  171. package/dist/llm/client.js +48 -14
  172. package/dist/llm/feature-gate.js +15 -47
  173. package/dist/llm/graph-extract.js +1 -1
  174. package/dist/llm/index-passes.js +8 -42
  175. package/dist/llm/memory-infer-impl.js +1 -1
  176. package/dist/llm/usage-persist.js +4 -0
  177. package/dist/llm/usage-telemetry.js +35 -5
  178. package/dist/output/renderers.js +3 -2
  179. package/dist/output/shapes/helpers.js +2 -1
  180. package/dist/output/shapes/passthrough.js +6 -0
  181. package/dist/output/text/helpers.js +215 -2
  182. package/dist/output/text/workflow.js +3 -1
  183. package/dist/schemas/akm-config.json +16638 -0
  184. package/dist/schemas/akm-task.json +87 -0
  185. package/dist/schemas/akm-workflow.json +372 -0
  186. package/dist/scripts/migrate-storage.js +10944 -8801
  187. package/dist/scripts/migrations/import-fs-improve-runs-to-db.js +9247 -350
  188. package/dist/setup/detected-engines.js +142 -0
  189. package/dist/setup/engine-config.js +89 -0
  190. package/dist/setup/setup.js +236 -132
  191. package/dist/setup/steps/connection.js +61 -32
  192. package/dist/setup/steps/platforms.js +4 -4
  193. package/dist/setup/steps.js +3 -2
  194. package/dist/storage/database.js +13 -1
  195. package/dist/storage/engines/sqlite-migrations.js +1 -0
  196. package/dist/storage/repositories/improve-runs-repository.js +5 -5
  197. package/dist/storage/repositories/task-history-repository.js +78 -0
  198. package/dist/storage/repositories/workflow-runs-repository.js +190 -1
  199. package/dist/tasks/parser.js +138 -52
  200. package/dist/tasks/runner.js +71 -75
  201. package/dist/tasks/schema.js +1 -1
  202. package/dist/tasks/validator.js +11 -6
  203. package/dist/text-import-hook.mjs +1 -1
  204. package/dist/wiki/wiki.js +9 -8
  205. package/dist/workflows/authoring/authoring.js +123 -10
  206. package/dist/workflows/authoring/workflow-program-template.yaml +31 -0
  207. package/dist/workflows/cli.js +4 -0
  208. package/dist/workflows/concurrency-policy.js +15 -0
  209. package/dist/workflows/db.js +200 -13
  210. package/dist/workflows/exec/brief.js +478 -0
  211. package/dist/workflows/exec/frozen-judge.js +47 -0
  212. package/dist/workflows/exec/native-executor.js +1034 -0
  213. package/dist/workflows/exec/param-secrets.js +115 -0
  214. package/dist/workflows/exec/report.js +1355 -0
  215. package/dist/workflows/exec/run-workflow.js +609 -0
  216. package/dist/workflows/exec/scheduler.js +71 -0
  217. package/dist/workflows/exec/step-work.js +1212 -0
  218. package/dist/workflows/exec/unit-writer.js +23 -0
  219. package/dist/workflows/exec/watch.js +116 -0
  220. package/dist/workflows/exec/worktree.js +171 -0
  221. package/dist/workflows/ir/compile.js +375 -0
  222. package/dist/workflows/ir/freeze.js +243 -0
  223. package/dist/workflows/ir/params.js +54 -0
  224. package/dist/workflows/ir/plan-hash.js +68 -0
  225. package/dist/workflows/ir/schema.js +545 -0
  226. package/dist/workflows/parser.js +10 -1
  227. package/dist/workflows/program/expressions.js +369 -0
  228. package/dist/workflows/program/parser.js +869 -0
  229. package/dist/workflows/program/project.js +104 -0
  230. package/dist/workflows/program/schema.js +54 -0
  231. package/dist/workflows/renderer.js +82 -5
  232. package/dist/workflows/resource-limits.js +20 -0
  233. package/dist/workflows/runtime/agent-identity.js +59 -14
  234. package/dist/workflows/runtime/plan-classifier.js +187 -0
  235. package/dist/workflows/runtime/runs.js +246 -69
  236. package/dist/workflows/runtime/unit-checkin.js +45 -0
  237. package/dist/workflows/runtime/workflow-asset-loader.js +42 -1
  238. package/dist/workflows/validate-summary.js +24 -3
  239. package/dist/workflows/validator.js +26 -1
  240. package/docs/data-and-telemetry.md +4 -3
  241. package/docs/migration/release-notes/0.6.0.md +1 -1
  242. package/docs/migration/release-notes/0.7.0.md +5 -4
  243. package/docs/migration/release-notes/0.9.0-beta.60.md +19 -0
  244. package/docs/migration/v0.8-to-v0.9.md +401 -0
  245. package/package.json +4 -2
  246. package/schemas/akm-config.json +16638 -0
  247. package/schemas/akm-task.json +87 -0
  248. package/schemas/akm-workflow.json +372 -0
  249. package/dist/commands/improve/improve-profiles.js +0 -168
  250. package/dist/core/config/config-migration.js +0 -602
  251. package/dist/core/deep-merge.js +0 -38
  252. package/dist/llm/call-ai.js +0 -62
  253. package/dist/setup/legacy-config.js +0 -106
  254. package/docs/README.md +0 -104
  255. /package/dist/assets/{profiles → improve-strategies}/catchup.json +0 -0
  256. /package/dist/assets/{profiles → improve-strategies}/consolidate.json +0 -0
  257. /package/dist/assets/{profiles → improve-strategies}/frequent.json +0 -0
  258. /package/dist/assets/{profiles → improve-strategies}/memory-focus.json +0 -0
  259. /package/dist/assets/{profiles → improve-strategies}/quick.json +0 -0
  260. /package/dist/assets/{profiles → improve-strategies}/recombine-only.json +0 -0
  261. /package/dist/assets/{profiles → improve-strategies}/synthesize.json +0 -0
  262. /package/dist/assets/{profiles → improve-strategies}/thorough.json +0 -0
@@ -0,0 +1,478 @@
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
+ * `akm workflow brief <run>` — the read-only half of the harness-neutral driver
6
+ * protocol (redesign addendum R3). It tells ANY agent session (Claude Code,
7
+ * opencode, Codex, a human at a shell) exactly what units the native engine
8
+ * would dispatch for a run's active step, and how to report the results back
9
+ * through `akm workflow report` (the mutating half, R3 step 3).
10
+ *
11
+ * ## Read-only, no lease, no dispatch, no mutation
12
+ *
13
+ * `brief` computes; it never writes. It takes no engine lease, dispatches no
14
+ * units, and never advances the gate spine. The only database access is
15
+ * SELECTs (`getNextWorkflowStep` + the run row + the unit journal). A test
16
+ * proves the workflow.db file is byte-identical before and after a `brief`.
17
+ *
18
+ * ## No duplicated semantics (the cardinal rule)
19
+ *
20
+ * The expected work-list is computed by the SAME shared functions the engine
21
+ * uses (`step-work.ts`): {@link computeStepWorkList} for item resolution +
22
+ * content-derived unit ids + input hashes + prompt assembly,
23
+ * {@link activeGateLoop} / {@link recoverGateFeedback} to recover the gate-loop
24
+ * number and the judge feedback the engine threads into loop-N prompts (so a
25
+ * loop-2 brief's unit ids/hashes equal what the engine would compute),
26
+ * {@link stepOutputsFromEvidence} for the expression scope, and
27
+ * {@link evaluateRoute} for the deterministic route decision. Because both
28
+ * surfaces call one implementation, an engine-driven run and a brief/report
29
+ * driven run of the same frozen plan produce byte-identical unit graphs — the
30
+ * invariant R4 asserts.
31
+ */
32
+ import { parseAssetRef } from "../../core/asset/asset-ref.js";
33
+ import { canonicalizeWorkflowName } from "../../core/asset/asset-spec.js";
34
+ import { NotFoundError, UsageError } from "../../core/errors.js";
35
+ import { withWorkflowRunsRepo } from "../../storage/repositories/workflow-runs-repository.js";
36
+ import { getCurrentWorkflowScopeKey } from "../authoring/scope-key.js";
37
+ import { assertRunParamsSatisfyPlan } from "../ir/params.js";
38
+ import { frozenStepRows, requireExecutableWorkflowPlan } from "../runtime/plan-classifier.js";
39
+ import { snapshotRunForDriver } from "../runtime/runs.js";
40
+ import { evaluateStaleUnits } from "../runtime/unit-checkin.js";
41
+ import { detectSecretShapedParams } from "./param-secrets.js";
42
+ import { activeGateLoop, assertJournaledRouteSelectionsValid, computeStepWorkList, evaluateRoute, GATE_EVALUATION_PHASE, isWorkListFullyTerminal, recoverGateFeedback, selectUnitAttemptRow, stepOutputsFromEvidence, } from "./step-work.js";
43
+ const EMPTY_WORK_LIST = { isFanOut: false, reducer: null, itemCount: 0, units: [] };
44
+ // ── Entry point ──────────────────────────────────────────────────────────────
45
+ /**
46
+ * Build the read-only brief for a run. `target` is a run id (preferred) or a
47
+ * workflow ref that ALREADY has an active run in the current scope — brief
48
+ * never auto-starts a run (that would mutate), so a ref with no active run is a
49
+ * NotFoundError, not a silent start.
50
+ */
51
+ export async function buildWorkflowBrief(target) {
52
+ const runId = await resolveRunId(target);
53
+ // Read-only spine walk. #14: read the run row, its steps, AND its unit journal
54
+ // in ONE transaction so a concurrent report/run/manual completion cannot change
55
+ // the active step between the spine read and the unit-journal read. A bare run
56
+ // id never auto-starts (we resolved to a concrete id above).
57
+ const { next, run: runRow, units } = await snapshotRunForDriver(runId);
58
+ const leaseHolder = runRow.engine_lease_holder;
59
+ const leaseUntil = runRow.engine_lease_until;
60
+ const run = {
61
+ id: next.run.id,
62
+ workflowRef: next.run.workflowRef,
63
+ workflowTitle: next.run.workflowTitle,
64
+ status: next.run.status,
65
+ currentStepId: next.run.currentStepId ?? null,
66
+ params: next.run.params ?? {},
67
+ };
68
+ const warnings = [];
69
+ // #13: params are declared NON-SECRET. They are interpolated into every unit
70
+ // prompt AND hashed into the unit identity, so `brief` cannot redact them
71
+ // without breaking the byte-identical-prompt contract a driver executes
72
+ // against. Surface the standing advisory (whenever the run carries params) plus
73
+ // any best-effort secret-shaped-value hits, so an author moves credentials to
74
+ // an env binding (which `brief` only ever names).
75
+ if (Object.keys(run.params).length > 0) {
76
+ warnings.push("Workflow params are copied verbatim into every unit prompt shown to any driver and are hashed into the unit " +
77
+ "identity — they are NOT secret. Never put credentials in params; put secrets in env bindings (`env:` refs), " +
78
+ "which `brief` surfaces by name only and never resolves.");
79
+ }
80
+ warnings.push(...detectSecretShapedParams(run.params));
81
+ const lease = buildLease(leaseHolder, leaseUntil);
82
+ if (lease?.live) {
83
+ warnings.push(`Engine ${lease.holder} holds a LIVE run lease (expires ${lease.until}). This run is being driven by the ` +
84
+ `native engine right now — \`akm workflow report\` is REFUSED while the lease is live. Do NOT execute these ` +
85
+ `units; wait for the engine to finish or for the lease to expire.`);
86
+ }
87
+ // Stale claimed units (pure timestamp evaluation): a driver claimed these via
88
+ // `report --status running` but has not heartbeated within the window — flag
89
+ // them so another driver can reclaim the abandoned work.
90
+ const staleUnits = evaluateStaleUnits(units);
91
+ if (staleUnits.length > 0) {
92
+ warnings.push(`${staleUnits.length} unit(s) were claimed with \`report --status running\` but have gone silent past the ` +
93
+ `check-in window (${staleUnits.map((u) => u.unitId).join(", ")}). Their driver may have died — you can ` +
94
+ `reclaim and re-execute them.`);
95
+ }
96
+ const reportGuidance = {
97
+ checkin: `akm workflow report ${run.id} --unit <unit_id> --status running --note "<short progress note>"`,
98
+ failure: `akm workflow report ${run.id} --unit <unit_id> --status failed --failure-reason <vocab>`,
99
+ note: "Run each unit, then report its result. A unit belongs to the active step's work-list; its unit_id is content-derived — copy it verbatim.",
100
+ };
101
+ // Spine watermark (#14): run-mutation counter shared by every return below.
102
+ // The active branch re-stamps it with the real gate loop + active step id.
103
+ const watermark = `${runRow.updated_at}:u${units.length}`;
104
+ const base = {
105
+ ok: true,
106
+ run,
107
+ spineToken: makeSpineToken(run.id, run.currentStepId, 1, watermark),
108
+ ...(lease ? { engineLease: lease } : {}),
109
+ reportGuidance,
110
+ staleUnits,
111
+ warnings,
112
+ };
113
+ // Completed run: nothing to do.
114
+ if (next.done || run.status === "completed") {
115
+ return {
116
+ ...base,
117
+ done: true,
118
+ active: false,
119
+ workList: EMPTY_WORK_LIST,
120
+ message: "Workflow run is completed — no work remains.",
121
+ };
122
+ }
123
+ // Blocked / failed: not active, so the engine dispatches nothing. Point the
124
+ // driver at `resume` rather than inventing a work-list for a dead run.
125
+ if (run.status !== "active") {
126
+ warnings.push(`Workflow run is ${run.status}, not active — no work-list. Reopen it first: \`akm workflow resume ${run.id}\`.`);
127
+ return {
128
+ ...base,
129
+ active: false,
130
+ workList: EMPTY_WORK_LIST,
131
+ message: `Workflow run is ${run.status} — resume it to continue.`,
132
+ };
133
+ }
134
+ const stepState = next.step;
135
+ if (!stepState) {
136
+ return {
137
+ ...base,
138
+ active: false,
139
+ workList: EMPTY_WORK_LIST,
140
+ message: "Workflow run is active but has no current step.",
141
+ };
142
+ }
143
+ // Load the FROZEN plan the engine executes (migration 006). A legacy run
144
+ // (NULL plan_json) has no plan for brief to read — point at engine-driven
145
+ // mode, which still handles pre-006 runs by compiling from the asset.
146
+ const plan = requireExecutableWorkflowPlan(runRow);
147
+ // Reviewer #12: the journaled params row must still satisfy the frozen param
148
+ // schemas — a violation is post-start corruption, loud on the brief surface
149
+ // too (mirrors the frozen-plan hash check and the tampered-params divergence).
150
+ assertRunParamsSatisfyPlan(run.id, plan, next.run.params ?? {});
151
+ // Reviewer #7: a completed route step whose journaled decision names a target
152
+ // the route never declared is tampered evidence — fail loudly on the read-only
153
+ // brief surface too, not just on the resume/report surfaces that replay it.
154
+ assertJournaledRouteSelectionsValid(plan, next);
155
+ const stepPlan = plan.steps.find((s) => s.stepId === stepState.id);
156
+ if (!stepPlan) {
157
+ throw new UsageError(`Step "${stepState.id}" of run ${run.id} is not present in the run's frozen plan. The plan and the step ` +
158
+ `journal disagree — this run cannot be described; drive it manually with \`akm workflow complete\`.`);
159
+ }
160
+ // Expression scope: prior steps' promoted artifacts + run params, projected
161
+ // exactly as the engine does (stepOutputsFromEvidence). The current (pending)
162
+ // step contributes no output yet.
163
+ const evidence = {};
164
+ for (const s of next.workflow.steps)
165
+ evidence[s.id] = s.evidence;
166
+ const stepOutputs = stepOutputsFromEvidence(evidence);
167
+ // Gate loop + recovered feedback — the journal-derived state that makes a
168
+ // loop-N brief predict the engine's loop-N dispatch (unit ids + hashes).
169
+ const gateLoop = activeGateLoop(units, stepState.id);
170
+ const gateFeedback = recoverGateFeedback(units, stepState.id, gateLoop);
171
+ const isRouteOnly = !!stepPlan.route && !stepPlan.root;
172
+ const kind = isRouteOnly ? "route" : stepPlan.route ? "execute-and-route" : "execute";
173
+ const criteria = stepPlan.gate.criteria;
174
+ const instructions = frozenStepRows(plan).find((step) => step.stepId === stepState.id)?.instructions;
175
+ if (instructions === undefined)
176
+ throw new UsageError(`Step "${stepState.id}" has no frozen instructions.`);
177
+ const step = {
178
+ stepId: stepState.id,
179
+ title: stepPlan.title,
180
+ sequenceIndex: stepPlan.sequenceIndex,
181
+ kind,
182
+ instructions,
183
+ gate: {
184
+ criteria,
185
+ maxLoops: Math.max(1, stepPlan.gate.maxLoops ?? 1),
186
+ currentLoop: gateLoop,
187
+ judgesArtifact: !isRouteOnly && criteria.length > 0,
188
+ required: stepPlan.gate.required === true,
189
+ },
190
+ ...(stepPlan.outputSchema ? { outputSchema: stepPlan.outputSchema } : {}),
191
+ };
192
+ // Journaled dispatch rows for THIS step, keyed by unit id (exclude gate rows).
193
+ const journaledByUnit = new Map();
194
+ for (const row of units) {
195
+ if (row.step_id === stepState.id && row.phase !== GATE_EVALUATION_PHASE) {
196
+ journaledByUnit.set(row.unit_id, row);
197
+ }
198
+ }
199
+ // #15 action derivation inputs: the stale-claim set (by unit id) and whether a
200
+ // live engine lease means the whole work-list is `do_not_run` right now.
201
+ const staleIds = new Set(staleUnits.map((u) => u.unitId));
202
+ const leaseLive = lease?.live === true;
203
+ // The work-list — the SAME computation the engine runs (no drift).
204
+ let workList = EMPTY_WORK_LIST;
205
+ // True when every resolvable unit ran to a terminal state but the step never
206
+ // finalized (a required-gate block that was resumed, or a crash between the
207
+ // last unit write and completion) — the fully-terminal recovery state.
208
+ let fullyTerminal = false;
209
+ if (!isRouteOnly) {
210
+ const computed = computeStepWorkList(stepPlan, {
211
+ runId: run.id,
212
+ params: run.params,
213
+ stepOutputs,
214
+ engines: plan.execution.engines,
215
+ gateLoop,
216
+ ...(gateFeedback ? { gateFeedback } : {}),
217
+ });
218
+ if (!computed.ok) {
219
+ workList = { ...EMPTY_WORK_LIST, error: computed.error };
220
+ }
221
+ else {
222
+ const list = computed.list;
223
+ fullyTerminal = !leaseLive && isWorkListFullyTerminal(list, journaledByUnit);
224
+ // #21: a worktree-isolated unit runs in a throwaway git worktree that is
225
+ // auto-removed when clean. Files it writes to a `.gitignore`d path are
226
+ // treated as disposable and discarded — warn any driver so collectible
227
+ // artifacts go to a non-ignored path or come back as a reported result.
228
+ if (list.units.some((u) => u.isolation === "worktree")) {
229
+ warnings.push("This step runs unit(s) in an isolated git worktree (`isolation: worktree`). Outputs matched by the " +
230
+ "repository's `.gitignore` are treated as DISPOSABLE — a clean worktree is auto-removed, discarding them. " +
231
+ "Write any artifact that must survive to a NON-ignored path (a tracked or untracked-unignored file), or " +
232
+ "report it as the unit's result. Do not leave collectible work under `node_modules`/`dist`/build/cache paths.");
233
+ }
234
+ workList = {
235
+ isFanOut: list.isFanOut,
236
+ reducer: list.reducer,
237
+ ...(list.concurrency !== undefined ? { concurrency: list.concurrency } : {}),
238
+ itemCount: list.items.length,
239
+ units: list.units.map((u) =>
240
+ // Resolve the unit's journaled state by its BEST terminal attempt
241
+ // (base + `~r<n>` retries), the SAME reuse the engine and report
242
+ // surfaces apply (shared selectUnitAttemptRow, finding C): a unit whose
243
+ // base attempt failed but whose retry completed surfaces as `done`, not
244
+ // `failed`, so brief never advertises re-running work a prior retry
245
+ // already finished — keeping the read-only surface consistent with what
246
+ // report/resume would reduce.
247
+ toBriefUnit(run.id, u, stepState.id, selectUnitAttemptRow(u, journaledByUnit), {
248
+ stale: staleIds.has(u.journalBaseId),
249
+ leaseLive,
250
+ })),
251
+ };
252
+ }
253
+ }
254
+ // Route contract. A route-only step's decision depends solely on prior step
255
+ // outputs, so brief evaluates it deterministically NOW. An execute-and-route
256
+ // step's decision needs the current step's fresh output, which does not exist
257
+ // until the units run — so brief surfaces the contract without a decision.
258
+ let route;
259
+ if (stepPlan.route) {
260
+ route = {
261
+ input: stepPlan.route.input,
262
+ when: stepPlan.route.when,
263
+ ...(stepPlan.route.defaultStepId ? { defaultStepId: stepPlan.route.defaultStepId } : {}),
264
+ evaluatedNow: isRouteOnly,
265
+ };
266
+ if (isRouteOnly) {
267
+ const scope = { params: run.params, stepOutputs };
268
+ const decision = evaluateRoute(stepPlan.route, scope);
269
+ if (decision.ok)
270
+ route.decision = { value: decision.value, selected: decision.selected };
271
+ else
272
+ route.decisionError = decision.error;
273
+ }
274
+ }
275
+ // A step the driver cannot advance with a per-unit `report --unit` gets the
276
+ // `--settle` verb instead. TWO cases:
277
+ // - NON-DISPATCHING (finding D): a route-only step, an empty fan-out, an
278
+ // all-unresolvable work-list, or a whole-list failure — nothing was ever
279
+ // dispatchable.
280
+ // - FULLY TERMINAL (owner manual-validation finding 3): every resolvable
281
+ // unit already ran to a terminal state, but the step never finalized (a
282
+ // required-gate block that was resumed, or a crash before completion). The
283
+ // units show `done`/`failed` with no report command, so without this the
284
+ // driver is stranded — `--settle` runs the shared completion path.
285
+ // Never while a live engine lease owns the spine (a report/settle is refused
286
+ // then anyway). `--expect-step` guards a stale copy once the spine moves.
287
+ const hasReportableWork = !isRouteOnly && !workList.error && workList.units.some((u) => u.resolved.ok);
288
+ const nonDispatching = !hasReportableWork;
289
+ const settleable = !leaseLive && (nonDispatching || fullyTerminal);
290
+ const settleCommand = settleable ? `akm workflow report ${run.id} --settle --expect-step ${stepState.id}` : undefined;
291
+ const settleState = !settleable
292
+ ? "none"
293
+ : fullyTerminal
294
+ ? "finalize"
295
+ : "non-dispatching";
296
+ const message = buildMessage(step, workList, route, gateLoop, settleState);
297
+ return {
298
+ ...base,
299
+ // Re-stamp the spine token with the resolved active step + real gate loop.
300
+ spineToken: makeSpineToken(run.id, stepState.id, gateLoop, watermark),
301
+ active: true,
302
+ step,
303
+ ...(gateFeedback ? { gateFeedback } : {}),
304
+ workList,
305
+ ...(route ? { route } : {}),
306
+ ...(settleCommand ? { settleCommand } : {}),
307
+ message,
308
+ };
309
+ }
310
+ /**
311
+ * The spine watermark stamped on every brief (#14): run id, active step id,
312
+ * gate loop, and a run-mutation watermark (`updated_at` + journal row count). A
313
+ * driver diffs it across polls to notice the spine moved; `report --expect-step`
314
+ * enforces the step half server-side.
315
+ */
316
+ function makeSpineToken(runId, stepId, gateLoop, watermark) {
317
+ return `${runId}#${stepId ?? "-"}#l${gateLoop}#${watermark}`;
318
+ }
319
+ // ── Helpers ──────────────────────────────────────────────────────────────────
320
+ function toBriefUnit(runId, unit, stepId, journaled, ctx) {
321
+ if (!unit.engine || !unit.invocation) {
322
+ throw new UsageError(`Unit "${unit.unitId}" has no complete frozen engine attribution.`);
323
+ }
324
+ const action = deriveUnitAction(unit, journaled, ctx);
325
+ const report = reportCommandForAction(runId, unit, stepId, action, journaled?.claim_holder ?? null);
326
+ return {
327
+ unitId: unit.unitId,
328
+ nodeId: unit.nodeId,
329
+ index: unit.index,
330
+ engine: unit.invocation.engine,
331
+ runtimeKind: unit.runner,
332
+ platform: unit.engine.kind === "agent" ? unit.engine.platform : null,
333
+ model: unit.invocation.model,
334
+ timeoutMs: unit.timeoutMs,
335
+ ...(unit.schema ? { outputSchema: unit.schema } : {}),
336
+ // Env asset REF names only — brief never resolves bindings, so no secret
337
+ // value can ever reach this output.
338
+ ...(unit.env ? { env: unit.env } : {}),
339
+ ...(unit.retry ? { retry: unit.retry } : {}),
340
+ onError: unit.onError,
341
+ ...(unit.isFanOut ? { item: unit.item } : {}),
342
+ resolved: unit.resolved.ok
343
+ ? { ok: true, instructions: unit.resolved.prompt, inputHash: unit.resolved.inputHash }
344
+ : { ok: false, error: unit.resolved.error },
345
+ ...(journaled ? { journaled: toBriefJournaled(journaled) } : {}),
346
+ action,
347
+ ...(report ? { report } : {}),
348
+ };
349
+ }
350
+ /**
351
+ * Fold the journaled row + engine lease + resolvability into ONE driver-facing
352
+ * action (#15). A live engine lease or an unresolvable unit is `do_not_run`; a
353
+ * terminal row is `done`/`failed`; a live claim is `claimed` (or `stale` once
354
+ * silent); no row is `pending`.
355
+ */
356
+ function deriveUnitAction(unit, journaled, ctx) {
357
+ if (!unit.resolved.ok)
358
+ return "do_not_run";
359
+ if (ctx.leaseLive)
360
+ return "do_not_run";
361
+ if (!journaled)
362
+ return "pending";
363
+ if (journaled.status === "completed")
364
+ return "done";
365
+ if (journaled.status === "failed")
366
+ return "failed";
367
+ if (journaled.status === "running")
368
+ return ctx.stale ? "stale" : "claimed";
369
+ return "pending";
370
+ }
371
+ function toBriefJournaled(row) {
372
+ // Claim state is meaningful only while the unit is still running; a terminal
373
+ // row keeps its claim columns but they are no longer actionable.
374
+ const claim = row.status === "running"
375
+ ? {
376
+ ...(row.claim_holder ? { claimedBy: row.claim_holder } : {}),
377
+ ...(row.claim_expires_at ? { claimExpiresAt: row.claim_expires_at } : {}),
378
+ }
379
+ : {};
380
+ return {
381
+ unitId: row.unit_id,
382
+ status: row.status,
383
+ ...(row.failure_reason ? { failureReason: row.failure_reason } : {}),
384
+ ...(row.tokens !== null ? { tokens: row.tokens } : {}),
385
+ ...(row.started_at ? { startedAt: row.started_at } : {}),
386
+ ...(row.finished_at ? { finishedAt: row.finished_at } : {}),
387
+ ...claim,
388
+ };
389
+ }
390
+ /**
391
+ * The `report` command line for a unit, tailored to its action (#15). Terminal
392
+ * `done` and `do_not_run` units get NO command; a `failed` unit gets the
393
+ * `--rerun` form (records a fresh attempt, per #25); `pending`/`stale`/`claimed`
394
+ * get the completed form. Every command carries `--expect-step` (#14) so a
395
+ * copy-pasted command from a stale brief is refused once the spine moves on.
396
+ *
397
+ * A `claimed` unit is held by a LIVE `--status running` claim (`claimHolder`):
398
+ * ONLY that holder can finish it — the report path's claim compare-and-set
399
+ * refuses any other `--session-id`. So its command carries `--session-id
400
+ * <holder>`, which (a) is the exact form the holding driver must use to finish
401
+ * its OWN claim, and (b) makes it unmistakable to a SECOND driver that the unit
402
+ * is spoken for rather than free, runnable work (owner manual-validation
403
+ * finding 2: two drivers must not both treat a live-claimed unit as free). A
404
+ * `stale` unit's claim has expired and is freely reclaimable/finishable by
405
+ * anyone, so it keeps the plain completed form (no `--session-id`).
406
+ */
407
+ function reportCommandForAction(runId, unit, stepId, action, claimHolder) {
408
+ if (action === "done" || action === "do_not_run")
409
+ return undefined;
410
+ const resultHint = unit.schema
411
+ ? "--result-file <result.json> # JSON matching the unit's outputSchema"
412
+ : "--result-file <result.txt> # or --result '<text>' / pipe via stdin";
413
+ const rerun = action === "failed" ? " --rerun" : "";
414
+ // A live claim requires its holder's --session-id to finish; surface it so the
415
+ // holder's command is correct and other drivers see the unit is claimed.
416
+ const session = action === "claimed" && claimHolder ? ` --session-id ${claimHolder}` : "";
417
+ return `akm workflow report ${runId} --unit ${unit.unitId} --expect-step ${stepId} --status completed${rerun}${session} ${resultHint}`;
418
+ }
419
+ export function buildLease(holder, until) {
420
+ if (!holder || !until)
421
+ return undefined;
422
+ return { holder, until, live: until >= new Date().toISOString() };
423
+ }
424
+ function buildMessage(step, workList, route, gateLoop, settleState) {
425
+ const loopNote = gateLoop > 1 ? ` (gate loop ${gateLoop}, addressing prior rejection feedback)` : "";
426
+ const settleNote = settleState !== "none" ? " Advance it with `akm workflow report --settle` (see settleCommand)." : "";
427
+ if (step.kind === "route") {
428
+ const decided = route?.decision ? ` → selects step "${route.decision.selected}"` : "";
429
+ return `Active step "${step.stepId}" is a route step — no units to execute${decided}.${settleNote || " Advances deterministically."}`;
430
+ }
431
+ if (workList.error) {
432
+ return `Active step "${step.stepId}" could not compute a work-list: ${workList.error}${settleNote}`;
433
+ }
434
+ const n = workList.units.length;
435
+ if (settleState === "finalize") {
436
+ // Fully-terminal work-list on a still-active step: everything ran, nothing
437
+ // remains to execute — the step only needs finalization (the run was
438
+ // gate-blocked then resumed, or a crash interrupted completion). A required
439
+ // gate with no judge available will re-block, which is correct behavior.
440
+ const gateNote = step.gate.required && step.gate.criteria.length > 0
441
+ ? " If this step's REQUIRED gate has no judge available it will re-block, pending a configured judge or a manual `akm workflow complete`."
442
+ : "";
443
+ return (`Active step "${step.stepId}" has run all ${n} unit(s) to a terminal state${loopNote} — nothing remains to ` +
444
+ `execute or report. Finalize it with \`akm workflow report --settle\` (see settleCommand): the gate is judged ` +
445
+ `and the step advances.${gateNote}`);
446
+ }
447
+ if (settleState === "non-dispatching") {
448
+ return `Active step "${step.stepId}" dispatches no reportable units${loopNote}.${settleNote}`;
449
+ }
450
+ return `Active step "${step.stepId}" expects ${n} unit(s)${loopNote}. Execute them, then report each result.`;
451
+ }
452
+ /**
453
+ * Resolve `target` to a concrete run id WITHOUT starting anything. A run id
454
+ * resolves directly; a workflow ref resolves to its active run in the current
455
+ * scope, and NO active run is a NotFoundError (brief never auto-starts — that
456
+ * would mutate).
457
+ */
458
+ export async function resolveRunId(target) {
459
+ return withWorkflowRunsRepo((repo) => {
460
+ const byId = repo.getRunById(target);
461
+ if (byId)
462
+ return byId.id;
463
+ if (!target.includes(":")) {
464
+ throw new NotFoundError(`Workflow run "${target}" not found.`, "WORKFLOW_NOT_FOUND");
465
+ }
466
+ const parsed = parseAssetRef(target);
467
+ if (parsed.type !== "workflow") {
468
+ throw new UsageError(`Expected a workflow run id or workflow ref (workflow:<name>), got "${target}".`);
469
+ }
470
+ const ref = `${parsed.origin ? `${parsed.origin}//` : ""}workflow:${canonicalizeWorkflowName(parsed.name)}`;
471
+ const active = repo.getActiveRunRowForScope(ref, getCurrentWorkflowScopeKey());
472
+ if (!active) {
473
+ throw new NotFoundError(`No active workflow run for ${ref} in this scope. \`akm workflow brief\` describes an existing run and never ` +
474
+ `starts one — run \`akm workflow start ${ref}\` (or \`akm workflow run ${ref}\`) first.`, "WORKFLOW_NOT_FOUND");
475
+ }
476
+ return active.id;
477
+ });
478
+ }
@@ -0,0 +1,47 @@
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 { deepMergeConfig } from "../../core/config/deep-merge.js";
5
+ import { ConfigError } from "../../core/errors.js";
6
+ /** Build a gate judge from a v3 catalog entry without consulting live config. */
7
+ export function frozenSummaryJudge(plan, invocation) {
8
+ if (!invocation)
9
+ return null;
10
+ const engine = plan.execution?.engines[invocation.engine];
11
+ if (!engine || engine.kind !== "llm")
12
+ throw new ConfigError(`Frozen gate engine "${invocation.engine}" is unavailable.`, "INVALID_CONFIG_FILE");
13
+ return async ({ system, user }) => {
14
+ const { chatCompletion } = await import("../../llm/client.js");
15
+ return chatCompletion(materialize(engine, invocation), [
16
+ { role: "system", content: system },
17
+ { role: "user", content: user },
18
+ ], {
19
+ timeoutMs: invocation.timeoutMs,
20
+ });
21
+ };
22
+ }
23
+ function materialize(engine, invocation) {
24
+ let apiKey;
25
+ for (const name of engine.credential?.names ?? []) {
26
+ const value = process.env[name]?.trim();
27
+ if (value) {
28
+ apiKey = value;
29
+ break;
30
+ }
31
+ }
32
+ if (engine.credential?.required && !apiKey)
33
+ throw new ConfigError(`Required engine credential ${engine.credential.names[0]} is not set.`, "INVALID_CONFIG_FILE");
34
+ const base = {
35
+ provider: engine.provider,
36
+ endpoint: engine.endpoint,
37
+ model: invocation.model ?? engine.model,
38
+ ...(engine.temperature !== undefined ? { temperature: engine.temperature } : {}),
39
+ ...(engine.maxTokens !== undefined ? { maxTokens: engine.maxTokens } : {}),
40
+ ...(engine.supportsJsonSchema !== undefined ? { supportsJsonSchema: engine.supportsJsonSchema } : {}),
41
+ ...(engine.extraParams ? { extraParams: engine.extraParams } : {}),
42
+ ...(engine.contextLength !== undefined ? { contextLength: engine.contextLength } : {}),
43
+ ...(engine.enableThinking !== undefined ? { enableThinking: engine.enableThinking } : {}),
44
+ ...(apiKey ? { apiKey } : {}),
45
+ };
46
+ return (invocation.llm ? deepMergeConfig(base, invocation.llm) : base);
47
+ }