@psimona/darkf 0.3.0 → 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.
@@ -0,0 +1,29 @@
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@psimona/darkf",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "A small, typed workflow engine for agent + script state graphs.",
5
5
  "license": "MIT",
6
6
  "author": "Patrizio Simona <patriziosimona@gmail.com>",
@@ -61,6 +61,9 @@ async function runCli(
61
61
  cwd,
62
62
  stdout: "pipe",
63
63
  stderr: "pipe",
64
+ // Self-update gate: real-CLI spawns stay off the network and notice-free
65
+ // (no stdio changes to parse around), per the suite's no-network doctrine.
66
+ env: { ...process.env, DARKF_NO_UPDATE_CHECK: "1" },
64
67
  });
65
68
  const [stdout, stderr, code] = await Promise.all([
66
69
  new Response(proc.stdout).text(),
package/src/cli/index.ts CHANGED
@@ -4,6 +4,7 @@ import { closeSync, existsSync, openSync, readdirSync, readFileSync } from "node
4
4
  import { mkdir, writeFile } from "node:fs/promises";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import packageJson from "../../package.json";
7
8
  import {
8
9
  type AgentRunner,
9
10
  buildRegistry,
@@ -47,6 +48,7 @@ import {
47
48
  stallWarning,
48
49
  type TerminalState,
49
50
  } from "../kit/status.ts";
51
+ import { type UpdateDeps, updateGate, upgradeCmd } from "./update.ts";
50
52
 
51
53
  const INDEX_PATH = fileURLToPath(import.meta.url);
52
54
  // Fixed, not yet measured against a cold `bun` import on real hosts — see
@@ -342,7 +344,7 @@ function parseRunArgs(args: string[]): {
342
344
 
343
345
  // Start-time config guard (registry-lifecycle, lesson-2 companion): a
344
346
  // workflow config edit left uncommitted *will* be swept into a run commit or
345
- // reset away by the run itself — blueprint lost config edits both ways.
347
+ // reset away by the run itself — a consumer repo lost config edits both ways.
346
348
  // Scoped to the bare `darkf/` directory — the user/consumer-repo convention
347
349
  // for versioned workflow config — never `.darkf` (dot-prefixed), which is
348
350
  // darkf's own runtime/run-storage directory (registry, journals, this very
@@ -438,7 +440,7 @@ async function runCmd(dir: string, message?: string): Promise<void> {
438
440
  if (result.node.phase === "succeeded" || result.node.phase === "failed") {
439
441
  console.log("output:", result.node.result.output);
440
442
  }
441
- console.log(`journal: ${resolve(dir, ".darkf", "run", result.runId, "journal.jsonl")}`);
443
+ console.log(`journal: ${join(rootDir, ".darkf", "run", result.runId, "journal.jsonl")}`);
442
444
 
443
445
  const lastState = result.trace.at(-1)?.state;
444
446
  if (lastState) {
@@ -786,7 +788,7 @@ function isHeartbeatEvent(events: NodeEvent[], index: number): boolean {
786
788
 
787
789
  // Dwell hint (P2): flag an open dispatch whose elapsed time exceeds 3× the
788
790
  // median of that node's completed visits (floor 2 min) — the supervisor's
789
- // cue to inspect or `steer`, printed once per visit. Blueprint E8.5b: a
791
+ // cue to inspect or `steer`, printed once per visit. An unattended run: a
790
792
  // GREEN agent thrashed for 35 minutes before anyone looked; a hint at
791
793
  // minute 10 would have surfaced it. Purely advisory — never exits.
792
794
  function dwellHint(events: NodeEvent[], runId: string, hinted: Set<string>): void {
@@ -964,9 +966,35 @@ async function monitorCmd(args: string[]): Promise<number> {
964
966
  }
965
967
  }
966
968
 
969
+ // Per-install state location for the self-update feature (self-update D-2):
970
+ // XDG state semantics, not `.darkf/` (NG-5 — nothing per-project). The first
971
+ // candidate whose defining environment variable exists wins; tests point
972
+ // elsewhere by injecting `stateFile` through UpdateDeps.
973
+ function updateStateFile(): string {
974
+ const xdg = process.env.XDG_STATE_HOME;
975
+ if (xdg) return join(xdg, "darkf", "last-update-check.json");
976
+ return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-update-check.json");
977
+ }
978
+
967
979
  async function main(): Promise<void> {
968
980
  const [cmd, ...rest] = process.argv.slice(2);
969
981
 
982
+ // Self-update gate (REQ-1..REQ-5, REQ-11): runs before every dispatch, so
983
+ // its notice is the first line of stdout (NFR-3). The gate itself skips
984
+ // `upgrade`, which fetches on its own. Silent by contract (REQ-4).
985
+ const updateDeps: UpdateDeps = {
986
+ now: () => Date.now(),
987
+ fetchImpl: fetch,
988
+ spawnImpl: Bun.spawnSync,
989
+ stateFile: updateStateFile(),
990
+ installed: packageJson.version,
991
+ };
992
+ await updateGate(cmd, updateDeps);
993
+
994
+ if (cmd === "upgrade") {
995
+ process.exit(await upgradeCmd(updateDeps));
996
+ return;
997
+ }
970
998
  if (cmd === "workflows") {
971
999
  workflowsCmd();
972
1000
  return;
@@ -0,0 +1,486 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import {
6
+ checkRegistry,
7
+ isDue,
8
+ isNewer,
9
+ readState,
10
+ type UpdateDeps,
11
+ updateGate,
12
+ upgradeCmd,
13
+ writeState,
14
+ } from "./update.ts";
15
+
16
+ // --- fixtures: injectable clock, fetch, spawner, temp state file ---
17
+
18
+ const NOW = 1_793_000_000_000; // fixed epoch ms; every test's "today"
19
+ const INSTALLED = "0.3.0";
20
+ const HOUR_MS = 60 * 60 * 1000;
21
+
22
+ const roots: string[] = [];
23
+ afterAll(() => {
24
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
25
+ });
26
+
27
+ function tempDir(): string {
28
+ const dir = mkdtempSync(join(tmpdir(), "darkf-update-"));
29
+ roots.push(dir);
30
+ return dir;
31
+ }
32
+
33
+ function tempStateFile(): string {
34
+ // Parent deliberately absent — writeState must mkdir -p it.
35
+ return join(tempDir(), "state", "darkf", "last-update-check.json");
36
+ }
37
+
38
+ function seedState(file: string, state: object): void {
39
+ mkdirSync(dirname(file), { recursive: true });
40
+ writeFileSync(file, JSON.stringify(state));
41
+ }
42
+
43
+ function rawFile(file: string): string | null {
44
+ try {
45
+ return readFileSync(file, "utf8");
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ function deps(overrides: Partial<UpdateDeps> = {}): UpdateDeps {
52
+ return {
53
+ now: () => NOW,
54
+ fetchImpl: (async () => {
55
+ throw new Error("unexpected registry access");
56
+ }) as unknown as typeof fetch,
57
+ spawnImpl: (() => {
58
+ throw new Error("unexpected spawn");
59
+ }) as unknown as typeof Bun.spawnSync,
60
+ stateFile: tempStateFile(),
61
+ installed: INSTALLED,
62
+ ...overrides,
63
+ };
64
+ }
65
+
66
+ /** 200-with-body fetch unless a status is given; records the requested URLs. */
67
+ function fetchReturning(body: string, status = 200): { fetchImpl: typeof fetch; urls: string[] } {
68
+ const urls: string[] = [];
69
+ const fetchImpl = (async (input: unknown) => {
70
+ urls.push(String(input));
71
+ return new Response(body, { status });
72
+ }) as unknown as typeof fetch;
73
+ return { fetchImpl, urls };
74
+ }
75
+
76
+ function fetchCounting(
77
+ body: string,
78
+ status = 200,
79
+ ): { fetchImpl: typeof fetch; count: () => number } {
80
+ let calls = 0;
81
+ const fetchImpl = (async () => {
82
+ calls += 1;
83
+ return new Response(body, { status });
84
+ }) as unknown as typeof fetch;
85
+ return { fetchImpl, count: () => calls };
86
+ }
87
+
88
+ /** Hangs until the caller's AbortSignal fires — honors the signal like real fetch. */
89
+ const hangingFetch = ((_input: unknown, init?: RequestInit) =>
90
+ new Promise<Response>((_resolve, reject) => {
91
+ const signal = init?.signal;
92
+ signal?.addEventListener("abort", () => reject(signal.reason));
93
+ })) as typeof fetch;
94
+
95
+ interface SpawnReply {
96
+ exitCode: number;
97
+ stdout?: string;
98
+ }
99
+
100
+ /** Scripted spawnSync: the reply fn answers each command; unscripted ones throw. */
101
+ function spawnStub(script: (cmd: string[]) => SpawnReply | undefined): {
102
+ spawnImpl: typeof Bun.spawnSync;
103
+ calls: string[][];
104
+ } {
105
+ const calls: string[][] = [];
106
+ const spawnImpl = ((cmd: unknown, _opts?: unknown) => {
107
+ const argv = [...(cmd as string[])];
108
+ calls.push(argv);
109
+ const reply = script(argv);
110
+ if (!reply) throw new Error(`unexpected spawn: ${argv.join(" ")}`);
111
+ return {
112
+ exitCode: reply.exitCode,
113
+ success: reply.exitCode === 0,
114
+ stdout: Buffer.from(reply.stdout ?? ""),
115
+ stderr: Buffer.from(""),
116
+ };
117
+ }) as unknown as typeof Bun.spawnSync;
118
+ return { spawnImpl, calls };
119
+ }
120
+
121
+ async function captured<T>(fn: () => Promise<T> | T): Promise<{
122
+ result: T;
123
+ out: string[];
124
+ err: string[];
125
+ }> {
126
+ const out: string[] = [];
127
+ const err: string[] = [];
128
+ const { log, error } = console;
129
+ console.log = (...args: unknown[]) => void out.push(args.map(String).join(" "));
130
+ console.error = (...args: unknown[]) => void err.push(args.map(String).join(" "));
131
+ try {
132
+ return { result: await fn(), out, err };
133
+ } finally {
134
+ console.log = log;
135
+ console.error = error;
136
+ }
137
+ }
138
+
139
+ async function withOptOut<T>(fn: () => Promise<T> | T): Promise<T> {
140
+ const prev = process.env.DARKF_NO_UPDATE_CHECK;
141
+ process.env.DARKF_NO_UPDATE_CHECK = "1";
142
+ try {
143
+ return await fn();
144
+ } finally {
145
+ if (prev === undefined) delete process.env.DARKF_NO_UPDATE_CHECK;
146
+ else process.env.DARKF_NO_UPDATE_CHECK = prev;
147
+ }
148
+ }
149
+
150
+ // --- comparison and due-ness ---
151
+
152
+ test("isNewer: older, equal, newer, prerelease", () => {
153
+ expect(isNewer("0.3.0", "0.4.0")).toBe(true);
154
+ expect(isNewer("0.3.0", "0.3.0")).toBe(false);
155
+ expect(isNewer("0.4.0", "0.3.0")).toBe(false);
156
+ expect(isNewer("0.3.0", "0.4.0-beta.1")).toBe(true);
157
+ });
158
+
159
+ test("isDue: missing, corrupt, fresh, and the 24h boundary", () => {
160
+ expect(isDue({}, NOW)).toBe(true);
161
+ expect(isDue({ lastCheck: "not a timestamp" }, NOW)).toBe(true);
162
+ expect(isDue({ lastCheck: new Date(NOW - 23 * HOUR_MS).toISOString() }, NOW)).toBe(false);
163
+ // Data model: now - lastCheck >= 24h — exactly one day is due again.
164
+ expect(isDue({ lastCheck: new Date(NOW - 24 * HOUR_MS).toISOString() }, NOW)).toBe(true);
165
+ expect(isDue({ lastCheck: new Date(NOW - 24 * HOUR_MS + 1000).toISOString() }, NOW)).toBe(false);
166
+ });
167
+
168
+ // --- state file ---
169
+
170
+ test("readState: absent, corrupt, and wrong-shaped files all read as empty", () => {
171
+ expect(readState(join(tempDir(), "does-not-exist.json"))).toEqual({});
172
+ const dir = tempDir();
173
+ const corrupt = join(dir, "state.json");
174
+ writeFileSync(corrupt, "{not json");
175
+ expect(readState(corrupt)).toEqual({});
176
+ const array = join(dir, "array.json");
177
+ writeFileSync(array, "[1,2,3]");
178
+ expect(readState(array)).toEqual({});
179
+ const wrongTypes = join(dir, "types.json");
180
+ writeFileSync(wrongTypes, JSON.stringify({ lastCheck: 5, latestSeen: true }));
181
+ expect(readState(wrongTypes)).toEqual({});
182
+ });
183
+
184
+ test("writeState round-trips and creates missing parent directories", () => {
185
+ const file = tempStateFile();
186
+ writeState(file, { lastCheck: "2026-10-30T08:00:00.000Z", latestSeen: "0.4.0" });
187
+ expect(readState(file)).toEqual({
188
+ lastCheck: "2026-10-30T08:00:00.000Z",
189
+ latestSeen: "0.4.0",
190
+ });
191
+ });
192
+
193
+ test("writeState swallows an unwritable location (REQ-4)", () => {
194
+ const dir = tempDir();
195
+ const blocker = join(dir, "blocker");
196
+ writeFileSync(blocker, "a file, not a directory");
197
+ expect(() => writeState(join(blocker, "darkf", "state.json"), {})).not.toThrow();
198
+ });
199
+
200
+ // --- checkRegistry ---
201
+
202
+ test("checkRegistry: 200 with a semver-shaped latest returns it, at the pinned endpoint", async () => {
203
+ const { fetchImpl, urls } = fetchReturning('{"latest":"0.4.0","next":"0.5.0-rc.1"}');
204
+ expect(await checkRegistry(fetchImpl)).toBe("0.4.0");
205
+ expect(urls).toEqual(["https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags"]);
206
+ });
207
+
208
+ test("checkRegistry: non-200, malformed JSON, and non-semver latest all return null", async () => {
209
+ expect(await checkRegistry(fetchReturning('{"latest":"9.9.9"}', 503).fetchImpl)).toBeNull();
210
+ expect(await checkRegistry(fetchReturning("not json at all").fetchImpl)).toBeNull();
211
+ expect(await checkRegistry(fetchReturning('{"latest":"banana"}').fetchImpl)).toBeNull();
212
+ expect(await checkRegistry(fetchReturning('{"latest":123}').fetchImpl)).toBeNull();
213
+ expect(await checkRegistry(fetchReturning("{}").fetchImpl)).toBeNull();
214
+ });
215
+
216
+ test("checkRegistry: a fetch that rejects (no network) returns null, never throws", async () => {
217
+ const rejecting = (async () => {
218
+ throw new TypeError("fetch failed");
219
+ }) as unknown as typeof fetch;
220
+ expect(await checkRegistry(rejecting)).toBeNull();
221
+ });
222
+
223
+ test("checkRegistry: a hanging request returns null at the 2s abort (NFR-1)", async () => {
224
+ const start = Date.now();
225
+ expect(await checkRegistry(hangingFetch)).toBeNull();
226
+ expect(Date.now() - start).toBeGreaterThanOrEqual(1900);
227
+ });
228
+
229
+ // --- startup gate ---
230
+
231
+ test("gate on a due day: one request, stamped, newer latestSeen recorded, one notice line", async () => {
232
+ const file = tempStateFile();
233
+ const { fetchImpl, urls } = fetchReturning('{"latest":"9.9.9"}');
234
+ const { out, err } = await captured(() =>
235
+ updateGate("status", deps({ stateFile: file, fetchImpl })),
236
+ );
237
+
238
+ expect(urls).toEqual(["https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags"]);
239
+ expect(out).toEqual([`darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`]);
240
+ expect(err).toEqual([]);
241
+ expect(readState(file)).toEqual({
242
+ lastCheck: new Date(NOW).toISOString(),
243
+ latestSeen: "9.9.9",
244
+ });
245
+ });
246
+
247
+ test("gate same-day re-run: no request, notice still printed from the record (REQ-2, REQ-11)", async () => {
248
+ const file = tempStateFile();
249
+ const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
250
+ await captured(() => updateGate("run", deps({ stateFile: file, fetchImpl })));
251
+ expect(count()).toBe(1);
252
+
253
+ const later = await captured(() =>
254
+ updateGate("run", deps({ stateFile: file, fetchImpl, now: () => NOW + 3 * HOUR_MS })),
255
+ );
256
+ expect(count()).toBe(1); // no second request within 24 h
257
+ expect(later.out).toEqual([
258
+ `darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`,
259
+ ]);
260
+ });
261
+
262
+ test("gate: a failed check still stamps and prints nothing (REQ-2, REQ-4)", async () => {
263
+ const file = tempStateFile();
264
+ const { out, err } = await captured(() => updateGate("status", deps({ stateFile: file })));
265
+
266
+ expect(out).toEqual([]);
267
+ expect(err).toEqual([]);
268
+ expect(readState(file)).toEqual({ lastCheck: new Date(NOW).toISOString() });
269
+ });
270
+
271
+ test("gate: a stale notice survives a failed check (REQ-11)", async () => {
272
+ const file = tempStateFile();
273
+ seedState(file, { lastCheck: new Date(NOW - 48 * HOUR_MS).toISOString(), latestSeen: "9.9.9" });
274
+
275
+ const { out } = await captured(() => updateGate("status", deps({ stateFile: file })));
276
+
277
+ expect(out).toEqual([`darkf 9.9.9 available (installed ${INSTALLED}) — run 'darkf upgrade'`]);
278
+ expect(readState(file)).toEqual({
279
+ lastCheck: new Date(NOW).toISOString(), // restamped by the failed attempt
280
+ latestSeen: "9.9.9", // untouched by the null result
281
+ });
282
+ });
283
+
284
+ test("gate: finding the installed version clears the record (REQ-11)", async () => {
285
+ const file = tempStateFile();
286
+ seedState(file, { lastCheck: new Date(NOW - 48 * HOUR_MS).toISOString(), latestSeen: "9.9.9" });
287
+ const { fetchImpl } = fetchReturning(`{"latest":"${INSTALLED}"}`);
288
+
289
+ const { out } = await captured(() => updateGate("status", deps({ stateFile: file, fetchImpl })));
290
+
291
+ expect(out).toEqual([]);
292
+ expect(readState(file)).toEqual({ lastCheck: new Date(NOW).toISOString() });
293
+ });
294
+
295
+ test("gate: DARKF_NO_UPDATE_CHECK returns before any state read, request, or print (REQ-5)", async () => {
296
+ const file = tempStateFile();
297
+ const sentinel = '{"lastCheck":"kept-untouched"}';
298
+ mkdirSync(dirname(file), { recursive: true });
299
+ writeFileSync(file, sentinel);
300
+ const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
301
+
302
+ const { out, err } = await withOptOut(() =>
303
+ captured(() => updateGate("status", deps({ stateFile: file, fetchImpl }))),
304
+ );
305
+
306
+ expect(count()).toBe(0);
307
+ expect(out).toEqual([]);
308
+ expect(err).toEqual([]);
309
+ expect(rawFile(file)).toBe(sentinel); // not even a state read side effect
310
+ });
311
+
312
+ test("gate: `upgrade` is skipped — the command fetches on its own", async () => {
313
+ const file = tempStateFile();
314
+ const { fetchImpl, count } = fetchCounting('{"latest":"9.9.9"}');
315
+
316
+ const { out, err } = await captured(() =>
317
+ updateGate("upgrade", deps({ stateFile: file, fetchImpl })),
318
+ );
319
+
320
+ expect(count()).toBe(0);
321
+ expect(out).toEqual([]);
322
+ expect(err).toEqual([]);
323
+ expect(rawFile(file)).toBeNull(); // no state written for the upgrade command
324
+ });
325
+
326
+ // --- upgrade ---
327
+
328
+ test("upgrade: already-current prints current and exits 0 (REQ-6)", async () => {
329
+ const file = tempStateFile();
330
+ const { fetchImpl } = fetchReturning(`{"latest":"${INSTALLED}"}`);
331
+ const { spawnImpl, calls } = spawnStub(() => undefined);
332
+
333
+ const { result, out, err } = await captured(() =>
334
+ upgradeCmd(deps({ stateFile: file, fetchImpl, spawnImpl })),
335
+ );
336
+
337
+ expect(result).toBe(0);
338
+ expect(out).toEqual([`darkf is current (installed ${INSTALLED})`]);
339
+ expect(err).toEqual([]);
340
+ expect(calls).toEqual([]); // no probe, no installer
341
+ });
342
+
343
+ test("upgrade: registry failure prints a reason and exits 1 (REQ-10)", async () => {
344
+ const { result, out, err } = await captured(() => upgradeCmd(deps()));
345
+ expect(result).toBe(1);
346
+ expect(out).toEqual([]);
347
+ expect(err).toHaveLength(1);
348
+ expect(err[0]).toContain("update check failed");
349
+ });
350
+
351
+ test("upgrade: no manager lists the package — exit 1, no installer run (REQ-9)", async () => {
352
+ const { spawnImpl, calls } = spawnStub(() => ({ exitCode: 1, stdout: "nothing here" }));
353
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
354
+
355
+ const { result, out, err } = await captured(() => upgradeCmd(deps({ spawnImpl, fetchImpl })));
356
+
357
+ expect(result).toBe(1);
358
+ expect(out).toEqual([]); // never claims to upgrade
359
+ expect(err).toEqual([
360
+ "cannot determine how this darkf was installed — not managed by bun or npm",
361
+ ]);
362
+ expect(calls.every((cmd) => cmd[1] !== "install")).toBe(true);
363
+ });
364
+
365
+ test("upgrade: bun is probed first and wins the install (design: D-4)", async () => {
366
+ const { spawnImpl, calls } = spawnStub((cmd) => {
367
+ if (cmd[0] === "bun" && cmd[1] === "pm")
368
+ return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
369
+ if (cmd[0] === "npm") return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
370
+ if (cmd[0] === "bun" && cmd[1] === "install") return { exitCode: 0 };
371
+ return undefined;
372
+ });
373
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
374
+
375
+ const { result, out } = await captured(() => upgradeCmd(deps({ spawnImpl, fetchImpl })));
376
+
377
+ expect(result).toBe(0);
378
+ expect(out).toEqual([`upgrading ${INSTALLED} → 9.9.9`]);
379
+ expect(calls[0]).toEqual(["bun", "pm", "ls", "-g"]);
380
+ expect(calls[1]).toEqual(["bun", "install", "-g", "@psimona/darkf@9.9.9"]);
381
+ expect(calls.some((cmd) => cmd[0] === "npm")).toBe(false); // npm never consulted
382
+ });
383
+
384
+ test("upgrade: falls back to npm when bun does not list the package", async () => {
385
+ const { spawnImpl, calls } = spawnStub((cmd) => {
386
+ if (cmd[0] === "bun" && cmd[1] === "pm") return { exitCode: 0, stdout: "nothing relevant" };
387
+ if (cmd[0] === "npm") return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
388
+ if (cmd[0] === "npm" && cmd[1] === "install") return { exitCode: 0 };
389
+ return undefined;
390
+ });
391
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
392
+
393
+ const { result } = await captured(() => upgradeCmd(deps({ spawnImpl, fetchImpl })));
394
+
395
+ expect(result).toBe(0);
396
+ expect(calls.some((cmd) => cmd[0] === "npm" && cmd[1] === "install")).toBe(true);
397
+ expect(calls[calls.length - 1]).toEqual(["npm", "install", "-g", "@psimona/darkf@9.9.9"]);
398
+ });
399
+
400
+ test("upgrade: installer failure propagates its exit code and writes no state", async () => {
401
+ const file = tempStateFile();
402
+ const { spawnImpl } = spawnStub((cmd) => {
403
+ if (cmd[1] === "install") return { exitCode: 7 };
404
+ return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
405
+ });
406
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
407
+
408
+ const { result } = await captured(() =>
409
+ upgradeCmd(deps({ stateFile: file, spawnImpl, fetchImpl })),
410
+ );
411
+
412
+ expect(result).toBe(7);
413
+ expect(rawFile(file)).toBeNull(); // a failed install leaves no record
414
+ });
415
+
416
+ test("upgrade: success clears latestSeen so no stale notice survives (REQ-7, REQ-8)", async () => {
417
+ const file = tempStateFile();
418
+ seedState(file, { lastCheck: new Date(NOW - HOUR_MS).toISOString(), latestSeen: "9.9.9" });
419
+ const { spawnImpl, calls } = spawnStub((cmd) => {
420
+ if (cmd[1] === "install") return { exitCode: 0 };
421
+ return { exitCode: 0, stdout: "└── @psimona/darkf@0.3.0" };
422
+ });
423
+ const { fetchImpl } = fetchReturning('{"latest":"9.9.9"}');
424
+
425
+ const { result } = await captured(() =>
426
+ upgradeCmd(deps({ stateFile: file, spawnImpl, fetchImpl, now: () => NOW })),
427
+ );
428
+
429
+ expect(result).toBe(0);
430
+ expect(calls[calls.length - 1]).toEqual(["bun", "install", "-g", "@psimona/darkf@9.9.9"]);
431
+ expect(readState(file)).toEqual({ lastCheck: new Date(NOW).toISOString() }); // latestSeen gone
432
+ });
433
+
434
+ // --- smoke: the real CLI entrypoint (no network; state seeded or opted out) ---
435
+
436
+ const pkgDir = resolve(import.meta.dir, "..", "..");
437
+ const indexTs = join(pkgDir, "src", "cli", "index.ts");
438
+ const installedVersion = (
439
+ JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")) as {
440
+ version: string;
441
+ }
442
+ ).version;
443
+
444
+ async function runRealCli(
445
+ args: string[],
446
+ stateHome: string,
447
+ extraEnv: Record<string, string> = {},
448
+ ): Promise<{ code: number; stdout: string; stderr: string }> {
449
+ const proc = Bun.spawn([process.execPath, indexTs, ...args], {
450
+ cwd: tempDir(),
451
+ stdout: "pipe",
452
+ stderr: "pipe",
453
+ env: { ...process.env, XDG_STATE_HOME: stateHome, ...extraEnv },
454
+ });
455
+ const [stdout, stderr, code] = await Promise.all([
456
+ new Response(proc.stdout).text(),
457
+ new Response(proc.stderr).text(),
458
+ proc.exited,
459
+ ]);
460
+ return { code, stdout, stderr };
461
+ }
462
+
463
+ test("real CLI with the opt-out: no notice line and no state file (REQ-5, wiring)", async () => {
464
+ const stateHome = tempDir();
465
+ const res = await runRealCli(["workflows"], stateHome, { DARKF_NO_UPDATE_CHECK: "1" });
466
+ expect(res.code).toBe(0);
467
+ expect(res.stdout).not.toContain("available");
468
+ expect(rawFile(join(stateHome, "darkf", "last-update-check.json"))).toBeNull();
469
+ });
470
+
471
+ test("real CLI with a fresh not-due record: the notice is the first stdout line, no request (REQ-3, REQ-11, NFR-3)", async () => {
472
+ const stateHome = tempDir();
473
+ seedState(join(stateHome, "darkf", "last-update-check.json"), {
474
+ // Fresh stamp: the gate must print from the record without any registry request.
475
+ lastCheck: new Date().toISOString(),
476
+ latestSeen: "99.0.0",
477
+ });
478
+
479
+ const res = await runRealCli(["workflows"], stateHome, { DARKF_NO_UPDATE_CHECK: "" });
480
+
481
+ expect(res.code).toBe(0);
482
+ const firstLine = res.stdout.split("\n")[0];
483
+ expect(firstLine).toBe(
484
+ `darkf 99.0.0 available (installed ${installedVersion}) — run 'darkf upgrade'`,
485
+ );
486
+ });
@@ -0,0 +1,191 @@
1
+ // CLI self-update (docs/specs/self-update): a daily startup version check and
2
+ // the `darkf upgrade` command. Every dependency arrives via UpdateDeps, so the
3
+ // whole module runs in tests without network, a real clock, or a real package
4
+ // manager. No module-level mutable state.
5
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { dirname } from "node:path";
7
+
8
+ const PACKAGE_SPEC = "@psimona/darkf";
9
+ const REGISTRY_URL = "https://registry.npmjs.org/-/package/@psimona%2Fdarkf/dist-tags";
10
+ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
11
+ const CHECK_TIMEOUT_MS = 2_000;
12
+ // Design-originated: no REQ covers probe duration; the cap bounds a hung
13
+ // package manager.
14
+ const PROBE_TIMEOUT_MS = 10_000;
15
+ // Trust boundary: the registry response is untrusted input. `latest` must
16
+ // match this before any argv uses it (design: Security Considerations).
17
+ const SEMVER_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
18
+
19
+ export interface UpdateState {
20
+ lastCheck?: string; // ISO timestamp of the last check attempt
21
+ latestSeen?: string; // newest version known to exist; drives the notice
22
+ }
23
+
24
+ export interface UpdateDeps {
25
+ now(): number; // injectable clock
26
+ fetchImpl: typeof fetch; // injectable registry access
27
+ spawnImpl: typeof Bun.spawnSync; // injectable probes and installer
28
+ stateFile: string; // injectable state location
29
+ installed: string; // version from the package package.json
30
+ }
31
+
32
+ /** Absent or corrupt file returns {}. Never throws. */
33
+ export function readState(file: string): UpdateState {
34
+ try {
35
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
36
+ if (typeof parsed !== "object" || parsed === null) return {};
37
+ const rec = parsed as Record<string, unknown>;
38
+ const state: UpdateState = {};
39
+ if (typeof rec.lastCheck === "string") state.lastCheck = rec.lastCheck;
40
+ if (typeof rec.latestSeen === "string") state.latestSeen = rec.latestSeen;
41
+ return state;
42
+ } catch {
43
+ return {};
44
+ }
45
+ }
46
+
47
+ /** mkdir -p on the parent; best-effort — swallow write errors (REQ-4). */
48
+ export function writeState(file: string, state: UpdateState): void {
49
+ try {
50
+ mkdirSync(dirname(file), { recursive: true });
51
+ writeFileSync(file, JSON.stringify(state));
52
+ } catch {
53
+ // An unwritable state location degrades to re-checking next invocation.
54
+ }
55
+ }
56
+
57
+ /** True when lastCheck is missing, unparseable, or older than 24 h. */
58
+ export function isDue(state: UpdateState, now: number): boolean {
59
+ if (state.lastCheck === undefined) return true;
60
+ const last = Date.parse(state.lastCheck);
61
+ if (Number.isNaN(last)) return true;
62
+ return now - last >= CHECK_INTERVAL_MS;
63
+ }
64
+
65
+ /** Bun.semver.order(installed, latest) < 0. */
66
+ export function isNewer(installed: string, latest: string): boolean {
67
+ return Bun.semver.order(installed, latest) < 0;
68
+ }
69
+
70
+ /**
71
+ * GET the dist-tags endpoint with AbortSignal.timeout(2000). Returns `latest`
72
+ * when it is a semver-shaped string, else null. Never throws.
73
+ */
74
+ export async function checkRegistry(fetchImpl: typeof fetch): Promise<string | null> {
75
+ try {
76
+ const res = await fetchImpl(REGISTRY_URL, { signal: AbortSignal.timeout(CHECK_TIMEOUT_MS) });
77
+ if (res.status !== 200) return null;
78
+ const tags: unknown = await res.json();
79
+ const latest =
80
+ typeof tags === "object" && tags !== null
81
+ ? (tags as Record<string, unknown>).latest
82
+ : undefined;
83
+ return typeof latest === "string" && SEMVER_RE.test(latest) ? latest : null;
84
+ } catch {
85
+ // Rejects, aborts, and malformed JSON are all the same silent no-op.
86
+ return null;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * The startup path, called from main() before command dispatch. Sends at most
92
+ * one registry request per invocation, bounded to one per 24 h across
93
+ * invocations (REQ-1, REQ-2). Silent by contract: every failure continues the
94
+ * started command with no added output (REQ-4).
95
+ */
96
+ export async function updateGate(cmd: string | undefined, deps: UpdateDeps): Promise<void> {
97
+ // `upgrade` fetches on its own; the opt-out never blocks it.
98
+ if (cmd === "upgrade") return;
99
+ // Opt-out (REQ-5): no state read, no request, no print.
100
+ if (process.env.DARKF_NO_UPDATE_CHECK) return;
101
+
102
+ const state = readState(deps.stateFile);
103
+ if (isDue(state, deps.now())) {
104
+ const latest = await checkRegistry(deps.fetchImpl);
105
+ // null (failed check): leave latestSeen untouched — a stale notice survives.
106
+ if (latest !== null) {
107
+ if (isNewer(deps.installed, latest)) state.latestSeen = latest;
108
+ else delete state.latestSeen;
109
+ }
110
+ // Stamp on attempt (REQ-2): a failed check counts as a check.
111
+ state.lastCheck = new Date(deps.now()).toISOString();
112
+ writeState(deps.stateFile, state);
113
+ }
114
+ // Notice from the record: no registry request (REQ-11), exactly one line,
115
+ // printed before dispatch so it is the first line of stdout (NFR-3).
116
+ if (state.latestSeen !== undefined && isNewer(deps.installed, state.latestSeen)) {
117
+ console.log(
118
+ `darkf ${state.latestSeen} available (installed ${deps.installed}) — run 'darkf upgrade'`,
119
+ );
120
+ }
121
+ }
122
+
123
+ /** Marker shared by `bun pm ls -g` and `npm ls -g --depth=0` output. */
124
+ const INSTALLED_MARKER = `${PACKAGE_SPEC}@`;
125
+
126
+ /** False when the manager fails, times out, or does not list the package. */
127
+ function probeManager(spawnImpl: typeof Bun.spawnSync, cmd: string[]): boolean {
128
+ let out: { exitCode: number; stdout: Buffer };
129
+ try {
130
+ out = spawnImpl(cmd, { timeout: PROBE_TIMEOUT_MS });
131
+ } catch {
132
+ return false;
133
+ }
134
+ if (out.exitCode !== 0) return false;
135
+ return new TextDecoder().decode(out.stdout).includes(INSTALLED_MARKER);
136
+ }
137
+
138
+ /**
139
+ * bun first (the darkf bin runs under bun by construction), then npm when
140
+ * present — so a pack:local snapshot resolves to bun (design: D-4).
141
+ */
142
+ function pickManager(spawnImpl: typeof Bun.spawnSync): "bun" | "npm" | null {
143
+ if (probeManager(spawnImpl, ["bun", "pm", "ls", "-g"])) return "bun";
144
+ if (Bun.which("npm") !== null && probeManager(spawnImpl, ["npm", "ls", "-g", "--depth=0"])) {
145
+ return "npm";
146
+ }
147
+ return null;
148
+ }
149
+
150
+ /**
151
+ * The `darkf upgrade` command. Loud where the startup gate is silent: registry
152
+ * and provenance failures print a one-line stderr reason and exit non-zero
153
+ * (REQ-9, REQ-10). Returns the process exit code.
154
+ */
155
+ export async function upgradeCmd(deps: UpdateDeps): Promise<number> {
156
+ const latest = await checkRegistry(deps.fetchImpl);
157
+ if (latest === null) {
158
+ console.error(
159
+ `update check failed: could not read the latest version of ${PACKAGE_SPEC} from the npm registry`,
160
+ );
161
+ return 1;
162
+ }
163
+ // Current, or a local snapshot newer than the published release: no
164
+ // downgrade (REQ-6).
165
+ if (Bun.semver.order(deps.installed, latest) >= 0) {
166
+ console.log(`darkf is current (installed ${deps.installed})`);
167
+ return 0;
168
+ }
169
+ const pm = pickManager(deps.spawnImpl);
170
+ if (pm === null) {
171
+ console.error("cannot determine how this darkf was installed — not managed by bun or npm");
172
+ return 1;
173
+ }
174
+ // The before/after line REQ-7 requires, printed before anything changes.
175
+ console.log(`upgrading ${deps.installed} → ${latest}`);
176
+ if (!SEMVER_RE.test(latest)) {
177
+ console.error(`registry returned a malformed version: ${JSON.stringify(latest)}`);
178
+ return 1;
179
+ }
180
+ // Argv array, never a shell string; stdio inherited so the installer's own
181
+ // output flows through (REQ-8, design: Security Considerations).
182
+ const install = deps.spawnImpl([pm, "install", "-g", `${PACKAGE_SPEC}@${latest}`], {
183
+ stdio: ["inherit", "inherit", "inherit"],
184
+ });
185
+ const code = install.exitCode;
186
+ // On success clear any stale record so no notice survives the upgrade.
187
+ if (code === 0) {
188
+ writeState(deps.stateFile, { lastCheck: new Date(deps.now()).toISOString() });
189
+ }
190
+ return code;
191
+ }
package/src/core/types.ts CHANGED
@@ -38,7 +38,7 @@ export const DONE = "[*]" as const;
38
38
  // DONE's pseudostate notation; `mermaid.ts` special-cases it the same way,
39
39
  // since `[-]` has no built-in meaning to stateDiagram-v2 the way `[*]` does.
40
40
  export const FAILED = "[-]" as const;
41
- // Deprecated alias — kept only for blueprint's own give-up edges, which still
41
+ // Deprecated alias — kept only for a consumer repo's give-up edges, which still
42
42
  // route to EXIT on its own schedule (docs/specs/failed-terminal/spec.md).
43
43
  // Removed in the same change that lands the `run_failure` node + retarget
44
44
  // table there; any surviving `EXIT` import then fails to compile.
@@ -44,7 +44,7 @@ export interface StepFinishScan {
44
44
  // opencode's `--format json` is NDJSON (one event object per line). The
45
45
  // step-finish event carries `part.reason` — the terminal reason for the
46
46
  // turn: "stop" (clean), "tool-calls" (ended between tool calls), "length"
47
- // (output budget exhausted). Blueprint runs 2026-10-09: THREE crash classes
47
+ // (output budget exhausted). Unattended runs 2026-10-09: THREE crash classes
48
48
  // (silent resume hang, finish=length authoring abort, finish=tool-calls
49
49
  // mid-turn death) all surfaced as `exit 0` + missing handoff → a bare
50
50
  // ENOENT minutes after the real failure. Capture the reason and make a
@@ -58,7 +58,7 @@ export interface StepFinishScan {
58
58
  // and a count of step-finish events seen, in the same single pass:
59
59
  // `stepCount` is the positive-evidence gate for ever reporting a session id
60
60
  // at all — this is the resumability fix for the session that hung 15
61
- // minutes on zero persisted messages (blueprint run 82ee6c61, E8.5b,
61
+ // minutes on zero persisted messages (2026-10-08):
62
62
  // 2026-10-08): the hang's root cause was resuming a session with no
63
63
  // evidence it had done anything, not resuming as such.
64
64
  export function scanStepFinish(stdout: string): StepFinishScan {
@@ -170,8 +170,8 @@ export const opencodeRunner: AgentRunner = {
170
170
  }
171
171
  // Opt-in per agent state: agent: { auto: true } passes opencode's --auto,
172
172
  // which approves every ask-level permission for the dispatch (explicit
173
- // deny rules still hold). Deliberately NOT a runner default — blueprint
174
- // run aeac93f6 (2026-10-13) crashed twice on `rm -rf *` asks that
173
+ // deny rules still hold). Deliberately NOT a runner default — an
174
+ // unattended run (2026-10-13) crashed twice on `rm -rf *` asks that
175
175
  // headless mode auto-rejects (finish=tool-calls, handoff not written),
176
176
  // but blanket --auto would also silently approve force-push asks in
177
177
  // unattended runs. Each workflow chooses.
@@ -218,7 +218,7 @@ export const opencodeRunner: AgentRunner = {
218
218
  // (e.g. scratch-dir `rm -rf`) needs --auto or a narrower config allow.
219
219
  // Resolve once: spawn can miss PATH lookups in daemonized workers.
220
220
  //
221
- // No -s outside a nudge: blueprint run 82ee6c61 (E8.5b, 2026-10-08) — the
221
+ // No -s outside a nudge: an unattended run (2026-10-08) — the
222
222
  // task_plan dispatch resumed req_gate's session via `-s` and hung 15
223
223
  // minutes with ZERO messages persisted (opencode.db: session's last row
224
224
  // predates the dispatch), then exited 0 without writing the handoff →
@@ -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
+ };
@@ -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