@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
@@ -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
- }
@@ -1,10 +0,0 @@
1
- import type { NodeResult } from "@psimona/darkf/src/core/index.ts";
2
-
3
- interface WriteHandoff {
4
- writeAttempts?: number;
5
- }
6
-
7
- export default function write(handoff: NodeResult): NodeResult {
8
- const writeAttempts = ((handoff.output as WriteHandoff | undefined)?.writeAttempts ?? 0) + 1;
9
- return { output: { writeAttempts } };
10
- }
@@ -1,41 +0,0 @@
1
- import { type AgentRunner, DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
2
-
3
- let reviewCalls = 0;
4
-
5
- export const agentRunner: AgentRunner = {
6
- async run(id) {
7
- if (id === "Plan") return { event: "approved" };
8
- // Review
9
- reviewCalls++;
10
- return { event: reviewCalls === 1 ? "changes_requested" : "done" };
11
- },
12
- };
13
-
14
- export const workflow: WorkflowDef = {
15
- initial: "Plan",
16
- states: {
17
- Plan: {
18
- type: "agent",
19
- // The goal is a durable fact about this workflow, not per-run data —
20
- // it belongs in the prompt an author wrote, not in a data channel.
21
- prompt: "Plan the change needed to add a haiku to the README.",
22
- on: { approved: "Implement" },
23
- },
24
- Implement: {
25
- initial: "Write",
26
- states: {
27
- Write: { type: "script", file: "write.ts", next: "Test" },
28
- Test: {
29
- type: "script",
30
- file: "test.ts",
31
- on: { passed: "Review", failed: "Write" },
32
- },
33
- },
34
- },
35
- Review: {
36
- type: "agent",
37
- prompt: "Review the implementation against the goal.",
38
- on: { done: DONE, changes_requested: "Write" },
39
- },
40
- },
41
- };
@@ -1,20 +0,0 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
4
-
5
- interface Task {
6
- id: string;
7
- title: string;
8
- status: "pending" | "in-progress" | "done";
9
- }
10
-
11
- export default function next(_handoff: NodeResult, info: DispatchInfo): NodeResult {
12
- const path = join(info.rootDir, "tasks.json");
13
- const tasks: Task[] = JSON.parse(readFileSync(path, "utf8"));
14
- const task = tasks.find((t) => t.status === "pending");
15
- if (!task) return { event: "empty" };
16
-
17
- task.status = "in-progress";
18
- writeFileSync(path, JSON.stringify(tasks, null, 2));
19
- return { event: "found", output: { title: task.title } };
20
- }
@@ -1,20 +0,0 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
4
-
5
- interface Task {
6
- id: string;
7
- title: string;
8
- status: "pending" | "in-progress" | "done";
9
- }
10
-
11
- export default function record(_handoff: NodeResult, info: DispatchInfo): NodeResult {
12
- const path = join(info.rootDir, "tasks.json");
13
- const tasks: Task[] = JSON.parse(readFileSync(path, "utf8"));
14
- const task = tasks.find((t) => t.status === "in-progress");
15
- if (!task) throw new Error("no in-progress task to record");
16
-
17
- task.status = "done";
18
- writeFileSync(path, JSON.stringify(tasks, null, 2));
19
- return { event: "recorded" };
20
- }
@@ -1,57 +0,0 @@
1
- #!/usr/bin/env bun
2
- // A minimal supervisor: start the workflow, then react to things `darkf
3
- // monitor` only warns about (a stalled or orphaned worker) instead of
4
- // leaving a human to notice. Run from the same directory as tasks.json —
5
- // the workflow's rootDir — exactly like `darkf start` itself:
6
- //
7
- // bunx bun examples/task-queue/supervise.ts
8
- //
9
- // This is the "supervisor" the rest of darkf's CLI output already assumes
10
- // exists (status/monitor call stalls "warn-only — the supervisor decides").
11
- // It doesn't have to be a script like this one — an agent harness invoking
12
- // `darkf start` directly is a supervisor too, and darkf detects that case
13
- // (see SUPERVISOR_ENV_SIGNALS in darkf-cli/src/registry.ts) so a UI like the
14
- // OpenCode plugin can show which session is driving a run.
15
- const WORKFLOW = new URL(".", import.meta.url).pathname;
16
- const POLL_MS = 5_000;
17
-
18
- async function darkf(...args: string[]): Promise<number> {
19
- const proc = Bun.spawn(["bunx", "darkf", ...args], { stdout: "inherit", stderr: "inherit" });
20
- return await proc.exited;
21
- }
22
-
23
- async function start(): Promise<string> {
24
- const proc = Bun.spawn(["bunx", "darkf", "start", WORKFLOW], {
25
- stdout: "pipe",
26
- stderr: "inherit",
27
- });
28
- const stdout = await new Response(proc.stdout).text();
29
- await proc.exited;
30
- return (JSON.parse(stdout) as { runId: string }).runId;
31
- }
32
-
33
- let runId = await start();
34
- console.log(`started run ${runId}`);
35
-
36
- for (;;) {
37
- const code = await darkf("monitor", "--run", runId, "--once");
38
- if (code === 0) {
39
- console.log("succeeded");
40
- await darkf("report", "--run", runId);
41
- break;
42
- }
43
- if (code === 1) {
44
- console.log("crashed — see report before deciding whether to resume");
45
- await darkf("report", "--run", runId);
46
- break;
47
- }
48
- if (code === 2) {
49
- console.log("orphaned — worker died without a terminal journal entry; restarting");
50
- runId = await start();
51
- continue;
52
- }
53
- // 6: the run is still going. darkf status --run would also show a
54
- // stall-suspected warning here once a dispatch sits past its heartbeat
55
- // window — that's this script's cue to act, not darkf's.
56
- await Bun.sleep(POLL_MS);
57
- }
@@ -1,33 +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
- // The durable-queue version of the Next/Work/Record loop: article-classifier
5
- // (../article-classifier) tracks its queue in in-memory module state, fine
6
- // for a single blocking `darkf run`. This one tracks it in tasks.json on
7
- // disk instead, so the same run survives being detached (`darkf start`) and
8
- // re-entered by a different process checking status.
9
- export const agentRunner = claudeCodeRunner;
10
-
11
- export const workflow: WorkflowDef = {
12
- initial: "Next",
13
- states: {
14
- Next: {
15
- type: "script",
16
- file: "next.ts",
17
- on: { found: "Work", empty: DONE },
18
- },
19
- Work: {
20
- type: "agent",
21
- prompt:
22
- 'Do the task named in the handoff\'s "title" field: append one ' +
23
- "sentence to notes.md describing what you did, creating the file " +
24
- "if it doesn't exist yet. Don't overwrite what's already there.",
25
- next: "Record",
26
- },
27
- Record: {
28
- type: "script",
29
- file: "record.ts",
30
- next: "Next",
31
- },
32
- },
33
- };
@@ -1,29 +0,0 @@
1
- # Run feedback — self-update dev-loop run
2
-
3
- - **Date:** 2026-10-30
4
- - **Engine/workflow:** darkf dev-loop
5
- - **Run:** c078c63d-399e-41b1-b0d3-90edccdec766
6
- - **Final outcome:** Merged. `feature/self-update` squashed to master as `feat: self-update (self-update)` (2651989); branch deleted. Every state succeeded on attempt 1.
7
- - **Scopes:** Shipped `darkf/src/cli/update.ts` and its test suite (24h gate, `DARKF_NO_UPDATE_CHECK` opt-out, one-line notice before dispatch, `upgrade` command), wired into `index.ts`, plus specs under `docs/specs/self-update/`.
8
-
9
- ## What worked
10
-
11
- - The full loop ran clean: Begin → Implement → Check → Review → Finish, one attempt per state, no retries.
12
- - Implement detected the working tree already matched `docs/specs/self-update/design.md` and verified instead of rewriting.
13
- - All gates passed on the first pass: 25/25 in `update.test.ts`, 162/162 across the full suite, secret-scan, typecheck, lint, arch-check clean.
14
- - Coverage held at 95.61% funcs / 95.72% lines; `update.ts` at 100% funcs.
15
- - Zero new dependencies; only `fetch`, `Bun.semver`, `node:fs`, `Bun.spawnSync`; `bun.lock` untouched.
16
- - Review independently re-ran the tests and mapped REQ-1 through REQ-5 to code-level line references before approving.
17
- - The real-CLI smoke tests keep the suite network-free by setting `DARKF_NO_UPDATE_CHECK=1`.
18
-
19
- ## Failures and root causes
20
-
21
- none observed
22
-
23
- ## Notes
24
-
25
- - The dev-loop workflow itself (`darkf/workflows/dev-loop/`) is untracked. It sits outside the self-update design scope, so the merge did not include it. Commit it separately so future runs are reproducible.
26
- - This run's Implement step shortcut worked because the working tree already held the implementation. A run from a clean checkout will pay the full implementation cost; plan attempts accordingly.
27
- - Total wall clock was about 3 minutes; heartbeats show roughly 30-60s of agent idle time per agent state (Implement, Review). Harmless, but it is most of the run time.
28
- - `update.ts` lines 131 and 177-178 stay uncovered: a defensive semver re-check already guaranteed by `checkRegistry`. The reviewer accepted this; do not chase it.
29
- - The implementer shipped two real-CLI smoke tests where the design says "one optional smoke test may". Permissive wording, no action needed.
@@ -1,26 +0,0 @@
1
- # Run feedback — task-list-json
2
-
3
- - **Date:** 2026-10-31
4
- - **Engine/workflow:** darkf dev-loop
5
- - **Run:** 7f95d772-b147-42d8-b40a-1e40b9ce51d5
6
- - **Final outcome:** merged. Squashed `feature/task-list-json` to master as `feat: task-list-json (task-list-json)`; branch deleted. Confirmed in git log as `02a7aa2`.
7
- - **Scopes:** TaskList support shipped end to end: `Task`/`TaskList` types in core, hand-written zero-dependency `parseTaskList`, `foldTaskList` in the kit, and a new tasks tab (absent/invalid/valid views, strict done/total, stall warning) in the opencode plugin overlay.
8
-
9
- ## What worked
10
-
11
- - One pass through the loop: Implement → Check → Fix → Check → Review approved → merged. No retry loops.
12
- - All gates green at merge: secret-scan, typecheck, lint, arch-check, darkf 179 tests, plugin 12 tests, coverage at ~96% lines.
13
- - Implementation matched the spec field for field (`docs/specs/task-list-json/spec.md`); the reviewer verified types, decisions, and tests against it and approved with no change requests.
14
- - `parseTaskList` narrowing is proven by tests: legacy `moscow` and task-side `requirements` are dropped, bad unions and non-object roots rejected with path-prefixed errors.
15
- - The plugin reads `tasks.json` via the existing 1s poll plus an `fs.watch` with the same retry-until-exists pattern as the journal watcher; teardown cleans up both.
16
-
17
- ## Failures and root causes
18
-
19
- 1. First Check gate failed on a biome format error in `darkf/workflows/dev-loop/scripts/finish.ts:17` (the `ALLOWED` array needed multi-line formatting). Root cause: this feature's own retarget commit (a054445) edited the finish script and committed it unformatted. The Implement summary then mislabeled it as "pre-existing and outside allowed paths". Cost: one extra Fix → Check cycle, about 3 minutes per journal timestamps (fail at 1793474949114, pass at 1793475128840).
20
-
21
- ## Notes
22
-
23
- - The dev-loop finish script (`darkf/workflows/dev-loop/scripts/finish.ts`) sits in the lint path. Any run that retargets it must format it before committing, or the Check gate will fail.
24
- - When a failing file is outside the feature's allowed paths, check `git log`/`git blame` before calling it pre-existing. Here the implementing agent's claim was wrong and the fix step had to re-derive the cause.
25
- - The spec's mention of item-loop.ts refers to the separate, not-yet-implemented item-loop-convention spec. No migration was required for this run. Future item-loop work will need it.
26
- - No tasks.json was produced by this run itself; the feature only adds the consumer side. Exercise the producer path in a later run.
package/tsconfig.json DELETED
@@ -1,4 +0,0 @@
1
- {
2
- "extends": "../tsconfig.base.json",
3
- "include": ["src", "examples", "workflows"]
4
- }