@psimona/darkf 0.0.0-stage → 0.4.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 (51) hide show
  1. package/README.md +28 -2
  2. package/bunfig.toml +13 -0
  3. package/examples/article-classifier/data/articles.ts +38 -0
  4. package/examples/article-classifier/scripts/next.ts +7 -0
  5. package/examples/article-classifier/scripts/queue.ts +33 -0
  6. package/examples/article-classifier/scripts/record.ts +9 -0
  7. package/examples/article-classifier/workflow.ts +44 -0
  8. package/examples/haiku-commit/scripts/check.ts +24 -0
  9. package/examples/haiku-commit/workflow.ts +28 -0
  10. package/examples/haiku-readme/scripts/test.ts +13 -0
  11. package/examples/haiku-readme/scripts/write.ts +10 -0
  12. package/examples/haiku-readme/workflow.ts +41 -0
  13. package/examples/task-queue/scripts/next.ts +20 -0
  14. package/examples/task-queue/scripts/record.ts +20 -0
  15. package/examples/task-queue/supervise.ts +57 -0
  16. package/examples/task-queue/workflow.ts +33 -0
  17. package/feedback/2026-10-30-self-update.md +29 -0
  18. package/package.json +30 -4
  19. package/src/cli/detached.test.ts +560 -0
  20. package/src/cli/index.ts +1040 -0
  21. package/src/cli/update.test.ts +486 -0
  22. package/src/cli/update.ts +191 -0
  23. package/src/core/graph.test.ts +172 -0
  24. package/src/core/graph.ts +148 -0
  25. package/src/core/index.ts +4 -0
  26. package/src/core/journal.ts +21 -0
  27. package/src/core/mermaid.test.ts +34 -0
  28. package/src/core/mermaid.ts +95 -0
  29. package/src/core/types.ts +279 -0
  30. package/src/engine/eventLog.ts +17 -0
  31. package/src/engine/index.ts +2 -0
  32. package/src/engine/run.test.ts +1068 -0
  33. package/src/engine/run.ts +359 -0
  34. package/src/exports.ts +2 -0
  35. package/src/kit/agents/claude-code.test.ts +37 -0
  36. package/src/kit/agents/claude-code.ts +180 -0
  37. package/src/kit/agents/handoff.test.ts +128 -0
  38. package/src/kit/agents/handoff.ts +69 -0
  39. package/src/kit/agents/opencode.test.ts +136 -0
  40. package/src/kit/agents/opencode.ts +327 -0
  41. package/src/kit/registry.test.ts +386 -0
  42. package/src/kit/registry.ts +296 -0
  43. package/src/kit/status.test.ts +423 -0
  44. package/src/kit/status.ts +282 -0
  45. package/tsconfig.json +4 -0
  46. package/workflows/dev-loop/scripts/begin.ts +22 -0
  47. package/workflows/dev-loop/scripts/check.ts +19 -0
  48. package/workflows/dev-loop/scripts/finish.ts +114 -0
  49. package/workflows/dev-loop/workflow.ts +135 -0
  50. package/workflows/series-ordering/scripts/verify.ts +18 -0
  51. package/workflows/series-ordering/workflow.ts +80 -0
package/tsconfig.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "../tsconfig.base.json",
3
+ "include": ["src", "examples", "workflows"]
4
+ }
@@ -0,0 +1,22 @@
1
+ import type { DispatchInfo } from "@psimona/darkf/src/core/index.ts";
2
+
3
+ // Ported from blueprint's build-backend create_branch: cut feature/<slug>
4
+ // from the current tree. Uncommitted work (the feature under construction)
5
+ // rides along on the branch — Finish commits it there before the squash.
6
+ // The slug is a workflow-file constant for the pilot; editing this file per
7
+ // feature is the contract until engine-side input plumbing exists.
8
+ const FEATURE = "self-update";
9
+
10
+ function sh(...args: string[]): [string, number] {
11
+ const proc = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe" });
12
+ return [`${proc.stdout?.toString() ?? ""}${proc.stderr?.toString() ?? ""}`, proc.exitCode ?? 1];
13
+ }
14
+
15
+ export default function begin(_handoff: unknown, _info: DispatchInfo) {
16
+ const target = `feature/${FEATURE}`;
17
+ const [, exists] = sh("git", "rev-parse", "--verify", target);
18
+ const co = exists === 0 ? sh("git", "checkout", target) : sh("git", "checkout", "-b", target);
19
+ return co[1] === 0
20
+ ? { event: "started", output: { branch: target, reused: exists === 0 } }
21
+ : { event: "branch_failed", output: { reason: co[0] } };
22
+ }
@@ -0,0 +1,19 @@
1
+ import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
2
+
3
+ // Runs the repo's full quality gate (`bun run check`: gitleaks, typecheck,
4
+ // biome, dependency-cruiser, bun test with coverage thresholds) at
5
+ // info.rootDir — the invocation cwd, wherever the workflow runs from. The
6
+ // last 80 lines of output travel to Fix via the handoff: the one hop the
7
+ // fix agent gets.
8
+ export default function check(_handoff: NodeResult, info: DispatchInfo): NodeResult {
9
+ const proc = Bun.spawnSync(["bun", "run", "check"], {
10
+ cwd: info.rootDir,
11
+ stdout: "pipe",
12
+ stderr: "pipe",
13
+ });
14
+ const output = `${proc.stdout?.toString() ?? ""}\n${proc.stderr?.toString() ?? ""}`;
15
+ const tail = output.split("\n").slice(-80).join("\n");
16
+ return proc.exitCode === 0
17
+ ? { event: "passed", output: { tail } }
18
+ : { event: "failed", output: { tail } };
19
+ }
@@ -0,0 +1,114 @@
1
+ import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
2
+
3
+ // Ported from blueprint's build-backend finish_branch (node 4): commit the
4
+ // loop's work on the feature branch, squash-merge onto master as one commit
5
+ // (subject from the prd H1), delete the branch. The run ends with the work
6
+ // merged; no supervisor merge.
7
+ //
8
+ // Safety rails:
9
+ // - only runs on feature/<slug>;
10
+ // - refuses when the dirty tree touches paths outside the loop's known
11
+ // surface (the anti-sweep rail — a blind `git add -A` once wiped a
12
+ // repo's .darkf state in the registry-lifecycle incident);
13
+ // - refuses unless master is an ancestor of the branch (master must not
14
+ // have moved mid-run — the only case where the squash could conflict);
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/"];
18
+
19
+ function sh(...args: string[]): [string, number] {
20
+ const proc = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe" });
21
+ return [`${proc.stdout?.toString() ?? ""}${proc.stderr?.toString() ?? ""}`, proc.exitCode ?? 1];
22
+ }
23
+
24
+ function prdTitle(): string | null {
25
+ const [out, rc] = sh("head", "-1", `docs/specs/${FEATURE}/prd.md`);
26
+ if (rc !== 0) return null;
27
+ const line = out.trim();
28
+ return line.startsWith("# ") ? line.slice(2).trim() : null;
29
+ }
30
+
31
+ export default function finishBranch(_handoff: NodeResult, _info: DispatchInfo): NodeResult {
32
+ const branch = `feature/${FEATURE}`;
33
+
34
+ const [current, currentRc] = sh("git", "branch", "--show-current");
35
+ if (currentRc !== 0 || current.trim() !== branch) {
36
+ return {
37
+ event: "merge_failed",
38
+ output: { failure: `not on ${branch} (on '${current.trim()}')` },
39
+ };
40
+ }
41
+
42
+ const [status, statusRc] = sh("git", "status", "--porcelain");
43
+ if (statusRc !== 0) {
44
+ return { event: "merge_failed", output: { failure: "git status failed" } };
45
+ }
46
+ const dirty = status
47
+ .split("\n")
48
+ .map((l) => l.slice(3).trim())
49
+ .filter(Boolean);
50
+ const foreign = dirty.filter((p) => !ALLOWED.some((prefix) => p.startsWith(prefix)));
51
+ if (foreign.length > 0) {
52
+ return {
53
+ event: "merge_failed",
54
+ output: {
55
+ failure: `dirty paths outside the loop's surface — human decision:\n${foreign.join("\n")}`,
56
+ },
57
+ };
58
+ }
59
+
60
+ const title = prdTitle() ?? FEATURE;
61
+ const subject = `feat: ${title} (${FEATURE})`;
62
+ const add = sh("git", "add", "-A");
63
+ const commit = add[1] === 0 ? sh("git", "commit", "-m", subject) : [add[0], 1];
64
+ if (commit[1] !== 0) {
65
+ return {
66
+ event: "merge_failed",
67
+ output: { failure: `commit on ${branch} failed: ${commit[0]}` },
68
+ };
69
+ }
70
+
71
+ const [, ancestorRc] = sh("git", "merge-base", "--is-ancestor", "master", "HEAD");
72
+ if (ancestorRc !== 0) {
73
+ return {
74
+ event: "merge_failed",
75
+ output: {
76
+ failure:
77
+ "master has moved since the branch was cut — squash could conflict; human merge required",
78
+ },
79
+ };
80
+ }
81
+
82
+ const [ahead] = sh("git", "log", "--oneline", `master..${branch}`);
83
+ if (ahead.trim() === "") {
84
+ return { event: "merged", output: { note: "no commits ahead of master — nothing to merge" } };
85
+ }
86
+
87
+ const checkout = sh("git", "checkout", "master");
88
+ if (checkout[1] !== 0) {
89
+ return { event: "merge_failed", output: { failure: `checkout master failed: ${checkout[0]}` } };
90
+ }
91
+
92
+ const merge = sh("git", "merge", "--squash", branch);
93
+ if (merge[1] !== 0) {
94
+ sh("git", "reset", "--hard", "HEAD");
95
+ sh("git", "checkout", branch);
96
+ return { event: "merge_failed", output: { failure: `squash merge failed: ${merge[0]}` } };
97
+ }
98
+
99
+ const body =
100
+ "Landed via the dev-loop darkf workflow — check gate green, independent review approved.";
101
+ const final = sh("git", "commit", "-m", subject, "-m", body);
102
+ if (final[1] !== 0) {
103
+ sh("git", "reset", "--hard", "HEAD");
104
+ sh("git", "checkout", branch);
105
+ return { event: "merge_failed", output: { failure: `squash commit failed: ${final[0]}` } };
106
+ }
107
+
108
+ const del = sh("git", "branch", "-D", branch);
109
+ const note =
110
+ del[1] === 0
111
+ ? `squashed ${branch} to master as ${subject}; branch deleted`
112
+ : `merged as ${subject}; branch delete failed: ${del[0]}`;
113
+ return { event: "merged", output: { merged: true, note } };
114
+ }
@@ -0,0 +1,135 @@
1
+ import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
2
+ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
3
+
4
+ // dev-loop — begin → implement → check → review → finish(squash) → feedback.
5
+ //
6
+ // The darkf-on-darkf pilot, expanded after its first real run built the CLI
7
+ // self-update feature (docs/specs/self-update/). Shape ported from
8
+ // blueprint's build-backend: Begin cuts the feature branch, the composite
9
+ // bounds the implement/fix/review cycle, Finish squash-merges onto master
10
+ // with blueprint's rails, Feedback writes the run retrospective under
11
+ // darkf/feedback/.
12
+ //
13
+ // Run from the target repo root with a globally installed darkf (never the
14
+ // workspace symlink — doctor's selfRoot guard fails inside the checkout):
15
+ //
16
+ // bun run install:global # once, to refresh the global binary
17
+ // darkf doctor darkf/workflows/dev-loop
18
+ // darkf start darkf/workflows/dev-loop "message" --allow-dirty-workflow
19
+ //
20
+ // Editing the FEATURE / RUN_DATE constants at the top of the begin/finish
21
+ // scripts and this file's agent prompts is the per-feature contract until
22
+ // engine-side input plumbing exists. Resume is the fresh-run semantics: a
23
+ // second run on an already-implemented tree verifies and ships it (see the
24
+ // Implement prompt). No other git automation: the human curates what the
25
+ // workflow leaves behind (spec archive, roadmap entry, feedback note).
26
+ //
27
+ // The implementer, fixer, and reviewer are separate dispatches. Their only
28
+ // shared channels are the repo itself (files, git diff, the spec docs) and
29
+ // the one-hop handoff — matching PHILOSOPHY.md: nothing rides along for
30
+ // free.
31
+
32
+ export const agentRunner = opencodeRunner;
33
+
34
+ const MODEL = "zai-coding-plan/glm-5.3-flash";
35
+ const RUN_DATE = "2026-10-30";
36
+ const FEATURE = "self-update";
37
+
38
+ export const workflow: WorkflowDef = {
39
+ initial: "Begin",
40
+ states: {
41
+ Begin: {
42
+ type: "script",
43
+ file: "begin.ts",
44
+ retries: 1,
45
+ on: { started: "Loop", branch_failed: DONE },
46
+ },
47
+ Loop: {
48
+ 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,
53
+ states: {
54
+ Implement: {
55
+ type: "agent",
56
+ agent: { model: MODEL },
57
+ retries: 1,
58
+ prompt: `Implement the ${FEATURE} feature in this repository.
59
+
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.
61
+
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.
63
+
64
+ 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
+
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}/.
70
+
71
+ 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
+ on: { implemented: "Check", blocked: DONE, disputed: DONE },
73
+ },
74
+ Check: {
75
+ type: "script",
76
+ file: "check.ts",
77
+ retries: 1,
78
+ on: { passed: "Review", failed: "Fix" },
79
+ },
80
+ Fix: {
81
+ type: "agent",
82
+ agent: { model: MODEL },
83
+ retries: 1,
84
+ prompt: `You are repairing the ${FEATURE} implementation after a failed gate.
85
+
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/.
87
+
88
+ 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
+ on: { fixed: "Check", blocked: DONE, disputed: DONE },
90
+ },
91
+ Review: {
92
+ type: "agent",
93
+ agent: { model: MODEL },
94
+ retries: 1,
95
+ prompt: `You are an independent reviewer. Do not modify any files.
96
+
97
+ Verify the working tree against docs/specs/${FEATURE}/prd.md and docs/specs/${FEATURE}/design.md:
98
+ - 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.
104
+
105
+ Finish with event "approved" or event "changes_requested".`,
106
+ on: { approved: "Finish", changes_requested: "Fix" },
107
+ },
108
+ },
109
+ },
110
+ Finish: {
111
+ type: "script",
112
+ file: "finish.ts",
113
+ retries: 1,
114
+ on: { merged: "Feedback", merge_failed: DONE },
115
+ },
116
+ Feedback: {
117
+ type: "agent",
118
+ agent: { model: MODEL },
119
+ retries: 1,
120
+ prompt: `Write the run retrospective for the ${FEATURE} dev-loop run, in the style of a post-run feedback note.
121
+
122
+ Read the newest journal: the run directory under .darkf/run/ with the latest mtime, file journal.jsonl (one JSON event per line). Also run git log -3 --oneline to confirm the merge.
123
+
124
+ Write darkf/feedback/${RUN_DATE}-${FEATURE}.md with exactly this shape:
125
+ - a "# Run feedback — <title>" heading
126
+ - bullet fields: Date, Engine/workflow (darkf dev-loop), Run (the runId from the journal), Final outcome, Scopes (one line on what shipped)
127
+ - a "## What worked" section — factual bullets only
128
+ - a "## Failures and root causes" section — numbered, with cost where visible; write "none observed" if empty
129
+ - a "## Notes" section — anything the next run of this workflow should know
130
+
131
+ Do not modify any other file. Do not commit. Finish with event "recorded". If the journal is unreadable, finish with event "skipped".`,
132
+ on: { recorded: DONE, skipped: DONE },
133
+ },
134
+ },
135
+ };
@@ -0,0 +1,18 @@
1
+ // Verify: run the target repo's Gradle check suite. green → Review, red → Implement.
2
+ // rootDir (the invocation cwd) IS the target repo — no path hardcoding.
3
+ import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
4
+
5
+ export default function verify(_handoff: NodeResult, info: DispatchInfo): NodeResult {
6
+ const proc = Bun.spawnSync(["./gradlew", "check"], {
7
+ cwd: info.rootDir,
8
+ stdout: "pipe",
9
+ stderr: "pipe",
10
+ timeout: 1_200_000,
11
+ });
12
+ const tail = `${proc.stdout?.toString() ?? ""}\n${proc.stderr?.toString() ?? ""}`
13
+ .split("\n")
14
+ .slice(-120)
15
+ .join("\n");
16
+ if (proc.exitCode === 0) return { event: "green", output: { tail } };
17
+ return { event: "red", output: { exitCode: proc.exitCode, tail: tail.slice(-6000) } };
18
+ }
@@ -0,0 +1,80 @@
1
+ // series-ordering — dogfood workflow: implement + verify + review a bug
2
+ // fix in a Kotlin/JVM + Gradle repo (any repo you point it at; developed
3
+ // against a real chronological-ordering bug fix).
4
+ //
5
+ // Uses the built-in claude-code harness (handoff-file contract, session
6
+ // resume). rootDir — the agent's working directory and the run-artifact root —
7
+ // is the INVOCATION directory, so run from the repo you target:
8
+ // cd /path/to/your-gradle-repo
9
+ // darkf start <this dir> "<bug id>"
10
+ import { type AgentRunner, DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
11
+ import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
12
+
13
+ export const agentRunner: AgentRunner = claudeCodeRunner;
14
+
15
+ const IMPLEMENT_PROMPT = `You are implementing an approved, fully specified bug fix in the Kotlin/JVM + Gradle repo at your working directory.
16
+
17
+ If the working tree already contains a partial implementation (a previous attempt), verify and complete it instead of starting over.
18
+
19
+ Read both spec files first (paths relative to the repo root):
20
+ - docs/specs/_implemented/marketdata-series-chronological-order/prd.md (REQ-1..REQ-5, CON-1..CON-3)
21
+ - docs/specs/_implemented/marketdata-series-chronological-order/design.md (exact changes, code sketches, test plan)
22
+
23
+ Implement exactly the design, nothing more:
24
+ 1. MarketDataPort: add the ordering-contract KDoc (design has the wording).
25
+ 2. PostgresMarketDataAdapter: ORDER BY asset_id, date, market, currency (quotes); ORDER BY asset_id, date, type (corporate actions).
26
+ 3. MarketDataMapping: sort before groupBy — quotes compareBy(date, market, currency); corporate actions compareBy(date, type.wireName).
27
+ 4. Extend existing test classes only (design Testing Strategy):
28
+ - MarketDataMappingTest: shuffled rows read back ascending; equal-date tiebreak cases (quotes and corporate actions).
29
+ - PostgresMarketDataAdapterTest: seed rows in reverse date order, read ascending, read twice identical (DatabaseIntegrationTestBase).
30
+ - ComputePipelineIntegrationTest: multi-date data via its FakeLoaders, pipeline run twice with differently-constructed but ascending list instances, identical nav/marketValue/twr. The test's inputs must both honor the port contract (ascending); do not import marketdata's adapter.outbound.database internals.
31
+
32
+ Then run ./gradlew check from the repo root; it must pass. If Docker (Testcontainers) is unavailable, run ./gradlew test instead and say so in your report.
33
+
34
+ Rules: touch only the files the design names; no new files; do NOT commit or stage anything; no code comments.
35
+
36
+ If a review demand contradicts the spec (prd.md/design.md) or would make a test unable to fail, do NOT silently comply — object. Write your result with event "disputed", the demand you reject, and your spec-grounded rationale in output.
37
+
38
+ Write your result per the handoff instructions: event "implemented" (done and check green), "blocked" (cannot proceed — reason in output), or "disputed" (review demand contradicts the spec — demand + rationale in output).`;
39
+
40
+ const REVIEW_PROMPT = `You are reviewing an implementation in the repo at your working directory.
41
+
42
+ Spec: docs/specs/_implemented/marketdata-series-chronological-order/prd.md and design.md.
43
+
44
+ Inspect EVERYTHING in the working tree: git diff for tracked files AND git status --porcelain for untracked files — an earlier review missed agent-authored extra files because git diff alone does not show them. Nothing beyond the six files the design names may exist as part of this change.
45
+
46
+ Check:
47
+ 1. Every REQ-1..REQ-5 in prd.md is implemented and backed by a test that can actually fail if the production fix is reverted.
48
+ 2. The diff matches the design change list exactly — no scope creep, no unrelated edits, no extra files.
49
+ 3. Constraints hold: no REST wire-shape change (CON-1), no schema change (CON-2), no module-boundary violations (CON-3).
50
+
51
+ Write your result per the handoff instructions: event "done" if it matches the spec, or "changes_requested" with a numbered list of concrete fixes in output.`;
52
+
53
+ export const workflow: WorkflowDef = {
54
+ initial: "Fix",
55
+ states: {
56
+ Fix: {
57
+ initial: "Implement",
58
+ maxCycles: 8,
59
+ states: {
60
+ Implement: {
61
+ type: "agent",
62
+ retries: 1,
63
+ prompt: IMPLEMENT_PROMPT,
64
+ on: { implemented: "Verify", blocked: DONE, disputed: DONE },
65
+ },
66
+ Verify: {
67
+ type: "script",
68
+ file: "verify.ts",
69
+ on: { green: "Review", red: "Implement" },
70
+ },
71
+ },
72
+ },
73
+ Review: {
74
+ type: "agent",
75
+ retries: 1,
76
+ prompt: REVIEW_PROMPT,
77
+ on: { done: DONE, changes_requested: "Implement" },
78
+ },
79
+ },
80
+ };