@psimona/darkf 0.6.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 (39) hide show
  1. package/docs/concepts/failure-modes.md +18 -5
  2. package/docs/concepts/node-types.md +4 -2
  3. package/docs/guides/plan-with-a-task-queue.md +6 -5
  4. package/docs/guides/write-your-first-workflow.md +8 -2
  5. package/docs/index.mdx +4 -0
  6. package/docs/reference/core-types.md +5 -0
  7. package/docs/reference/package-map.md +12 -8
  8. package/docs/start-here/quickstart.md +12 -5
  9. package/package.json +9 -2
  10. package/skills/darkf-writing-workflows/SKILL.md +131 -6
  11. package/src/cli/doctor.test.ts +1 -1
  12. package/src/cli/index.ts +25 -15
  13. package/src/cli/setup.ts +4 -9
  14. package/src/cli/state-file.ts +14 -0
  15. package/src/cli/tarball.test.ts +3 -1
  16. package/src/cli/update.ts +4 -9
  17. package/src/core/tasks.ts +1 -1
  18. package/src/core/types.test.ts +52 -0
  19. package/src/core/types.ts +27 -18
  20. package/src/engine/run.test.ts +286 -4
  21. package/src/engine/run.ts +51 -9
  22. package/src/exports.ts +4 -0
  23. package/src/kit/agents/claude-code.ts +4 -34
  24. package/src/kit/agents/handoff.test.ts +12 -0
  25. package/src/kit/agents/handoff.ts +32 -8
  26. package/src/kit/agents/opencode.test.ts +1 -1
  27. package/src/kit/agents/opencode.ts +14 -28
  28. package/src/kit/specs.test.ts +247 -0
  29. package/src/kit/specs.ts +344 -0
  30. package/src/kit/status.ts +6 -6
  31. package/src/kit/validation/zod.test.ts +42 -0
  32. package/src/kit/validation/zod.ts +20 -0
  33. package/workflows/dev-loop/scripts/begin.ts +9 -6
  34. package/workflows/dev-loop/scripts/dispatch.ts +50 -0
  35. package/workflows/dev-loop/scripts/finish.ts +23 -21
  36. package/workflows/dev-loop/scripts/mark-done.ts +22 -0
  37. package/workflows/dev-loop/scripts/validate-plan.ts +30 -0
  38. package/workflows/dev-loop/workflow.ts +164 -68
  39. /package/workflows/dev-loop/scripts/{check.ts → test.ts} +0 -0
@@ -57,13 +57,19 @@ of each variant's payload is required too, with one exception:
57
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
58
  | `timeout` | `elapsedMs` (required) | The dispatch outran its `timeoutMs`. |
59
59
  | `malformed-result` | none | The reply didn't parse as a well-formed `NodeResult`. |
60
- | `validation-failed` | `message` (required) | The state's `validate` returned a rejection string. |
60
+ | `validation-failed` | `message` (required) | An agent leaf's `outputType` failed its shape check, or the state's `validate` returned a rejection string. |
61
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
62
  | `unresolved-target` | `from` (required), `target` (required) | An edge named a state id that doesn't exist anywhere in the workflow. |
63
63
  | `duplicate-id` | `id` (required) | `buildRegistry` found two states sharing an id. |
64
64
  | `max-steps` | `steps` (required), `state` (required) | The engine-wide `maxSteps` backstop tripped. |
65
65
  | `cycle-limit` | `composite` (required), `cycles` (required) | A composite's own `maxCycles` tripped. |
66
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
+
67
73
  A runner that throws, times out, returns something malformed, or fails
68
74
  its state's `validate` hook produces a crash. It never produces a
69
75
  routed transition.
@@ -95,6 +101,12 @@ attempt — retry count untouched — for up to `usageLimitMaxWaitMs`
95
101
  `timeoutMs`: each re-probe starts with a fresh per-attempt budget. At
96
102
  the cap the run ends in a terminal `usage-limit` crash.
97
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
+
98
110
  **`maxCycles`** (per composite, opt-in) bounds a *multi-leaf loop*: two
99
111
  nodes handing back and forth indefinitely, never tripping any single
100
112
  dispatch's timeout or retry count. Each full pass through the composite
@@ -110,10 +122,11 @@ exhausted and the run ends with a terminal `crashed` status, or a
110
122
  bound still has budget and the *same* leaf is dispatched again from
111
123
  scratch — not resumed. The next attempt's `DispatchInfo.previousFailure`
112
124
  carries what went wrong, so an agent runner can tell the model what to
113
- fix. The usage-limit wait is the one exception to "from scratch": when
114
- the failed attempt left session evidence, the post-wait re-dispatch
115
- resumes that session with a short continuation prompt instead of
116
- replaying the full fresh prompt, so work done before the limit is kept.
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.
117
130
 
118
131
  ## What you observe
119
132
 
@@ -17,6 +17,7 @@ export interface AgentStateDef {
17
17
  type: "agent";
18
18
  prompt: string;
19
19
  agent?: Record<string, unknown>;
20
+ outputType?: OutputSchema;
20
21
  on?: Record<string, string>;
21
22
  next?: string;
22
23
  retries?: number;
@@ -38,7 +39,8 @@ export interface AgentStateDef {
38
39
  | `timeoutMs` | No | 1 hour | Ceiling on a single dispatch attempt. Exceeding it is a `timeout` crash, consuming a retry attempt like any other. |
39
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. |
40
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/). |
41
- | `validate` | No | — | `(result, handoff) => string \| undefined`, run after the reply already parses as a well-formed `NodeResult`. Return a string to reject it — consuming a retry, exactly like a crash — or `undefined` to accept. |
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/). |
42
44
 
43
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.
44
46
 
@@ -67,7 +69,7 @@ export interface ScriptStateDef {
67
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. |
68
70
  | `timeoutMs` | No | 1 hour | Same as the agent case — a hang past this is a `timeout` crash. |
69
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. |
70
- | `validate` | No | — | Same contract as the agent case. 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. |
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. |
71
73
 
72
74
  `type` and `file` are the only two a script state can't do without. Both leaf kinds leave every other field optional.
73
75
 
@@ -71,11 +71,12 @@ handed out, that `Record` hasn't closed out yet" — so a crash between the
71
71
  two is visible as a stuck `in-progress` row, not a silently lost item.
72
72
 
73
73
  This project-level `tasks.json` is the workflow's own durable, committed
74
- queue. It is not the file the OpenCode plugin's tasks tab renders. That tab
75
- reads `.darkf/run/<runId>/tasks.json`, colocated with the run's journal.
76
- If you want the tab, have `Record` write a copy there too — `info.runId`
77
- carries the run id. The plugin is experimental: bundled in this repo, no
78
- public release.
74
+ queue. It is not the file the OpenCode plugin renders. The plugin's runs
75
+ tab reads `.darkf/run/<runId>/tasks.json`, colocated with the run's
76
+ journal, and shows it as the run detail view's task pane once the file
77
+ exists. If you want that pane, have `Record` write a copy there too —
78
+ `info.runId` carries the run id. The plugin is experimental: bundled in
79
+ this repo, no public release.
79
80
 
80
81
  ```ts
81
82
  // scripts/next.ts
@@ -86,9 +86,15 @@ built-in options.
86
86
  a provider usage limit (defaults: re-probe every 30 minutes, give up
87
87
  after 24 hours). A wait consumes no retry attempt and no `timeoutMs`
88
88
  budget; see [Failure modes](../../concepts/failure-modes/).
89
+ - `outputType` checks the shape of an agent's `output` payload before
90
+ `validate` runs — build one from a Zod schema with `zodOutputType()`
91
+ (`@psimona/darkf/src/kit/validation/zod.ts`); see
92
+ [Node types](../../concepts/node-types/).
89
93
  - `validate(result, handoff)` runs a plain code check against a result
90
- before it's accepted as `succeeded`; returning a string rejects it as a
91
- crash, consuming a retry attempt exactly like a runner throwing would.
94
+ before it's accepted as `succeeded`; returning a string rejects it as
95
+ `validation-failed` — an agent leaf gets up to three corrective nudges
96
+ in its live session before a fresh attempt spends a retry; see
97
+ [Failure modes](../../concepts/failure-modes/).
92
98
 
93
99
  There is no condition-expression or YAML config layer here on purpose — see
94
100
  the repo's `PHILOSOPHY.md` for why. Anything more conditional than a plain
package/docs/index.mdx CHANGED
@@ -35,6 +35,10 @@ and a skill writes the workflow for you — best practices included. Every
35
35
  workflow shows as a diagram, so the whole path stays visible and you
36
36
  stay in control.
37
37
 
38
+ Lights out when a run is clean. Lights on the moment it isn't — the
39
+ same stop-the-line principle (jidoka) a lean factory runs on, applied
40
+ to agent steps.
41
+
38
42
  Start with one workflow. Grow it into your dark factory.
39
43
 
40
44
  <CardGrid>
@@ -19,6 +19,7 @@ export interface AgentStateDef {
19
19
  type: "agent";
20
20
  prompt: string;
21
21
  agent?: Record<string, unknown>;
22
+ outputType?: OutputSchema; // checks result.output, before `validate` runs
22
23
  on?: Record<string, string>;
23
24
  next?: string;
24
25
  retries?: number;
@@ -28,6 +29,10 @@ export interface AgentStateDef {
28
29
  validate?: (result: NodeResult, handoff: NodeResult) => string | undefined;
29
30
  }
30
31
 
32
+ export interface OutputSchema {
33
+ safeParse(value: unknown): { success: true } | { success: false; message: string };
34
+ }
35
+
31
36
  export interface ScriptStateDef {
32
37
  type: "script";
33
38
  file: string;
@@ -12,22 +12,26 @@ darkf ships two packages:
12
12
  - **`core/`** — the shared vocabulary: `types.ts` (every type on this
13
13
  site's [Core types](../core-types/) page), `graph.ts`
14
14
  (registry-building and target resolution), `mermaid.ts` (render-only,
15
- never parsed back), `journal.ts` (the JSONL event shape). Zero
16
- runtime dependencies — nothing it depends on, by design.
15
+ never parsed back), `journal.ts` (the JSONL event shape). One
16
+ runtime dependency, Zod — `types.ts` uses it for the fixed
17
+ `NodeResult` envelope check; no public type references a schema
18
+ library.
17
19
  - **`engine/`** — the interpreter. `run.ts` is the dispatch loop:
18
- retries, per-attempt timeouts, the `validate` hook, usage-limit
19
- backoff, cycle-limit and
20
+ retries, per-attempt timeouts, the `outputType` shape check and
21
+ `validate` hook, usage-limit backoff, cycle-limit and
20
22
  `maxSteps` circuit breakers, unconditional journaling. Depends only
21
23
  on `core/`.
22
24
  - **`kit/`** — the workflow-authoring library: the two built-in
23
25
  `AgentRunner` adapters (`claudeCodeRunner`, `opencodeRunner`), the
24
- handoff contract, and the run registry/status helpers behind
26
+ handoff contract, the Zod adapter for `outputType` shape checks
27
+ (`validation/zod.ts`), and the run registry/status helpers behind
25
28
  [CLI commands](../cli-commands/). Depends on `core/` and `engine/`.
26
29
  - **`cli/`** — the `darkf` binary itself. Depends on all three.
27
30
  - **`darkf-opencode-plugin`** — an experimental OpenCode TUI integration
28
- (a live pane showing run status inside the OpenCode editor). No public
29
- release yet. Its own package,
30
- because its peer dependencies (`@opencode-ai/plugin`, `@opentui/*`,
31
+ (a non-modal panel inside the OpenCode editor: workflow definitions and
32
+ run status, with active runs tiled side by side). No public release
33
+ yet. Its own package,
34
+ because its peer dependencies (`@opencode/plugin`, `@opentui/*`,
31
35
  `solid-js`) are real and optional — no other consumer needs them.
32
36
 
33
37
  A dependency-cruiser rule enforces the one-way chain
@@ -225,13 +225,20 @@ exercise this same routing logic without spending anything.
225
225
 
226
226
  ## See it in an editor
227
227
 
228
- darkf also ships an experimental OpenCode plugin — a live pane showing a
229
- run's status, journal, and dwell warnings inside the editor while a
230
- workflow executes, instead of needing a second terminal for `darkf
231
- monitor`.
228
+ darkf also ships an experimental OpenCode plugin — a panel inside the
229
+ editor, instead of a second terminal for `darkf monitor`. Chat stays
230
+ visible beside it. A `panel │ full` toggle flips the panel full-screen,
231
+ and a narrow terminal always gets full-screen. Two tabs: `workflows`
232
+ catalogs every workflow definition as an expandable state graph, and
233
+ `runs` shows your runs. Active runs tile side by side, as many as the
234
+ width fits, and each drops out of the grid the moment it finishes. With
235
+ none active, `runs` falls back to a plain list — active runs first, each
236
+ with a spinner, with a search box. Selecting a run shows its live graph,
237
+ task tree, and dwell warnings. `Tab` cycles focus across the tab strip,
238
+ the content, and each tile.
232
239
 
233
240
  <div style="border: 2px dashed var(--sl-color-gray-4); border-radius: 0.5rem; padding: 3rem 1.5rem; text-align: center; color: var(--sl-color-gray-3); margin: 1.5rem 0;">
234
- Screenshot coming soon — OpenCode plugin status pane
241
+ Screenshot coming soon — OpenCode plugin overlay
235
242
  </div>
236
243
 
237
244
  It's part of this repo (`darkf-opencode-plugin`), not yet published or
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@psimona/darkf",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
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>",
@@ -30,9 +30,16 @@
30
30
  "state-graph",
31
31
  "claude-code",
32
32
  "opencode",
33
- "bun"
33
+ "bun",
34
+ "dark-factory",
35
+ "software-factory",
36
+ "automation",
37
+ "llm-agents"
34
38
  ],
35
39
  "engines": {
36
40
  "bun": ">=1.2"
41
+ },
42
+ "dependencies": {
43
+ "zod": "^4.6.7"
37
44
  }
38
45
  }
@@ -22,7 +22,7 @@ Every state that can route backward must live inside ONE composite. `maxCycles`
22
22
  ## Skeleton
23
23
 
24
24
  ```ts
25
- import { EXIT, type AgentRunner, type WorkflowDef } from "/abs/path/to/darkf/src/core/index.ts";
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
27
 
28
28
  export const agentRunner: AgentRunner = claudeCodeRunner;
@@ -39,17 +39,17 @@ export const workflow: WorkflowDef = {
39
39
  states: {
40
40
  Implement: {
41
41
  type: "agent", retries: 1, prompt: IMPL,
42
- on: { implemented: "Verify", disputed: EXIT, blocked: EXIT },
42
+ on: { implemented: "Verify", disputed: DONE, blocked: DONE },
43
43
  },
44
44
  Verify: {
45
45
  // Review only sees Verify output. Relay what Implement reported:
46
46
  // return { event: "green", output: { implemented: handoff.output } }
47
47
  type: "script", file: "verify.ts", retries: 1,
48
- on: { green: "Review", red: "Implement", blocked: EXIT },
48
+ on: { green: "Review", red: "Implement", blocked: DONE },
49
49
  },
50
50
  Review: {
51
51
  type: "agent", retries: 1, prompt: REVIEW,
52
- on: { done: EXIT, changes_requested: "Implement" },
52
+ on: { done: DONE, changes_requested: "Implement" },
53
53
  },
54
54
  },
55
55
  },
@@ -67,17 +67,142 @@ Workflows outside the darkf package use absolute paths into the package, as in t
67
67
  - The handoff contains only the immediate predecessor result. If Verify must report what Implement did, Verify must relay it in its own output. Nothing carries forward unless each node re-emits it.
68
68
  - Do not ask the agent to echo events in prose. Describe the event semantics. The runner appends the mechanics.
69
69
 
70
+ ### Reading an agent claim off the handoff
71
+
72
+ Agents emit the claim in several shapes: flat at the handoff top level,
73
+ nested under `output`, or hybrid — flat claim plus a nested summary block.
74
+ Never read `handoff.output ?? handoff`. A truthy `output` without the claim
75
+ field shadows a correct flat verdict (run 0a1b2ca3: a passing
76
+ `behavior_ok: true` verdict was declared invalid, and the repair loop
77
+ tripped the composite's cycle budget on a healthy tree). Scan the
78
+ candidates and prefer whichever shape actually carries the claim field:
79
+
80
+ ```ts
81
+ const claim = [handoff.output, handoff].find(
82
+ (c) => c != null && typeof (c as Claim).verdict_field === "boolean",
83
+ );
84
+ ```
85
+
86
+ Pair this with the maxCycles rule above: one false rejection costs a full
87
+ repair round, and the budget counts dispatches, not repairs.
88
+
70
89
  ## Scripts
71
90
 
72
91
  A script default export receives `(handoff, info)` and returns a `NodeResult`. `info.rootDir` is the invocation cwd (the target repo). Use it for every repo path so the workflow stays location-independent. `file:` resolves against `<workflow-dir>/scripts/`, not the workflow dir.
73
92
 
93
+ ## Validate agent output with `outputType`
94
+
95
+ 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
+
97
+ ### The `OutputSchema` interface
98
+
99
+ `outputType` is typed `OutputSchema` (`src/core/types.ts`), deliberately narrow and Zod-free:
100
+
101
+ ```ts
102
+ export interface OutputSchema {
103
+ safeParse(value: unknown): { success: true } | { success: false; message: string };
104
+ }
105
+ ```
106
+
107
+ Any schema library with a `.safeParse()` can implement it in a few lines. darkf-core's public types never reference a schema library, so your Zod version can never conflict with darkf's.
108
+
109
+ ### The shipped Zod adapter
110
+
111
+ darkf ships exactly one adapter, for Zod (`src/kit/validation/zod.ts`):
112
+
113
+ ```ts
114
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
115
+ ```
116
+
117
+ It joins every issue from one failed parse into a single message — `summary: Invalid input: expected string, received number; count: Invalid input: expected number, received string` — so one corrective round names every bad field, not just the first. Valibot or ArkType follow the same two-method shape; write your own, darkf ships no others.
118
+
119
+ ### Schema-first: the schema lives in its own file
120
+
121
+ Define the Zod schema once in its own file, derive the type with `z.infer`, and export the built adapter value. The workflow definition imports only that value — never Zod directly — and stays what it already is, a plain TypeScript object:
122
+
123
+ ```ts
124
+ // workflows/dev-loop/schemas/plan-output.ts
125
+ import { z } from "zod";
126
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
127
+
128
+ const PlanOutputSchema = z.object({
129
+ summary: z.string(),
130
+ tasks: z.array(z.object({ id: z.string(), title: z.string() })),
131
+ });
132
+
133
+ export type PlanOutput = z.infer<typeof PlanOutputSchema>;
134
+ export const planOutputType = zodOutputType(PlanOutputSchema);
135
+ ```
136
+
137
+ ```ts
138
+ // workflow.ts
139
+ import { planOutputType } from "./schemas/plan-output.ts";
140
+
141
+ Plan: { type: "agent", prompt: PLAN_PROMPT, outputType: planOutputType, on: { planned: "ValidatePlan" } },
142
+ ```
143
+
144
+ A failed check rejects the dispatch as `validation-failed`, with the joined message as the reason. It nudges before it retries: up to three corrective nudges in the same agent session, each fed the message, then a fresh attempt against `retries`. The whole sequence is one node visit — no extra `retries` consumed, no extra `maxCycles` count — but each nudge is still a full dispatch call.
145
+
146
+ ## Three-phase vs. one lane: only plan when planning earns its keep
147
+
148
+ The two sections below (generate a `TaskList`, walk it with a `Dispatch`
149
+ node) describe a three-phase shape: a planning phase that distills a spec
150
+ into a list of items, a loop that works through that list one item at a
151
+ time, and whatever finishes the run. Treat this as the shape to reach for
152
+ when a workflow justifies it, not the default shape for every workflow:
153
+
154
+ - **Use it** when the spec implies more than one independently-buildable,
155
+ independently-verifiable deliverable, and you can't enumerate them by
156
+ hand at authoring time — the count and shape of the work only become
157
+ known once an agent actually reads the spec. A backend feature with an
158
+ unknown number of files/behaviors to add is the motivating case.
159
+ - **Skip it** when the workflow already does one well-defined thing, or a
160
+ small fixed number of known steps you can enumerate yourself while
161
+ writing the workflow. One fix, one script change, one narrowly-scoped
162
+ task — hardcode the lane directly (the Skeleton above: one composite,
163
+ `Implement → Verify → Review`, no `TaskList`, no `Plan`, no `Dispatch`).
164
+ Forcing a planning phase onto a workflow with nothing real to plan adds
165
+ two more dispatches and a loop with nothing to walk, for zero benefit.
166
+
167
+ The tell: if you can write out every state the graph needs just from
168
+ reading the spec's title, skip planning — build that lane directly. If
169
+ you can't say in advance how many deliverables the spec implies, that's
170
+ exactly what a planning phase is for.
171
+
172
+ ## Keep prompts feature-agnostic
173
+
174
+ A workflow's `prompt` strings are fixed at authoring time — they cannot read the spec per dispatch. The temptation, once a workflow targets one real feature, is to hand-transcribe spec content straight into the prompt: a deliverables checklist, a review checklist, extracted requirements. Don't. That content drifts the moment the spec changes after the prompt was written, and someone has to hand-rewrite it for every new feature the same workflow file later dispatches.
175
+
176
+ If a node needs a concrete artifact derived from the spec, add a dedicated pair of steps that generates and persists it, and have every downstream node read what was persisted instead of carrying feature-specific prose in the workflow file:
177
+
178
+ - **Generating** is almost always an **agent**, not a script — distilling free-form spec prose into a checklist takes judgment. Have it emit the artifact as structured JSON in its own `output`, not as a file it writes itself.
179
+ - If the artifact is a plan or task breakdown, don't invent a one-off shape: darkf already has a shared `TaskList`/`Task`/`TaskRequirement` vocabulary (`darkf/src/core/types.ts`) with a hand-written, zero-dep validator (`parseTaskList`) and a canonical location the OpenCode plugin already renders live progress from. Emit that shape, not markdown prose — you get free validation, a `satisfies`-linked requirement/task map (a review checklist falls out of it: for each requirement, is there a `done` task that satisfies it?), and live status in the plugin's "tasks" tab if the runner is `opencodeRunner`.
180
+ - **Persisting** is a script, immediately after the generating agent: it validates the candidate (`parseTaskList`, or your own check for a non-TaskList artifact) and writes it to the canonical run-scoped path, `.darkf/run/<runId>/<name>.json` — a script gets `info.rootDir`/`info.runId` to compute that path; a static agent prompt cannot interpolate a per-dispatch `runId`, only a compile-time constant like `FEATURE`. Route an invalid candidate back to the generating step (bounded by the same composite's `maxCycles`, per the Bounded loops rule above), not forward to a node that can't use it.
181
+ - Every downstream node's prompt reads the file back by finding the run's own directory — "the directory under `.darkf/run/` with the latest mtime" (there is exactly one active run per dispatch) — the same pattern a run-retrospective step already needs to locate its own journal. Never by the engine handoff, which only ever carries the immediately preceding node's result, and never by pasting the artifact's content into the prompt by hand.
182
+ - A review checklist is exactly as spec-specific as a deliverables list, and belongs in the same generated artifact, not hand-copied into the Review prompt either — if you used a `TaskList`, it's the `requirements` array, already there.
183
+ - One generating/persisting pair can feed several downstream nodes several hops apart (e.g. the planner feeding both the implementer and a much later reviewer) without anything carrying it through every hop in between — it's a file on disk, not a handoff value, so the "nothing rides along for free" rule doesn't apply to it. `.darkf/` is already gitignored, so nothing here needs its own ignore rule or merge-time cleanup.
184
+
185
+ ## Walk a plan one item at a time, with a dedicated Dispatch node
186
+
187
+ 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.
188
+
189
+ 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):
190
+
191
+ - **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."
192
+ - 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.
193
+ - 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.
194
+ - 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.
195
+ - **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.
196
+ - 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.
197
+ - 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.
198
+
74
199
  ## Event design
75
200
 
76
- Keep event sets small and semantic: `implemented`/`blocked`, `green`/`red`, `done`/`changes_requested`. Use `EXIT` for terminal human gates. A crash is not a verdict. A blocked agent is not a crash either: exit cleanly and let a human re-enter.
201
+ Keep event sets small and semantic: `implemented`/`blocked`, `green`/`red`, `done`/`changes_requested`. Use `DONE` for terminal human gates. A crash is not a verdict. A blocked agent is not a crash either: exit cleanly and let a human re-enter.
77
202
 
78
203
  ### The `disputed` event
79
204
 
80
- Give the implementer a reserved `disputed` event. When a review demand contradicts the spec, the implementer objects and routes `disputed → EXIT`. The demand and a spec-grounded rationale go in `output`. The run ends with the disagreement recorded for a human. Compliance must never be the only path.
205
+ Give the implementer a reserved `disputed` event. When a review demand contradicts the spec, the implementer objects and routes `disputed → DONE`. The demand and a spec-grounded rationale go in `output`. The run ends with the disagreement recorded for a human. Compliance must never be the only path.
81
206
 
82
207
  ## Review prompts
83
208
 
@@ -5,7 +5,7 @@ import { join, resolve } from "node:path";
5
5
  import { todayLocal, writeProbeState } from "./setup.ts";
6
6
 
7
7
  // doctor/validate split, `darkf setup`, and the daily probe — the CLI-level
8
- // wiring from docs/specs/skill-setup. These spawn the real CLI entrypoint:
8
+ // wiring from docs/specs/_built/skill-setup. These spawn the real CLI entrypoint:
9
9
  // a temp HOME (host skill dirs), a temp XDG_STATE_HOME (probe stamp), and a
10
10
  // temp cwd keep the suite off the real ~ and off the network.
11
11
 
package/src/cli/index.ts CHANGED
@@ -133,12 +133,12 @@ function resolveWorkflowDir(ref: string): string {
133
133
  process.exit(1);
134
134
  }
135
135
 
136
- interface WorkflowListing {
136
+ export interface WorkflowListing {
137
137
  name: string;
138
138
  source: "workspace" | "built-in";
139
139
  }
140
140
 
141
- function listWorkflows(): WorkflowListing[] {
141
+ export function listWorkflows(): WorkflowListing[] {
142
142
  const roots: Array<[string, WorkflowListing["source"]]> = [
143
143
  [resolve(process.cwd(), "darkf"), "workspace"],
144
144
  [resolve(selfRoot(), "workflows"), "built-in"],
@@ -245,13 +245,23 @@ function describeValidationError(err: WorkflowValidationError): string {
245
245
  * not checked here — a workflow can be sound on a machine whose skills are
246
246
  * stale; the two verdicts stay independent.
247
247
  */
248
- async function validateCmd(args: string[]): Promise<number> {
249
- const ref = args[0];
248
+ /** Shared ok/FAIL line printer for `validate` and `doctor`: logs each check
249
+ * as it runs and remembers whether any of them failed. */
250
+ function makeChecker(): {
251
+ check: (label: string, ok: boolean, detail?: string) => void;
252
+ failed: () => boolean;
253
+ } {
250
254
  let fail = false;
251
255
  const check = (label: string, ok: boolean, detail?: string) => {
252
256
  console.log(`${ok ? "ok " : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
253
257
  if (!ok) fail = true;
254
258
  };
259
+ return { check, failed: () => fail };
260
+ }
261
+
262
+ async function validateCmd(args: string[]): Promise<number> {
263
+ const ref = args[0];
264
+ const { check, failed } = makeChecker();
255
265
 
256
266
  // 1. workflow resolution
257
267
  if (ref === undefined) {
@@ -311,7 +321,7 @@ async function validateCmd(args: string[]): Promise<number> {
311
321
  check("exports `agentRunner`", false, "skipped — no resolved workflow");
312
322
  }
313
323
 
314
- return Promise.resolve(fail ? 1 : 0);
324
+ return Promise.resolve(failed() ? 1 : 0);
315
325
  }
316
326
 
317
327
  /**
@@ -325,11 +335,7 @@ function doctorCmd(args: string[]): number {
325
335
  console.log("usage: darkf doctor takes no ref — darkf validate <ref> for workflow checks");
326
336
  return 1;
327
337
  }
328
- let fail = false;
329
- const check = (label: string, ok: boolean, detail?: string) => {
330
- console.log(`${ok ? "ok " : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
331
- if (!ok) fail = true;
332
- };
338
+ const { check, failed } = makeChecker();
333
339
 
334
340
  // 1. agent binaries
335
341
  for (const bin of ["claude", "opencode"]) {
@@ -369,7 +375,7 @@ function doctorCmd(args: string[]): number {
369
375
  }
370
376
  }
371
377
 
372
- return fail ? 1 : 0;
378
+ return failed() ? 1 : 0;
373
379
  }
374
380
 
375
381
  function workflowsCmd(): void {
@@ -744,7 +750,7 @@ function printDigest(entry: RegistryEntry, state: TerminalState, journalText: st
744
750
  }
745
751
  if (digest.current?.phase === "running" && digest.current.startedAt !== undefined) {
746
752
  // Live elapsed, computed at print time — journal-frozen runtime goes stale
747
- // during long nodes (spec: docs/specs/live-runtime).
753
+ // during long nodes (spec: docs/specs/_built/live-runtime).
748
754
  console.log(
749
755
  `elapsed: ${formatMs(Date.now() - digest.current.startedAt)} (node ${digest.current.state})`,
750
756
  );
@@ -813,7 +819,7 @@ function printTransition(e: NodeEvent, prevTs: number | null, isHeartbeat = fals
813
819
  const idle = startedAt !== undefined ? e.timestamp - startedAt : 0;
814
820
  let line = `${e.state} still running — ${(idle / 1000).toFixed(0)}s elapsed`;
815
821
  // Agent-level liveness, distinct from the engine-heartbeat idle above —
816
- // see docs/specs/agent-liveness/spec.md. Absent for script dispatches or
822
+ // see docs/specs/_built/agent-liveness/spec.md. Absent for script dispatches or
817
823
  // runners that don't report progress.
818
824
  if (status.phase === "running" && status.agentIdleMs !== undefined) {
819
825
  const agentIdleSec = Math.round(status.agentIdleMs / 1000);
@@ -916,7 +922,7 @@ async function monitorRun(entry: RegistryEntry, windowSec: number, once: boolean
916
922
  lastSeen = events.length;
917
923
  dwellHint(events, entry.runId, hinted);
918
924
 
919
- // Usage-limit wait (docs/specs/usage-limit-backoff/spec.md): re-render
925
+ // Usage-limit wait (docs/specs/_built/usage-limit-backoff/spec.md): re-render
920
926
  // the wait line when the probe advances, so a monitored wait shows the
921
927
  // countdown instead of silence — same one-line warn style as the status
922
928
  // digest's stallWarning/nudgeWarning.
@@ -1151,4 +1157,8 @@ async function main(): Promise<void> {
1151
1157
  await runCmd(resolveWorkflowDir(cmd ?? "."), undefined);
1152
1158
  }
1153
1159
 
1154
- main();
1160
+ // Dispatch only when this file is the process entry point — the `darkf` bin,
1161
+ // or the spawned `__worker` (startCmd spawns this same file directly). The
1162
+ // package public surface (src/exports.ts) re-exports `listWorkflows` from
1163
+ // here; importing it must not execute the CLI against the host's own argv.
1164
+ if (import.meta.main) main();
package/src/cli/setup.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Skill setup (docs/specs/skill-setup): the shared skills-check core, the
1
+ // Skill setup (docs/specs/_built/skill-setup): the shared skills-check core, the
2
2
  // `darkf setup` sync, and the daily first-invocation probe. The bundled
3
3
  // darkf-* skills ship inside the package (darkf/skills/); every dependency
4
4
  // arrives via deps objects, so the whole module runs in tests without a real
@@ -12,9 +12,9 @@ import {
12
12
  readFileSync,
13
13
  renameSync,
14
14
  rmSync,
15
- writeFileSync,
16
15
  } from "node:fs";
17
- import { dirname, join } from "node:path";
16
+ import { join } from "node:path";
17
+ import { writeJsonState } from "./state-file.ts";
18
18
 
19
19
  // The known harnesses are a table in code — adding one is a row plus a test
20
20
  // fixture, not a feature (spec: Host detection). `dir` is relative to HOME;
@@ -227,12 +227,7 @@ export function readProbeState(file: string): ProbeState {
227
227
 
228
228
  /** mkdir -p on the parent; best-effort — swallow write errors. */
229
229
  export function writeProbeState(file: string, state: ProbeState): void {
230
- try {
231
- mkdirSync(dirname(file), { recursive: true });
232
- writeFileSync(file, JSON.stringify(state));
233
- } catch {
234
- // An unwritable state location degrades to re-probing next invocation.
235
- }
230
+ writeJsonState(file, state);
236
231
  }
237
232
 
238
233
  /** The local calendar date — the day a probe compares against, not UTC. */
@@ -0,0 +1,14 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+
4
+ /** mkdir -p on the parent; best-effort — swallow write errors. Shared by
5
+ * `setup.ts`'s probe state and `update.ts`'s update-check state; both
6
+ * degrade to re-running next invocation when the location is unwritable. */
7
+ export function writeJsonState<T>(file: string, state: T): void {
8
+ try {
9
+ mkdirSync(dirname(file), { recursive: true });
10
+ writeFileSync(file, JSON.stringify(state));
11
+ } catch {
12
+ // An unwritable state location degrades to re-probing/re-checking next invocation.
13
+ }
14
+ }
@@ -61,8 +61,10 @@ test("tarball smoke: allowlist ships the runtime dirs and the installed CLI work
61
61
  expect(existsSync(join(prefix, "bin", "darkf"))).toBe(true);
62
62
 
63
63
  // Temp HOME and state; the probe stamped so its block stays out of the way.
64
+ // The home carries a .claude/skills dir so host detection works by dir
65
+ // alone — CI runners have no claude binary on PATH.
64
66
  const home = join(root, "home");
65
- mkdirSync(home);
67
+ mkdirSync(join(home, ".claude", "skills"), { recursive: true });
66
68
  const stateHome = join(root, "state");
67
69
  mkdirSync(stateHome, { recursive: true });
68
70
  writeProbeState(join(stateHome, "darkf", "last-skills-check.json"), {
package/src/cli/update.ts CHANGED
@@ -1,10 +1,10 @@
1
- // CLI self-update (docs/specs/self-update): a daily startup version check and
1
+ // CLI self-update (docs/specs/_built/self-update): a daily startup version check and
2
2
  // the `darkf upgrade` command. Every dependency arrives via UpdateDeps, so the
3
3
  // whole module runs in tests without network, a real clock, or a real package
4
4
  // manager. No module-level mutable state.
5
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import { dirname } from "node:path";
5
+ import { readFileSync } from "node:fs";
7
6
  import { type SkillsDeps, syncAll } from "./setup.ts";
7
+ import { writeJsonState } from "./state-file.ts";
8
8
 
9
9
  const PACKAGE_SPEC = "@psimona/darkf";
10
10
  const REGISTRY_URL = "https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags";
@@ -47,12 +47,7 @@ export function readState(file: string): UpdateState {
47
47
 
48
48
  /** mkdir -p on the parent; best-effort — swallow write errors (REQ-4). */
49
49
  export function writeState(file: string, state: UpdateState): void {
50
- try {
51
- mkdirSync(dirname(file), { recursive: true });
52
- writeFileSync(file, JSON.stringify(state));
53
- } catch {
54
- // An unwritable state location degrades to re-checking next invocation.
55
- }
50
+ writeJsonState(file, state);
56
51
  }
57
52
 
58
53
  /** True when lastCheck is missing, unparseable, or older than 24 h. */