@psimona/darkf 0.4.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 (56) 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/index.ts +1 -0
  28. package/src/core/tasks.test.ts +146 -0
  29. package/src/core/tasks.ts +158 -0
  30. package/src/core/types.ts +42 -0
  31. package/src/engine/run.test.ts +177 -0
  32. package/src/engine/run.ts +66 -2
  33. package/src/kit/agents/opencode.test.ts +232 -2
  34. package/src/kit/agents/opencode.ts +69 -6
  35. package/src/kit/status.test.ts +118 -1
  36. package/src/kit/status.ts +67 -1
  37. package/workflows/dev-loop/scripts/begin.ts +1 -1
  38. package/workflows/dev-loop/scripts/finish.ts +13 -2
  39. package/workflows/dev-loop/workflow.ts +57 -23
  40. package/bunfig.toml +0 -13
  41. package/examples/article-classifier/data/articles.ts +0 -38
  42. package/examples/article-classifier/scripts/next.ts +0 -7
  43. package/examples/article-classifier/scripts/queue.ts +0 -33
  44. package/examples/article-classifier/scripts/record.ts +0 -9
  45. package/examples/article-classifier/workflow.ts +0 -44
  46. package/examples/haiku-commit/scripts/check.ts +0 -24
  47. package/examples/haiku-commit/workflow.ts +0 -28
  48. package/examples/haiku-readme/scripts/test.ts +0 -13
  49. package/examples/haiku-readme/scripts/write.ts +0 -10
  50. package/examples/haiku-readme/workflow.ts +0 -41
  51. package/examples/task-queue/scripts/next.ts +0 -20
  52. package/examples/task-queue/scripts/record.ts +0 -20
  53. package/examples/task-queue/supervise.ts +0 -57
  54. package/examples/task-queue/workflow.ts +0 -33
  55. package/feedback/2026-10-30-self-update.md +0 -29
  56. package/tsconfig.json +0 -4
@@ -1,10 +1,19 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { type CrashReason, EXIT, FAILED, type NodeEvent, type NodeResult } from "../core/index.ts";
2
+ import {
3
+ type CrashReason,
4
+ EXIT,
5
+ FAILED,
6
+ type NodeEvent,
7
+ type NodeResult,
8
+ type TaskList,
9
+ } from "../core/index.ts";
3
10
  import {
4
11
  agentStallWarning,
5
12
  classifyTerminal,
6
13
  foldJournal,
7
14
  foldReport,
15
+ foldTaskList,
16
+ limitWarning,
8
17
  nudgeWarning,
9
18
  stallWarning,
10
19
  } from "./status.ts";
@@ -288,6 +297,72 @@ test("nudgeWarning fires only for a running node with an active nudge", () => {
288
297
  expect(nudgeWarning(done)).toBeNull();
289
298
  });
290
299
 
300
+ function runningWithLimitBackoff(
301
+ state: string,
302
+ heartbeatTs: number,
303
+ backoff: { probe: number; nextAttemptAt: number; waitedMs: number },
304
+ ): NodeEvent {
305
+ return {
306
+ runId: R,
307
+ state,
308
+ scopePath: [],
309
+ status: {
310
+ phase: "running",
311
+ attempt: 1,
312
+ startedAt: heartbeatTs,
313
+ lastHeartbeat: heartbeatTs,
314
+ limitBackoff: backoff,
315
+ },
316
+ timestamp: heartbeatTs,
317
+ };
318
+ }
319
+
320
+ test("foldJournal surfaces a running node's limitBackoff, omits it when absent", () => {
321
+ const waiting = foldJournal(
322
+ journalText([
323
+ begin(),
324
+ runningWithLimitBackoff("Write", 2000, { probe: 1, nextAttemptAt: 2600, waitedMs: 600 }),
325
+ ]),
326
+ );
327
+ expect(waiting.current?.limitBackoff).toEqual({ probe: 1, nextAttemptAt: 2600, waitedMs: 600 });
328
+
329
+ const plain = foldJournal(journalText([begin(), running("Write", 2000)]));
330
+ expect(plain.current?.limitBackoff).toBeUndefined();
331
+ });
332
+
333
+ test("limitWarning renders the probe countdown from the latest waiting heartbeat", () => {
334
+ const NOW = 3_600_000;
335
+ // 22 minutes until the next attempt; defaults give a 24h/30min = 48 total.
336
+ const digest = foldJournal(
337
+ journalText([
338
+ begin(),
339
+ running("Write", NOW - 8 * 60_000),
340
+ runningWithLimitBackoff("Write", NOW - 1_000, {
341
+ probe: 3,
342
+ nextAttemptAt: NOW + 22 * 60_000,
343
+ waitedMs: 90 * 60_000,
344
+ }),
345
+ ]),
346
+ );
347
+ expect(limitWarning(digest, NOW)).toBe("usage limit — probe 3/48, next attempt in 22m");
348
+ });
349
+
350
+ test("limitWarning is null for a plain running heartbeat, and once the wait ends (latest running status has no limitBackoff)", () => {
351
+ const plain = foldJournal(journalText([begin(), running("Write", 2000)]));
352
+ expect(limitWarning(plain)).toBeNull();
353
+
354
+ // The post-wait re-dispatch's running status carries no limitBackoff — the
355
+ // warning must clear while the probe dispatch itself is running.
356
+ const probing = foldJournal(
357
+ journalText([
358
+ begin(),
359
+ runningWithLimitBackoff("Write", 2000, { probe: 1, nextAttemptAt: 2600, waitedMs: 600 }),
360
+ running("Write", 2600),
361
+ ]),
362
+ );
363
+ expect(limitWarning(probing)).toBeNull();
364
+ });
365
+
291
366
  test("foldJournal counts distinct visits, not retry attempts", () => {
292
367
  // Write visited once (two attempts), then Test visited once
293
368
  const events = [
@@ -421,3 +496,45 @@ describe("foldReport", () => {
421
496
  });
422
497
  });
423
498
  });
499
+
500
+ describe("foldTaskList", () => {
501
+ const LIST: TaskList = {
502
+ id: "x",
503
+ tasks: [
504
+ { id: "T-1", title: "a", status: "done" },
505
+ { id: "T-2", title: "b", status: "done" },
506
+ { id: "T-3", title: "c", status: "in-progress" },
507
+ { id: "T-4", title: "d", status: "pending" },
508
+ { id: "T-5", title: "e", status: "failed" },
509
+ ],
510
+ };
511
+
512
+ test("strict counts: done only; failed/pending/in-progress are all not-done", () => {
513
+ expect(foldTaskList(LIST).done).toBe(2);
514
+ expect(foldTaskList(LIST).total).toBe(5);
515
+ });
516
+
517
+ test("current is the file's in-progress task, null when nothing is in-progress", () => {
518
+ expect(foldTaskList(LIST).current?.id).toBe("T-3");
519
+ expect(
520
+ foldTaskList({ id: "x", tasks: [{ id: "T-1", title: "a", status: "pending" }] }).current,
521
+ ).toBeNull();
522
+ });
523
+
524
+ test("no stall when exactly one (or zero) task is in-progress", () => {
525
+ expect(foldTaskList(LIST).stall).toBeNull();
526
+ expect(foldTaskList({ id: "x", tasks: [] }).stall).toBeNull();
527
+ });
528
+
529
+ test("stall when the list names more than one current task", () => {
530
+ const digest = foldTaskList({
531
+ id: "x",
532
+ tasks: [
533
+ { id: "T-1", title: "a", status: "in-progress" },
534
+ { id: "T-2", title: "b", status: "in-progress" },
535
+ ],
536
+ });
537
+ expect(digest.stall).toContain("2 tasks in-progress");
538
+ expect(digest.current?.id).toBe("T-1");
539
+ });
540
+ });
package/src/kit/status.ts CHANGED
@@ -1,4 +1,12 @@
1
- import { type CrashReason, DONE, FAILED, type NodeResult, parseEventLog } from "../core/index.ts";
1
+ import {
2
+ type CrashReason,
3
+ DONE,
4
+ FAILED,
5
+ type NodeResult,
6
+ parseEventLog,
7
+ type Task,
8
+ type TaskList,
9
+ } from "../core/index.ts";
2
10
  import { journalTerminal, type RegistryStatus } from "./registry.ts";
3
11
 
4
12
  export interface JournalDigest {
@@ -23,6 +31,10 @@ export interface JournalDigest {
23
31
  agentStepCount?: number;
24
32
  /** Milliseconds idle as of the last heartbeat — see `agentStallWarning`. */
25
33
  agentIdleMs?: number;
34
+ /** Present while the engine is waiting out a provider usage-limit
35
+ * backoff for the current attempt — see `limitWarning` and
36
+ * docs/specs/usage-limit-backoff/spec.md. */
37
+ limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number };
26
38
  } | null;
27
39
  crash?: { attempt: number; reason: CrashReason };
28
40
  visits: Record<string, number>;
@@ -80,6 +92,7 @@ export function foldJournal(journalText: string): JournalDigest {
80
92
  nudgeReason: lastStatus.nudgeReason,
81
93
  agentStepCount: lastStatus.agentStepCount,
82
94
  agentIdleMs: lastStatus.agentIdleMs,
95
+ limitBackoff: lastStatus.limitBackoff,
83
96
  }
84
97
  : {}),
85
98
  };
@@ -107,6 +120,39 @@ export function foldJournal(journalText: string): JournalDigest {
107
120
  return digest;
108
121
  }
109
122
 
123
+ // --- task lists (docs/specs/task-list-json/spec.md) ---
124
+
125
+ export interface TaskListDigest {
126
+ /** Strict count: only `done` tasks — pending, in-progress, and failed all
127
+ * count as not-done, so the plugin's `nn/mm` tab title is honest. */
128
+ done: number;
129
+ total: number;
130
+ /** The task the file says the run is on — its `in-progress` status is
131
+ * authoritative (no journal join); `null` when nothing is in-progress. */
132
+ current: Task | null;
133
+ /** Non-null only when the list is incoherent about "where the run is":
134
+ * more than one task in-progress. A `TaskList` carries no timestamps, so
135
+ * a time-based stall isn't derivable here — staleness of the current row
136
+ * stays covered by the workflow view's own stall warning. */
137
+ stall: string | null;
138
+ }
139
+
140
+ // Pure fold over a parsed TaskList for rendering: done/total counts, the
141
+ // current in-progress item, and stall state. Never throws — input is an
142
+ // already-narrowed TaskList (see `parseTaskList`).
143
+ export function foldTaskList(list: TaskList): TaskListDigest {
144
+ const inProgress = list.tasks.filter((t) => t.status === "in-progress");
145
+ return {
146
+ done: list.tasks.filter((t) => t.status === "done").length,
147
+ total: list.tasks.length,
148
+ current: inProgress[0] ?? null,
149
+ stall:
150
+ inProgress.length > 1
151
+ ? `${inProgress.length} tasks in-progress — expected one; the list's current position is ambiguous`
152
+ : null,
153
+ };
154
+ }
155
+
110
156
  export type TerminalState =
111
157
  | "succeeded"
112
158
  | "failed"
@@ -280,3 +326,23 @@ export function nudgeWarning(digest: JournalDigest): string | null {
280
326
  if (digest.current?.phase !== "running" || nudgeAttempt === undefined) return null;
281
327
  return `nudging attempt ${nudgeAttempt}/3 (${nudgeReason}) — supervisor decides`;
282
328
  }
329
+
330
+ // Display-only usage-limit config defaults (docs/specs/usage-limit-backoff/
331
+ // spec.md), mirroring how this module already treats other engine constants
332
+ // as display knowledge, not a shared dependency. The denominator assumes the
333
+ // defaults; a leaf overriding usageLimitRetryMs/usageLimitMaxWaitMs renders
334
+ // a best-effort total until leaf config is recorded in the journal.
335
+ const USAGE_LIMIT_RETRY_MS = 30 * 60_000;
336
+ const USAGE_LIMIT_MAX_WAIT_MS = 24 * 60 * 60_000;
337
+
338
+ /** Warn-only usage-limit wait note, same contract as `stallWarning`: folded
339
+ * from the latest running status's `limitBackoff` — present only while the
340
+ * engine sleeps between usage-limit re-probes, so the supervisor sees the
341
+ * wait instead of silence. Purely a display string, never acts. */
342
+ export function limitWarning(digest: JournalDigest, now: number = Date.now()): string | null {
343
+ const backoff = digest.current?.limitBackoff;
344
+ if (digest.current?.phase !== "running" || backoff === undefined) return null;
345
+ const totalProbes = Math.ceil(USAGE_LIMIT_MAX_WAIT_MS / USAGE_LIMIT_RETRY_MS);
346
+ const minutes = Math.max(0, Math.round((backoff.nextAttemptAt - now) / 60_000));
347
+ return `usage limit — probe ${backoff.probe}/${totalProbes}, next attempt in ${minutes}m`;
348
+ }
@@ -5,7 +5,7 @@ import type { DispatchInfo } from "@psimona/darkf/src/core/index.ts";
5
5
  // rides along on the branch — Finish commits it there before the squash.
6
6
  // The slug is a workflow-file constant for the pilot; editing this file per
7
7
  // feature is the contract until engine-side input plumbing exists.
8
- const FEATURE = "self-update";
8
+ const FEATURE = "skill-setup";
9
9
 
10
10
  function sh(...args: string[]): [string, number] {
11
11
  const proc = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe" });
@@ -13,8 +13,19 @@ import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts"
13
13
  // - refuses unless master is an ancestor of the branch (master must not
14
14
  // have moved mid-run — the only case where the squash could conflict);
15
15
  // - rolls back (reset --hard + checkout back) on any git failure.
16
- const FEATURE = "self-update";
17
- const ALLOWED = ["docs/specs/", "darkf/src/", "ROADMAP.md", "darkf/workflows/"];
16
+ const FEATURE = "skill-setup";
17
+ const ALLOWED = [
18
+ "docs/",
19
+ "darkf/src/",
20
+ "darkf/skills/",
21
+ "darkf/docs/",
22
+ "darkf/package.json",
23
+ "darkf-opencode-plugin/",
24
+ "ROADMAP.md",
25
+ "README.md",
26
+ "site/",
27
+ "darkf/workflows/",
28
+ ];
18
29
 
19
30
  function sh(...args: string[]): [string, number] {
20
31
  const proc = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe" });
@@ -1,7 +1,8 @@
1
1
  import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
2
2
  import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
3
3
 
4
- // dev-loop — begin → implement → check → review → finish(squash) → feedback.
4
+ // dev-loop — begin → implement → check → review → document → finish(squash) →
5
+ // feedback.
5
6
  //
6
7
  // The darkf-on-darkf pilot, expanded after its first real run built the CLI
7
8
  // self-update feature (docs/specs/self-update/). Shape ported from
@@ -14,7 +15,7 @@ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
14
15
  // workspace symlink — doctor's selfRoot guard fails inside the checkout):
15
16
  //
16
17
  // bun run install:global # once, to refresh the global binary
17
- // darkf doctor darkf/workflows/dev-loop
18
+ // darkf validate darkf/workflows/dev-loop
18
19
  // darkf start darkf/workflows/dev-loop "message" --allow-dirty-workflow
19
20
  //
20
21
  // Editing the FEATURE / RUN_DATE constants at the top of the begin/finish
@@ -24,7 +25,8 @@ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
24
25
  // Implement prompt). No other git automation: the human curates what the
25
26
  // workflow leaves behind (spec archive, roadmap entry, feedback note).
26
27
  //
27
- // The implementer, fixer, and reviewer are separate dispatches. Their only
28
+ // The implementer, fixer, reviewer, and documenter are separate dispatches.
29
+ // Their only
28
30
  // shared channels are the repo itself (files, git diff, the spec docs) and
29
31
  // the one-hop handoff — matching PHILOSOPHY.md: nothing rides along for
30
32
  // free.
@@ -32,8 +34,8 @@ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
32
34
  export const agentRunner = opencodeRunner;
33
35
 
34
36
  const MODEL = "zai-coding-plan/glm-5.3-flash";
35
- const RUN_DATE = "2026-10-30";
36
- const FEATURE = "self-update";
37
+ const RUN_DATE = "2026-11-09";
38
+ const FEATURE = "skill-setup";
37
39
 
38
40
  export const workflow: WorkflowDef = {
39
41
  initial: "Begin",
@@ -46,10 +48,11 @@ export const workflow: WorkflowDef = {
46
48
  },
47
49
  Loop: {
48
50
  initial: "Implement",
49
- // The normal path is one cycle (Implement → Check → Review → Finish).
50
- // Each Fix → Check re-entry costs another. 6 leaves room for several
51
- // fix rounds before the engine calls the run stuck.
52
- maxCycles: 6,
51
+ // The normal path is one cycle (Implement → Check → Review → Document
52
+ // → Finish). Each Fix → Check re-entry costs another. 8 leaves room
53
+ // for two fix rounds including the terminal Document dispatch before
54
+ // the engine calls the run stuck.
55
+ maxCycles: 8,
53
56
  states: {
54
57
  Implement: {
55
58
  type: "agent",
@@ -57,16 +60,20 @@ export const workflow: WorkflowDef = {
57
60
  retries: 1,
58
61
  prompt: `Implement the ${FEATURE} feature in this repository.
59
62
 
60
- First read docs/specs/${FEATURE}/prd.md and docs/specs/${FEATURE}/design.md. They are the contract: implement exactly what the design specifies, nothing more.
63
+ First read docs/specs/${FEATURE}/spec.md. It is the contract: its Decisions and Non-goals sections are locked — implement exactly what they specify, nothing more. The spec is the only contract artifact; no design.md exists for this feature.
61
64
 
62
- Resume semantics: if the working tree already implements the spec, verify that instead of re-implementing — read the existing darkf/src/cli/update.ts and update.test.ts, confirm they match the design, and finish "implemented" without rewriting.
65
+ Resume semantics: if the working tree already implements part of the spec, verify that part instead of re-implementing. The bundled skills already exist and are final content — darkf/skills/darkf-usage/SKILL.md and darkf/skills/darkf-writing-workflows/SKILL.md. Do not rewrite them. Wire them into setup, doctor, packaging, and the docs move as the spec specifies.
63
66
 
64
67
  Deliverables (when not already present):
65
- - new file darkf/src/cli/update.ts with the module interface from the design (UpdateState, UpdateDeps, readState, writeState, isDue, isNewer, checkRegistry, updateGate, upgradeCmd)
66
- - edits to darkf/src/cli/index.ts: the updateGate call in main() before command dispatch, and the upgrade branch
67
- - tests in darkf/src/cli/update.test.ts covering the design's testing coverage areas
68
+ - darkf/src/cli/setup.ts (new): \`darkf setup\` — sync both bundled skills into every detected host's skills dir. Hosts are a table in code per the spec: claude code (~/.claude/skills, binary claude), opencode (~/.opencode/skills, opencode), codex cli (~/.codex/skills, codex), gemini cli (~/.gemini/skills, gemini), cursor (~/.cursor/skills, cursor-agent); a host is detected when its skills dir exists OR its binary is on PATH. Write policy: darkf-* is darkf's namespace — copy when missing; when present, replace the whole dir (copy bundled to a dot-prefixed temp dir inside the skills dir, remove the installed dir, rename into place) so the destination is an exact mirror. States missing/ok/differs per skill. Output: one host-detection line, then one line per host per skill. Creates a missing skills dir (mode 0755) for a detected host; skips an undetected host without creating anything. Exits non-zero when a present host still ends missing/differs after the sync attempt. Takes no flags and no positional args; never prompts.
69
+ - \`darkf upgrade\` (darkf/src/cli/update.ts) runs the same sync after self-update, under a "skills:" header, best-effort: a sync failure is reported and exits non-zero but never masks the upgrade itself.
70
+ - doctor/validate split in darkf/src/cli/index.ts: \`darkf doctor\` with no ref checks the environment only — agent binaries, cwd sanity, skills section. \`darkf validate <ref>\` inherits the workflow checks doctor has today (resolves, loads, exports, structure), unchanged lines and exit codes. Back-compat: \`darkf doctor <ref>\` prints the new usage and exits 1. The skills section names every known harness: per skill ok/missing/differs for a present harness, \`harness not present\` for an absent one; it writes nothing and exits non-zero only for missing/differs on a present harness, with \`run darkf setup\` as the fix hint. All three (doctor skills section, validate checks, setup sync) share one skills-check function. Fix doctor's stale runner hint while there: "built-ins live in src/agents/" — the real location is src/kit/agents/.
71
+ - Daily probe: once per calendar day, the first darkf invocation after the update gate runs a skills-only check via the same shared function. State file per the spec (XDG state semantics like updateStateFile) stores the last probe date; missing or corrupt counts as never probed. Silent when every present harness is ok. On missing/differs, print one compact block (the failing lines plus "fix: run darkf setup") before the invoked command's own output. Never fatal — the probe never changes the invoking command's exit code. \`setup\` and \`upgrade\` skip the probe and refresh the state file.
72
+ - Packaging: darkf/package.json gains "files": ["src", "workflows", "skills", "docs"].
73
+ - Docs move: move site/src/content/docs/** to darkf/docs/** and rebase the site's content loading onto darkf/docs/ (site/src/content.config.ts, starlight docsLoader — rebase it, or if the loader cannot rebase, a prepack copy with a drift check per the spec). bun run build in site/ must still succeed.
74
+ - Tests per the spec's Testing section: setup tests with deps injected like update.ts's UpdateDeps (home, bundledDir, existsBinary) covering host detection by dir alone / by binary / absent, copy and mirror semantics including leftover-file wipe and crashed-temp-dir replacement, state reporting, and exit codes; doctor/validate split tests; daily-probe tests (first-of-day runs, same-day skip, corrupt state file, silent-ok, block-on-failure, exemptions); the tarball smoke check (npm pack, temp-prefix install, run setup/doctor/render and the skill-referenced docs paths).
68
75
 
69
- Follow the existing code style of darkf/src/cli/index.ts. Do not commit, do not touch files outside darkf/src/ and docs/specs/${FEATURE}/.
76
+ Follow the existing code style of darkf/src/cli/index.ts and darkf/src/cli/update.ts. Do not commit. Do not touch files outside darkf/src/, darkf/package.json, darkf/skills/, darkf/docs/, site/, and docs/specs/${FEATURE}/.
70
77
 
71
78
  Finish with event "implemented". If the spec cannot be implemented as written, finish with event "blocked" and put the reason in the output. If a review demand contradicts the spec, finish with event "disputed" and ground the objection in the spec text.`,
72
79
  on: { implemented: "Check", blocked: DONE, disputed: DONE },
@@ -83,7 +90,7 @@ Finish with event "implemented". If the spec cannot be implemented as written, f
83
90
  retries: 1,
84
91
  prompt: `You are repairing the ${FEATURE} implementation after a failed gate.
85
92
 
86
- The handoff you received carries either the failing tail of "bun run check" or the reviewer's change list. Read docs/specs/${FEATURE}/design.md for the contract. Fix the code minimally. Do not redesign. Do not commit. Do not touch files outside darkf/src/.
93
+ The handoff you received carries either the failing tail of "bun run check" or the reviewer's change list. Read docs/specs/${FEATURE}/spec.md for the contract. Fix the code minimally. Do not redesign. Do not commit. Do not touch files outside darkf/src/, darkf/package.json, darkf/skills/, darkf/docs/, and site/.
87
94
 
88
95
  Finish with event "fixed". If the failure exposes a spec defect you cannot resolve in code, finish with event "blocked" and the reason. If the demand contradicts the spec, finish with event "disputed" and ground the objection in the spec text.`,
89
96
  on: { fixed: "Check", blocked: DONE, disputed: DONE },
@@ -94,16 +101,43 @@ Finish with event "fixed". If the failure exposes a spec defect you cannot resol
94
101
  retries: 1,
95
102
  prompt: `You are an independent reviewer. Do not modify any files.
96
103
 
97
- Verify the working tree against docs/specs/${FEATURE}/prd.md and docs/specs/${FEATURE}/design.md:
104
+ Verify the working tree against docs/specs/${FEATURE}/spec.md:
98
105
  - inspect git status --porcelain in addition to git diff — agent-authored new files are invisible to git diff alone
99
- - check every REQ-1 to REQ-11 and NFR-1 to NFR-3 in prd.md has a code-level home
100
- - check darkf/src/cli/update.test.ts covers the design's testing coverage areas
101
- - you may run bun test darkf/src/cli/update.test.ts yourself
102
-
103
- Approve only if the implementation fulfills the design. Otherwise list every required change concretely in the output.
106
+ - check the host table matches the spec exactly: five harnesses (claude code, opencode, codex cli, gemini cli, cursor), their skills dirs and binary names, and dir-exists OR binary-on-PATH detection
107
+ - check the write policy: darkf-* namespace only, dir replacement not file merge (temp-dir copy, remove, rename), exact-mirror destinations, no flags, no prompts, undetected hosts skipped without dir creation
108
+ - check the upgrade sync: runs after self-update under a "skills:" header, best-effort, same code path as setup
109
+ - check the doctor/validate split: doctor with no ref = environment only (binaries, cwd sanity, skills section); validate <ref> inherits the workflow checks with unchanged lines and exit codes; doctor <ref> back-compat prints usage and exits 1; the skills section names every known harness with the spec's states and exit rules; the stale "src/agents/" hint is fixed to src/kit/agents/
110
+ - check the daily probe: once per calendar day on first invocation after the update gate, skills-only via the shared function, spec state file with missing/corrupt treated as never probed, silent on ok, compact block plus fix hint on missing/differs, never fatal, setup/upgrade exempt and refreshing the state file
111
+ - check packaging: package.json files allowlist exactly ["src", "workflows", "skills", "docs"]; docs moved to darkf/docs/; the site still builds from the moved docs (loader rebase or prepack copy with drift check)
112
+ - check the bundled skills are byte-unchanged: darkf/skills/darkf-usage/SKILL.md and darkf/skills/darkf-writing-workflows/SKILL.md
113
+ - check the tests cover the spec's Testing section: setup deps-injection fixtures, mirror semantics, doctor/validate split, daily probe behaviors, tarball smoke check
114
+ - you may run "bun test darkf/src" and "bun run lint" yourself
115
+
116
+ Approve only if the implementation fulfills the spec. Otherwise list every required change concretely in the output.
104
117
 
105
118
  Finish with event "approved" or event "changes_requested".`,
106
- on: { approved: "Finish", changes_requested: "Fix" },
119
+ on: { approved: "Document", changes_requested: "Fix" },
120
+ },
121
+ Document: {
122
+ type: "agent",
123
+ agent: { model: MODEL },
124
+ retries: 1,
125
+ prompt: `You are updating user-facing documentation for the ${FEATURE} feature, after an independent review approved the implementation. Do not modify code or tests.
126
+
127
+ Read docs/specs/${FEATURE}/spec.md (or prd.md/design.md when present) for what the feature does, and run git diff master plus git status --porcelain to see what shipped.
128
+
129
+ Docs must match the spec when this run lands — drift accumulates one stale page at a time. Update everything the feature's surface touches:
130
+ - README.md — CLI flags/commands, plugin behavior, setup steps that changed
131
+ - packaged docs under darkf/docs/ — the site renders from these files, so they are the docs:
132
+ - reference/cli-commands.md for any CLI surface change (new command, flag, exit code, default)
133
+ - the guides and concepts pages the feature's surface touches — re-read them and fix stale paths, stale command names, and claims the feature made wrong
134
+ - start-here/install.md when setup, packaging, or install steps changed
135
+ - cross-references anywhere in darkf/docs/ or README.md that now point at moved or renamed paths
136
+
137
+ Do NOT touch: ROADMAP.md, darkf/feedback/, docs/specs/ (the spec archive move and roadmap entry are post-merge human curation), any file under darkf/src/ or darkf-opencode-plugin/.
138
+
139
+ If nothing user-facing changed and no doc drifted, finish with event "skipped" and put the one-line reason in the output. Otherwise make the edits and finish with event "documented". If the docs cannot be updated (for example the site is broken), finish with event "blocked" and the reason.`,
140
+ on: { documented: "Finish", skipped: "Finish", blocked: DONE },
107
141
  },
108
142
  },
109
143
  },
package/bunfig.toml DELETED
@@ -1,13 +0,0 @@
1
- # One merged suite, one threshold. `darkf-core`, `darkf-engine`, and the
2
- # old `darkf-cli` coverage configs (0.85/0.80 engine, 0.30/0.30 cli) died
3
- # with the package merge — the package-boundaries spec moved all sources
4
- # under one roof, so coverage is measured once, across the whole tree.
5
- #
6
- # kit/agents is excluded because the runners' real code paths execute
7
- # inside spawned worker subprocesses (see src/cli/detached.test.ts), which
8
- # the in-process profiler cannot see; their harness-side logic is still
9
- # covered in-process (handoff, registry, status).
10
- [test]
11
- coverage = true
12
- coveragePathIgnorePatterns = ["src/kit/agents/**"]
13
- coverageThreshold = { lines = 0.30, functions = 0.30 }
@@ -1,38 +0,0 @@
1
- export interface Article {
2
- id: string;
3
- title: string;
4
- text: string;
5
- }
6
-
7
- export const articles: Article[] = [
8
- {
9
- id: "a1",
10
- title: "New chip promises 10x inference speedup",
11
- text: "A startup unveiled a chip design claiming an order-of-magnitude improvement in inference throughput for large language models, at a fraction of the power draw of current GPUs.",
12
- },
13
- {
14
- id: "a2",
15
- title: "Exoplanet found in habitable zone of nearby star",
16
- text: "Astronomers using a new survey telescope identified a rocky exoplanet orbiting within the habitable zone of a star 40 light-years away, a strong candidate for atmospheric follow-up.",
17
- },
18
- {
19
- id: "a3",
20
- title: "Retailer reports record quarterly earnings",
21
- text: "A national retail chain posted its strongest quarterly earnings in a decade, citing holiday demand and improved supply chain efficiency across its distribution network.",
22
- },
23
- {
24
- id: "a4",
25
- title: "Local bakery wins regional sourdough award",
26
- text: "A family-run bakery took first place in the region's annual bread competition, praised by judges for a distinctive tang developed over a decade-old starter culture.",
27
- },
28
- {
29
- id: "a5",
30
- title: "Open-source database project reaches 1.0",
31
- text: "After four years of development, a community-maintained embedded database project shipped its first stable 1.0 release, adding transactional guarantees and a new query planner.",
32
- },
33
- {
34
- id: "a6",
35
- title: "Study links sleep patterns to memory consolidation",
36
- text: "Researchers tracking sleep stages in a longitudinal study found a strong correlation between deep sleep duration and next-day recall performance in memory tasks.",
37
- },
38
- ];
@@ -1,7 +0,0 @@
1
- import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
2
- import { allResults, currentArticle, isDone } from "./queue.ts";
3
-
4
- export default function next(_handoff: NodeResult): NodeResult {
5
- if (isDone()) return { event: "done", output: { results: allResults() } };
6
- return { event: "have_item", output: { article: currentArticle() } };
7
- }
@@ -1,33 +0,0 @@
1
- import { type Article, articles } from "../data/articles.ts";
2
-
3
- export interface ClassifiedArticle extends Article {
4
- category: string;
5
- }
6
-
7
- // This is run-scoped bookkeeping shared by next.ts and record.ts via plain
8
- // module scope — not the handoff, and not a file. It doesn't need to be a
9
- // file: it's private coordination between two script nodes, invisible to the
10
- // engine, and doesn't need to survive past this one process. See
11
- // PHILOSOPHY.md's "no global, accumulating context" — this is the sanctioned
12
- // escape hatch (a node's own code choosing to carry state), scoped as
13
- // narrowly as possible instead of riding through the handoff or the agent.
14
- let index = 0;
15
- const results: ClassifiedArticle[] = [];
16
-
17
- export function isDone(): boolean {
18
- return index >= articles.length;
19
- }
20
-
21
- export function currentArticle(): Article {
22
- return articles[index]!;
23
- }
24
-
25
- export function recordCategory(category: string): ClassifiedArticle[] {
26
- results.push({ ...currentArticle(), category });
27
- index++;
28
- return results;
29
- }
30
-
31
- export function allResults(): ClassifiedArticle[] {
32
- return results;
33
- }
@@ -1,9 +0,0 @@
1
- import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
2
- import { recordCategory } from "./queue.ts";
3
-
4
- export default function record(handoff: NodeResult): NodeResult {
5
- // Classify's event IS the category — this script's only job is the
6
- // "useful thing to do" with it (here: file it away for the final report).
7
- const results = recordCategory(handoff.event ?? "other");
8
- return { output: { results } };
9
- }
@@ -1,44 +0,0 @@
1
- import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
2
- import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
3
-
4
- // Real LLM calls, one per article in data/articles.ts (6 by default) — this
5
- // example is the one demo actually wired to claudeCodeRunner. See
6
- // docs/specs/_built/agent-handoff/spec.md.
7
- export const agentRunner = claudeCodeRunner;
8
-
9
- export const workflow: WorkflowDef = {
10
- initial: "Loop",
11
- states: {
12
- Loop: {
13
- initial: "Next",
14
- // Safety net for the whole Next/Classify/Record cycle, not a tuning
15
- // knob: 6 articles x 3 leaf dispatches each + the final "done" check
16
- // is 19 in the normal case, so 30 never trips unless something is
17
- // actually stuck flapping.
18
- maxCycles: 30,
19
- states: {
20
- Next: {
21
- type: "script",
22
- file: "next.ts",
23
- on: { have_item: "Classify", done: DONE },
24
- },
25
- Classify: {
26
- type: "agent",
27
- prompt: "Classify the topic of the given article.",
28
- retries: 1,
29
- on: {
30
- tech: "Record",
31
- science: "Record",
32
- business: "Record",
33
- other: "Record",
34
- },
35
- },
36
- Record: {
37
- type: "script",
38
- file: "record.ts",
39
- next: "Next",
40
- },
41
- },
42
- },
43
- },
44
- };
@@ -1,24 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
4
-
5
- const START_MARKER = "<!-- haiku:start -->";
6
- const END_MARKER = "<!-- haiku:end -->";
7
-
8
- export default async function check(_handoff: NodeResult, info: DispatchInfo): Promise<NodeResult> {
9
- const readmePath = join(info.rootDir, "README.md");
10
- const text = existsSync(readmePath) ? readFileSync(readmePath, "utf8") : "";
11
- if (!text.includes(START_MARKER) || !text.includes(END_MARKER)) {
12
- return { event: "missing" };
13
- }
14
-
15
- const add = Bun.spawn(["git", "add", "README.md"], { cwd: info.rootDir });
16
- if ((await add.exited) !== 0) throw new Error("git add README.md failed");
17
-
18
- const commit = Bun.spawn(["git", "commit", "-m", "Add haiku to README"], {
19
- cwd: info.rootDir,
20
- });
21
- if ((await commit.exited) !== 0) throw new Error("git commit failed");
22
-
23
- return { event: "committed" };
24
- }
@@ -1,28 +0,0 @@
1
- import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
2
- import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
3
-
4
- // A real LLM call, not a stub — the docs site's Quickstart example. One
5
- // cheap agent dispatch per attempt, so the cost is trivial; see
6
- // docs/specs/docs-site/spec.md.
7
- export const agentRunner = claudeCodeRunner;
8
-
9
- export const workflow: WorkflowDef = {
10
- initial: "Write",
11
- states: {
12
- Write: {
13
- type: "agent",
14
- prompt:
15
- "Add a haiku about darkf to README.md, wrapped in HTML comments " +
16
- "<!-- haiku:start --> and <!-- haiku:end --> on their own lines, " +
17
- "so an automated check can find it.",
18
- // Unconditional: Check decides what actually happened by reading the
19
- // file, not by trusting whatever event the agent reports.
20
- next: "Check",
21
- },
22
- Check: {
23
- type: "script",
24
- file: "check.ts",
25
- on: { committed: DONE, missing: "Write" },
26
- },
27
- },
28
- };
@@ -1,13 +0,0 @@
1
- import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
2
-
3
- interface TestHandoff {
4
- writeAttempts?: number;
5
- }
6
-
7
- export default function test(handoff: NodeResult): NodeResult {
8
- const writeAttempts = (handoff.output as TestHandoff | undefined)?.writeAttempts ?? 0;
9
- // Must re-emit writeAttempts: if Test fails and routes back to Write, Write
10
- // only ever sees THIS result as its next handoff — nothing carries forward
11
- // unless this node's own code chooses to relay it.
12
- return { event: writeAttempts >= 2 ? "passed" : "failed", output: { writeAttempts } };
13
- }