UNPKG

akm-cli

Version:

akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur

245 lines (208 loc) • 13.7 kB
# Architecture: The Workflow Engine > **Deprecated.** Workflows are removed in 0.11, when tasks take over ordered > steps. See [STABILITY.md](../../STABILITY.md#workflow-formats-and-capabilities-deprecated). A workflow compiles to a frozen plan, persists run and unit state, dispatches its work, verifies declared gates, and resumes without replaying completed units. This page is the architecture-level reference for that engine — how a run's plan is frozen and stored, how dispatch and resume actually work, and how one engine owns a run. For the exact frontmatter/body syntax that produces the plan, see [Workflow Schema](../reference/workflow-schema.md). For the day-to-day commands that drive a run, see [Running Workflows](../guides/run-workflows.md). > **`akm run` (formerly `akm workflow run`, Deprecated; see `STABILITY.md`) is > ungated and the only execution surface.** It is the canonical start/resume/execute command; there is > no separate external-driver protocol. ## Frozen plans The first `akm run <ref>` compiles the Markdown source straight to the one plan type and stores it as durable plan **`irVersion` 8** on the run row (`plan_json` + `plan_hash`); a new start never emits an older version. `plan_ir_version` and `plan_hash` are recorded provenance: a stored plan is decoded as it is — irVersion 5, 6 and 7 plans that hold no model step included. One frozen by an older akm that still decodes runs with one warning. One frozen by a newer akm (`plan_ir_version` above 8) is refused unread with a message naming "Upgrade akm". A plan frozen before 8 with a model step recorded an engine where 8 records a connection or harness; it does not decode, and `akm run` abandons it and starts afresh. The durable plan records `sourceHash`, the sha256 of the workflow source file at freeze. It is used only for the resume warning below, never to refuse a run. **Freeze records identities, never locations.** The resolved request is frozen, the resolved target is frozen, and runner selection is frozen. So are the refs the engine itself dereferences, qualified with their bundle: the run's `workflow_ref`, each unit's `env:` refs (`{ kind: "env-ref", ref, precedence }`) and each child workflow's ref. Exact models, inference, tools and authorization, execution limits, parameter snapshots, command/script bytes, and verifier selection therefore cannot drift under an in-flight run. Everything else is live, found again at dispatch through the one ref lookup `akm show` uses (no database is opened): | Frozen | Live at dispatch | | --- | --- | | argv, `exec.cwd` and `pass_env` names as authored | the owner root of the run's workflow, which every exec unit and agent works in (`exec.cwd` joins it once) | | `env:` refs, bundle-qualified | the env file, its keys and every `${ref}` in it, and the secrets they name | | `${ref}` tokens in argv and `cwd`, as authored | the secret value or asset path each one names | The executable a unit runs is resolved at dispatch too, so upgrading a CLI (say, `claude`) never strands a run, and a `bundle update` that moves a bundle to a new revision directory in the middle of a run is harmless: the next step runs from the new directory. Plans frozen as irVersion 5 or 6 also carry a `cwdIdentity` and env owner paths; the decoder drops them and such a run dispatches by ref. Durable plans never store secret values. **A run executes the plan compiled at creation; edits to source need a new run.** Resuming a run re-reads its workflow source only to warn, once, when the source changed since the freeze — the run continues on the frozen plan. Orchestration decisions are pure functions of the frozen plan, run params, and journaled results. ## Child workflows A step that composes another workflow — directly (`uses: workflows/<ref>`) or through a task whose own target is a workflow (`uses: tasks/<ref>`) — freezes to a `child-workflow` frozen target. Unlike the `command`/`shell`/ `script` targets, a `child-workflow` target carries the child's **complete frozen plan, embedded**: compiling the parent recursively compiles, validates, and freezes each child in full — depth-first, all of it — before the parent run is ever published. Nothing about a child is re-read at dispatch time; the embedded plan is authoritative. A composition cycle is refused at freeze (`COMPOSITION_INVALID`, `src/workflows/freeze/targets/child-workflow.ts`). See [Workflow Schema: Child workflows](../reference/workflow-schema.md#child-workflows) for the authoring-side view. **Decoding.** An embedded child plan is decoded by the same structural decoder as its parent, recursively. Its `planHash` and the target's `contentHash` are recorded provenance, carried as data and never re-verified against the bytes. **The dispatch seam.** Dispatching a step whose target is `kind: "child-workflow"` is the one branch point in `dispatchJournaledAttempt` (`src/workflows/exec/native-executor.ts`) that does not call the ordinary unit dispatcher: it calls `driveChildWorkflowUnit` instead, with everything the composing unit already resolved — the frozen target, the parent's dispatch context, the child's resolved params, and the unit input hash. The branch sits **inside** the existing retry loop, after the parent unit's attempt row is already claimed `running` (so a crash between claiming that row and publishing the child leaves a recoverable `running` parent unit and no orphaned child) and **before** the ordinary post-dispatch journaling (redaction, attempt finishing), which runs unchanged either way — a child-workflow unit is journaled exactly like any other. **The drive contract.** `driveChildWorkflowUnit` validates and resolves the child's params through the same input-binding resolution every frozen target uses, computes the child's identity key from `{parentRunId, parentUnitId, unitInputHash}`, and publishes the child run — idempotently: the same three inputs always resolve to the same child row, so a retried or resumed composing step re-drives the run it already started rather than starting a new one, and only a change to the composing step's own inputs (params, an upstream step output it reads, or gate feedback from a rejected verification loop) produces a different child. A child found already `blocked` or `failed` is not re-driven — driving happens once per call, and a terminal-but-unhealthy child surfaces through the status mapping below instead. The child's final status maps onto the composing unit, and from there onto the parent step and run, exactly as described in [Workflow Schema: Child execution](../reference/workflow-schema.md#child-execution). **Why `runWorkflowSteps` is reused, not a second executor.** The child drive calls the exact same exported entry point `akm run` calls — `runWorkflowSteps(options)`, pointed at the child's run id as `target` — with no special-casing for "this target is a child": resolving a run id, decoding the stored plan, taking that run's own lock, and walking its spine through `completeWorkflowStep` are identical to the top-level path. That reuse is what makes child run locks arbitrate two-parent contention with no new mechanism, and what makes a resumed parent skip a completed child step with zero dispatcher calls. The child drive passes no `maxSteps` or `maxRetries` (the parent's own budgets count only its own spine steps). The lower-level `driveRun` that `runWorkflowSteps` wraps stays module-private — reaching for it directly, instead of the public entry point, would be exactly the second executor this design avoids. **Why `hashVersion` is 7, and why child composition did not move it.** The version prefix mixed into a unit's input hash is 7 (`src/workflows/exec/step-work.ts`); it became 7 when `taskInputs`, the resolved values of a composed task's reference-kind `inputBindings`, joined the preimage. Child composition itself contributed nothing to that bump: the parent unit's input-hash preimage already covers everything the child drive depends on — the frozen target carries the child's ref, plan hash, content hash, binding mode, and its entire embedded plan, so any change anywhere in the child changes the parent unit's own input hash transitively. The child run id (minted at dispatch) and its result (the child's last step output) are unit *outputs*, not inputs, so neither belongs in the preimage — adding either would be a hashing-boundary violation, not a fix. ## Resume skips completed units Resume never re-reads config or the asset index, and reads the workflow source only for the drift warning above. It consumes the frozen plan plus the journaled attempts and results. A stored plan that this akm cannot decode is not an error to fix in place: `akm run` marks such a run abandoned (status `failed`) and says to start a new run with `akm run <ref>`; `akm workflow status`, `list`, and `abandon` never read the plan at all. A plan frozen by a newer akm that this one cannot decode is left untouched, and the message names upgrading akm. Every dispatched unit is journaled under a content-derived identity — the node id plus a hash of its item for a map unit (`<node>:solo` otherwise) — together with an input hash over everything the unit was asked to do (its frozen instructions and target, declared `inputs:` artifacts, the params snapshot, gate feedback, and the resolved values of a composed task's input bindings). Environment bindings enter the hash by name, never by value, and `retry` and `onError` do not enter it. On re-run, a unit whose journal row is `completed` is **reused**, never re-dispatched; a failed or missing unit is dispatched live. The recorded input hash is informational: a completed unit stays completed even when the params row or an upstream artifact changed since — a fresh run is what recomputes it. ## Durable attempts and at-least-once dispatch Workflow dispatch is at-least-once. Every unit has a stable content-derived unit id and an append-only sequence of attempts. A crash reclaim reuses the same stable dispatchId for the interrupted attempt. An explicit retry gets a new dispatchId under one stable unit id and increments the attempt number. One driver per run (below) keeps a second engine off a run, and a finished attempt accepts no second terminal write, but neither can prove whether an external process completed immediately before a crash. An ambiguous crash outcome may re-run and can produce a duplicate side effect. Workflow actions should be idempotent or use the stable dispatch identity as their own deduplication key. ## One engine drives a run (the run lock) `akm run` takes the run's **lock file** before reading the plan or dispatching anything: one `O_EXCL` file per run id under the data directory (`workflow-run-locks/<run id>.lock`, next to `state.db`), recording the holder's pid, released when the invocation exits. A second `workflow run` against a run another live process holds refuses up front with `RUN_LEASE_HELD` (exit 75), naming the holder pid. A lock whose holder pid is dead is reclaimed at once, so a crashed engine does not wedge a run; nothing expires by age and nothing renews. `workflow status` and `list` never take the lock. ## Concurrency limits Native fan-out (`akm run`) uses the minimum of four limits: the map's `concurrency` (4 when the map declares none, or `workflow.defaultMapConcurrency` when set), the run's frozen `workflow.maxConcurrency`, the selected frozen connection's `concurrency` (a harness has none), and the current host's CPU-derived limit. The host limit is applied again on resume, so a run resumed on a smaller machine uses fewer workers. The policy lives in `src/workflows/concurrency-policy.ts`. `targetConcurrency` (`src/workflows/freeze/step-values.ts`) freezes the connection's value as the target's `concurrency` in the plan, and `scheduleUnits` (`src/workflows/exec/scheduler.ts`) applies it as `llmConcurrency` to cap `map` and `over` fan-out. The scheduler's own default of one is a fail-safe for a caller that names no width, not the `map` default. - **Unset (default):** the CPU-derived value `min(16, max(1, cores − 2))`. - **Set:** an explicit positive integer, clamped when frozen to `[1, 64]` (values above 64 are clamped down, so one config can be shared across machines with different core counts). ```console $ akm config set workflow.maxConcurrency 8 # raise the frozen workflow limit $ akm config get workflow.maxConcurrency 8 ``` A fan-out runs up to N agents at once, not one; see [Running Workflows](../guides/run-workflows.md). ## Run identity and persistence Run state (`plan_json`, `plan_hash`, step statuses, and the unit journal) persists in the host's `state.db`; the per-run lock file sits beside it. A run is identified by its run id and a workflow by its bundle-qualified ref. Run state is not scoped to a directory: `akm run <ref>` always starts a new run, `akm run <run-id>` drives an existing one, `akm workflow resume <run-id>` re-activates a blocked or failed one, and `akm workflow list`/`status` show every run on the host from any working directory. Starting a ref that already has active runs warns and names them; it is never refused. `akm run <ref> --skip-if-locked` skips (exit 0) instead of starting when an active run of that ref is held by a live process. ## See also - [Workflow Schema](../reference/workflow-schema.md) — exact frontmatter, refs, gates, and outputs syntax - [Running Workflows](../guides/run-workflows.md) — start, inspect, resume, and abandon a run - [Author's Guide: Writing Workflows](../guides/author-workflows.md) — writing and testing a workflow definition