@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,92 @@
1
+ ---
2
+ name: darkf-usage
3
+ description: Use when starting, monitoring, or inspecting a darkf workflow run, checking whether a run is stuck, or reading a run report or journal
4
+ ---
5
+
6
+ # Using darkf
7
+
8
+ ## Overview
9
+
10
+ darkf runs a TypeScript workflow graph. It dispatches AI agents (Claude Code or opencode) against a target repo. Each run detaches from your terminal and writes a journal. One rule governs everything: run darkf from the target repo, never from the darkf checkout.
11
+
12
+ ## The cwd rule
13
+
14
+ `rootDir` is the run-artifact root and the agent working directory. It is the invocation cwd. Start every run from the repo the agents will edit. `darkf validate <ref>` fails when run inside the darkf checkout. It catches the wrong-directory mistake before you waste a run.
15
+
16
+ ## Quick reference
17
+
18
+ | Task | Command (from the target repo) |
19
+ |---|---|
20
+ | Preflight | `darkf validate <ref>` |
21
+ | List visible workflows | `darkf workflows` |
22
+ | Start a detached run | `darkf start <ref> "message"` |
23
+ | Run in foreground | `darkf run <ref> "message"` |
24
+ | One-shot status | `darkf status` (add `--run <id>` for a specific run) |
25
+ | Live tail | `darkf monitor --window 120` |
26
+ | Efficacy report | `darkf report` (add `--run <id>` for a specific run) |
27
+ | Show the graph | `darkf render <ref>` |
28
+
29
+ - `<ref>` resolves in order: a path, then `<cwd>/darkf/<ref>` (project workspace), then workflows shipped with darkf.
30
+ - There is no `--help` flag. Bare `darkf` is an error.
31
+ - There is no `resume` command. Resume semantics belong to each workflow. Check the journal and `git log` first. Never re-implement finished work by hand.
32
+ - `start` prints `{"runId":...,"pid":...}` and returns. The message is positional argument 2.
33
+ - `start` and `run` refuse to start when `darkf/` has uncommitted changes. Commit or stash first, or pass `--allow-dirty-workflow`.
34
+
35
+ ## Exit codes
36
+
37
+ Exit codes for `status`. `monitor` shares most of them:
38
+
39
+ | Code | `status` says | `monitor` says |
40
+ |---|---|---|
41
+ | 0 | succeeded | succeeded |
42
+ | 1 | crashed | crashed |
43
+ | 2 | orphaned | orphaned |
44
+ | 3 | running | failed |
45
+ | 4 | failed | host-died |
46
+ | 5 | host-died | failed-start |
47
+ | 6 | failed-start | window elapsed, run still going |
48
+ | 7 | no run | no run |
49
+
50
+ A wrong `--run <id>` also exits 4. Multiple cached `running` entries make `status` exit 5 and ask for `--run <id>`.
51
+
52
+ ## Run artifacts
53
+
54
+ Everything lands under the target repo:
55
+
56
+ - `.darkf/run/<runId>/journal.jsonl` is the event log. The journal is authoritative. The registry is only a pointer.
57
+ - `.darkf/run/<runId>/usage/` holds per-dispatch cost and token sidecars.
58
+ - `.darkf/registry/<runId>.json` is a pointer entry (runId, pid, rootDir).
59
+
60
+ Add `.darkf/` to the target repo `.gitignore`.
61
+
62
+ ## Is the run alive?
63
+
64
+ Open dispatches write a heartbeat to the journal every 30 seconds. `darkf status` shows advancing `elapsed` for the open node.
65
+
66
+ - No heartbeat for more than 90 seconds → status prints `warn: stall suspected`. The warning only informs.
67
+ - Worker process gone and no terminal journal marker → status reports `orphaned` (exit 2). The outcome is unknown. Re-run.
68
+ - Journal ends with a terminal marker → `succeeded` (exit 0) or `crashed` (exit 1). The pid state does not matter.
69
+
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
+
72
+ ## After launch
73
+
74
+ The run detaches. Watching is your job.
75
+
76
+ - Tail with `darkf monitor --window 120`. One-shot with `darkf status`. A silent 10 minutes is normal. Trust the heartbeat.
77
+ - Stay with the run until it reaches a terminal state.
78
+ - A terminal state is not a shipped feature. `succeeded` means the graph completed. What happened lives in the event of the last dispatch: `darkf report --run <id>`.
79
+ - Any event routed to `DONE` ends the run with exit 0. Whether an event means shipped, stopped, or a human gate is the decision of the workflow, recorded in its `on` routes.
80
+ - `darkf report` needs `--run <id>` for a finished run. The `runId` is in the `start` output and in `.darkf/registry/`.
81
+
82
+ ## Gotchas
83
+
84
+ - A workflow may hardcode spec paths in its prompts. Read the workflow first. Check that those paths still exist in the target repo.
85
+ - Check git history first. A workflow will re-implement work that already shipped.
86
+ - The `start` message is only a label for some workflows. Check the prompts.
87
+ - Agents run for minutes per dispatch. A silent 10 minutes is normal. Trust the heartbeat, not the silence.
88
+ - The journal is authoritative. If cached registry state and the journal disagree, trust the journal. Delete nothing by hand.
89
+
90
+ ## Deep reference
91
+
92
+ The darkf package ships its full docs. Find the package: `readlink -f "$(which darkf)"`. Start at `docs/guides/run-detached-and-monitor.md` inside that directory.
@@ -0,0 +1,213 @@
1
+ ---
2
+ name: darkf-writing-workflows
3
+ description: Use when authoring or editing a darkf workflow.ts state graph of agent, script, and composite states, especially to bound implement-verify-review loops, design events, or wire agent runners and the handoff contract
4
+ ---
5
+
6
+ # Writing darkf Workflows
7
+
8
+ ## Overview
9
+
10
+ A darkf workflow is a TypeScript module. It exports a state graph. `agent` states dispatch an AI agent. `script` states run TypeScript. `composite` states nest subgraphs. Put deterministic checks in scripts. Reserve agent states for judgment.
11
+
12
+ Shipped workflows live in `workflows/` inside the darkf package. Find the package: `readlink -f "$(which darkf)"`. Treat them as examples. Check any example against the bounded-loops rule before you copy its shape.
13
+
14
+ ## Bounded loops: the critical rule
15
+
16
+ Every state that can route backward must live inside ONE composite. `maxCycles` counts leaf dispatches per continuous pass. It resets when execution re-enters the composite. A composite `Fix{Implement,Verify}` with `Review` outside it has no cycle cap. `changes_requested → Implement` re-enters `Fix` and clears the counter. Put Implement, Verify, and Review inside one composite.
17
+
18
+ - `maxCycles` counts dispatches, not cycles. 15 means five rounds of three states.
19
+ - `retries` do not consume the cycle budget. Give every agent and script state `retries: 1`. A transient spawn failure then costs one attempt, not the run.
20
+ - An event with no matching `on` route is a terminal `no-transition` crash. Cover every declared event.
21
+
22
+ ## Skeleton
23
+
24
+ ```ts
25
+ import { DONE, type AgentRunner, type WorkflowDef } from "/abs/path/to/darkf/src/core/index.ts";
26
+ import { claudeCodeRunner } from "/abs/path/to/darkf/src/kit/agents/claude-code.ts";
27
+
28
+ export const agentRunner: AgentRunner = claudeCodeRunner;
29
+
30
+ export const workflow: WorkflowDef = {
31
+ initial: "Loop",
32
+ states: {
33
+ Loop: {
34
+ initial: "Implement",
35
+ // maxCycles counts dispatches: rounds = maxCycles / states-per-round.
36
+ // Budget above your expected worst case. Legitimate review loops can
37
+ // exceed 5 rounds; a tight budget trips the breaker mid-run.
38
+ maxCycles: 24,
39
+ states: {
40
+ Implement: {
41
+ type: "agent", retries: 1, prompt: IMPL,
42
+ on: { implemented: "Verify", disputed: DONE, blocked: DONE },
43
+ },
44
+ Verify: {
45
+ // Review only sees Verify output. Relay what Implement reported:
46
+ // return { event: "green", output: { implemented: handoff.output } }
47
+ type: "script", file: "verify.ts", retries: 1,
48
+ on: { green: "Review", red: "Implement", blocked: DONE },
49
+ },
50
+ Review: {
51
+ type: "agent", retries: 1, prompt: REVIEW,
52
+ on: { done: DONE, changes_requested: "Implement" },
53
+ },
54
+ },
55
+ },
56
+ },
57
+ };
58
+ ```
59
+
60
+ ## Imports
61
+
62
+ Workflows outside the darkf package use absolute paths into the package, as in the skeleton. A target repo with `@psimona/darkf` as a dependency can import the package name instead: `@psimona/darkf/src/core/index.ts`. Other bare imports do not resolve through node_modules from other directories.
63
+
64
+ ## Runners and the handoff contract
65
+
66
+ - Use the built-in runners (`claudeCodeRunner`, `opencodeRunner` from `src/kit/agents/`). Never parse agent stdout. The runner injects the event contract into the prompt and reads the handoff JSON file the agent writes.
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
+ - Do not ask the agent to echo events in prose. Describe the event semantics. The runner appends the mechanics.
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
+
89
+ ## Scripts
90
+
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.
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
+
199
+ ## Event design
200
+
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.
202
+
203
+ ### The `disputed` event
204
+
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.
206
+
207
+ ## Review prompts
208
+
209
+ Agent-authored extra files are invisible to `git diff`. Every review prompt must say: inspect `git status --porcelain` in addition to `git diff`.
210
+
211
+ ## Verify before you run
212
+
213
+ From the target repo: `darkf validate <ref>`, then `darkf render <ref>`. The packaged guide is the long form: `docs/guides/write-your-first-workflow.md` inside the darkf package.
@@ -0,0 +1,338 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { todayLocal, writeProbeState } from "./setup.ts";
6
+
7
+ // doctor/validate split, `darkf setup`, and the daily probe — the CLI-level
8
+ // wiring from docs/specs/_built/skill-setup. These spawn the real CLI entrypoint:
9
+ // a temp HOME (host skill dirs), a temp XDG_STATE_HOME (probe stamp), and a
10
+ // temp cwd keep the suite off the real ~ and off the network.
11
+
12
+ const pkgDir = resolve(import.meta.dir, "..", "..");
13
+ const indexTs = join(pkgDir, "src", "cli", "index.ts");
14
+ const bundledDir = join(pkgDir, "skills");
15
+ const SKILLS = ["darkf-usage", "darkf-writing-workflows"];
16
+
17
+ const roots: string[] = [];
18
+ afterAll(() => {
19
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
20
+ });
21
+
22
+ function tempDir(prefix = "darkf-cli-"): string {
23
+ const dir = mkdtempSync(join(tmpdir(), prefix));
24
+ roots.push(dir);
25
+ return dir;
26
+ }
27
+
28
+ interface Env {
29
+ home: string;
30
+ stateHome: string;
31
+ cwd: string;
32
+ }
33
+
34
+ function makeEnv({ git = false, stamp = true } = {}): Env {
35
+ const home = tempDir();
36
+ const stateHome = tempDir();
37
+ const cwd = tempDir();
38
+ if (git) mkdirSync(join(cwd, ".git"));
39
+ if (stamp) {
40
+ writeProbeState(join(stateHome, "darkf", "last-skills-check.json"), {
41
+ lastProbe: todayLocal(),
42
+ });
43
+ }
44
+ return { home, stateHome, cwd };
45
+ }
46
+
47
+ function seedOk(env: Env, host: string, skill: string): void {
48
+ const dir = join(env.home, host, "skills", skill);
49
+ mkdirSync(dir, { recursive: true });
50
+ cpSync(join(bundledDir, skill), dir, { recursive: true });
51
+ }
52
+
53
+ function seedStale(env: Env, host: string, skill: string, content = "a stale copy\n"): void {
54
+ const file = join(env.home, host, "skills", skill, "SKILL.md");
55
+ mkdirSync(join(file, ".."), { recursive: true });
56
+ writeFileSync(file, content);
57
+ }
58
+
59
+ async function runCli(
60
+ args: string[],
61
+ env: Env,
62
+ extraEnv: Record<string, string> = {},
63
+ ): Promise<{ code: number; stdout: string; stderr: string }> {
64
+ const proc = Bun.spawn([process.execPath, indexTs, ...args], {
65
+ cwd: env.cwd,
66
+ stdout: "pipe",
67
+ stderr: "pipe",
68
+ env: {
69
+ ...process.env,
70
+ HOME: env.home,
71
+ XDG_STATE_HOME: env.stateHome,
72
+ DARKF_NO_UPDATE_CHECK: "1",
73
+ ...extraEnv,
74
+ },
75
+ });
76
+ const [stdout, stderr, code] = await Promise.all([
77
+ new Response(proc.stdout).text(),
78
+ new Response(proc.stderr).text(),
79
+ proc.exited,
80
+ ]);
81
+ return { code, stdout, stderr };
82
+ }
83
+
84
+ function lines(stdout: string): string[] {
85
+ return stdout.split("\n").filter((l) => l.length > 0);
86
+ }
87
+
88
+ // --- doctor: environment only ---
89
+
90
+ test("doctor with no ref checks the environment only and never loads a workflow module", async () => {
91
+ const env = makeEnv({ git: true });
92
+ seedOk(env, ".claude", "darkf-usage");
93
+ seedOk(env, ".claude", "darkf-writing-workflows");
94
+ seedOk(env, ".opencode", "darkf-usage");
95
+ seedOk(env, ".opencode", "darkf-writing-workflows");
96
+
97
+ const res = await runCli(["doctor"], env);
98
+
99
+ const out = lines(res.stdout);
100
+ // Environment only — no workflow check ever ran.
101
+ expect(out.some((l) => l.includes("workflow"))).toBe(false);
102
+ expect(out.some((l) => l.includes("agent binary 'claude'"))).toBe(true);
103
+ expect(out.some((l) => l.includes("agent binary 'opencode'"))).toBe(true);
104
+ expect(out).toContain("ok skills (claude) — 2/2 installed");
105
+ expect(out).toContain("ok skills (opencode) — 2/2 installed");
106
+ // Every known harness is always named; undetected ones are informational.
107
+ for (const host of ["codex", "gemini", "cursor"]) {
108
+ expect(out.some((l) => l === `ok skills (${host}) — harness not present`)).toBe(true);
109
+ }
110
+ const binariesReady = Bun.which("claude") !== null && Bun.which("opencode") !== null;
111
+ expect(res.code).toBe(binariesReady ? 0 : 1); // git repo cwd, skills ok
112
+ });
113
+
114
+ test("doctor reports a differing copy via FAIL with the run darkf setup hint, and writes nothing", async () => {
115
+ const env = makeEnv({ git: true });
116
+ seedStale(env, ".claude", "darkf-usage", "locally edited\n");
117
+ seedOk(env, ".claude", "darkf-writing-workflows");
118
+ seedOk(env, ".opencode", "darkf-usage");
119
+ seedOk(env, ".opencode", "darkf-writing-workflows");
120
+
121
+ const res = await runCli(["doctor"], env);
122
+
123
+ expect(lines(res.stdout)).toContain(
124
+ "FAIL skills (claude) — darkf-usage differs from bundled — run: darkf setup",
125
+ );
126
+ expect(res.code).toBe(1);
127
+ // Read-only: the installed (stale) copy was not touched.
128
+ expect(readFileSync(join(env.home, ".claude", "skills", "darkf-usage", "SKILL.md"), "utf8")).toBe(
129
+ "locally edited\n",
130
+ );
131
+ });
132
+
133
+ test("doctor reports a missing copy and fails the exit code", async () => {
134
+ const env = makeEnv({ git: true });
135
+ mkdirSync(join(env.home, ".claude", "skills"), { recursive: true });
136
+ seedOk(env, ".opencode", "darkf-usage");
137
+ seedOk(env, ".opencode", "darkf-writing-workflows");
138
+
139
+ const res = await runCli(["doctor"], env);
140
+
141
+ expect(lines(res.stdout)).toContain(
142
+ "FAIL skills (claude) — darkf-usage missing; darkf-writing-workflows missing — run: darkf setup",
143
+ );
144
+ expect(res.code).toBe(1);
145
+ });
146
+ test("doctor <ref> prints the new usage and exits 1", async () => {
147
+ const env = makeEnv({ git: true });
148
+ const res = await runCli(["doctor", "my-workflow"], env);
149
+ expect(lines(res.stdout)).toEqual([
150
+ "usage: darkf doctor takes no ref — darkf validate <ref> for workflow checks",
151
+ ]);
152
+ expect(res.code).toBe(1);
153
+ });
154
+
155
+ // --- validate: the inherited workflow checks ---
156
+
157
+ const RUNNER_IMPORTS = `import { EXIT, type AgentRunner, type WorkflowDef } from "${pkgDir}/src/core/index.ts";
158
+ import { claudeCodeRunner } from "${pkgDir}/src/kit/agents/claude-code.ts";
159
+
160
+ export const agentRunner: AgentRunner = claudeCodeRunner;
161
+ `;
162
+
163
+ function writeFixture(env: Env, name: string, states: string): string {
164
+ const dir = join(env.cwd, name);
165
+ mkdirSync(dir, { recursive: true });
166
+ writeFileSync(
167
+ join(dir, "workflow.ts"),
168
+ `${RUNNER_IMPORTS}\nexport const workflow: WorkflowDef = {\n initial: "A",\n states: { ${states} },\n};\n`,
169
+ );
170
+ return dir;
171
+ }
172
+
173
+ test("validate inherits the workflow checks: happy path, same lines, exit 0", async () => {
174
+ const env = makeEnv();
175
+ const dir = writeFixture(env, "happy", `A: { type: "agent", prompt: "p", on: { done: EXIT } }`);
176
+
177
+ const res = await runCli(["validate", dir], env);
178
+
179
+ // The same lines doctor's workflow path has always printed — including the
180
+ // runner hint detail on the passing exports check.
181
+ expect(lines(res.stdout)).toEqual([
182
+ `ok workflow resolves — ${dir}`,
183
+ "ok workflow.ts loads",
184
+ "ok exports `workflow`",
185
+ "ok exports `agentRunner` — agent states need a runner; built-ins live in src/kit/agents/",
186
+ "ok workflow structure",
187
+ ]);
188
+ expect(res.code).toBe(0);
189
+ });
190
+
191
+ test("validate reports unresolved targets", async () => {
192
+ const env = makeEnv();
193
+ const dir = writeFixture(
194
+ env,
195
+ "unresolved",
196
+ `A: { type: "agent", prompt: "p", on: { done: "nope" } }`,
197
+ );
198
+ const res = await runCli(["validate", dir], env);
199
+ expect(lines(res.stdout)).toContain('FAIL workflow structure — A -> "nope": no such state');
200
+ expect(res.code).toBe(1);
201
+ });
202
+
203
+ test("validate reports dead-end leaves", async () => {
204
+ const env = makeEnv();
205
+ const dir = writeFixture(env, "dead-end", `A: { type: "agent", prompt: "p" }`);
206
+ const res = await runCli(["validate", dir], env);
207
+ expect(lines(res.stdout)).toContain('FAIL workflow structure — "A": dead end, no on/next');
208
+ expect(res.code).toBe(1);
209
+ });
210
+
211
+ test("validate reports initial cycles", async () => {
212
+ const env = makeEnv();
213
+ const dir = join(env.cwd, "cycle");
214
+ mkdirSync(dir, { recursive: true });
215
+ writeFileSync(
216
+ join(dir, "workflow.ts"),
217
+ `${RUNNER_IMPORTS}
218
+ export const workflow: WorkflowDef = {
219
+ initial: "A",
220
+ states: {
221
+ A: { initial: "B", states: { LeafA: { type: "script", file: "l.ts", next: EXIT } } },
222
+ B: { initial: "A", states: { LeafB: { type: "script", file: "l.ts", next: EXIT } } },
223
+ },
224
+ };
225
+ `,
226
+ );
227
+ const res = await runCli(["validate", dir], env);
228
+ expect(lines(res.stdout)).toContain("FAIL workflow structure — initial cycle: A -> B -> A");
229
+ expect(res.code).toBe(1);
230
+ });
231
+
232
+ test("validate with no ref prints its usage and exits 1", async () => {
233
+ const env = makeEnv();
234
+ const res = await runCli(["validate"], env);
235
+ expect(lines(res.stdout)).toContain("FAIL workflow ref — usage: darkf validate <ref-or-path>");
236
+ expect(res.code).toBe(1);
237
+ });
238
+
239
+ test("validate with an unresolvable ref skips the load and exports checks", async () => {
240
+ const env = makeEnv();
241
+ const missing = join(env.cwd, "no-such-workflow");
242
+ const res = await runCli(["validate", missing], env);
243
+ const out = lines(res.stdout);
244
+ expect(out[0]).toContain("FAIL workflow resolves");
245
+ expect(out).toContain("FAIL workflow.ts loads — skipped — no resolved workflow");
246
+ expect(out).toContain("FAIL exports `workflow` — skipped — no resolved workflow");
247
+ expect(out).toContain("FAIL exports `agentRunner` — skipped — no resolved workflow");
248
+ expect(out).toHaveLength(4);
249
+ expect(res.code).toBe(1);
250
+ });
251
+
252
+ test("validate does not check skills — stale copies never touch its verdict", async () => {
253
+ const env = makeEnv();
254
+ seedStale(env, ".claude", "darkf-usage");
255
+ const dir = writeFixture(env, "happy", `A: { type: "agent", prompt: "p", on: { done: EXIT } }`);
256
+
257
+ const res = await runCli(["validate", dir], env);
258
+
259
+ expect(res.code).toBe(0);
260
+ expect(res.stdout).not.toContain("skills");
261
+ });
262
+
263
+ // --- daily probe wiring: silent unless actionable, never fatal ---
264
+
265
+ test("the first invocation of the day prints the block before the command output", async () => {
266
+ const env = makeEnv({ stamp: false });
267
+ seedStale(env, ".claude", "darkf-usage");
268
+ seedOk(env, ".claude", "darkf-writing-workflows");
269
+
270
+ const res = await runCli(["workflows"], env);
271
+
272
+ const out = lines(res.stdout);
273
+ // One compact block — failing harness lines, then the fix — before the
274
+ // command's own output. (The opencode line depends on the machine's PATH;
275
+ // claude is seeded stale, so it always leads the block.)
276
+ expect(out[0]).toBe("skills (claude): darkf-usage differs from bundled");
277
+ const fixIdx = out.indexOf("fix: run darkf setup");
278
+ expect(fixIdx).toBeGreaterThan(0);
279
+ // The invoked command's own output follows the block.
280
+ expect(out.slice(fixIdx + 1)).toContain("dev-loop built-in");
281
+ expect(res.code).toBe(0); // never changes the invoking command's exit code
282
+ // Stamped, so the rest of the day stays silent.
283
+ expect(readFileSync(join(env.stateHome, "darkf", "last-skills-check.json"), "utf8")).toContain(
284
+ todayLocal(),
285
+ );
286
+ });
287
+
288
+ test("a stamped same-day invocation skips the probe silently", async () => {
289
+ const env = makeEnv({ stamp: true });
290
+ seedStale(env, ".claude", "darkf-usage");
291
+
292
+ const res = await runCli(["workflows"], env);
293
+
294
+ expect(res.stdout).not.toContain("fix: run darkf setup");
295
+ expect(res.code).toBe(0);
296
+ });
297
+
298
+ test("setup and upgrade skip the probe; setup refreshes the stamp", async () => {
299
+ const env = makeEnv({ stamp: false });
300
+ seedStale(env, ".claude", "darkf-usage");
301
+
302
+ const res = await runCli(["setup"], env);
303
+
304
+ expect(res.stdout).not.toContain("fix: run darkf setup");
305
+ expect(readFileSync(join(env.stateHome, "darkf", "last-skills-check.json"), "utf8")).toContain(
306
+ todayLocal(),
307
+ );
308
+ });
309
+
310
+ // --- setup wiring ---
311
+
312
+ test("darkf setup syncs a detected host and skips an absent one; exits 0", async () => {
313
+ const env = makeEnv({ stamp: true });
314
+ seedStale(env, ".claude", "darkf-usage", "stale\n");
315
+
316
+ const res = await runCli(["setup"], env);
317
+
318
+ expect(res.code).toBe(0);
319
+ const out = lines(res.stdout);
320
+ expect(out).toContain("host claude (~/.claude/skills)");
321
+ expect(out.some((l) => l.startsWith(" darkf-usage") && l.endsWith("updated (was stale)"))).toBe(
322
+ true,
323
+ );
324
+ expect(out).toContain("host codex — harness not present");
325
+ for (const skill of SKILLS) {
326
+ expect(readFileSync(join(env.home, ".claude", "skills", skill, "SKILL.md"), "utf8")).toBe(
327
+ readFileSync(join(bundledDir, skill, "SKILL.md"), "utf8"),
328
+ );
329
+ }
330
+ });
331
+
332
+ test("darkf setup takes no positional args — a stray arg is still just a sync", async () => {
333
+ // No flags, no positionals: the arg list is ignored by contract.
334
+ const env = makeEnv({ stamp: true });
335
+ const res = await runCli(["setup", "--check"], env);
336
+ expect(res.stdout).toContain("host claude");
337
+ expect(res.code).toBe(0);
338
+ });