@psimona/darkf 0.5.0 → 0.7.1

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 (69) hide show
  1. package/docs/concepts/failure-modes.md +177 -0
  2. package/docs/concepts/handoff.md +91 -0
  3. package/docs/concepts/journal.md +92 -0
  4. package/docs/concepts/node-types.md +177 -0
  5. package/docs/guides/pick-an-agent-runner.md +57 -0
  6. package/docs/guides/plan-with-a-task-queue.md +411 -0
  7. package/docs/guides/render-to-mermaid.md +22 -0
  8. package/docs/guides/run-detached-and-monitor.md +76 -0
  9. package/docs/guides/test-your-workflow.md +20 -0
  10. package/docs/guides/write-your-first-workflow.md +101 -0
  11. package/docs/index.mdx +68 -0
  12. package/docs/reference/cli-commands.md +105 -0
  13. package/docs/reference/core-types.md +128 -0
  14. package/docs/reference/package-map.md +39 -0
  15. package/docs/start-here/install.md +71 -0
  16. package/docs/start-here/quickstart.md +248 -0
  17. package/package.json +15 -2
  18. package/skills/darkf-usage/SKILL.md +92 -0
  19. package/skills/darkf-writing-workflows/SKILL.md +213 -0
  20. package/src/cli/doctor.test.ts +338 -0
  21. package/src/cli/index.ts +139 -15
  22. package/src/cli/setup.test.ts +384 -0
  23. package/src/cli/setup.ts +281 -0
  24. package/src/cli/state-file.ts +14 -0
  25. package/src/cli/tarball.test.ts +127 -0
  26. package/src/cli/update.test.ts +82 -0
  27. package/src/cli/update.ts +24 -9
  28. package/src/core/tasks.ts +1 -1
  29. package/src/core/types.test.ts +52 -0
  30. package/src/core/types.ts +33 -16
  31. package/src/engine/run.test.ts +462 -3
  32. package/src/engine/run.ts +114 -8
  33. package/src/exports.ts +4 -0
  34. package/src/kit/agents/claude-code.ts +4 -34
  35. package/src/kit/agents/handoff.test.ts +12 -0
  36. package/src/kit/agents/handoff.ts +32 -8
  37. package/src/kit/agents/opencode.test.ts +232 -2
  38. package/src/kit/agents/opencode.ts +80 -31
  39. package/src/kit/specs.test.ts +247 -0
  40. package/src/kit/specs.ts +344 -0
  41. package/src/kit/status.test.ts +67 -0
  42. package/src/kit/status.ts +29 -4
  43. package/src/kit/validation/zod.test.ts +42 -0
  44. package/src/kit/validation/zod.ts +20 -0
  45. package/workflows/dev-loop/scripts/begin.ts +9 -6
  46. package/workflows/dev-loop/scripts/dispatch.ts +50 -0
  47. package/workflows/dev-loop/scripts/finish.ts +26 -21
  48. package/workflows/dev-loop/scripts/mark-done.ts +22 -0
  49. package/workflows/dev-loop/scripts/validate-plan.ts +30 -0
  50. package/workflows/dev-loop/workflow.ts +171 -64
  51. package/bunfig.toml +0 -13
  52. package/examples/article-classifier/data/articles.ts +0 -38
  53. package/examples/article-classifier/scripts/next.ts +0 -7
  54. package/examples/article-classifier/scripts/queue.ts +0 -33
  55. package/examples/article-classifier/scripts/record.ts +0 -9
  56. package/examples/article-classifier/workflow.ts +0 -44
  57. package/examples/haiku-commit/scripts/check.ts +0 -24
  58. package/examples/haiku-commit/workflow.ts +0 -28
  59. package/examples/haiku-readme/scripts/test.ts +0 -13
  60. package/examples/haiku-readme/scripts/write.ts +0 -10
  61. package/examples/haiku-readme/workflow.ts +0 -41
  62. package/examples/task-queue/scripts/next.ts +0 -20
  63. package/examples/task-queue/scripts/record.ts +0 -20
  64. package/examples/task-queue/supervise.ts +0 -57
  65. package/examples/task-queue/workflow.ts +0 -33
  66. package/feedback/2026-10-30-self-update.md +0 -29
  67. package/feedback/2026-10-31-task-list-json.md +0 -26
  68. package/tsconfig.json +0 -4
  69. /package/workflows/dev-loop/scripts/{check.ts → test.ts} +0 -0
@@ -0,0 +1,177 @@
1
+ ---
2
+ title: Failure modes
3
+ description: A mechanism failure is never confused with a workflow outcome.
4
+ ---
5
+
6
+ Every node's execution goes through one lifecycle. It's used recursively
7
+ at every depth: a single leaf dispatch, a composite's currently-active
8
+ descendant, and the whole run's terminal outcome are all "a node
9
+ executing."
10
+
11
+ ```ts
12
+ export type NodeStatus =
13
+ | { phase: "pending" }
14
+ | { phase: "running"; attempt: number; startedAt: number; lastHeartbeat: number; sessionId?: string;
15
+ limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number } }
16
+ | { phase: "succeeded"; result: NodeResult }
17
+ | { phase: "crashed"; reason: CrashReason; attempt: number };
18
+ ```
19
+
20
+ `pending` carries nothing. `succeeded` carries one required field,
21
+ `result`. The other two phases carry more than one field each, and not
22
+ all of them are required:
23
+
24
+ | Phase | Field | Required | What it is |
25
+ |---|---|---|---|
26
+ | `running` | `attempt` | Yes | Which attempt number is in flight — `1` for the first try. |
27
+ | `running` | `startedAt` | Yes | Timestamp this attempt began. |
28
+ | `running` | `lastHeartbeat` | Yes | Timestamp of the latest heartbeat, updated every 30s. |
29
+ | `running` | `sessionId` | No | Only present once some earlier attempt's runner returned one. |
30
+ | `running` | `limitBackoff` | No | Present only while the engine is waiting out a provider usage limit — which probe this is, when the next one fires, and the total waited so far. |
31
+ | `crashed` | `reason` | Yes | A `CrashReason` — which of the ten shapes below. |
32
+ | `crashed` | `attempt` | Yes | Which attempt number crashed. |
33
+
34
+ A **crash** means the mechanism itself failed. It doesn't mean the
35
+ workflow reached a bad outcome on purpose.
36
+
37
+ ```ts
38
+ export type CrashReason =
39
+ | { kind: "runner-error"; error: string }
40
+ | { kind: "usage-limit"; detail: string }
41
+ | { kind: "timeout"; elapsedMs: number }
42
+ | { kind: "malformed-result" }
43
+ | { kind: "validation-failed"; message: string }
44
+ | { kind: "no-transition"; state: string; event?: string }
45
+ | { kind: "unresolved-target"; from: string; target: string }
46
+ | { kind: "duplicate-id"; id: string }
47
+ | { kind: "max-steps"; steps: number; state: string }
48
+ | { kind: "cycle-limit"; composite: string; cycles: number };
49
+ ```
50
+
51
+ Every variant's `kind` is required — it's the discriminant. The rest
52
+ of each variant's payload is required too, with one exception:
53
+
54
+ | Kind | Payload | What it means |
55
+ |---|---|---|
56
+ | `runner-error` | `error` (required) | A runner itself threw. |
57
+ | `usage-limit` | `detail` (required) | The provider's usage limit stayed exhausted until the leaf's wait budget ran out — `detail` is the provider line that matched. |
58
+ | `timeout` | `elapsedMs` (required) | The dispatch outran its `timeoutMs`. |
59
+ | `malformed-result` | none | The reply didn't parse as a well-formed `NodeResult`. |
60
+ | `validation-failed` | `message` (required) | An agent leaf's `outputType` failed its shape check, or the state's `validate` returned a rejection string. |
61
+ | `no-transition` | `state` (required), `event` (optional) | Nothing in `on`/`next` matched the returned event — `event` is absent if the result didn't carry one either. |
62
+ | `unresolved-target` | `from` (required), `target` (required) | An edge named a state id that doesn't exist anywhere in the workflow. |
63
+ | `duplicate-id` | `id` (required) | `buildRegistry` found two states sharing an id. |
64
+ | `max-steps` | `steps` (required), `state` (required) | The engine-wide `maxSteps` backstop tripped. |
65
+ | `cycle-limit` | `composite` (required), `cycles` (required) | A composite's own `maxCycles` tripped. |
66
+
67
+ `validation-failed` nudges before it retries. When a result fails one
68
+ of these checks, the engine keeps the same session alive and sends a
69
+ short corrective prompt quoting `message` — up to three times per leaf
70
+ visit, none costing a retry — and only then falls back to a fresh
71
+ attempt.
72
+
73
+ A runner that throws, times out, returns something malformed, or fails
74
+ its state's `validate` hook produces a crash. It never produces a
75
+ routed transition.
76
+
77
+ Crashes never reach the routing layer. They're never confused with a
78
+ workflow-modeled outcome, like `{ event: "rejected" }`. Both are real
79
+ answers a node can produce — only one of them means the mechanism
80
+ itself failed.
81
+
82
+ This separation is why a workflow author can model "the reviewer
83
+ rejected the change" as a normal `on: { rejected: "Write" }` edge.
84
+ "The reviewer's CLI process hung for an hour," meanwhile, surfaces as a
85
+ `timeout` crash — not a silent-looking rejection.
86
+
87
+ ## How failures propagate
88
+
89
+ Three independent bounds catch three different failure shapes. Each
90
+ one escalates to the next when it doesn't apply.
91
+
92
+ **`retries`** (default 0, per leaf) bounds reattempts of *one
93
+ dispatch*. A crash consumes an attempt — `maxAttempts = retries + 1`.
94
+ Once attempts run out, the leaf's crash becomes the run's crash.
95
+
96
+ One exception: a `usage-limit` crash consumes no attempt. When a
97
+ dispatch dies on the provider's usage limit, the engine waits
98
+ (`usageLimitRetryMs`, default 30 minutes) and re-probes the same
99
+ attempt — retry count untouched — for up to `usageLimitMaxWaitMs`
100
+ (default 24 hours) per node visit. The wait also runs outside
101
+ `timeoutMs`: each re-probe starts with a fresh per-attempt budget. At
102
+ the cap the run ends in a terminal `usage-limit` crash.
103
+
104
+ A second exception: the `validation-failed` nudges above consume no
105
+ attempt either. Each nudge resumes the live session with a corrective
106
+ prompt; only when the three-nudge budget runs out does the crash fall
107
+ back to a fresh attempt — the attempt that finally counts against
108
+ `retries`.
109
+
110
+ **`maxCycles`** (per composite, opt-in) bounds a *multi-leaf loop*: two
111
+ nodes handing back and forth indefinitely, never tripping any single
112
+ dispatch's timeout or retry count. Each full pass through the composite
113
+ counts as one cycle. Exceeding it is a `cycle-limit` crash, naming the
114
+ composite.
115
+
116
+ **`maxSteps`** (engine-wide, default 1000) is the unconditional
117
+ backstop. Any run, any shape — dispatching past this many steps total
118
+ crashes with `max-steps`, naming the state it was on.
119
+
120
+ A crash never retries itself into a transition. Either a bound is
121
+ exhausted and the run ends with a terminal `crashed` status, or a
122
+ bound still has budget and the *same* leaf is dispatched again from
123
+ scratch — not resumed. The next attempt's `DispatchInfo.previousFailure`
124
+ carries what went wrong, so an agent runner can tell the model what to
125
+ fix. Two exceptions to "from scratch", both resuming session evidence
126
+ instead of replaying the full fresh prompt: the usage-limit wait's
127
+ post-wait re-dispatch sends a short continuation prompt, and a
128
+ `validation-failed` nudge sends a short corrective one quoting
129
+ `message` — so work already done is kept.
130
+
131
+ ## What you observe
132
+
133
+ None of this requires watching a live process. `darkf status`,
134
+ `monitor`, and `report` all read the journal. A crash looks the same
135
+ whether you're watching live or looking at a finished run's history.
136
+
137
+ **A terminal crash.** `darkf status` exits `1` and prints `crash:
138
+ attempt=<n> reason=<CrashReason>` directly — the same tagged object
139
+ shown above, not a prose guess at what went wrong.
140
+
141
+ **A stall, not yet a crash.** A dispatch still `running`, whose
142
+ heartbeat (written every 30s by a live worker) has gone quiet for more
143
+ than 90 seconds, prints a `warn: stall suspected ...` line. This is
144
+ deliberately warn-only: darkf doesn't kill or restart anything itself,
145
+ since "gone quiet" and "about to finish" look identical from the
146
+ journal alone. Deciding what to do about it is the job of whatever is
147
+ watching — see [Plan with a task queue](../../guides/plan-with-a-task-queue/)'s
148
+ supervisor section.
149
+
150
+ **A usage-limit wait, not a crash.** When a dispatch exits non-zero
151
+ because the provider's usage limit is exhausted, the engine waits and
152
+ re-probes instead of burning a retry (see above). While it waits,
153
+ `status` and `monitor` print the same one-line warn style as a stall:
154
+
155
+ ```text
156
+ warn: usage limit — probe 3/48, next attempt in 22m
157
+ ```
158
+
159
+ The probe denominator assumes the defaults (24 h budget, 30 min
160
+ interval); `next attempt in` counts down to the re-probe. The run is
161
+ alive the whole time — the supervisor can kill it at any moment, and
162
+ the journal says exactly where the wait stopped. Classification is
163
+ runner-side: the opencode runner recognizes limit-shaped errors
164
+ (`usage limit`, `rate limit`, `limit exceeded`, `429`) on a non-zero
165
+ exit; a script that calls an LLM itself owns its error handling.
166
+
167
+ **A thrash, not (yet) a `cycle-limit` crash.** If one state's visit
168
+ count is the run's highest and reaches 4 or more, `status` prints a
169
+ `warn:` suggesting a review/thrash loop, and points at wrapping it in a
170
+ composite with `maxCycles`. A run can still be healthy at 6 visits — a
171
+ legitimate back-and-forth. Nothing stops it short of `maxCycles` or
172
+ `maxSteps` if it isn't.
173
+
174
+ **The full history.** `darkf report` lists every crash reason that
175
+ occurred across the whole run, not just the terminal one. Useful once
176
+ retries are involved — an attempt that eventually succeeded still
177
+ crashed once on the way.
@@ -0,0 +1,91 @@
1
+ ---
2
+ title: Handoff
3
+ description: Data moves between nodes only by explicit choice.
4
+ ---
5
+
6
+ darkf does not thread a shared, ever-growing key-value bag through
7
+ every node. A node receives only the immediately preceding node's full
8
+ result — the **handoff**. One hop. Nothing accumulated.
9
+
10
+ ```ts
11
+ Write: { type: "script", file: "write.ts", next: "Test" }
12
+ ```
13
+
14
+ `write.ts` gets `Plan`'s (or whichever node ran before it) `NodeResult`
15
+ as its only input.
16
+
17
+ If a value needs to survive past the very next node, some later node's
18
+ own code has to choose to re-emit it in its own `output`. Nothing rides
19
+ along for free.
20
+
21
+ ```ts
22
+ export default function write(handoff: NodeResult): NodeResult {
23
+ const writeAttempts = ((handoff.output as { writeAttempts?: number } | undefined)
24
+ ?.writeAttempts ?? 0) + 1;
25
+ return { output: { writeAttempts } };
26
+ }
27
+ ```
28
+
29
+ Anything durable for the *whole run* — a goal, a repo path, config —
30
+ doesn't belong in this hop-to-hop channel at all.
31
+
32
+ It should be a real file instead. Every node is already arbitrary code
33
+ with normal filesystem access. the `article-classifier` example in `darkf/examples/`
34
+ shows the pattern: a script module (`scripts/queue.ts`) keeps run-scoped
35
+ state on disk, rather than threading it through handoffs.
36
+
37
+ ## DispatchInfo
38
+
39
+ A leaf also receives a `DispatchInfo` alongside the handoff:
40
+
41
+ ```ts
42
+ export interface DispatchInfo {
43
+ runId: string;
44
+ validEvents: string[];
45
+ hasFallback: boolean;
46
+ attempt: number;
47
+ sessionId?: string;
48
+ previousFailure?: CrashReason;
49
+ step: number;
50
+ rootDir: string;
51
+ }
52
+ ```
53
+
54
+ | Field | Required | What it is |
55
+ |---|---|---|
56
+ | `runId` | Yes | This run's id. |
57
+ | `validEvents` | Yes | Derived straight from this state's own `on` keys — the events it can route on. |
58
+ | `hasFallback` | Yes | Whether `next` is also set, meaning the node may omit `event` entirely and still route. |
59
+ | `attempt` | Yes | Which attempt of this dispatch is in flight — `1` the first time. |
60
+ | `sessionId` | No | Only present once a prior attempt's own `NodeResult` returned one. |
61
+ | `previousFailure` | No | Only present on a retry — the [`CrashReason`](../failure-modes/) that rejected the attempt before this one. |
62
+ | `step` | Yes | The engine's own step counter for this node's current visit, constant across every retry attempt of that visit. |
63
+ | `rootDir` | Yes | The run's root directory — the base a runner resolves its own `.darkf/run/<runId>/...` paths against. |
64
+
65
+ `step` plus `rootDir` plus `runId` is what a runner needs to compute a
66
+ deterministic path under `.darkf/run/<runId>/...` for its own
67
+ artifacts. No in-memory visit map of its own required.
68
+
69
+ ## What's needed, what's handled
70
+
71
+ Your own code decides, every single time, what belongs in `output` for
72
+ the next node to see. darkf never infers this. A value not re-emitted
73
+ this hop simply isn't there next hop — even a value the node itself
74
+ just received.
75
+
76
+ Everything else is automatic. Whatever a leaf returns (or an agent
77
+ runner parses out of a reply) becomes exactly the next leaf's `handoff`
78
+ argument. No copying, filtering, or merging in between. That's true
79
+ whether the hop crosses an `agent`→`script` boundary, a `script`→`agent`
80
+ one, or either into a composite's first child.
81
+
82
+ `DispatchInfo` is automatic too. `step`/`attempt`/`runId` are the
83
+ engine's own bookkeeping. `validEvents`/`hasFallback` are derived
84
+ straight from that state's own `on`/`next` — nothing to redeclare.
85
+ `sessionId`/`previousFailure` only appear once a retry has actually
86
+ happened.
87
+
88
+ The gap in between is deliberate. Anything durable for the whole run
89
+ has no handoff-shaped answer, on purpose. That's what the file-on-disk
90
+ escape hatch above is for — and why `DispatchInfo.rootDir` is handed to
91
+ every node, not just the ones that look like they'll need it.
@@ -0,0 +1,92 @@
1
+ ---
2
+ title: Journal
3
+ description: The one durable, authoritative record of a run.
4
+ ---
5
+
6
+ Every run writes an unconditional, append-only JSONL journal to
7
+ `.darkf/run/<runId>/journal.jsonl`. One line per transition of any
8
+ node's execution machine, at any depth: a dispatch starting, a retry
9
+ re-entering `running`, a terminal `succeeded`/`crashed`.
10
+
11
+ Each line is one `NodeEvent`:
12
+
13
+ ```ts
14
+ export interface NodeEvent {
15
+ runId: string;
16
+ state: string;
17
+ scopePath: string[];
18
+ status: NodeStatus;
19
+ timestamp: number;
20
+ }
21
+ ```
22
+
23
+ | Field | Required | What it is |
24
+ |---|---|---|
25
+ | `runId` | Yes | Which run this line belongs to. |
26
+ | `state` | Yes | The id of the node whose transition this line records. |
27
+ | `scopePath` | Yes | The chain of enclosing composite ids, outermost first — empty at the top level. |
28
+ | `status` | Yes | A [`NodeStatus`](../failure-modes/) — `pending`, `running`, `succeeded`, or `crashed`, with that phase's own payload. |
29
+ | `timestamp` | Yes | When this transition was written. |
30
+
31
+ Every field here is required — a journal line never omits one. What
32
+ varies line to line is only the shape nested inside `status`.
33
+
34
+ The journal always opens with a begin marker — the run's seed input. On
35
+ success, it closes with an end marker — the final `NodeResult`. Both
36
+ are tagged with the engine's `EXIT` sentinel.
37
+
38
+ A crash writes no end marker. The crashing leaf's own `crashed` line is
39
+ the file's last line. That asymmetry is deliberate: the file alone
40
+ answers "did it finish, and how," with no separate state to go stale.
41
+
42
+ This is why darkf's CLI commands — `status`, `monitor`, `report` — all
43
+ read the journal directly, rather than querying a live process. `darkf
44
+ status` classifies a run as `succeeded`, `crashed`, `orphaned` (the
45
+ worker PID is gone and the journal has no terminal marker), or
46
+ `running`, purely from the journal plus a liveness check on the
47
+ recorded PID. Nothing comes from in-memory state of its own.
48
+
49
+ ```sh
50
+ bunx darkf status
51
+ ```
52
+
53
+ ```
54
+ run: 7e1c9b2a-...
55
+ root: /path/to/your/project
56
+ state: succeeded
57
+ visits: {"Write":1,"Test":1,"Review":1}
58
+ runtime: 4.2s
59
+ ```
60
+
61
+ A detached run (`darkf start`) and an in-process run (`darkf run`)
62
+ write the exact same journal shape. The only difference is whether the
63
+ caller blocks on it. See [Run detached and monitor it](../../guides/run-detached-and-monitor/).
64
+
65
+ ## What's automatic, and what you'd still add
66
+
67
+ Nothing is needed from a workflow author. The journal isn't a feature
68
+ you opt into. Every run writes one, unconditionally, whether or not
69
+ anything ever reads it back. There's no flag that turns it off, and no
70
+ per-state configuration that changes what gets logged.
71
+
72
+ darkf writes three things to it without being asked:
73
+
74
+ - Every phase transition of every node, at every depth. Not just
75
+ leaves — a composite's own `running`/`succeeded` lines are in there
76
+ too.
77
+ - A **heartbeat** every 30 seconds, for any dispatch still `running`.
78
+ It updates `lastHeartbeat` on that same line's status. This is what
79
+ lets `darkf status` tell "still working" apart from "silently
80
+ stuck," without asking the worker process anything.
81
+ - A **usage sidecar** (`.darkf/run/<runId>/usage/<step>-<nodeId>.json`)
82
+ for every agent dispatch — cost and token counts. It's written next
83
+ to the journal, not into it, since usage is telemetry about a
84
+ dispatch, deliberately kept out of the `NodeResult` data flow
85
+ `on`/`next` route on.
86
+
87
+ The journal is deliberately not a queryable database. Reading it back
88
+ for anything beyond what `status`/`monitor`/`report` already show —
89
+ say, a dashboard of every `Classify` outcome across a run — means
90
+ writing that read yourself. `parseEventLog` from `@psimona/darkf/src/core` is the
91
+ function to start from; it's the same one those commands use
92
+ internally.
@@ -0,0 +1,177 @@
1
+ ---
2
+ title: Node types
3
+ description: Every leaf is agent or script, dispatched the same way.
4
+ ---
5
+
6
+ A `WorkflowDef` is a plain object. It has one `initial` state and a
7
+ `states` map.
8
+
9
+ Every state is one of three shapes: `agent`, `script`, or `composite`.
10
+ The first two are leaves — the engine actually dispatches them. The
11
+ third is pure nesting.
12
+
13
+ ## Agent
14
+
15
+ ```ts
16
+ export interface AgentStateDef {
17
+ type: "agent";
18
+ prompt: string;
19
+ agent?: Record<string, unknown>;
20
+ outputType?: OutputSchema;
21
+ on?: Record<string, string>;
22
+ next?: string;
23
+ retries?: number;
24
+ timeoutMs?: number;
25
+ usageLimitRetryMs?: number;
26
+ usageLimitMaxWaitMs?: number;
27
+ validate?: (result: NodeResult, handoff: NodeResult) => string | undefined;
28
+ }
29
+ ```
30
+
31
+ | Field | Required | Default | What it does |
32
+ |---|---|---|---|
33
+ | `type` | Yes | — | `"agent"`. The discriminant — how darkf tells this state apart from a `script` or a `composite`. |
34
+ | `prompt` | Yes | — | darkf builds the full prompt a runner sees by combining it with the incoming handoff and `validEvents` — computed straight from `on`'s own keys, so there's nothing to keep in sync by hand. |
35
+ | `agent` | No | `{}` | An untyped bag core never reads itself. Each runner interprets it its own way: `claudeCodeRunner` reads `model`/`permissionMode`, `opencodeRunner` reads `model`/`auto`. Unset, a runner falls back to its own defaults. |
36
+ | `on` | No | — | Routes by the reply's event — `{ approved: "Next" }` means "go to `Next` when the event is `approved`." |
37
+ | `next` | No | — | Unconditional alternative to `on`: always go there, regardless of what event comes back. Also sets `DispatchInfo.hasFallback`, telling the agent it may omit `event` entirely. |
38
+ | `retries` | No | `0` | Reattempts of this one dispatch after a crash — a malformed reply, a failed `validate`, a runner throwing. Each retry's prompt includes `DispatchInfo.previousFailure`, naming what went wrong last time. |
39
+ | `timeoutMs` | No | 1 hour | Ceiling on a single dispatch attempt. Exceeding it is a `timeout` crash, consuming a retry attempt like any other. |
40
+ | `usageLimitRetryMs` | No | 30 minutes | Interval between re-probes after a dispatch fails on the provider's usage limit. The wait runs outside `timeoutMs` — each re-probe starts with a fresh per-attempt budget — and consumes no retry attempt. |
41
+ | `usageLimitMaxWaitMs` | No | 24 hours | Total wait budget per node visit for usage-limit backoff. Spending it crashes the run with a `usage-limit` crash — see [Failure modes](../failure-modes/). |
42
+ | `outputType` | No | — | Shape check on the reply's `output`, run before `validate`. Any object with a `safeParse(value)` method returning `{ success: true }` or `{ success: false, message }` — build one from a Zod schema with `zodOutputType()` (`src/kit/validation/zod.ts`) and import only that built value, never Zod itself. Agent leaves only — an agent's `output` comes from text an LLM wrote, a script's from code you already control. A failure rejects the dispatch exactly like a failed `validate` — see [Failure modes](../failure-modes/). |
43
+ | `validate` | No | — | `(result, handoff) => string \| undefined`, run after the reply already parses as a well-formed `NodeResult` — and after `outputType`, when set. Return a string to reject it as `validation-failed`, or `undefined` to accept. A rejection nudges before it retries — up to three corrective prompts in the live session, none costing a retry — then falls back to a fresh attempt like any crash; see [Failure modes](../failure-modes/). |
44
+
45
+ Only `prompt` has no default and no fallback behavior — it's the one field a workflow author must always supply. Everything else is safe to omit.
46
+
47
+ ## Script
48
+
49
+ ```ts
50
+ export interface ScriptStateDef {
51
+ type: "script";
52
+ file: string;
53
+ on?: Record<string, string>;
54
+ next?: string;
55
+ retries?: number;
56
+ timeoutMs?: number;
57
+ usageLimitRetryMs?: number;
58
+ usageLimitMaxWaitMs?: number;
59
+ validate?: (result: NodeResult, handoff: NodeResult) => string | undefined;
60
+ }
61
+ ```
62
+
63
+ | Field | Required | Default | What it does |
64
+ |---|---|---|---|
65
+ | `type` | Yes | — | `"script"`. The discriminant. |
66
+ | `file` | Yes | — | Resolved relative to the workflow's `scripts/` directory. Must export a default `(handoff, info) => NodeResult \| Promise<NodeResult>`. darkf imports it, calls it, and treats whatever comes back exactly like an agent's result. |
67
+ | `on` | No | — | Same as the agent case: routes by the event the returned result carries. |
68
+ | `next` | No | — | Same as the agent case: unconditional alternative to `on`. |
69
+ | `retries` | No | `0` | Reattempts after a crash — the function throwing, returning something malformed, or failing `validate`. Each retry calls the function again from scratch; no conversation to repair, but `DispatchInfo.previousFailure` still carries what went wrong, if the script wants to branch on it. |
70
+ | `timeoutMs` | No | 1 hour | Same as the agent case — a hang past this is a `timeout` crash. |
71
+ | `usageLimitRetryMs` / `usageLimitMaxWaitMs` | No | 30 min / 24 h | Present on both leaf kinds, but only a failure classified as `usage-limit` starts a wait — the built-in agent runners do that classification, and a script's own throws are `runner-error`. A script that calls an LLM itself owns its error handling. |
72
+ | `validate` | No | — | Same contract as the agent case, minus the nudging — a script has no session to resume, so a rejection spends a retry attempt directly. Rarely needed, since a script's own result is usually correct by construction — but useful for confirming a side effect (a file actually got written) before the dispatch counts as done. |
73
+
74
+ `type` and `file` are the only two a script state can't do without. Both leaf kinds leave every other field optional.
75
+
76
+ ## Composite
77
+
78
+ ```ts
79
+ export interface CompositeStateDef {
80
+ initial: string;
81
+ states: Record<string, StateDef>;
82
+ maxCycles?: number;
83
+ }
84
+ ```
85
+
86
+ A composite isn't a leaf — it has no `type`, no `on`, no `next` of its
87
+ own. It's organizational nesting.
88
+
89
+ | Field | Required | Default | What it does |
90
+ |---|---|---|---|
91
+ | `initial` | Yes | — | Which of this composite's own `states` is active first. The engine never dispatches a composite directly — it resolves down to whichever leaf is active, at any depth, by following `initial` chains until it hits one. |
92
+ | `states` | Yes | — | This composite's own nested state map, same shape as a `WorkflowDef`'s top-level one. States inside it can themselves be composites. |
93
+ | `maxCycles` | No | unset (unbounded) | A circuit breaker on a runaway loop spanning multiple leaves inside this composite — the kind no single dispatch's `retries`/`timeoutMs` would ever catch. Exceeding it crashes with `cycle-limit`. Unset, only the engine-wide `maxSteps` backstop remains. |
94
+
95
+ `initial` and `states` are both mandatory — a composite with no states to nest, or no way to pick the first one, isn't a composite.
96
+
97
+ State ids aren't scoped to their parent composite, though. Any
98
+ `on`/`next` target can name any state anywhere in the tree, directly —
99
+ nested or not.
100
+
101
+ `darkf/workflows/series-ordering` shows this for real. `Review` is
102
+ a top-level state. `Implement` is nested inside `Fix`. `Review`'s
103
+ `changes_requested` edge still names `Implement` directly:
104
+
105
+ ```ts
106
+ // darkf/workflows/series-ordering/workflow.ts (prompts omitted)
107
+ Fix: {
108
+ initial: "Implement",
109
+ maxCycles: 8,
110
+ states: {
111
+ Implement: { type: "agent", on: { implemented: "Verify", blocked: EXIT, disputed: EXIT } },
112
+ Verify: { type: "script", file: "verify.ts", on: { green: "Review", red: "Implement" } },
113
+ },
114
+ },
115
+ Review: {
116
+ type: "agent",
117
+ on: { done: EXIT, changes_requested: "Implement" },
118
+ },
119
+ ```
120
+
121
+ `Review` doesn't name `Fix`. It doesn't need to know `Implement` is
122
+ nested at all.
123
+
124
+ Since ids are global and any edge can reach any leaf, nesting isn't
125
+ routing scope. It buys exactly two things:
126
+
127
+ 1. **A composite's own id is a routable target** — pointing an edge at
128
+ it resolves (via `enter()`) to whichever leaf its `initial`
129
+ currently names, recursively, if composites nest inside composites.
130
+ That's indirection against restructuring, not scoping: change which
131
+ leaf goes first inside `Fix`, and every edge that targets `Fix` by
132
+ name keeps working, unchanged.
133
+ 2. **`maxCycles` is scoped to the subtree, and resets on re-entry** —
134
+ a circuit breaker that's reusable per-pass (e.g. once per item in
135
+ an outer queue), not a global counter. `Fix: { maxCycles: 8 }` only
136
+ counts dispatches of `Implement`/`Verify` while execution stays
137
+ inside `Fix`, and resets the moment execution leaves (dispatching
138
+ `Review`) and later re-enters.
139
+
140
+ And explicitly what it does *not* buy: no namespacing — `Implement`'s
141
+ id still has to be unique across the *entire* workflow, nested or not;
142
+ `buildRegistry` throws `duplicate-id` the same way whether the clash is
143
+ top-level or three levels deep. And no firewalling — `Review`'s edge
144
+ above is the proof: anything, anywhere, can route straight into a
145
+ nested leaf, bypassing the composite's own `initial` entirely.
146
+
147
+ ## One contract either way
148
+
149
+ Both leaf kinds return the same shape:
150
+
151
+ ```ts
152
+ export interface NodeResult {
153
+ event?: string;
154
+ output?: unknown;
155
+ sessionId?: string;
156
+ }
157
+ ```
158
+
159
+ | Field | Required | What it's for |
160
+ |---|---|---|
161
+ | `event` | No | What `on`/`next` route on. Omit it and only `next` can match. |
162
+ | `output` | No | This node's payload for whatever node runs next. See [Handoff](../handoff/) for the rule governing it — nothing carries further than one hop unless a node re-emits it. |
163
+ | `sessionId` | No | Opaque, runner-native session id, relayed back into `DispatchInfo` on this same node's next retry attempt, so a stateless runner can resume instead of starting cold. core never interprets it. |
164
+
165
+ All three are optional — every field on `NodeResult` carries a `?`. A leaf can return `{}` and still be valid, as long as some edge's `next` is there to catch it.
166
+
167
+ The engine doesn't know or care which kind produced a result. Routing
168
+ (`on`/`next`), retries, `validate`, and journaling all treat an agent's
169
+ result and a script's result identically.
170
+
171
+ The quickstart's `haiku-readme` example leans on this directly: `Plan`
172
+ and `Review` are `agent` states, `Write` and `Test` are `script`
173
+ states, and all four sit in the same graph, routed and journaled
174
+ exactly the same way. Swap `claudeCodeRunner` for a plain stub object
175
+ (as `haiku-readme` does, to demo without a real LLM call) and nothing
176
+ about the workflow's wiring changes either — the engine never sees the
177
+ difference.
@@ -0,0 +1,57 @@
1
+ ---
2
+ title: Pick an agent runner
3
+ description: The two built-in AgentRunner adapters, and the contract they implement.
4
+ ---
5
+
6
+ Any `agent` state needs a workflow-supplied `AgentRunner`:
7
+
8
+ ```ts
9
+ export interface AgentRunner {
10
+ kind?: string;
11
+ run(id: string, def: AgentStateDef, handoff: NodeResult, info: DispatchInfo): Promise<NodeResult>;
12
+ }
13
+ ```
14
+
15
+ darkf ships two concrete adapters in @psimona/darkf/src/kit/agents/`.
16
+
17
+ ### `claudeCodeRunner`
18
+
19
+ Shells out to the `claude` CLI. Builds a prompt from the state's `prompt`,
20
+ the handoff, and the set of valid events, writes a handoff-file contract
21
+ the agent is instructed to fill in, and reads that file back as the
22
+ `NodeResult`. Reuses the CLI's own `session_id` across retries via
23
+ `sessionId` so a repair turn resumes context instead of starting cold.
24
+
25
+ ```ts
26
+ import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
27
+
28
+ export const agentRunner = claudeCodeRunner;
29
+ ```
30
+
31
+ ### `opencodeRunner`
32
+
33
+ Shells out to the `opencode` CLI (`opencode run -m <provider/model>
34
+ --format json`) — useful for pointing a workflow at any model OpenCode
35
+ supports, including a self-hosted one. Same handoff-file contract as
36
+ `claudeCodeRunner`. Parses OpenCode's NDJSON output stream and surfaces a
37
+ turn's finish reason (`stop`, `tool-calls`, `length`) directly in a crash,
38
+ rather than letting a silently-incomplete turn look like a clean exit with
39
+ a missing handoff file.
40
+
41
+ ```ts
42
+ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
43
+
44
+ export const agentRunner = opencodeRunner;
45
+ ```
46
+
47
+ ### Writing your own
48
+
49
+ Both adapters follow the same two moves: build a prompt that includes the
50
+ handoff and the valid events, then read back a result the harness wrote
51
+ somewhere durable. A third harness (pi, codex, or anything else with a
52
+ headless CLI or API) implements the same `AgentRunner` interface — nothing
53
+ in core or engine is specific to either shipped adapter.
54
+
55
+ For demos and tests, skip a real harness entirely — a plain object
56
+ satisfying `AgentRunner` is enough, as the `haiku-readme` example's stub
57
+ runner shows (see [Quickstart](../../start-here/quickstart/)).