@psimona/darkf 0.3.0 → 0.5.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.
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 {
@@ -107,6 +115,39 @@ export function foldJournal(journalText: string): JournalDigest {
107
115
  return digest;
108
116
  }
109
117
 
118
+ // --- task lists (docs/specs/task-list-json/spec.md) ---
119
+
120
+ export interface TaskListDigest {
121
+ /** Strict count: only `done` tasks — pending, in-progress, and failed all
122
+ * count as not-done, so the plugin's `nn/mm` tab title is honest. */
123
+ done: number;
124
+ total: number;
125
+ /** The task the file says the run is on — its `in-progress` status is
126
+ * authoritative (no journal join); `null` when nothing is in-progress. */
127
+ current: Task | null;
128
+ /** Non-null only when the list is incoherent about "where the run is":
129
+ * more than one task in-progress. A `TaskList` carries no timestamps, so
130
+ * a time-based stall isn't derivable here — staleness of the current row
131
+ * stays covered by the workflow view's own stall warning. */
132
+ stall: string | null;
133
+ }
134
+
135
+ // Pure fold over a parsed TaskList for rendering: done/total counts, the
136
+ // current in-progress item, and stall state. Never throws — input is an
137
+ // already-narrowed TaskList (see `parseTaskList`).
138
+ export function foldTaskList(list: TaskList): TaskListDigest {
139
+ const inProgress = list.tasks.filter((t) => t.status === "in-progress");
140
+ return {
141
+ done: list.tasks.filter((t) => t.status === "done").length,
142
+ total: list.tasks.length,
143
+ current: inProgress[0] ?? null,
144
+ stall:
145
+ inProgress.length > 1
146
+ ? `${inProgress.length} tasks in-progress — expected one; the list's current position is ambiguous`
147
+ : null,
148
+ };
149
+ }
150
+
110
151
  export type TerminalState =
111
152
  | "succeeded"
112
153
  | "failed"
@@ -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 = "task-list-json";
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,122 @@
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 = "task-list-json";
17
+ const ALLOWED = [
18
+ "docs/",
19
+ "darkf/src/",
20
+ "darkf-opencode-plugin/",
21
+ "ROADMAP.md",
22
+ "README.md",
23
+ "site/",
24
+ "darkf/workflows/",
25
+ ];
26
+
27
+ function sh(...args: string[]): [string, number] {
28
+ const proc = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe" });
29
+ return [`${proc.stdout?.toString() ?? ""}${proc.stderr?.toString() ?? ""}`, proc.exitCode ?? 1];
30
+ }
31
+
32
+ function prdTitle(): string | null {
33
+ const [out, rc] = sh("head", "-1", `docs/specs/${FEATURE}/prd.md`);
34
+ if (rc !== 0) return null;
35
+ const line = out.trim();
36
+ return line.startsWith("# ") ? line.slice(2).trim() : null;
37
+ }
38
+
39
+ export default function finishBranch(_handoff: NodeResult, _info: DispatchInfo): NodeResult {
40
+ const branch = `feature/${FEATURE}`;
41
+
42
+ const [current, currentRc] = sh("git", "branch", "--show-current");
43
+ if (currentRc !== 0 || current.trim() !== branch) {
44
+ return {
45
+ event: "merge_failed",
46
+ output: { failure: `not on ${branch} (on '${current.trim()}')` },
47
+ };
48
+ }
49
+
50
+ const [status, statusRc] = sh("git", "status", "--porcelain");
51
+ if (statusRc !== 0) {
52
+ return { event: "merge_failed", output: { failure: "git status failed" } };
53
+ }
54
+ const dirty = status
55
+ .split("\n")
56
+ .map((l) => l.slice(3).trim())
57
+ .filter(Boolean);
58
+ const foreign = dirty.filter((p) => !ALLOWED.some((prefix) => p.startsWith(prefix)));
59
+ if (foreign.length > 0) {
60
+ return {
61
+ event: "merge_failed",
62
+ output: {
63
+ failure: `dirty paths outside the loop's surface — human decision:\n${foreign.join("\n")}`,
64
+ },
65
+ };
66
+ }
67
+
68
+ const title = prdTitle() ?? FEATURE;
69
+ const subject = `feat: ${title} (${FEATURE})`;
70
+ const add = sh("git", "add", "-A");
71
+ const commit = add[1] === 0 ? sh("git", "commit", "-m", subject) : [add[0], 1];
72
+ if (commit[1] !== 0) {
73
+ return {
74
+ event: "merge_failed",
75
+ output: { failure: `commit on ${branch} failed: ${commit[0]}` },
76
+ };
77
+ }
78
+
79
+ const [, ancestorRc] = sh("git", "merge-base", "--is-ancestor", "master", "HEAD");
80
+ if (ancestorRc !== 0) {
81
+ return {
82
+ event: "merge_failed",
83
+ output: {
84
+ failure:
85
+ "master has moved since the branch was cut — squash could conflict; human merge required",
86
+ },
87
+ };
88
+ }
89
+
90
+ const [ahead] = sh("git", "log", "--oneline", `master..${branch}`);
91
+ if (ahead.trim() === "") {
92
+ return { event: "merged", output: { note: "no commits ahead of master — nothing to merge" } };
93
+ }
94
+
95
+ const checkout = sh("git", "checkout", "master");
96
+ if (checkout[1] !== 0) {
97
+ return { event: "merge_failed", output: { failure: `checkout master failed: ${checkout[0]}` } };
98
+ }
99
+
100
+ const merge = sh("git", "merge", "--squash", branch);
101
+ if (merge[1] !== 0) {
102
+ sh("git", "reset", "--hard", "HEAD");
103
+ sh("git", "checkout", branch);
104
+ return { event: "merge_failed", output: { failure: `squash merge failed: ${merge[0]}` } };
105
+ }
106
+
107
+ const body =
108
+ "Landed via the dev-loop darkf workflow — check gate green, independent review approved.";
109
+ const final = sh("git", "commit", "-m", subject, "-m", body);
110
+ if (final[1] !== 0) {
111
+ sh("git", "reset", "--hard", "HEAD");
112
+ sh("git", "checkout", branch);
113
+ return { event: "merge_failed", output: { failure: `squash commit failed: ${final[0]}` } };
114
+ }
115
+
116
+ const del = sh("git", "branch", "-D", branch);
117
+ const note =
118
+ del[1] === 0
119
+ ? `squashed ${branch} to master as ${subject}; branch deleted`
120
+ : `merged as ${subject}; branch delete failed: ${del[0]}`;
121
+ return { event: "merged", output: { merged: true, note } };
122
+ }
@@ -0,0 +1,158 @@
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 → document → finish(squash) →
5
+ // feedback.
6
+ //
7
+ // The darkf-on-darkf pilot, expanded after its first real run built the CLI
8
+ // self-update feature (docs/specs/self-update/). Shape ported from
9
+ // blueprint's build-backend: Begin cuts the feature branch, the composite
10
+ // bounds the implement/fix/review cycle, Finish squash-merges onto master
11
+ // with blueprint's rails, Feedback writes the run retrospective under
12
+ // darkf/feedback/.
13
+ //
14
+ // Run from the target repo root with a globally installed darkf (never the
15
+ // workspace symlink — doctor's selfRoot guard fails inside the checkout):
16
+ //
17
+ // bun run install:global # once, to refresh the global binary
18
+ // darkf doctor darkf/workflows/dev-loop
19
+ // darkf start darkf/workflows/dev-loop "message" --allow-dirty-workflow
20
+ //
21
+ // Editing the FEATURE / RUN_DATE constants at the top of the begin/finish
22
+ // scripts and this file's agent prompts is the per-feature contract until
23
+ // engine-side input plumbing exists. Resume is the fresh-run semantics: a
24
+ // second run on an already-implemented tree verifies and ships it (see the
25
+ // Implement prompt). No other git automation: the human curates what the
26
+ // workflow leaves behind (spec archive, roadmap entry, feedback note).
27
+ //
28
+ // The implementer, fixer, reviewer, and documenter are separate dispatches.
29
+ // Their only
30
+ // shared channels are the repo itself (files, git diff, the spec docs) and
31
+ // the one-hop handoff — matching PHILOSOPHY.md: nothing rides along for
32
+ // free.
33
+
34
+ export const agentRunner = opencodeRunner;
35
+
36
+ const MODEL = "zai-coding-plan/glm-5.3-flash";
37
+ const RUN_DATE = "2026-10-31";
38
+ const FEATURE = "task-list-json";
39
+
40
+ export const workflow: WorkflowDef = {
41
+ initial: "Begin",
42
+ states: {
43
+ Begin: {
44
+ type: "script",
45
+ file: "begin.ts",
46
+ retries: 1,
47
+ on: { started: "Loop", branch_failed: DONE },
48
+ },
49
+ Loop: {
50
+ initial: "Implement",
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,
56
+ states: {
57
+ Implement: {
58
+ type: "agent",
59
+ agent: { model: MODEL },
60
+ retries: 1,
61
+ prompt: `Implement the ${FEATURE} feature in this repository.
62
+
63
+ First read docs/specs/${FEATURE}/spec.md. It is the contract: its Design sketch and both Decisions sections are locked — implement exactly what they specify, nothing more.
64
+
65
+ Resume semantics: if the working tree already implements the spec, verify that instead of re-implementing — read the existing darkf/src/core/tasks.ts and darkf-opencode-plugin/src/digest.ts, confirm they match the spec, and finish "implemented" without rewriting.
66
+
67
+ Deliverables (when not already present):
68
+ - the TaskList type family in darkf/src/core/types.ts per the spec's Design sketch (TaskStatus, TaskPriority, Task, TaskRequirement, TaskList), re-exported from darkf/src/core/index.ts
69
+ - parseTaskList in darkf/src/core/tasks.ts: hand-written, zero-dependency, narrowing unknown JSON to TaskList | { error } (Decisions: Validation)
70
+ - foldTaskList alongside foldJournal in darkf/src/kit/status.ts: a pure function returning done/total counts, the current in-progress item, and stall state
71
+ - the plugin (darkf-opencode-plugin/src/): TaskListView in digest.ts; store.ts reads .darkf/run/<runId>/tasks.json on the existing poll with an fs.watch next to the journal watcher; overlay.tsx grows a tab bar — tab "workflow" (today's PlanGraph, unchanged, the default) and tab "tasks nn/mm" (strict done/total in the title, hidden while tasks.json is absent, "?" counter plus the inline parse error when invalid); task rows per the plugin Decisions (glyph + id + title, "!" before the title for must priority, the active row's dim "↳ REQ-…" satisfies line, ○ pending / ● in-progress accent bold / ✓ done dim / ✗ failed error); keys "1"/"2" and clicking a tab title switch tabs; the supervisor pane stays below, shared by both tabs
72
+ - tests: parseTaskList narrowing cases (valid list, missing/wrong-typed fields, bad status and priority unions, tasks not an array), foldTaskList counts/current/stall, and the TaskListView digest in darkf-opencode-plugin/src/digest.test.ts
73
+
74
+ Follow the existing code style of darkf/src/kit/status.ts and darkf-opencode-plugin/src/. Do not commit. Do not touch files outside darkf/src/, darkf-opencode-plugin/src/, and docs/specs/${FEATURE}/.
75
+
76
+ 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.`,
77
+ on: { implemented: "Check", blocked: DONE, disputed: DONE },
78
+ },
79
+ Check: {
80
+ type: "script",
81
+ file: "check.ts",
82
+ retries: 1,
83
+ on: { passed: "Review", failed: "Fix" },
84
+ },
85
+ Fix: {
86
+ type: "agent",
87
+ agent: { model: MODEL },
88
+ retries: 1,
89
+ prompt: `You are repairing the ${FEATURE} implementation after a failed gate.
90
+
91
+ 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/ and darkf-opencode-plugin/src/.
92
+
93
+ 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.`,
94
+ on: { fixed: "Check", blocked: DONE, disputed: DONE },
95
+ },
96
+ Review: {
97
+ type: "agent",
98
+ agent: { model: MODEL },
99
+ retries: 1,
100
+ prompt: `You are an independent reviewer. Do not modify any files.
101
+
102
+ Verify the working tree against docs/specs/${FEATURE}/spec.md:
103
+ - inspect git status --porcelain in addition to git diff — agent-authored new files are invisible to git diff alone
104
+ - check the types match the spec's Design sketch field for field, and that both Decisions sections are each reflected in code (parseTaskList zero-dep narrowing; tasks.json read from .darkf/run/<runId>/; satisfies + lowercase MoSCoW; row format, glyph mapping, strict done/total counter, hidden-when-absent tab, file-status active row)
105
+ - check the test suites cover the spec: parseTaskList narrowing, foldTaskList, and the TaskListView digest
106
+ - you may run "bun test darkf/src/core darkf/src/kit darkf-opencode-plugin/src" yourself
107
+
108
+ Approve only if the implementation fulfills the spec. Otherwise list every required change concretely in the output.
109
+
110
+ Finish with event "approved" or event "changes_requested".`,
111
+ on: { approved: "Document", changes_requested: "Fix" },
112
+ },
113
+ Document: {
114
+ type: "agent",
115
+ agent: { model: MODEL },
116
+ retries: 1,
117
+ prompt: `You are updating user-facing documentation for the ${FEATURE} feature, after an independent review approved the implementation. Do not modify code or tests.
118
+
119
+ 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.
120
+
121
+ Update only what the feature's user-facing surface touches:
122
+ - README.md — CLI flags/commands, plugin behavior, setup steps that changed
123
+ - docs-site pages under site/src/content/docs/ — the affected guide or reference page; add a short new guide only for a genuinely user-visible capability
124
+ - cross-references in docs/ that now point at moved or renamed paths
125
+
126
+ 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/.
127
+
128
+ If nothing user-facing changed, or the docs need no edit, 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.`,
129
+ on: { documented: "Finish", skipped: "Finish", blocked: DONE },
130
+ },
131
+ },
132
+ },
133
+ Finish: {
134
+ type: "script",
135
+ file: "finish.ts",
136
+ retries: 1,
137
+ on: { merged: "Feedback", merge_failed: DONE },
138
+ },
139
+ Feedback: {
140
+ type: "agent",
141
+ agent: { model: MODEL },
142
+ retries: 1,
143
+ prompt: `Write the run retrospective for the ${FEATURE} dev-loop run, in the style of a post-run feedback note.
144
+
145
+ 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.
146
+
147
+ Write darkf/feedback/${RUN_DATE}-${FEATURE}.md with exactly this shape:
148
+ - a "# Run feedback — <title>" heading
149
+ - bullet fields: Date, Engine/workflow (darkf dev-loop), Run (the runId from the journal), Final outcome, Scopes (one line on what shipped)
150
+ - a "## What worked" section — factual bullets only
151
+ - a "## Failures and root causes" section — numbered, with cost where visible; write "none observed" if empty
152
+ - a "## Notes" section — anything the next run of this workflow should know
153
+
154
+ Do not modify any other file. Do not commit. Finish with event "recorded". If the journal is unreadable, finish with event "skipped".`,
155
+ on: { recorded: DONE, skipped: DONE },
156
+ },
157
+ },
158
+ };
@@ -1,4 +1,4 @@
1
- // Verify: run the blueprint Gradle check suite. green → Review, red → Implement.
1
+ // Verify: run the target repo's Gradle check suite. green → Review, red → Implement.
2
2
  // rootDir (the invocation cwd) IS the target repo — no path hardcoding.
3
3
  import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
4
4
 
@@ -1,11 +1,12 @@
1
- // series-ordering — dogfood workflow: implement + verify + review the
2
- // `marketdata-series-chronological-order` bug fix in the blueprint repo.
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).
3
4
  //
4
5
  // Uses the built-in claude-code harness (handoff-file contract, session
5
6
  // resume). rootDir — the agent's working directory and the run-artifact root —
6
7
  // is the INVOCATION directory, so run from the repo you target:
7
- // cd /path/to/blueprint
8
- // darkf start <this dir> "marketdata-series-chronological-order"
8
+ // cd /path/to/your-gradle-repo
9
+ // darkf start <this dir> "<bug id>"
9
10
  import { type AgentRunner, DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
10
11
  import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
11
12