akm-cli 0.9.0-rc.13 → 0.9.0-rc.15

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 (111) hide show
  1. package/CHANGELOG.md +162 -23
  2. package/dist/akm-migrate +3 -1
  3. package/dist/assets/hints/cli-hints-full.md +3 -4
  4. package/dist/assets/hints/cli-hints-short.md +5 -5
  5. package/dist/assets/workflows/workflow-template.md +4 -3
  6. package/dist/cli/invocation.js +3 -2
  7. package/dist/cli/retired-commands.js +5 -0
  8. package/dist/cli/unknown-flags.js +226 -0
  9. package/dist/cli.js +19 -35
  10. package/dist/commands/agent/agent-dispatch.js +7 -3
  11. package/dist/commands/agent/contribute-cli.js +15 -3
  12. package/dist/commands/feedback-cli.js +6 -3
  13. package/dist/commands/health/checks.js +6 -3
  14. package/dist/commands/improve/collapse-detector.js +2 -3
  15. package/dist/commands/improve/reflect.js +5 -3
  16. package/dist/commands/lint/base-linter.js +4 -16
  17. package/dist/commands/lint/index.js +13 -13
  18. package/dist/commands/log.js +6 -1
  19. package/dist/commands/migration-tool.js +4 -5
  20. package/dist/commands/observability-cli.js +1 -1
  21. package/dist/commands/proposal/propose.js +5 -3
  22. package/dist/commands/proposal/repository.js +5 -5
  23. package/dist/commands/read/knowledge.js +2 -0
  24. package/dist/commands/registry-cli.js +5 -3
  25. package/dist/commands/sources/add-cli.js +6 -6
  26. package/dist/commands/sources/init.js +1 -1
  27. package/dist/commands/sources/self-update.js +30 -7
  28. package/dist/commands/sources/source-add.js +17 -2
  29. package/dist/commands/tasks/tasks.js +10 -10
  30. package/dist/commands/workflow-cli.js +133 -259
  31. package/dist/core/adapter/adapters/akm-lint.js +17 -13
  32. package/dist/core/adapter/adapters/akm-task-adapter.js +14 -11
  33. package/dist/core/asset/akm-markdown.js +41 -8
  34. package/dist/core/asset/frontmatter.js +22 -0
  35. package/dist/core/asset/resolve-ref.js +23 -3
  36. package/dist/core/common.js +45 -2
  37. package/dist/core/config/config-schema.js +8 -0
  38. package/dist/core/config/schema/experimental.js +0 -17
  39. package/dist/core/config/schema/sources-bundles.js +11 -0
  40. package/dist/core/config/schema/workflow.js +3 -3
  41. package/dist/core/errors.js +5 -1
  42. package/dist/core/logs-db.js +2 -1
  43. package/dist/core/parse.js +4 -1
  44. package/dist/core/state/migrations.js +11 -14
  45. package/dist/core/state-db.js +4 -6
  46. package/dist/core/subprocess.js +6 -4
  47. package/dist/core/type-presentation.js +1 -1
  48. package/dist/indexer/indexer.js +16 -1
  49. package/dist/indexer/search/search-source.js +1 -1
  50. package/dist/indexer/walk/matchers.js +3 -1
  51. package/dist/integrations/agent/config.js +2 -2
  52. package/dist/integrations/agent/detect.js +49 -19
  53. package/dist/integrations/agent/engine-fallback.js +76 -0
  54. package/dist/integrations/agent/profiles.js +14 -0
  55. package/dist/integrations/agent/spawn.js +1 -2
  56. package/dist/integrations/harnesses/opencode-sdk/sdk-runner.js +13 -4
  57. package/dist/integrations/lockfile.js +11 -56
  58. package/dist/output/shapes/passthrough.js +0 -6
  59. package/dist/output/text/command-format.js +3 -3
  60. package/dist/output/text/helpers.js +1 -1
  61. package/dist/output/text/show-directives.js +4 -6
  62. package/dist/output/text/workflow-format.js +15 -181
  63. package/dist/output/text/workflow.js +1 -6
  64. package/dist/scripts/akm-migrate-node.js +58666 -0
  65. package/dist/scripts/akm-migrate.js +33976 -11498
  66. package/dist/setup/detect.js +42 -15
  67. package/dist/setup/setup.js +1 -1
  68. package/dist/sources/providers/git-stash.js +4 -2
  69. package/dist/sources/providers/website.js +5 -0
  70. package/dist/sources/snapshot-fetchers/bluesky.js +146 -0
  71. package/dist/sources/snapshot-fetchers/content-extract.js +370 -0
  72. package/dist/sources/snapshot-fetchers/fetcher-util.js +40 -0
  73. package/dist/sources/snapshot-fetchers/host-guard.js +199 -0
  74. package/dist/sources/snapshot-fetchers/registry.js +10 -1
  75. package/dist/sources/snapshot-fetchers/robots.js +348 -0
  76. package/dist/sources/snapshot-fetchers/rss.js +279 -0
  77. package/dist/sources/snapshot-fetchers/secret-seam.js +42 -0
  78. package/dist/sources/snapshot-fetchers/website-ingest.js +488 -257
  79. package/dist/sources/snapshot-fetchers/x.js +193 -0
  80. package/dist/storage/engines/sqlite-migrations.js +22 -107
  81. package/dist/storage/repositories/workflow-runs-repository.js +9 -23
  82. package/dist/tasks/runner.js +43 -19
  83. package/dist/tasks/schema.js +24 -1
  84. package/dist/tasks/validator.js +6 -2
  85. package/dist/workflows/exec/frozen-judge.js +28 -2
  86. package/dist/workflows/exec/native-executor.js +44 -28
  87. package/dist/workflows/exec/param-secrets.js +9 -9
  88. package/dist/workflows/exec/run-workflow.js +122 -60
  89. package/dist/workflows/exec/step-work.js +64 -175
  90. package/dist/workflows/exec/unit-dispatch.js +4 -0
  91. package/dist/workflows/ir/compile.js +2 -2
  92. package/dist/workflows/ir/freeze.js +29 -9
  93. package/dist/workflows/ir/params.js +135 -11
  94. package/dist/workflows/ir/plan-hash.js +1 -1
  95. package/dist/workflows/ir/schema.js +6 -2
  96. package/dist/workflows/renderer.js +2 -2
  97. package/dist/workflows/runtime/checkin.js +3 -3
  98. package/dist/workflows/runtime/runs.js +72 -92
  99. package/dist/workflows/runtime/unit-checkin.js +1 -1
  100. package/dist/workflows/runtime/unit-phases.js +2 -2
  101. package/dist/workflows/validate-summary.js +30 -14
  102. package/docs/migration/release-notes/0.9.0.md +31 -4
  103. package/docs/migration/v0.8-to-v0.9.md +70 -100
  104. package/docs/reference/data-and-telemetry.md +5 -5
  105. package/package.json +7 -3
  106. package/schemas/akm-config.json +24 -6
  107. package/schemas/akm-workflow.json +1 -1
  108. package/dist/workflows/cli.js +0 -33
  109. package/dist/workflows/exec/brief.js +0 -450
  110. package/dist/workflows/exec/report.js +0 -1460
  111. package/dist/workflows/exec/workflow-engine-gate.js +0 -67
@@ -4,12 +4,37 @@
4
4
  import { deepMergeConfig } from "../../core/config/deep-merge.js";
5
5
  import { ConfigError } from "../../core/errors.js";
6
6
  /** Build a gate judge from a v3 catalog entry without consulting live config. */
7
- export function frozenSummaryJudge(plan, invocation) {
7
+ export function frozenSummaryJudge(plan, invocation, signal, dispatcher) {
8
8
  if (!invocation)
9
9
  return null;
10
10
  const engine = plan.execution?.engines[invocation.engine];
11
- if (!engine || engine.kind !== "llm")
11
+ if (!engine)
12
12
  throw new ConfigError(`Frozen gate engine "${invocation.engine}" is unavailable.`, "INVALID_CONFIG_FILE");
13
+ if (engine.kind === "agent") {
14
+ if (!dispatcher) {
15
+ throw new ConfigError(`Frozen agent gate engine "${invocation.engine}" has no unit dispatcher.`, "INVALID_CONFIG_FILE");
16
+ }
17
+ return async ({ system, user }) => {
18
+ const fallbackEngine = engine.fallbackLlmEngine ? plan.execution.engines[engine.fallbackLlmEngine] : undefined;
19
+ const result = await dispatcher({
20
+ runId: "gate",
21
+ stepId: "gate",
22
+ unitId: "gate",
23
+ nodeId: "gate",
24
+ prompt: user,
25
+ systemPrompt: system,
26
+ engine,
27
+ ...(fallbackEngine?.kind === "llm" ? { fallbackEngine } : {}),
28
+ invocation,
29
+ timeoutMs: invocation.timeoutMs,
30
+ ...(signal ? { signal } : {}),
31
+ });
32
+ if (!result.ok) {
33
+ throw new Error(result.error || `Verification engine "${invocation.engine}" failed.`);
34
+ }
35
+ return result.text;
36
+ };
37
+ }
13
38
  return async ({ system, user }) => {
14
39
  const { chatCompletion } = await import("../../llm/client.js");
15
40
  return chatCompletion(materialize(engine, invocation), [
@@ -17,6 +42,7 @@ export function frozenSummaryJudge(plan, invocation) {
17
42
  { role: "user", content: user },
18
43
  ], {
19
44
  timeoutMs: invocation.timeoutMs,
45
+ ...(signal ? { signal } : {}),
20
46
  });
21
47
  };
22
48
  }
@@ -33,12 +33,11 @@
33
33
  *
34
34
  * Empty free-text outputs (peer review): a SUCCESSFUL schemaless unit that
35
35
  * returns the empty string is normalized to "no output" — {@link dispatchUnit}
36
- * drops the falsy `text`, `finishUnit` journals `result_json = NULL`, and both
37
- * durable-row reuse and the R3 report surface rehydrate the same absence
38
- * (`unitOutcomeFromRow`). This is the ONLY empty-output resolution: `''` never
39
- * survives on any surface, so the live artifact cannot diverge from the
40
- * resume/report artifact (the cross-surface parity cardinal rule; the
41
- * `EMPTY_OUTPUT` driver-parity golden pins it). Consequences that follow from
36
+ * drops the falsy `text`, `finishUnit` journals `result_json = NULL`, and
37
+ * durable-row reuse rehydrates the same absence (`unitOutcomeFromRow`). This is
38
+ * the ONLY empty-output resolution: `''` never survives into the journal, so the
39
+ * live artifact cannot diverge from the artifact a resume rebuilds from the same
40
+ * rows (the byte-identical-graph cardinal rule). Consequences that follow from
42
41
  * "empty == absent", not special-cased anywhere:
43
42
  * - a SOLO empty step promotes `output = null` (the unit's absent text ??
44
43
  * null); a `collect` fan-out promotes `null` in that item's slot.
@@ -137,9 +136,9 @@ import { warn } from "../../core/warn.js";
137
136
  import { insertEventStrict } from "../../storage/repositories/events-repository.js";
138
137
  import { withWorkflowRunsRepo } from "../../storage/repositories/workflow-runs-repository.js";
139
138
  import { LIFETIME_UNIT_CAP, scheduleUnits, UnitCapExceededError } from "./scheduler.js";
140
- // Shared step semantics — the ONE implementation consumed by both the engine
141
- // (this module + run-workflow.ts) and, from R3, the brief/report driver
142
- // protocol. This module dispatches; step-work.ts owns the pure decisions.
139
+ // Shared step semantics — the ONE implementation consumed by the engine
140
+ // (this module + run-workflow.ts) on both the fresh-execution and the resume
141
+ // path. This module dispatches; step-work.ts owns the pure decisions.
143
142
  import { computeStepWorkList, reduceEmptyStep, reduceStepOutcomes, stepOutputsFromEvidence, unitOutcomeFromRow, } from "./step-work.js";
144
143
  import { enqueueUnitWrite } from "./unit-writer.js";
145
144
  import { assertGitWorkTree, cleanupUnitWorktree, createUnitWorktree } from "./worktree.js";
@@ -244,10 +243,11 @@ export async function executeStepPlan(plan, ctx) {
244
243
  const dispatched = ctx.unitsDispatched ?? 0;
245
244
  // Work-list computation is the SHARED, PURE decision (step-work.ts): resolve
246
245
  // the fan-out list, derive content-derived unit ids, assemble each unit's
247
- // prompt, and hash its resolved input. `brief` (R3) computes the identical
248
- // list — that shared implementation is the anti-drift guarantee. This module
249
- // owns only the impure remainder: env/worktree preflight, durable-row reuse,
250
- // dispatch, journaling, budget.
246
+ // prompt, and hash its resolved input. A resume recomputes the identical list
247
+ // from the same frozen plan — that shared pure implementation is what lets
248
+ // journaled rows be matched instead of re-executed. This module owns only the
249
+ // impure remainder: env/worktree preflight, durable-row reuse, dispatch,
250
+ // journaling, budget.
251
251
  const workList = computeStepWorkList(plan, {
252
252
  runId: ctx.runId,
253
253
  params: ctx.params,
@@ -262,10 +262,9 @@ export async function executeStepPlan(plan, ctx) {
262
262
  const { template, reducer, isFanOut, items, units: workUnits } = workList.list;
263
263
  if (items.length === 0) {
264
264
  // Empty fan-out: the promoted artifact is the degenerate empty value, honored
265
- // against the step's declared output schema. `reduceEmptyStep` is the SHARED
266
- // decision (step-work.ts) the R3 report surface also uses to auto-complete an
267
- // empty step the spine reaches, so both surfaces promote the identical
268
- // artifact + schema verdict.
265
+ // against the step's declared output schema. `reduceEmptyStep` (step-work.ts)
266
+ // owns that decision so a zero-unit step promotes the identical artifact +
267
+ // schema verdict every time the spine reaches it.
269
268
  return { ...reduceEmptyStep(plan, reducer), unitsDispatched: dispatched };
270
269
  }
271
270
  const dispatcher = ctx.dispatcher ?? defaultUnitDispatcher;
@@ -485,8 +484,8 @@ async function runUnit(input) {
485
484
  const reuse = classifyUnitReuse(workUnit, input.existingUnits, gateLoop);
486
485
  if (reuse.kind === "reuse") {
487
486
  // Identity in the durable step evidence is the CONTENT-derived base id, not
488
- // the `~r<n>` attempt row it was reused from — the report surface reduces
489
- // from the base id too, so both surfaces' evidence.units[].unitId agree.
487
+ // the `~r<n>` attempt row it was reused from — the work list only ever knows
488
+ // base ids, so evidence.units[].unitId stays stable across retries+resumes.
490
489
  return reuseCompletedUnit(unitId, reuse.row, workUnit.schema !== undefined);
491
490
  }
492
491
  if (reuse.kind === "diverge") {
@@ -500,6 +499,14 @@ async function runUnit(input) {
500
499
  }
501
500
  let outcome;
502
501
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
502
+ if (input.signal?.aborted) {
503
+ return (outcome ?? {
504
+ unitId,
505
+ ok: false,
506
+ failureReason: "aborted",
507
+ error: "unit was not dispatched because the workflow invocation was interrupted",
508
+ });
509
+ }
503
510
  const attemptId = attemptIdFor(attempt);
504
511
  // Lifetime cap + declared budget ceilings, consumed per ACTUAL dispatch
505
512
  // (reuses above returned before reaching here). Refusal fails this unit
@@ -538,6 +545,8 @@ async function runUnit(input) {
538
545
  input.budget.addTokens(outcome.tokens);
539
546
  if (outcome.ok)
540
547
  return outcome;
548
+ if (input.signal?.aborted)
549
+ return outcome;
541
550
  const reason = outcome.failureReason;
542
551
  if (!retry || reason === undefined || !retry.on.includes(reason))
543
552
  return outcome;
@@ -704,12 +713,12 @@ async function dispatchUnit(request, dispatcher) {
704
713
  }
705
714
  const text = await dispatchOnce();
706
715
  // Normalize an EMPTY successful output to "no text". `finishUnit` journals
707
- // result_json = NULL for a falsy text, so durable-reuse and the R3 report
708
- // surface both rehydrate NO text from the row (unitOutcomeFromRow). Preserving
709
- // `text: ""` only in this live outcome would make the LIVE step artifact ("")
710
- // diverge from the resume/report artifact (null) — the exact byte-identical-
711
- // graph violation the cardinal rule forbids. Treating empty as absent keeps
712
- // the live engine, engine resume, and report surfaces identical.
716
+ // result_json = NULL for a falsy text, so durable-reuse rehydrates NO text
717
+ // from the row (unitOutcomeFromRow). Preserving `text: ""` only in this live
718
+ // outcome would make the LIVE step artifact ("") diverge from the artifact a
719
+ // resume rebuilds from the row (null) — the exact byte-identical-graph
720
+ // violation the cardinal rule forbids. Treating empty as absent keeps live
721
+ // dispatch and engine resume identical.
713
722
  return { unitId: request.unitId, ok: true, ...(text ? { text } : {}), ...captured() };
714
723
  }
715
724
  catch (err) {
@@ -781,6 +790,7 @@ async function resolveEnvBindings(refs) {
781
790
  export function buildAgentDispatchRequest(request, prompt) {
782
791
  return {
783
792
  prompt,
793
+ ...(request.systemPrompt ? { systemPrompt: request.systemPrompt } : {}),
784
794
  ...(request.invocation.model ? { model: request.invocation.model } : {}),
785
795
  ...(request.invocation.model ? { modelIsExact: true } : {}),
786
796
  ...(request.schema ? { schema: request.schema } : {}),
@@ -820,7 +830,13 @@ export const defaultUnitDispatcher = async (request, feedback) => {
820
830
  const { chatCompletion, LlmCallError } = await import("../../llm/client.js");
821
831
  const connection = resolved.connection;
822
832
  try {
823
- const text = await chatCompletion(connection, [{ role: "user", content: prompt }], {
833
+ const messages = request.systemPrompt
834
+ ? [
835
+ { role: "system", content: request.systemPrompt },
836
+ { role: "user", content: prompt },
837
+ ]
838
+ : [{ role: "user", content: prompt }];
839
+ const text = await chatCompletion(connection, messages, {
824
840
  timeoutMs: request.timeoutMs,
825
841
  ...(request.signal ? { signal: request.signal } : {}),
826
842
  // Native structured output where the connection supports it; the
@@ -1018,8 +1034,8 @@ function materializeFrozenLlm(snapshot, invocation) {
1018
1034
  * Rehydrate a journaled completed unit row into a UnitOutcome (durable-row
1019
1035
  * reuse). Delegates to the shared {@link unitOutcomeFromRow} — the reuse path
1020
1036
  * only reaches here for completed rows (the caller guards `status ===
1021
- * "completed"`), so the mapping is identical to what the R3 report path applies
1022
- * when it replays the same journal.
1037
+ * "completed"`), so a reused unit contributes exactly what its original
1038
+ * dispatch did.
1023
1039
  */
1024
1040
  function reuseCompletedUnit(unitId, row, hasSchema) {
1025
1041
  return unitOutcomeFromRow(unitId, row, hasSchema);
@@ -8,20 +8,20 @@
8
8
  *
9
9
  * A workflow's run params are interpolated into every unit prompt
10
10
  * (`buildUnitPrompt` → `{{PARAMS_JSON}}` + `${{ params.* }}` references) and,
11
- * critically, are part of the unit's **input hash**. The harness-neutral driver
12
- * protocol (`akm workflow brief`) MUST surface the byte-identical prompt an
13
- * external driver has to execute — redacting a param would change the prompt the
14
- * driver runs, break the input-hash contract, and defeat cross-surface parity.
15
- * So params CANNOT be redacted and are declared **non-secret**: secrets belong
16
- * in **env bindings** (`env:` refs), which `brief` surfaces by NAME ONLY and
17
- * never resolves.
11
+ * critically, are part of the unit's **input hash**. The prompt an executor runs
12
+ * must be byte-identical to the one the hash was taken over — redacting a param
13
+ * would change the prompt, break the input-hash contract, and make a resumed or
14
+ * replayed run diverge from the original. So params CANNOT be redacted and are
15
+ * declared **non-secret**: secrets belong in **env bindings** (`env:` refs),
16
+ * which are carried by NAME ONLY through the plan and the hash preimage and are
17
+ * resolved from the process environment at dispatch.
18
18
  *
19
19
  * This module is the loud, best-effort guardrail on top of that contract: it
20
20
  * scans params for values that LOOK like credentials (secret-suggesting key
21
21
  * names, long high-entropy strings, known token prefixes) and returns WARNING
22
22
  * strings. It is purely advisory — it NEVER blocks a run and NEVER mutates
23
- * params — and is surfaced both at `start` and in every `brief`. False positives
24
- * and false negatives are expected; it is a nudge, not a scanner.
23
+ * params — and is surfaced when a run starts. False positives and false
24
+ * negatives are expected; it is a nudge, not a scanner.
25
25
  */
26
26
  /**
27
27
  * Substrings that, when present in a param KEY (case-insensitive), suggest the
@@ -2,10 +2,9 @@
2
2
  // License, v. 2.0. If a copy of the MPL was not distributed with this
3
3
  // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
4
  /**
5
- * Engine-driven workflow execution — `akm workflow run` (orchestration plan
6
- * P1, owner decision 5). akm itself walks the plan and dispatches units; the
7
- * existing `next`/`complete` loop remains for manual/agent-driven advancement
8
- * of the same runs.
5
+ * Engine-driven workflow execution — the `akm workflow run`
6
+ * start/resume/execute path, and the single execution surface for a run: akm
7
+ * walks the frozen plan and dispatches every unit itself.
9
8
  *
10
9
  * Invariant (plan §*Never bypass the gate spine*): every step advances
11
10
  * through `completeWorkflowStep`, never by writing step rows directly, so the
@@ -46,8 +45,8 @@
46
45
  * `finally` unless a failed run retains it as forensic state; a second
47
46
  * `workflow run` on a live-leased run refuses up front,
48
47
  * and an expired lease is claimable (crash recovery). While the lease is
49
- * live, manual `workflow complete` is refused too — the engine owns the
50
- * spine while driving (enforced inside `completeWorkflowStep`).
48
+ * live, any competing spine advance is refused — the engine owns the run while
49
+ * driving (enforced inside `completeWorkflowStep`).
51
50
  *
52
51
  * Process-lifecycle contract (owner finding 4 — no leaked handles): the SDK
53
52
  * dispatch path caches `opencode serve` CHILD PROCESSES in a per-env registry
@@ -69,17 +68,51 @@ import { assertRunParamsSatisfyPlan } from "../ir/params.js";
69
68
  import { computePlanHash } from "../ir/plan-hash.js";
70
69
  import { decodeWorkflowPlanV3 } from "../ir/schema.js";
71
70
  import { requireExecutableWorkflowPlan } from "../runtime/plan-classifier.js";
72
- import { completeWorkflowStep, getNextWorkflowStep } from "../runtime/runs.js";
71
+ import { completeWorkflowStep, getNextWorkflowStep, resumeWorkflowRun } from "../runtime/runs.js";
73
72
  import { GATE_EVALUATION_PHASE } from "../runtime/unit-phases.js";
74
73
  import { frozenSummaryJudge } from "./frozen-judge.js";
75
- import { executeStepPlan } from "./native-executor.js";
74
+ import { defaultUnitDispatcher, executeStepPlan, } from "./native-executor.js";
76
75
  // Shared step semantics — route evaluation + cascaded-skip bookkeeping,
77
76
  // gate-evaluation journaling, and the whole step-completion path
78
- // (`finalizeExecutedStep`) live in step-work.ts so the engine loop and the R3
79
- // brief/report driver protocol share ONE implementation (no drift).
77
+ // (`finalizeExecutedStep`) live in step-work.ts as ONE implementation, so the
78
+ // fresh-execution and resume paths cannot drift from each other.
80
79
  import { activeGateLoop, cascadeSkippedRouter, finalizeExecutedStep, recoverGateFeedback, seedJournaledRouteDecisions, } from "./step-work.js";
81
80
  export async function runWorkflowSteps(options) {
82
- const next = await getNextWorkflowStep(options.target, options.params);
81
+ let target = options.target;
82
+ let params = options.params;
83
+ let parameterFlags = options.parameterFlags;
84
+ let remainingRetries = options.maxRetries ?? 0;
85
+ let remainingSteps = options.maxSteps;
86
+ const executed = [];
87
+ for (;;) {
88
+ const result = await runWorkflowAttempt({
89
+ ...options,
90
+ target,
91
+ ...(params !== undefined ? { params } : { params: undefined }),
92
+ ...(parameterFlags !== undefined ? { parameterFlags } : { parameterFlags: undefined }),
93
+ ...(remainingSteps !== undefined ? { maxSteps: remainingSteps } : { maxSteps: undefined }),
94
+ });
95
+ executed.push(...result.executed);
96
+ const aggregate = { ...result, executed };
97
+ if (result.run.status !== "failed" || result.aborted || result.gateRejection || remainingRetries <= 0) {
98
+ return aggregate;
99
+ }
100
+ if (remainingSteps !== undefined) {
101
+ remainingSteps -= result.executed.length;
102
+ if (remainingSteps <= 0)
103
+ return aggregate;
104
+ }
105
+ await resumeWorkflowRun(result.run.id);
106
+ target = result.run.id;
107
+ params = undefined;
108
+ parameterFlags = undefined;
109
+ remainingRetries -= 1;
110
+ }
111
+ }
112
+ async function runWorkflowAttempt(options) {
113
+ const next = await getNextWorkflowStep(options.target, options.params, {
114
+ parameterFlags: options.parameterFlags,
115
+ });
83
116
  // Version/canonical/hash validation precedes every executable mutation,
84
117
  // including lease acquisition. Historical rows remain inspectable/abandonable.
85
118
  if (!next.done && !options.loadPlan) {
@@ -125,7 +158,11 @@ export async function runWorkflowSteps(options) {
125
158
  : undefined;
126
159
  heartbeat?.start();
127
160
  try {
128
- return await driveRun(options, next, leaseHolder, heartbeat);
161
+ const result = await driveRun(options, next, leaseHolder, heartbeat);
162
+ // Creation-time notices reach the caller only here: the run row has no
163
+ // warnings column, and a later invocation of the same run must stay silent
164
+ // about a decision it did not make. `driveRun` never sets `warnings`.
165
+ return next.startWarnings?.length ? { ...result, warnings: next.startWarnings } : result;
129
166
  }
130
167
  finally {
131
168
  heartbeat?.stop();
@@ -294,30 +331,34 @@ class LeaseHeartbeat {
294
331
  this.detachUpstream?.();
295
332
  }
296
333
  }
334
+ /**
335
+ * A terminal run is a pure no-op: do not load or integrity-check its frozen
336
+ * plan, because post-completion plan corruption cannot change finished work.
337
+ */
338
+ async function completedRunResult(runId) {
339
+ const doneState = await getNextWorkflowStep(runId);
340
+ return {
341
+ run: doneState.run,
342
+ executed: [],
343
+ ...(doneState.run.status === "completed" ? { done: true } : {}),
344
+ };
345
+ }
346
+ function workflowSummaryJudge(options, plan, stepPlan, signal) {
347
+ if (options.summaryJudge !== undefined)
348
+ return options.summaryJudge;
349
+ return frozenSummaryJudge(plan, stepPlan.gate.judge, signal, options.dispatcher ?? defaultUnitDispatcher);
350
+ }
297
351
  /** The engine loop proper — runs under the lease held by `runWorkflowSteps`. */
298
352
  async function driveRun(options, initial, leaseHolder, heartbeat) {
299
353
  let next = initial;
300
- // A terminal (completed) run is a PURE no-op. `runWorkflowSteps` already
301
- // skipped lease acquisition for a done run (`leased = !next.done`), and this
302
- // path must ALSO refuse to read the journal or load/integrity-check the
303
- // frozen plan: a run that finished cleanly, then had its `plan_json` corrupted
304
- // or tampered afterwards, must still report `done` here rather than throwing a
305
- // frozen-plan integrity error (loadFrozenPlan would). Nothing will dispatch
306
- // and the engine_lease_* columns stay exactly as they were, so return the
307
- // fresh run state immediately.
308
- if (initial.done) {
309
- const doneState = await getNextWorkflowStep(initial.run.id);
310
- return {
311
- run: doneState.run,
312
- executed: [],
313
- ...(doneState.run.status === "completed" ? { done: true } : {}),
314
- };
315
- }
354
+ if (initial.done)
355
+ return completedRunResult(initial.run.id);
316
356
  // The effective dispatch signal: the heartbeat's controller (a lost lease or
317
357
  // a caller abort aborts it) while leased, else the raw caller signal.
318
358
  const dispatchSignal = heartbeat?.signal ?? options.signal;
319
359
  const executed = [];
320
360
  let gateRejection;
361
+ let aborted = false;
321
362
  const maxSteps = options.maxSteps ?? Number.POSITIVE_INFINITY;
322
363
  // Seed the lifetime unit cap AND the budget ceilings from the journal so
323
364
  // both are truly per-RUN: a resumed or re-invoked run must not restart the
@@ -356,10 +397,9 @@ async function driveRun(options, initial, leaseHolder, heartbeat) {
356
397
  throw new UsageError(`Injected workflow plan for run ${next.run.id} differs from its frozen plan.`);
357
398
  }
358
399
  // Reviewer #12: the journaled params row must still satisfy the frozen param
359
- // schemas before the engine resolves any unit prompt from it. Applied on ALL
360
- // THREE driver surfaces (engine here, brief, report) so schema-violating
361
- // params — post-start corruption — fail loudly and IDENTICALLY, preserving
362
- // cross-surface parity (start already validated the params it stored).
400
+ // schemas before the engine resolves any unit prompt from it, so
401
+ // schema-violating params — post-start corruption — fail loudly BEFORE any
402
+ // unit is dispatched (start already validated the params it stored).
363
403
  assertRunParamsSatisfyPlan(next.run.id, plan, next.run.params ?? {});
364
404
  // Route bookkeeping: targets a completed router did NOT select are skipped
365
405
  // when the spine reaches them; a target ANY router selected is protected
@@ -383,8 +423,10 @@ async function driveRun(options, initial, leaseHolder, heartbeat) {
383
423
  // another engine owns the spine now. A caller abort (options.signal) is a
384
424
  // graceful break, distinct from a lost lease.
385
425
  heartbeat?.assertAlive();
386
- if (options.signal?.aborted)
426
+ if (options.signal?.aborted) {
427
+ aborted = true;
387
428
  break;
429
+ }
388
430
  // Renew the run lease between steps (a fresh 90s window per iteration).
389
431
  // Losing it (expired mid-step + claimed by another engine) throws — the
390
432
  // new owner drives the spine now.
@@ -392,8 +434,8 @@ async function driveRun(options, initial, leaseHolder, heartbeat) {
392
434
  const step = next.step;
393
435
  const stepPlan = plan.steps.find((s) => s.stepId === step.id);
394
436
  if (!stepPlan) {
395
- throw new UsageError(`Step "${step.id}" of run ${next.run.id} is not present in the current workflow asset (${next.run.workflowRef}). ` +
396
- `The source file changed since the run started — advance this step manually with \`akm workflow complete\`.`);
437
+ throw new UsageError(`Step "${step.id}" of run ${next.run.id} is not present in its frozen workflow plan (${next.run.workflowRef}). ` +
438
+ "The run journal is inconsistent; abandon this run and start a new one.");
397
439
  }
398
440
  // A branch target no completed router selected → auto-skip, no dispatch.
399
441
  const skipInfo = routeUnselected.get(step.id);
@@ -437,13 +479,13 @@ async function driveRun(options, initial, leaseHolder, heartbeat) {
437
479
  // final rejection — this invocation is done.
438
480
  const maxLoops = Math.max(1, stepPlan.gate.maxLoops ?? 1);
439
481
  // Crash-resume gate state (Codex P1): SEED the starting gate loop from the
440
- // journal exactly as the brief/report surfaces do — the SAME shared helpers,
441
- // no fork. A run interrupted after a rejected gate was journaled
482
+ // journal through the SAME shared helpers the first pass used — no fork.
483
+ // A run interrupted after a rejected gate was journaled
442
484
  // (`<step>.gate:l<n>`, complete:false) must resume at loop n+1 with the
443
485
  // stored corrective feedback threaded into the unit prompts; without this
444
486
  // the engine restarts at loop 1, reuses the rejected loop-1 rows, overwrites
445
487
  // `<step>.gate:l1`, and re-judges the stale artifact — breaking journaled
446
- // replay and diverging from what brief computes for the same run. The rows
488
+ // replay and making the resumed run diverge from the interrupted one. The rows
447
489
  // are re-read here (NOT the once-at-start `journaledUnits` budget seed) so a
448
490
  // step reached later within THIS same invocation still starts fresh at loop 1.
449
491
  const stepJournal = await withWorkflowRunsRepo((repo) => repo.getUnitsForRun(next.run.id));
@@ -509,6 +551,11 @@ async function driveRun(options, initial, leaseHolder, heartbeat) {
509
551
  unitsDispatched = result.unitsDispatched;
510
552
  if (result.tokensUsed !== undefined)
511
553
  tokensUsed = result.tokensUsed;
554
+ if (options.signal?.aborted) {
555
+ aborted = true;
556
+ stopEngine = true;
557
+ break;
558
+ }
512
559
  executed.push({
513
560
  stepId: step.id,
514
561
  ok: result.ok,
@@ -518,28 +565,42 @@ async function driveRun(options, initial, leaseHolder, heartbeat) {
518
565
  });
519
566
  // Route evaluation + artifact-judged completion gate + gate-row
520
567
  // journaling + the bounded-loop rejection contract are the SHARED
521
- // completion path (`finalizeExecutedStep`): the R3 report surface drives
522
- // the identical sequence, so an engine-driven and a report-driven run of
523
- // the same frozen plan promote the same artifact and advance (or reject)
524
- // the spine identically. The engine owns only the loop control the result
525
- // maps onto (retry re-executes; advanced moves on; failure/exhaustion
526
- // stops this invocation).
527
- const finalize = await finalizeExecutedStep({
528
- runId: next.run.id,
529
- workflowRef: next.run.workflowRef,
530
- stepId: step.id,
531
- stepPlan,
532
- completionCriteria: stepPlan.gate.criteria,
533
- gateLoop,
534
- loopsRemaining: gateLoop < maxLoops,
535
- result,
536
- priorEvidence: evidence,
537
- params: next.run.params ?? {},
538
- routeSelected,
539
- routeUnselected,
540
- summaryJudge: options.summaryJudge === undefined ? frozenSummaryJudge(plan, stepPlan.gate.judge) : options.summaryJudge,
541
- leaseHolder,
542
- });
568
+ // completion path (`finalizeExecutedStep`): every step advances through
569
+ // that one sequence, whether its units were just dispatched or rehydrated
570
+ // from the journal on resume, so the same frozen plan always promotes the
571
+ // same artifact and advances (or rejects) the spine identically. The
572
+ // engine owns only the loop control the result maps onto (retry
573
+ // re-executes; advanced moves on; failure/exhaustion stops this invocation).
574
+ let finalize;
575
+ try {
576
+ finalize = await finalizeExecutedStep({
577
+ runId: next.run.id,
578
+ workflowRef: next.run.workflowRef,
579
+ stepId: step.id,
580
+ stepPlan,
581
+ completionCriteria: stepPlan.gate.criteria,
582
+ gateLoop,
583
+ loopsRemaining: gateLoop < maxLoops,
584
+ result,
585
+ priorEvidence: evidence,
586
+ params: next.run.params ?? {},
587
+ routeSelected,
588
+ routeUnselected,
589
+ summaryJudge: workflowSummaryJudge(options, plan, stepPlan, dispatchSignal),
590
+ signal: options.signal,
591
+ leaseHolder,
592
+ });
593
+ }
594
+ catch (error) {
595
+ heartbeat?.assertAlive();
596
+ if (options.signal?.aborted) {
597
+ aborted = true;
598
+ stopEngine = true;
599
+ break;
600
+ }
601
+ throw error;
602
+ }
603
+ heartbeat?.assertAlive();
543
604
  if (finalize.kind === "retry") {
544
605
  // Re-execute the subgraph with the judge/validation feedback threaded
545
606
  // into unit prompts — the changed prompt changes each unit's input
@@ -579,6 +640,7 @@ async function driveRun(options, initial, leaseHolder, heartbeat) {
579
640
  executed,
580
641
  ...(finalState.run.status === "completed" ? { done: true } : {}),
581
642
  ...(gateRejection ? { gateRejection } : {}),
643
+ ...(aborted ? { aborted: true } : {}),
582
644
  };
583
645
  }
584
646
  /**