@psimona/darkf 0.8.0 → 0.10.0

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 (43) hide show
  1. package/docs/concepts/failure-modes.md +13 -3
  2. package/docs/concepts/handoff.md +5 -1
  3. package/docs/concepts/node-types.md +7 -5
  4. package/docs/guides/pick-an-agent-runner.md +24 -3
  5. package/docs/guides/plan-with-a-task-queue.md +15 -0
  6. package/docs/guides/run-detached-and-monitor.md +2 -1
  7. package/docs/guides/write-your-first-workflow.md +19 -3
  8. package/docs/reference/cli-commands.md +19 -0
  9. package/docs/reference/core-types.md +17 -2
  10. package/docs/start-here/quickstart.md +19 -0
  11. package/package.json +1 -1
  12. package/skills/darkf-usage/SKILL.md +17 -0
  13. package/skills/darkf-writing-workflows/SKILL.md +16 -18
  14. package/src/cli/changelog.test.ts +44 -0
  15. package/src/cli/changelog.ts +26 -0
  16. package/src/cli/detached.test.ts +27 -5
  17. package/src/cli/doctor.test.ts +67 -8
  18. package/src/cli/help.test.ts +92 -0
  19. package/src/cli/help.ts +164 -0
  20. package/src/cli/index.ts +119 -3
  21. package/src/cli/tarball.test.ts +8 -2
  22. package/src/cli/update.test.ts +85 -17
  23. package/src/cli/update.ts +41 -7
  24. package/src/core/graph.test.ts +154 -13
  25. package/src/core/graph.ts +13 -3
  26. package/src/core/types.ts +21 -1
  27. package/src/engine/identity-guard.test.ts +47 -0
  28. package/src/engine/run.test.ts +268 -25
  29. package/src/engine/run.ts +4 -4
  30. package/src/kit/agents/handoff.ts +1 -1
  31. package/src/kit/agents/opencode.test.ts +89 -12
  32. package/src/kit/agents/opencode.ts +73 -8
  33. package/src/kit/registry.ts +5 -0
  34. package/src/kit/specs.test.ts +2 -2
  35. package/src/kit/specs.ts +3 -6
  36. package/src/test/ok-output.ts +11 -0
  37. package/workflows/dev-loop/output-types.ts +43 -0
  38. package/workflows/dev-loop/scripts/begin.ts +2 -2
  39. package/workflows/dev-loop/scripts/dispatch.ts +3 -5
  40. package/workflows/dev-loop/scripts/finish.ts +2 -36
  41. package/workflows/dev-loop/workflow.ts +26 -14
  42. package/workflows/series-ordering/output-types.ts +9 -0
  43. package/workflows/series-ordering/workflow.ts +3 -0
@@ -31,7 +31,7 @@ all of them are required:
31
31
  | `running` | `runner` | No | The runner name an agent state selected. Absent for the default runner and for script dispatches. |
32
32
  | `running` | `runnerKind` | No | The resolved agent runner's `kind`. Absent when it declares none, and for script dispatches. |
33
33
  | `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. |
34
- | `crashed` | `reason` | Yes | A `CrashReason` — which of the ten shapes below. |
34
+ | `crashed` | `reason` | Yes | A `CrashReason` — which of the eleven shapes below. |
35
35
  | `crashed` | `attempt` | Yes | Which attempt number crashed. |
36
36
 
37
37
  A **crash** means the mechanism itself failed. It doesn't mean the
@@ -48,7 +48,8 @@ export type CrashReason =
48
48
  | { kind: "unresolved-target"; from: string; target: string }
49
49
  | { kind: "duplicate-id"; id: string }
50
50
  | { kind: "max-steps"; steps: number; state: string }
51
- | { kind: "cycle-limit"; composite: string; cycles: number };
51
+ | { kind: "cycle-limit"; composite: string; cycles: number }
52
+ | { kind: "invalid-workflow"; errors: WorkflowValidationError[] };
52
53
  ```
53
54
 
54
55
  Every variant's `kind` is required — it's the discriminant. The rest
@@ -66,6 +67,7 @@ of each variant's payload is required too, with one exception:
66
67
  | `duplicate-id` | `id` (required) | `buildRegistry` found two states sharing an id. |
67
68
  | `max-steps` | `steps` (required), `state` (required) | The engine-wide `maxSteps` backstop tripped. |
68
69
  | `cycle-limit` | `composite` (required), `cycles` (required) | A composite's own `maxCycles` tripped. |
70
+ | `invalid-workflow` | `errors` (required) | `validateWorkflow` rejected the workflow before the first dispatch — the run crashes on the initial state at attempt 0, and no leaf ever runs. `errors` holds one entry per problem, each naming a state — e.g. `missing-output-type` for an agent leaf whose `outputType` is absent or has no `safeParse` function. |
69
71
 
70
72
  `validation-failed` nudges before it retries. When a result fails one
71
73
  of these checks, the engine keeps the same session alive and sends a
@@ -165,7 +167,15 @@ alive the whole time — the supervisor can kill it at any moment, and
165
167
  the journal says exactly where the wait stopped. Classification is
166
168
  runner-side: the opencode runner recognizes limit-shaped errors
167
169
  (`usage limit`, `rate limit`, `limit exceeded`, `429`) on a non-zero
168
- exit; a script that calls an LLM itself owns its error handling.
170
+ exit, and it reads the provider's `error` event that opencode prints on
171
+ stdout. Quota and throttle types (`provider.quota`, `provider.rate-limit`,
172
+ `provider.go-limit`, `provider.chatgpt-limit`,
173
+ `provider.chatgpt-workspace-limit`, `provider.budget-limit`) start the wait.
174
+ Other provider errors (`provider.auth`, `provider.no-route`,
175
+ `provider.free-limit`, `provider.model-budget-limit`) are not waited on: the
176
+ dispatch crashes as `runner-error` with the provider's message in `error`,
177
+ for example `opencode exited 1: provider.auth (401): This API key has
178
+ expired.` A script that calls an LLM itself owns its error handling.
169
179
 
170
180
  **A thrash, not (yet) a `cycle-limit` crash.** If one state's visit
171
181
  count is the run's highest and reaches 4 or more, `status` prints a
@@ -69,7 +69,11 @@ artifacts. No in-memory visit map of its own required.
69
69
  ## What's needed, what's handled
70
70
 
71
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
72
+ the next node to see. darkf never infers this. For an agent leaf, the
73
+ shape you decided on is declared up front as the state's `outputType` —
74
+ required, checked by `darkf validate` — so the next node can read
75
+ `handoff.output` as that schema's type instead of guessing; see
76
+ [Node types](../node-types/). A value not re-emitted
73
77
  this hop simply isn't there next hop — even a value the node itself
74
78
  just received.
75
79
 
@@ -32,7 +32,7 @@ export interface AgentStateDef {
32
32
  prompt: string;
33
33
  agent?: Record<string, unknown>;
34
34
  runner?: string;
35
- outputType?: OutputSchema;
35
+ outputType?: OutputSchema; // optional to the compiler; required by validateWorkflow
36
36
  on?: Record<string, string>;
37
37
  next?: string;
38
38
  retries?: number;
@@ -55,10 +55,10 @@ export interface AgentStateDef {
55
55
  | `timeoutMs` | No | 1 hour | Ceiling on a single dispatch attempt. Exceeding it is a `timeout` crash, consuming a retry attempt like any other. |
56
56
  | `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. |
57
57
  | `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/). |
58
- | `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/). |
58
+ | `outputType` | Yes | — | 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. Required with a validation error: `validateWorkflow` rejects an agent leaf without a usable `outputType` as `missing-output-type`, so `darkf validate` fails and a run crashes `invalid-workflow` before the first dispatch — even though the TypeScript field stays optional. 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/). |
59
59
  | `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/). |
60
60
 
61
- A workflow author must always supply `prompt`, and a `model` — in the state's own `agent` bag or, for a state with no `runner`, in `WorkflowDef.agent`. Everything else is safe to omit.
61
+ A workflow author must always supply `prompt`, a `model` — in the state's own `agent` bag or, for a state with no `runner`, in `WorkflowDef.agent` — and an `outputType` declaring the shape of the handoff output. Everything else is safe to omit.
62
62
 
63
63
  ## Script
64
64
 
@@ -87,7 +87,7 @@ export interface ScriptStateDef {
87
87
  | `usageLimitRetryMs` / `usageLimitMaxWaitMs` | No | 30 min / 24 h | Present on both leaf kinds, but only a failure classified as `usage-limit` starts a wait — only `opencodeRunner` does that classification (`claudeCodeRunner` does not, so its quota failures are `runner-error`), and a script's own throws are `runner-error`. A script that calls an LLM itself owns its error handling. |
88
88
  | `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. |
89
89
 
90
- `type` and `file` are the only two a script state can't do without. Both leaf kinds leave every other field optional.
90
+ `type` and `file` are the only two a script state can't do without — a script leaves every other field optional. An agent state additionally requires `prompt` and an `outputType`, as the agent table above shows.
91
91
 
92
92
  ## Composite
93
93
 
@@ -120,6 +120,7 @@ a top-level state. `Implement` is nested inside `Fix`. `Review`'s
120
120
 
121
121
  ```ts
122
122
  // darkf/workflows/series-ordering/workflow.ts (prompts and retries omitted)
123
+ import { implementOutput, reviewOutput } from "./output-types.ts";
123
124
  export const workflow: WorkflowDef = {
124
125
  initial: "Fix",
125
126
  agent: { model: "claude-sonnet-5-5" },
@@ -128,12 +129,13 @@ export const workflow: WorkflowDef = {
128
129
  initial: "Implement",
129
130
  maxCycles: 8,
130
131
  states: {
131
- Implement: { type: "agent", on: { implemented: "Verify", blocked: DONE, disputed: DONE } },
132
+ Implement: { type: "agent", outputType: implementOutput, on: { implemented: "Verify", blocked: DONE, disputed: DONE } },
132
133
  Verify: { type: "script", file: "verify.ts", on: { green: "Review", red: "Implement" } },
133
134
  },
134
135
  },
135
136
  Review: {
136
137
  type: "agent",
138
+ outputType: reviewOutput,
137
139
  on: { done: DONE, changes_requested: "Implement" },
138
140
  },
139
141
  },
@@ -31,6 +31,10 @@ the agent is instructed to fill in, and reads that file back as the
31
31
  ```ts
32
32
  import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
33
33
  import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
34
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
35
+ import { z } from "zod";
36
+
37
+ const greetOutput = zodOutputType(z.object({ greeting: z.string() }));
34
38
 
35
39
  export const agentRunner = claudeCodeRunner;
36
40
 
@@ -38,7 +42,7 @@ export const workflow: WorkflowDef = {
38
42
  initial: "Greet",
39
43
  agent: { model: "claude-sonnet-5-5" },
40
44
  states: {
41
- Greet: { type: "agent", prompt: "Write a one-sentence greeting.", next: DONE },
45
+ Greet: { type: "agent", outputType: greetOutput, prompt: "Write a one-sentence greeting.", next: DONE },
42
46
  },
43
47
  };
44
48
  ```
@@ -56,6 +60,10 @@ a missing handoff file.
56
60
  ```ts
57
61
  import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
58
62
  import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
63
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
64
+ import { z } from "zod";
65
+
66
+ const greetOutput = zodOutputType(z.object({ greeting: z.string() }));
59
67
 
60
68
  export const agentRunner = opencodeRunner;
61
69
 
@@ -63,7 +71,7 @@ export const workflow: WorkflowDef = {
63
71
  initial: "Greet",
64
72
  agent: { model: "zai-coding-plan/glm-5.3-flash" },
65
73
  states: {
66
- Greet: { type: "agent", prompt: "Write a one-sentence greeting.", next: DONE },
74
+ Greet: { type: "agent", outputType: greetOutput, prompt: "Write a one-sentence greeting.", next: DONE },
67
75
  },
68
76
  };
69
77
  ```
@@ -78,10 +86,17 @@ another one, register it by name in an `agentRunners` export and set
78
86
  import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
79
87
  import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
80
88
  import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
89
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
90
+ import { z } from "zod";
81
91
 
82
92
  export const agentRunner = opencodeRunner; // default
83
93
  export const agentRunners = { claude: claudeCodeRunner }; // selectable by name
84
94
 
95
+ // One outputType per agent state — shapes elided, this guide is about runners.
96
+ const planOutput = zodOutputType(z.unknown());
97
+ const buildOutput = zodOutputType(z.unknown());
98
+ const reviewOutput = zodOutputType(z.unknown());
99
+
85
100
  export const workflow: WorkflowDef = {
86
101
  initial: "plan",
87
102
  agent: { model: "zai-coding-plan/glm-5.3-flash", auto: true }, // default
@@ -90,17 +105,20 @@ export const workflow: WorkflowDef = {
90
105
  type: "agent",
91
106
  runner: "claude",
92
107
  agent: { model: "claude-sonnet-5-5" },
108
+ outputType: planOutput,
93
109
  prompt: "Plan the change.",
94
110
  next: "build",
95
111
  },
96
112
  build: {
97
113
  type: "agent", // inherits the default runner, model and auto
114
+ outputType: buildOutput,
98
115
  prompt: "Implement the plan.",
99
116
  next: "review",
100
117
  },
101
118
  review: {
102
119
  type: "agent",
103
120
  agent: { model: "zai-coding-plan/glm-5.3" }, // new model, keeps auto
121
+ outputType: reviewOutput,
104
122
  prompt: "Review the change.",
105
123
  next: DONE,
106
124
  },
@@ -134,6 +152,7 @@ another runner can change what its agent may do.
134
152
  | `unknown-runner` | A state names a runner that is not an own key of `agentRunners`. It never falls back to the default. |
135
153
  | `missing-runner` | A state names no runner and the workflow has no `agentRunner`. A workflow whose agent states all name one needs no default. |
136
154
  | `missing-model` | A state's effective bag has no non-empty string `model`. This applies to custom runners too. |
155
+ | `missing-output-type` | An agent state has no `outputType`, or its value has no `safeParse` method. Scripts don't need one. |
137
156
 
138
157
  `darkf validate` also fails on an `agentRunner` or `agentRunners` entry with
139
158
  no `run` function. If you call `run()` yourself, pass both as
@@ -172,4 +191,6 @@ in core or engine is specific to either shipped adapter.
172
191
  For demos and tests, skip a real harness entirely — a plain object
173
192
  satisfying `AgentRunner` is enough, as the `haiku-readme` example's stub
174
193
  runner shows (see [Quickstart](../../start-here/quickstart/)). Its states still
175
- need a `model` value, such as `agent: { model: "stub" }`.
194
+ need a `model` value, such as `agent: { model: "stub" }`, and an
195
+ `outputType` on every agent state — validateWorkflow doesn't care that
196
+ the runner is a stub.
@@ -37,6 +37,7 @@ in memory.
37
37
  // workflow.ts
38
38
  import { EXIT, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
39
39
  import { claudeCodeRunner } from "../../src/kit/agents/claude-code.ts";
40
+ import { workOutput } from "./output-types.ts";
40
41
 
41
42
  export const agentRunner = claudeCodeRunner;
42
43
 
@@ -51,6 +52,7 @@ export const workflow: WorkflowDef = {
51
52
  },
52
53
  Work: {
53
54
  type: "agent",
55
+ outputType: workOutput,
54
56
  prompt:
55
57
  'Do the task named in the handoff\'s "title" field: append one ' +
56
58
  "sentence to notes.md describing what you did, creating the file " +
@@ -66,6 +68,19 @@ export const workflow: WorkflowDef = {
66
68
  };
67
69
  ```
68
70
 
71
+ `Work` is an agent state, so it needs an `outputType` — every agent leaf
72
+ does; `darkf validate` rejects the workflow without one. `Record` reads
73
+ `tasks.json` from disk, not the handoff, so the declaration stays
74
+ permissive on purpose:
75
+
76
+ ```ts
77
+ // output-types.ts
78
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
79
+ import { z } from "zod";
80
+
81
+ export const workOutput = zodOutputType(z.unknown());
82
+ ```
83
+
69
84
  `next.ts` and `record.ts` are the only two places that touch `tasks.json`,
70
85
  and they agree on one convention: `"in-progress"` means "the item `Next`
71
86
  handed out, that `Record` hasn't closed out yet" — so a crash between the
@@ -69,7 +69,8 @@ bunx darkf validate my-workflow
69
69
 
70
70
  Checks that the workflow resolves, that `workflow.ts` loads and exports
71
71
  `workflow`, that the state graph is sound, and that every agent state
72
- resolves to a runner and a model. For the machine side, run `bunx darkf doctor`: the `claude` and `opencode` binaries on
72
+ resolves to a runner and a model and declares an `outputType` for its
73
+ handoff output. For the machine side, run `bunx darkf doctor`: the `claude` and `opencode` binaries on
73
74
  `PATH`, and that you're not accidentally running from inside the darkf
74
75
  checkout itself (a workflow's agent runner uses the invocation `cwd` as
75
76
  its working directory — a common mistake when first wiring a workflow
@@ -59,13 +59,28 @@ and `scriptRunner` (optional — only needed if a script needs run-aware
59
59
 
60
60
  ### Adding an agent state
61
61
 
62
- An `agent` state needs a `prompt`, a model, and a configured `agentRunner`:
62
+ An `agent` state needs a `prompt`, a model, an `outputType`, and a
63
+ configured `agentRunner`. Define the schema first — the `outputType`
64
+ declares the shape of the state's handoff output. Put it in its own
65
+ file, built with `zodOutputType()`, and import only the built value:
66
+
67
+ ```ts
68
+ // output-types.ts
69
+ import { z } from "zod";
70
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
71
+
72
+ const GreetOutputSchema = z.object({ greeting: z.string() });
73
+ export const greetOutput = zodOutputType(GreetOutputSchema);
74
+ ```
75
+
76
+ Then add the agent state, pointing `outputType` at the built value:
63
77
 
64
78
  ```ts
65
79
  Greet: {
66
80
  type: "agent",
67
81
  agent: { model: "claude-haiku-5-5" }, // required: every agent state needs a model
68
82
  prompt: "Write a one-sentence greeting.",
83
+ outputType: greetOutput, // required: validateWorkflow rejects an agent leaf without one
69
84
  on: { done: EXIT },
70
85
  },
71
86
  ```
@@ -90,8 +105,9 @@ built-in options and for choosing a runner per state.
90
105
  after 24 hours). A wait consumes no retry attempt and no `timeoutMs`
91
106
  budget; see [Failure modes](../../concepts/failure-modes/).
92
107
  - `outputType` checks the shape of an agent's `output` payload before
93
- `validate` runs — build one from a Zod schema with `zodOutputType()`
94
- (`@psimona/darkf/src/kit/validation/zod.ts`); see
108
+ `validate` runs — every agent leaf must declare one (`darkf validate`
109
+ rejects the workflow otherwise); build one from a Zod schema with
110
+ `zodOutputType()` (`@psimona/darkf/src/kit/validation/zod.ts`); see
95
111
  [Node types](../../concepts/node-types/).
96
112
  - `validate(result, handoff)` runs a plain code check against a result
97
113
  before it's accepted as `succeeded`; returning a string rejects it as
@@ -11,6 +11,18 @@ filesystem path, or a bare name resolved against
11
11
  `.darkf/` (dot-prefixed) is a different directory entirely: darkf's own
12
12
  runtime/run-storage, gitignore it wholesale.
13
13
 
14
+ `darkf run` is the only way to run a workflow. A word that is not a command,
15
+ as in `darkf my-workflow`, prints an error that names `darkf run my-workflow`
16
+ and exits `2`. An option that starts with `-` and that darkf does not know
17
+ also exits `2`.
18
+
19
+ ### `darkf help [command]`
20
+
21
+ `darkf --help`, `darkf -h`, and `darkf help` list every command with one line
22
+ of purpose. `darkf help <command>` and `darkf <command> --help` print the
23
+ usage of one command and do not run it. Help runs offline and writes no state.
24
+ Exits `0`. `darkf help <name>` for a name that is not a command exits `1`.
25
+
14
26
  ### `darkf render <dir>`
15
27
 
16
28
  Prints the workflow's mermaid `stateDiagram-v2` to stdout. Never executes
@@ -93,6 +105,8 @@ graph structure validates. Structure includes, for each agent state:
93
105
  - its `runner` is a key of `agentRunners`
94
106
  - without a `runner`, the module exports `agentRunner`
95
107
  - its effective `agent` bag has a non-empty string `model`
108
+ - it declares a usable `outputType` — an object with a `safeParse`
109
+ method — naming the schema of its handoff output (`missing-output-type`)
96
110
 
97
111
  A runner can also report models it does not recognize, as `warn agent models`
98
112
  lines. Warnings never change the exit code. `opencodeRunner` compares against
@@ -119,3 +133,8 @@ no-op. Takes no flags. Exits `0` on success, `1` if a copy failed.
119
133
  Lists every workflow darkf can resolve by bare name, from both
120
134
  `<cwd>/darkf/` and the darkf package's own `workflows/`,
121
135
  tagged `workspace` or `built-in`.
136
+
137
+ ### `darkf changelog`
138
+
139
+ Prints the newest section of the installed release's changelog. The update
140
+ notice points here. A missing changelog prints one line and does not fail.
@@ -20,7 +20,7 @@ export interface AgentStateDef {
20
20
  prompt: string;
21
21
  agent?: Record<string, unknown>;
22
22
  runner?: string; // key into the workflow's `agentRunners`; absent: the default `agentRunner`
23
- outputType?: OutputSchema; // checks result.output, before `validate` runs
23
+ outputType?: OutputSchema; // checks result.output, before `validate` runs; required by validateWorkflow — an agent leaf without a usable one is rejected (missing-output-type)
24
24
  on?: Record<string, string>;
25
25
  next?: string;
26
26
  retries?: number;
@@ -106,7 +106,18 @@ export type CrashReason =
106
106
  | { kind: "unresolved-target"; from: string; target: string }
107
107
  | { kind: "duplicate-id"; id: string }
108
108
  | { kind: "max-steps"; steps: number; state: string }
109
- | { kind: "cycle-limit"; composite: string; cycles: number };
109
+ | { kind: "cycle-limit"; composite: string; cycles: number }
110
+ | { kind: "invalid-workflow"; errors: WorkflowValidationError[] };
111
+
112
+ // from graph.ts — the problems `validateWorkflow` collects, one per state
113
+ export type WorkflowValidationError =
114
+ | { kind: "unresolved-target"; from: string | null; target: string }
115
+ | { kind: "initial-cycle"; cycle: string[] }
116
+ | { kind: "dead-end-leaf"; state: string }
117
+ | { kind: "unknown-runner"; state: string; runner: string; known: string[] }
118
+ | { kind: "missing-runner"; state: string }
119
+ | { kind: "missing-model"; state: string }
120
+ | { kind: "missing-output-type"; state: string };
110
121
 
111
122
  export interface StepTrace {
112
123
  state: string;
@@ -134,6 +145,10 @@ On a `running` agent dispatch, `runner` is the name the state selected
134
145
  (absent for the default runner) and `runnerKind` is the resolved runner's
135
146
  `kind` (absent when it declares none). Script dispatches carry neither.
136
147
 
148
+ An `invalid-workflow` crash means `validateWorkflow` rejected the
149
+ workflow before the first dispatch — see [Failure
150
+ modes](../../concepts/failure-modes/) for when that happens.
151
+
137
152
  The runner objects are not part of a `WorkflowDef`. A workflow module
138
153
  exports them, and `run()` takes them as `RunOptions.agentRunner` (the
139
154
  default) and `RunOptions.agentRunners?: Record<string, AgentRunner>` (the
@@ -54,6 +54,7 @@ flowchart LR
54
54
  // workflow.ts
55
55
  import { EXIT, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
56
56
  import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
57
+ import { writeOutput } from "./output-types.ts";
57
58
 
58
59
  export const agentRunner = claudeCodeRunner;
59
60
 
@@ -63,6 +64,7 @@ export const workflow: WorkflowDef = {
63
64
  states: {
64
65
  Write: {
65
66
  type: "agent",
67
+ outputType: writeOutput,
66
68
  prompt:
67
69
  "Add a haiku about darkf to README.md, wrapped in HTML comments " +
68
70
  "<!-- haiku:start --> and <!-- haiku:end --> on their own lines, " +
@@ -80,6 +82,23 @@ export const workflow: WorkflowDef = {
80
82
  };
81
83
  ```
82
84
 
85
+ Every agent leaf must declare an `outputType` — the schema of its
86
+ handoff output. `darkf validate` rejects the workflow without one
87
+ (`missing-output-type`), and a run crashes `invalid-workflow` before the
88
+ first dispatch. The declaration lives in its own file, built from a Zod
89
+ schema with `zodOutputType()`:
90
+
91
+ ```ts
92
+ // output-types.ts
93
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
94
+ import { z } from "zod";
95
+
96
+ // Check judges the README by reading the file from disk, not the handoff
97
+ // output. The declaration stays permissive — the rule guarantees a
98
+ // declaration, not a good one.
99
+ export const writeOutput = zodOutputType(z.unknown());
100
+ ```
101
+
83
102
  `check.ts` is plain code — no LLM involved in deciding whether the job is
84
103
  actually done:
85
104
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@psimona/darkf",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "A small, typed workflow engine for agent + script state graphs.",
5
5
  "license": "MIT",
6
6
  "author": "Patrizio Simona <patriziosimona@gmail.com>",
@@ -69,6 +69,23 @@ Open dispatches write a heartbeat to the journal every 30 seconds. `darkf status
69
69
 
70
70
  `darkf report` shows per-dispatch spans, a visit histogram, and usage totals. Four or more visits to one state hints at a cycle.
71
71
 
72
+ ## Supervisor session is recorded
73
+
74
+ **Warning:** `darkf start` and `darkf run` record the session that calls them as
75
+ the supervisor. With trace capture (planned, not built yet), darkf keeps the
76
+ **whole** supervisor session, with the parts that are not about the run. Uploaded
77
+ traces are kept without a time limit and are not redacted.
78
+
79
+ Before you start a run, tell the user this. To keep the session out, override
80
+ the signal with an empty value:
81
+
82
+ ```bash
83
+ CLAUDE_CODE_SESSION_ID= darkf start <workflow-dir> "<message>"
84
+ ```
85
+
86
+ The override applies to one command. Use it on every `start` and `run` that must
87
+ stay private. Detection reads only `CLAUDE_CODE_SESSION_ID`.
88
+
72
89
  ## After launch
73
90
 
74
91
  The run detaches. Watching is your job.
@@ -24,6 +24,7 @@ Every state that can route backward must live inside ONE composite. `maxCycles`
24
24
  ```ts
25
25
  import { DONE, type AgentRunner, type WorkflowDef } from "/abs/path/to/darkf/src/core/index.ts";
26
26
  import { claudeCodeRunner } from "/abs/path/to/darkf/src/kit/agents/claude-code.ts";
27
+ import { implementOutputType, reviewOutputType } from "./output-types.ts";
27
28
 
28
29
  export const agentRunner: AgentRunner = claudeCodeRunner;
29
30
 
@@ -40,7 +41,7 @@ export const workflow: WorkflowDef = {
40
41
  maxCycles: 24,
41
42
  states: {
42
43
  Implement: {
43
- type: "agent", retries: 1, prompt: IMPL,
44
+ type: "agent", retries: 1, prompt: IMPL, outputType: implementOutputType,
44
45
  on: { implemented: "Verify", disputed: DONE, blocked: DONE },
45
46
  },
46
47
  Verify: {
@@ -50,7 +51,7 @@ export const workflow: WorkflowDef = {
50
51
  on: { green: "Review", red: "Implement", blocked: DONE },
51
52
  },
52
53
  Review: {
53
- type: "agent", retries: 1, prompt: REVIEW,
54
+ type: "agent", retries: 1, prompt: REVIEW, outputType: reviewOutputType,
54
55
  on: { done: DONE, changes_requested: "Implement" },
55
56
  },
56
57
  },
@@ -72,19 +73,16 @@ Workflows outside the darkf package use absolute paths into the package, as in t
72
73
 
73
74
  ### Reading an agent claim off the handoff
74
75
 
75
- Agents emit the claim in several shapes: flat at the handoff top level,
76
- nested under `output`, or hybrid — flat claim plus a nested summary block.
77
- Never read `handoff.output ?? handoff`. A truthy `output` without the claim
78
- field shadows a correct flat verdict (run 0a1b2ca3: a passing
79
- `behavior_ok: true` verdict was declared invalid, and the repair loop
80
- tripped the composite's cycle budget on a healthy tree). Scan the
81
- candidates and prefer whichever shape actually carries the claim field:
82
-
83
- ```ts
84
- const claim = [handoff.output, handoff].find(
85
- (c) => c != null && typeof (c as Claim).verdict_field === "boolean",
86
- );
87
- ```
76
+ Every agent state declares `outputType`, so a consumer knows the claim's
77
+ shape at type-check time: read `handoff.output` as that declared schema's
78
+ type. Do not scan candidate shapes. The scan — guessing flat vs nested vs
79
+ hybrid at the consumer — is the historical anti-pattern (run `0a1b2ca3`: a
80
+ hybrid verdict, a passing `behavior_ok: true` plus a nested summary block,
81
+ was read as invalid; the verify step crashed `bad_verdict` on a healthy
82
+ tree, and the repair loop tripped the composite's cycle budget).
83
+ `validateWorkflow` rejects any agent leaf without `outputType`, so a
84
+ producer that stops promising a shape fails at `darkf validate` — seconds,
85
+ not a dispatch.
88
86
 
89
87
  Pair this with the maxCycles rule above: one false rejection costs a full
90
88
  repair round, and the budget counts dispatches, not repairs.
@@ -95,7 +93,7 @@ A script default export receives `(handoff, info)` and returns a `NodeResult`. `
95
93
 
96
94
  ## Validate agent output with `outputType`
97
95
 
98
- An agent state accepts an optional `outputType`: a shape check the engine runs against the node's `output` payload, before `validate`. Use it for structure ("does the output have these fields?"), keep `validate` for logic ("is the value acceptable?"). A state may set both. Type runs first, so a `validate` script can read `output.tasks[2].title` without re-checking the shape itself. `outputType` is agent-only: a script's output comes from code you already wrote and control. `validate` stays available on both agent and script states.
96
+ Every agent state requires an `outputType`: a shape check the engine runs against the node's `output` payload, before `validate`. `validateWorkflow` rejects an agent leaf without one — `darkf validate` fails with `agent leaf has no outputType`, and a run of the same workflow crashes `invalid-workflow` before the first dispatch. Use it for structure ("does the output have these fields?"), keep `validate` for logic ("is the value acceptable?"). A state may set both. Type runs first, so a `validate` script can read `output.tasks[2].title` without re-checking the shape itself. `outputType` is agent-only: a script's output comes from code you already wrote and control, so its leaf needs no declaration. `validate` stays available on both agent and script states.
99
97
 
100
98
  ### The `OutputSchema` interface
101
99
 
@@ -195,14 +193,14 @@ If a node needs a concrete artifact derived from the spec, add a dedicated pair
195
193
 
196
194
  Once you have a `TaskList` (previous section), don't hand it whole to one agent and ask it to work through every task in a single dispatch. That hides the per-task state inside one agent's own judgment about what it already finished, has no node any run status can point at ("which task is this run on right now?"), and a crash mid-plan loses track of exactly where it was.
197
195
 
198
- This is the `item-loop-convention` shape (a design doc, not shipped `darkf-core`/`kit` code as of this writing; hand-roll its algorithm directly in your own `scripts/` rather than importing a module that doesn't exist yet):
196
+ This is the item-loop shape. darkf ships no helper for it, so hand-roll the algorithm in your own `scripts/`:
199
197
 
200
198
  - **Dispatch** (a script) is the node that walks the plan. It reads the persisted `TaskList`, picks the first task whose status is not yet `"done"` (`"pending"` normally; an `"in-progress"` one found on resume means a crash interrupted it — dispatch that same one again, no special case needed), flips it `"in-progress"`, writes the file back, and hands that one task to the next node as its `output`. If every task is `"done"`, route to whatever follows the loop. If any are `"failed"` with none left `"pending"`, that's a distinct blocked outcome, not "exhausted."
201
199
  - The lane that follows (implement, test, fix, review — whatever one task's own work needs) operates on that single task only. It gets the task directly via the one-hop handoff from Dispatch if it's the very next node; anything further downstream (e.g. a reviewer several hops past Dispatch, past a fix-retry loop) rediscovers the right task by reading the plan file itself and finding the one still `"in-progress"` — never by relying on a value threaded through every intervening node.
202
200
  - Only flip a task to `"done"` once its result is independently confirmed, not when the implementing step merely claims it finished. If judgment is needed to confirm that (a reviewer checking the claim against the working tree), split it into the judging agent (which never touches the file) and a small script right after it that does the actual write — same agent/script split as everywhere else in this document.
203
201
  - The lane's last node routes back to Dispatch by its state id — a flat edge, which is fine even across composite boundaries (`buildRegistry` is one flat map keyed by state id; routing doesn't care which composite either side lives in). Dispatch gets re-entered once per task until the plan is exhausted.
204
202
  - **Keep Dispatch outside the lane's composite.** Wrap only the lane (implement, test, fix, review, mark-done) in its own composite; Dispatch sits as that composite's sibling, not inside it. This is what makes the lane's `maxCycles` budget one task's worst case, not the whole plan's: the engine resets a composite's cycle counter whenever the dispatch immediately before it did not already carry that composite in its scope (`CompositeStateDef.maxCycles`'s doc, `src/core/types.ts`). Every hand-off from Dispatch into the lane is such a reset, because Dispatch itself lives outside it.
205
- - Size the lane's `maxCycles` by hand for one task's worst case only: `dispatches per task in the worst case`, with slack (roughly ×1.5) for an occasional extra fix round. Never multiply by the expected task count — `WorkflowDef` is static and built before the real task count is known, so a budget sized against an assumed total crashes the whole run the first time a real plan comes out bigger, even when no single task is anywhere near a runaway. Put no `maxCycles` on Dispatch itself; the engine-wide `maxSteps` is the only backstop needed on the item-to-item loop, matching `item-loop-convention`'s own non-goal of not wiring this automatically.
203
+ - Size the lane's `maxCycles` by hand for one task's worst case only: `dispatches per task in the worst case`, with slack (roughly ×1.5) for an occasional extra fix round. Never multiply by the expected task count — `WorkflowDef` is static and built before the real task count is known, so a budget sized against an assumed total crashes the whole run the first time a real plan comes out bigger, even when no single task is anywhere near a runaway. Put no `maxCycles` on Dispatch itself; the engine-wide `maxSteps` is the only backstop needed on the item-to-item loop.
206
204
  - This loop and the plan-generation loop from the previous section are two separate composites with two separate `maxCycles` budgets, not one — they bound unrelated things (a small, fixed number of generation retries vs. one task's worst case), per the Bounded loops rule above.
207
205
 
208
206
  ## Event design
@@ -0,0 +1,44 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { changelogHead } from "./changelog.ts";
3
+
4
+ const CHANGELOG = [
5
+ "# Changelog",
6
+ "",
7
+ "## 1.2.0",
8
+ "",
9
+ "### Added",
10
+ "",
11
+ "- the newest feature.",
12
+ "",
13
+ "## 1.1.0",
14
+ "",
15
+ "### Fixed",
16
+ "",
17
+ "- an older fix.",
18
+ "",
19
+ ].join("\n");
20
+
21
+ describe("changelogHead", () => {
22
+ test("prints everything before the second ## heading", () => {
23
+ expect(changelogHead(CHANGELOG)).toBe(
24
+ ["# Changelog", "", "## 1.2.0", "", "### Added", "", "- the newest feature."].join("\n"),
25
+ );
26
+ });
27
+
28
+ test("a file with one heading prints to the end", () => {
29
+ expect(changelogHead("# Changelog\n\n## 1.0.0\n\n- all of it.")).toBe(
30
+ "# Changelog\n\n## 1.0.0\n\n- all of it.",
31
+ );
32
+ });
33
+
34
+ test("a heading-less file prints its head, capped", () => {
35
+ const body = Array.from({ length: 200 }, (_, i) => `line ${i}`).join("\n");
36
+ const head = changelogHead(body);
37
+ expect(head.split("\n")).toHaveLength(80);
38
+ expect(head).toContain("line 0");
39
+ });
40
+
41
+ test("trailing blank lines are trimmed", () => {
42
+ expect(changelogHead("## 1.0.0\n\n- x.\n\n\n")).toBe("## 1.0.0\n\n- x.");
43
+ });
44
+ });
@@ -0,0 +1,26 @@
1
+ // `darkf changelog` (self-update spec, 2026-12-05): print what changed in
2
+ // the installed release, so the upgrade notice can point at a real answer
3
+ // instead of a version number alone. Pure here: the section extraction is
4
+ // testable without the file; `index.ts` owns the path and the print.
5
+
6
+ const MAX_LINES = 80;
7
+
8
+ /** The newest changelog section: everything before the second `## ` heading
9
+ * (the first heading is the newest release or `Unreleased`), capped so a
10
+ * pathologically long section still prints as a digest. Never returns an
11
+ * empty string — a heading-less file prints its head lines. */
12
+ export function changelogHead(text: string): string {
13
+ const lines = text.split("\n");
14
+ const out: string[] = [];
15
+ let headings = 0;
16
+ for (const line of lines) {
17
+ if (line.startsWith("## ")) {
18
+ headings += 1;
19
+ if (headings === 2) break;
20
+ }
21
+ out.push(line);
22
+ if (out.length >= MAX_LINES) break;
23
+ }
24
+ while (out.length > 0 && out[out.length - 1] === "") out.pop();
25
+ return out.join("\n");
26
+ }