@psimona/darkf 0.5.0 → 0.6.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 (54) hide show
  1. package/docs/concepts/failure-modes.md +164 -0
  2. package/docs/concepts/handoff.md +91 -0
  3. package/docs/concepts/journal.md +92 -0
  4. package/docs/concepts/node-types.md +175 -0
  5. package/docs/guides/pick-an-agent-runner.md +57 -0
  6. package/docs/guides/plan-with-a-task-queue.md +410 -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 +95 -0
  11. package/docs/index.mdx +64 -0
  12. package/docs/reference/cli-commands.md +105 -0
  13. package/docs/reference/core-types.md +123 -0
  14. package/docs/reference/package-map.md +35 -0
  15. package/docs/start-here/install.md +71 -0
  16. package/docs/start-here/quickstart.md +241 -0
  17. package/package.json +7 -1
  18. package/skills/darkf-usage/SKILL.md +92 -0
  19. package/skills/darkf-writing-workflows/SKILL.md +88 -0
  20. package/src/cli/doctor.test.ts +338 -0
  21. package/src/cli/index.ts +123 -9
  22. package/src/cli/setup.test.ts +384 -0
  23. package/src/cli/setup.ts +286 -0
  24. package/src/cli/tarball.test.ts +125 -0
  25. package/src/cli/update.test.ts +82 -0
  26. package/src/cli/update.ts +20 -0
  27. package/src/core/types.ts +8 -0
  28. package/src/engine/run.test.ts +177 -0
  29. package/src/engine/run.ts +66 -2
  30. package/src/kit/agents/opencode.test.ts +232 -2
  31. package/src/kit/agents/opencode.ts +69 -6
  32. package/src/kit/status.test.ts +67 -0
  33. package/src/kit/status.ts +25 -0
  34. package/workflows/dev-loop/scripts/begin.ts +1 -1
  35. package/workflows/dev-loop/scripts/finish.ts +4 -1
  36. package/workflows/dev-loop/workflow.ts +30 -19
  37. package/bunfig.toml +0 -13
  38. package/examples/article-classifier/data/articles.ts +0 -38
  39. package/examples/article-classifier/scripts/next.ts +0 -7
  40. package/examples/article-classifier/scripts/queue.ts +0 -33
  41. package/examples/article-classifier/scripts/record.ts +0 -9
  42. package/examples/article-classifier/workflow.ts +0 -44
  43. package/examples/haiku-commit/scripts/check.ts +0 -24
  44. package/examples/haiku-commit/workflow.ts +0 -28
  45. package/examples/haiku-readme/scripts/test.ts +0 -13
  46. package/examples/haiku-readme/scripts/write.ts +0 -10
  47. package/examples/haiku-readme/workflow.ts +0 -41
  48. package/examples/task-queue/scripts/next.ts +0 -20
  49. package/examples/task-queue/scripts/record.ts +0 -20
  50. package/examples/task-queue/supervise.ts +0 -57
  51. package/examples/task-queue/workflow.ts +0 -33
  52. package/feedback/2026-10-30-self-update.md +0 -29
  53. package/feedback/2026-10-31-task-list-json.md +0 -26
  54. package/tsconfig.json +0 -4
@@ -0,0 +1,88 @@
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 { EXIT, 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: EXIT, blocked: EXIT },
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: EXIT },
49
+ },
50
+ Review: {
51
+ type: "agent", retries: 1, prompt: REVIEW,
52
+ on: { done: EXIT, 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
+ ## Scripts
71
+
72
+ 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
+
74
+ ## Event design
75
+
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.
77
+
78
+ ### The `disputed` event
79
+
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.
81
+
82
+ ## Review prompts
83
+
84
+ Agent-authored extra files are invisible to `git diff`. Every review prompt must say: inspect `git status --porcelain` in addition to `git diff`.
85
+
86
+ ## Verify before you run
87
+
88
+ 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/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
+ });
package/src/cli/index.ts CHANGED
@@ -44,11 +44,21 @@ import {
44
44
  classifyTerminal,
45
45
  foldJournal,
46
46
  foldReport,
47
+ limitWarning,
47
48
  nudgeWarning,
48
49
  stallWarning,
49
50
  type TerminalState,
50
51
  } from "../kit/status.ts";
51
- import { type UpdateDeps, updateGate, upgradeCmd } from "./update.ts";
52
+ import {
53
+ describeFailure,
54
+ failingSkills,
55
+ type ProbeDeps,
56
+ type SkillsDeps,
57
+ skillsCheck,
58
+ skillsProbeGate,
59
+ syncAll,
60
+ } from "./setup.ts";
61
+ import { type UpdateDeps, updateGate, upgradeWithSkills } from "./update.ts";
52
62
 
53
63
  const INDEX_PATH = fileURLToPath(import.meta.url);
54
64
  // Fixed, not yet measured against a cold `bun` import on real hosts — see
@@ -228,7 +238,14 @@ function describeValidationError(err: WorkflowValidationError): string {
228
238
  }
229
239
  }
230
240
 
231
- async function doctorCmd(args: string[]): Promise<number> {
241
+ /**
242
+ * Workflow checks (skill-setup spec: command split). `darkf validate <ref>`
243
+ * inherits doctor's artifact-level checks unchanged: workflow resolution,
244
+ * module load, exports, structure validation. Skill state is deliberately
245
+ * not checked here — a workflow can be sound on a machine whose skills are
246
+ * stale; the two verdicts stay independent.
247
+ */
248
+ async function validateCmd(args: string[]): Promise<number> {
232
249
  const ref = args[0];
233
250
  let fail = false;
234
251
  const check = (label: string, ok: boolean, detail?: string) => {
@@ -238,7 +255,7 @@ async function doctorCmd(args: string[]): Promise<number> {
238
255
 
239
256
  // 1. workflow resolution
240
257
  if (ref === undefined) {
241
- check("workflow ref", false, "usage: darkf doctor <workflow-ref-or-path>");
258
+ check("workflow ref", false, "usage: darkf validate <ref-or-path>");
242
259
  return Promise.resolve(1);
243
260
  }
244
261
  const candidates = workflowCandidates(ref);
@@ -263,7 +280,7 @@ async function doctorCmd(args: string[]): Promise<number> {
263
280
  check(
264
281
  "exports `agentRunner`",
265
282
  typeof mod.agentRunner?.run === "function",
266
- "agent states need a runner; built-ins live in src/agents/",
283
+ "agent states need a runner; built-ins live in src/kit/agents/",
267
284
  );
268
285
  if (typeof mod.workflow?.states === "object" && typeof mod.workflow?.initial === "string") {
269
286
  try {
@@ -294,12 +311,32 @@ async function doctorCmd(args: string[]): Promise<number> {
294
311
  check("exports `agentRunner`", false, "skipped — no resolved workflow");
295
312
  }
296
313
 
297
- // 3. agent binaries
314
+ return Promise.resolve(fail ? 1 : 0);
315
+ }
316
+
317
+ /**
318
+ * Environment checks (skill-setup spec: command split). `darkf doctor` takes
319
+ * no ref and is strictly machine-level: agent binaries, cwd sanity, and the
320
+ * skills section. Read-only — fixing skill drift is always `darkf setup`.
321
+ */
322
+ function doctorCmd(args: string[]): number {
323
+ if (args[0] !== undefined) {
324
+ // The command is young; no silent compatibility shim.
325
+ console.log("usage: darkf doctor takes no ref — darkf validate <ref> for workflow checks");
326
+ return 1;
327
+ }
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
+ };
333
+
334
+ // 1. agent binaries
298
335
  for (const bin of ["claude", "opencode"]) {
299
336
  check(`agent binary '${bin}'`, Bun.which(bin) !== null);
300
337
  }
301
338
 
302
- // 4. cwd sanity — the run-1 mistake: targeting a repo while sitting in the darkf checkout
339
+ // 2. cwd sanity — the run-1 mistake: targeting a repo while sitting in the darkf checkout
303
340
  const cwd = process.cwd();
304
341
  const insideSelf = cwd.startsWith(selfRoot());
305
342
  check(
@@ -310,7 +347,29 @@ async function doctorCmd(args: string[]): Promise<number> {
310
347
  const gitRoot = projectRoot();
311
348
  check("cwd is inside a git repo", existsSync(join(gitRoot, ".git")), gitRoot);
312
349
 
313
- return Promise.resolve(fail ? 1 : 0);
350
+ // 3. skills — every known harness always named; `harness not present` is
351
+ // informational and always passes (the binaries check above is the failure
352
+ // signal for an absent binary).
353
+ for (const h of skillsCheck(skillsDeps())) {
354
+ const label = `skills (${h.host})`;
355
+ if (!h.present) {
356
+ check(label, true, "harness not present");
357
+ continue;
358
+ }
359
+ const failing = failingSkills(h);
360
+ if (failing.length === 0) {
361
+ const total = Object.keys(h.states).length;
362
+ check(label, true, `${total}/${total} installed`);
363
+ } else {
364
+ check(
365
+ label,
366
+ false,
367
+ `${failing.map(([skill, state]) => describeFailure(skill, state)).join("; ")} — run: darkf setup`,
368
+ );
369
+ }
370
+ }
371
+
372
+ return fail ? 1 : 0;
314
373
  }
315
374
 
316
375
  function workflowsCmd(): void {
@@ -695,6 +754,8 @@ function printDigest(entry: RegistryEntry, state: TerminalState, journalText: st
695
754
  if (agentStall) console.log(`warn: ${agentStall}`);
696
755
  const nudge = nudgeWarning(digest);
697
756
  if (nudge) console.log(`warn: ${nudge}`);
757
+ const limit = limitWarning(digest);
758
+ if (limit) console.log(`warn: ${limit}`);
698
759
  }
699
760
  if (digest.runtimeMs !== null) console.log(`runtime: ${formatMs(digest.runtimeMs)}`);
700
761
  if (state === "orphaned") console.log("orphaned: true");
@@ -831,6 +892,7 @@ async function monitorRun(entry: RegistryEntry, windowSec: number, once: boolean
831
892
  const pid = entry.pid;
832
893
  const deadline = Date.now() + windowSec * 1000;
833
894
  const hinted = new Set<string>();
895
+ let lastLimitProbe = 0;
834
896
 
835
897
  // Open the window: if the begin marker is already there, print it once as
836
898
  // context (not a transition) and tail only lines added from this point on.
@@ -854,6 +916,18 @@ async function monitorRun(entry: RegistryEntry, windowSec: number, once: boolean
854
916
  lastSeen = events.length;
855
917
  dwellHint(events, entry.runId, hinted);
856
918
 
919
+ // Usage-limit wait (docs/specs/usage-limit-backoff/spec.md): re-render
920
+ // the wait line when the probe advances, so a monitored wait shows the
921
+ // countdown instead of silence — same one-line warn style as the status
922
+ // digest's stallWarning/nudgeWarning.
923
+ const limitDigest = foldJournal(text);
924
+ const backoff = limitDigest.current?.limitBackoff;
925
+ if (limitDigest.current?.phase === "running" && backoff && backoff.probe !== lastLimitProbe) {
926
+ const warning = limitWarning(limitDigest);
927
+ if (warning) console.log(`warn: ${warning}`);
928
+ lastLimitProbe = backoff.probe;
929
+ }
930
+
857
931
  // Re-check liveness every sub-poll: the journal's last line is authoritative
858
932
  // for succeeded/crashed, and a dead PID with no terminal marker is
859
933
  // orphaned/host-died.
@@ -976,6 +1050,28 @@ function updateStateFile(): string {
976
1050
  return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-update-check.json");
977
1051
  }
978
1052
 
1053
+ // Same XDG state scheme, for the daily skills probe (skill-setup spec).
1054
+ function skillsProbeStateFile(): string {
1055
+ const xdg = process.env.XDG_STATE_HOME;
1056
+ if (xdg) return join(xdg, "darkf", "last-skills-check.json");
1057
+ return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-skills-check.json");
1058
+ }
1059
+
1060
+ // The bundled skills dir is package-relative (sibling of workflows/), so a
1061
+ // global install and a sibling checkout both work — the same selfRoot()
1062
+ // mechanism workflows/ resolution already uses.
1063
+ function skillsDeps(): SkillsDeps {
1064
+ return {
1065
+ home: process.env.HOME ?? "",
1066
+ bundledDir: resolve(dirname(INDEX_PATH), "..", "..", "skills"),
1067
+ existsBinary: (name: string) => Bun.which(name) !== null,
1068
+ };
1069
+ }
1070
+
1071
+ function probeDeps(): ProbeDeps {
1072
+ return { ...skillsDeps(), stateFile: skillsProbeStateFile() };
1073
+ }
1074
+
979
1075
  async function main(): Promise<void> {
980
1076
  const [cmd, ...rest] = process.argv.slice(2);
981
1077
 
@@ -991,8 +1087,22 @@ async function main(): Promise<void> {
991
1087
  };
992
1088
  await updateGate(cmd, updateDeps);
993
1089
 
1090
+ // Daily skills probe (skill-setup spec): after the update gate, before the
1091
+ // command's own output. setup and upgrade are exempt (they sync the skills
1092
+ // themselves) and refresh the probe stamp. Never fatal — the outcome never
1093
+ // changes the invoking command's exit code.
1094
+ await skillsProbeGate(cmd, probeDeps());
1095
+
994
1096
  if (cmd === "upgrade") {
995
- process.exit(await upgradeCmd(updateDeps));
1097
+ // Skill sync after the install (skill-setup spec): the new package may
1098
+ // ship new skill content, and the running process resolves the new
1099
+ // bundled copies on disk. Best-effort: a sync failure is reported and
1100
+ // exits non-zero, but never masks the upgrade itself.
1101
+ process.exit(await upgradeWithSkills(updateDeps, skillsDeps()));
1102
+ return;
1103
+ }
1104
+ if (cmd === "setup") {
1105
+ process.exit(syncAll(skillsDeps()));
996
1106
  return;
997
1107
  }
998
1108
  if (cmd === "workflows") {
@@ -1004,7 +1114,11 @@ async function main(): Promise<void> {
1004
1114
  return;
1005
1115
  }
1006
1116
  if (cmd === "doctor") {
1007
- process.exit(await doctorCmd(rest));
1117
+ process.exit(doctorCmd(rest));
1118
+ return;
1119
+ }
1120
+ if (cmd === "validate") {
1121
+ process.exit(await validateCmd(rest));
1008
1122
  return;
1009
1123
  }
1010
1124
  if (cmd === "render") {