@psimona/darkf 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/docs/concepts/failure-modes.md +164 -0
  2. package/docs/concepts/handoff.md +91 -0
  3. package/docs/concepts/journal.md +92 -0
  4. package/docs/concepts/node-types.md +175 -0
  5. package/docs/guides/pick-an-agent-runner.md +57 -0
  6. package/docs/guides/plan-with-a-task-queue.md +410 -0
  7. package/docs/guides/render-to-mermaid.md +22 -0
  8. package/docs/guides/run-detached-and-monitor.md +76 -0
  9. package/docs/guides/test-your-workflow.md +20 -0
  10. package/docs/guides/write-your-first-workflow.md +95 -0
  11. package/docs/index.mdx +64 -0
  12. package/docs/reference/cli-commands.md +105 -0
  13. package/docs/reference/core-types.md +123 -0
  14. package/docs/reference/package-map.md +35 -0
  15. package/docs/start-here/install.md +71 -0
  16. package/docs/start-here/quickstart.md +241 -0
  17. package/package.json +7 -1
  18. package/skills/darkf-usage/SKILL.md +92 -0
  19. package/skills/darkf-writing-workflows/SKILL.md +88 -0
  20. package/src/cli/doctor.test.ts +338 -0
  21. package/src/cli/index.ts +123 -9
  22. package/src/cli/setup.test.ts +384 -0
  23. package/src/cli/setup.ts +286 -0
  24. package/src/cli/tarball.test.ts +125 -0
  25. package/src/cli/update.test.ts +82 -0
  26. package/src/cli/update.ts +20 -0
  27. package/src/core/types.ts +8 -0
  28. package/src/engine/run.test.ts +177 -0
  29. package/src/engine/run.ts +66 -2
  30. package/src/kit/agents/opencode.test.ts +232 -2
  31. package/src/kit/agents/opencode.ts +69 -6
  32. package/src/kit/status.test.ts +67 -0
  33. package/src/kit/status.ts +25 -0
  34. package/workflows/dev-loop/scripts/begin.ts +1 -1
  35. package/workflows/dev-loop/scripts/finish.ts +4 -1
  36. package/workflows/dev-loop/workflow.ts +30 -19
  37. package/bunfig.toml +0 -13
  38. package/examples/article-classifier/data/articles.ts +0 -38
  39. package/examples/article-classifier/scripts/next.ts +0 -7
  40. package/examples/article-classifier/scripts/queue.ts +0 -33
  41. package/examples/article-classifier/scripts/record.ts +0 -9
  42. package/examples/article-classifier/workflow.ts +0 -44
  43. package/examples/haiku-commit/scripts/check.ts +0 -24
  44. package/examples/haiku-commit/workflow.ts +0 -28
  45. package/examples/haiku-readme/scripts/test.ts +0 -13
  46. package/examples/haiku-readme/scripts/write.ts +0 -10
  47. package/examples/haiku-readme/workflow.ts +0 -41
  48. package/examples/task-queue/scripts/next.ts +0 -20
  49. package/examples/task-queue/scripts/record.ts +0 -20
  50. package/examples/task-queue/supervise.ts +0 -57
  51. package/examples/task-queue/workflow.ts +0 -33
  52. package/feedback/2026-10-30-self-update.md +0 -29
  53. package/feedback/2026-10-31-task-list-json.md +0 -26
  54. package/tsconfig.json +0 -4
@@ -0,0 +1,384 @@
1
+ import { afterAll, expect, test } from "bun:test";
2
+ import {
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ mkdtempSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ rmSync,
10
+ statSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import {
16
+ bundledSkills,
17
+ KNOWN_HOSTS,
18
+ type ProbeDeps,
19
+ probeBlock,
20
+ readProbeState,
21
+ type SyncDeps,
22
+ skillState,
23
+ skillsCheck,
24
+ skillsProbeGate,
25
+ syncAll,
26
+ todayLocal,
27
+ writeProbeState,
28
+ } from "./setup.ts";
29
+
30
+ // --- fixtures: temp HOME, a spied bundled dir, injectable binary lookup ---
31
+
32
+ const roots: string[] = [];
33
+ afterAll(() => {
34
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
35
+ });
36
+
37
+ function tempDir(prefix = "darkf-setup-"): string {
38
+ const dir = mkdtempSync(join(tmpdir(), prefix));
39
+ roots.push(dir);
40
+ return dir;
41
+ }
42
+
43
+ const USAGE = "usage skill content v1\n";
44
+ const WRITING = "writing-workflows skill content v1\n";
45
+
46
+ /** A bundled skills dir with the two real skill names and fixture content. */
47
+ function makeBundle(usage = USAGE, writing = WRITING): string {
48
+ const dir = tempDir("darkf-bundle-");
49
+ mkdirSync(join(dir, "darkf-usage"), { recursive: true });
50
+ mkdirSync(join(dir, "darkf-writing-workflows"), { recursive: true });
51
+ writeFileSync(join(dir, "darkf-usage", "SKILL.md"), usage);
52
+ writeFileSync(join(dir, "darkf-writing-workflows", "SKILL.md"), writing);
53
+ return dir;
54
+ }
55
+
56
+ function deps(overrides: Partial<SyncDeps & ProbeDeps> = {}): SyncDeps & ProbeDeps {
57
+ return {
58
+ home: tempDir(),
59
+ bundledDir: makeBundle(),
60
+ existsBinary: () => false,
61
+ stateFile: join(tempDir(), "state", "darkf", "last-skills-check.json"),
62
+ ...overrides,
63
+ };
64
+ }
65
+
66
+ /** A host skills dir the test created itself — detection via existing dir. */
67
+ function seedSkillsDir(home: string, host = ".claude/skills"): string {
68
+ const dir = join(home, host);
69
+ mkdirSync(dir, { recursive: true });
70
+ return dir;
71
+ }
72
+
73
+ function seedOk(dir: string, bundledDir: string, skill: string): void {
74
+ cpSync(join(bundledDir, skill), join(dir, skill), { recursive: true });
75
+ }
76
+
77
+ /** A stale/edited skill copy: parent dirs created, fixture content written. */
78
+ function putSkill(dir: string, name: string, content: string, file = "SKILL.md"): void {
79
+ mkdirSync(join(dir, name), { recursive: true });
80
+ writeFileSync(join(dir, name, file), content);
81
+ }
82
+
83
+ function capturedLog() {
84
+ const lines: string[] = [];
85
+ return { lines, log: (line: string) => void lines.push(line) };
86
+ }
87
+
88
+ // --- the known-harness table ---
89
+
90
+ test("the table names every known harness with its documented dir and binary", () => {
91
+ expect(KNOWN_HOSTS).toEqual([
92
+ { name: "claude", dir: ".claude/skills", binary: "claude" },
93
+ { name: "opencode", dir: ".opencode/skills", binary: "opencode" },
94
+ { name: "codex", dir: ".codex/skills", binary: "codex" },
95
+ { name: "gemini", dir: ".gemini/skills", binary: "gemini" },
96
+ { name: "cursor", dir: ".cursor/skills", binary: "cursor-agent" },
97
+ ]);
98
+ });
99
+
100
+ test("bundledSkills lists bundled dirs with a SKILL.md, sorted; missing dir lists none", () => {
101
+ expect(bundledSkills(deps().bundledDir)).toEqual(["darkf-usage", "darkf-writing-workflows"]);
102
+ expect(bundledSkills(join(tempDir(), "does-not-exist"))).toEqual([]);
103
+ const partial = tempDir();
104
+ writeFileSync(join(partial, "lonely-file.txt"), "not a skill");
105
+ mkdirSync(join(partial, "dir-without-skillmd"));
106
+ expect(bundledSkills(partial)).toEqual([]);
107
+ });
108
+
109
+ // --- skill state ---
110
+
111
+ test("skillState: missing, ok, and differs by byte equality on SKILL.md", () => {
112
+ const bundledDir = makeBundle();
113
+ const dir = seedSkillsDir(tempDir());
114
+ expect(skillState(dir, "darkf-usage", bundledDir)).toBe("missing");
115
+ seedOk(dir, bundledDir, "darkf-usage");
116
+ expect(skillState(dir, "darkf-usage", bundledDir)).toBe("ok");
117
+ writeFileSync(join(dir, "darkf-usage", "SKILL.md"), "locally edited\n");
118
+ expect(skillState(dir, "darkf-usage", bundledDir)).toBe("differs");
119
+ // A partial install — dir without SKILL.md — is missing, not differs.
120
+ mkdirSync(join(dir, "darkf-writing-workflows"));
121
+ expect(skillState(dir, "darkf-writing-workflows", bundledDir)).toBe("missing");
122
+ });
123
+
124
+ // --- skillsCheck (the read-only shared check) ---
125
+
126
+ test("skillsCheck names every known harness; absent host has no states", () => {
127
+ const d = deps();
128
+ const checks = skillsCheck(d);
129
+ expect(checks.map((h) => h.host)).toEqual(KNOWN_HOSTS.map((h) => h.name));
130
+ for (const h of checks) {
131
+ expect(h.present).toBe(false);
132
+ expect(h.states).toEqual({});
133
+ }
134
+ });
135
+
136
+ test("skillsCheck: detection by existing dir alone, states per bundled skill", () => {
137
+ const d = deps();
138
+ const dir = seedSkillsDir(d.home);
139
+ seedOk(dir, d.bundledDir, "darkf-usage");
140
+ const claude = skillsCheck(d).find((h) => h.host === "claude")!;
141
+ expect(claude.present).toBe(true);
142
+ expect(claude.states).toEqual({ "darkf-usage": "ok", "darkf-writing-workflows": "missing" });
143
+ });
144
+
145
+ test("skillsCheck: detection by binary when the dir does not exist yet", () => {
146
+ const d = deps({ existsBinary: (b) => b === "codex" });
147
+ const codex = skillsCheck(d).find((h) => h.host === "codex")!;
148
+ expect(codex.present).toBe(true);
149
+ expect(codex.states).toEqual({
150
+ "darkf-usage": "missing",
151
+ "darkf-writing-workflows": "missing",
152
+ });
153
+ expect(existsSync(join(d.home, ".codex", "skills"))).toBe(false); // read-only
154
+ });
155
+
156
+ // --- sync ---
157
+
158
+ test("sync: missing target is copied, byte-identical to bundled", () => {
159
+ const d = deps();
160
+ const dir = seedSkillsDir(d.home);
161
+ expect(syncAll(d)).toBe(0);
162
+ expect(readFileSync(join(dir, "darkf-usage", "SKILL.md"), "utf8")).toBe(USAGE);
163
+ expect(readFileSync(join(dir, "darkf-writing-workflows", "SKILL.md"), "utf8")).toBe(WRITING);
164
+ });
165
+
166
+ test("sync: partial install (dir without SKILL.md) is repaired by copy", () => {
167
+ const d = deps();
168
+ const dir = seedSkillsDir(d.home);
169
+ putSkill(dir, "darkf-usage", "leftover note\n", "NOTES.txt"); // no SKILL.md
170
+ const { lines } = capturedLog();
171
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(0);
172
+ expect(readFileSync(join(dir, "darkf-usage", "SKILL.md"), "utf8")).toBe(USAGE);
173
+ expect(readdirSync(join(dir, "darkf-usage"))).toEqual(["SKILL.md"]); // exact mirror
174
+ const line = lines.find((l) => l.includes("darkf-usage"))!;
175
+ expect(line.trimEnd().endsWith("installed")).toBe(true); // reported missing, then copied
176
+ });
177
+
178
+ test("sync: identical target is untouched and reported ok", () => {
179
+ const d = deps();
180
+ const dir = seedSkillsDir(d.home);
181
+ seedOk(dir, d.bundledDir, "darkf-usage");
182
+ const sentinel = statSync(join(dir, "darkf-usage", "SKILL.md")).ino;
183
+ const { lines } = capturedLog();
184
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(0);
185
+ const okLine = lines.find((l) => l.includes("darkf-usage"))!;
186
+ expect(okLine.trimEnd().endsWith("ok")).toBe(true);
187
+ expect(statSync(join(dir, "darkf-usage", "SKILL.md")).ino).toBe(sentinel); // no rewrite
188
+ });
189
+
190
+ test("sync: differing target is overwritten, byte-identical to bundled", () => {
191
+ const d = deps();
192
+ const dir = seedSkillsDir(d.home);
193
+ putSkill(dir, "darkf-usage", "a stale or edited copy\n");
194
+ expect(syncAll(d)).toBe(0);
195
+ expect(readFileSync(join(dir, "darkf-usage", "SKILL.md"), "utf8")).toBe(USAGE);
196
+ });
197
+
198
+ test("sync: leftover files are wiped — the destination is an exact mirror", () => {
199
+ const d = deps();
200
+ const dir = seedSkillsDir(d.home);
201
+ const staleDir = join(dir, "darkf-usage");
202
+ putSkill(staleDir, ".", "older bundled version\n");
203
+ writeFileSync(join(staleDir, "reference-removed.md"), "left by an older bundled version");
204
+ writeFileSync(join(staleDir, "someone-elses-note.txt"), "added inside the skill dir");
205
+ expect(syncAll(d)).toBe(0);
206
+ expect(readdirSync(staleDir)).toEqual(["SKILL.md"]);
207
+ expect(readFileSync(join(staleDir, "SKILL.md"), "utf8")).toBe(USAGE);
208
+ });
209
+
210
+ test("sync: a dot-prefixed temp dir from a crashed sync is replaced, never a skill state", () => {
211
+ const d = deps();
212
+ const dir = seedSkillsDir(d.home);
213
+ putSkill(dir, ".darkf-tmp-darkf-usage", "half-written junk\n");
214
+ const { lines } = capturedLog();
215
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(0);
216
+ expect(existsSync(join(dir, ".darkf-tmp-darkf-usage"))).toBe(false);
217
+ expect(readFileSync(join(dir, "darkf-usage", "SKILL.md"), "utf8")).toBe(USAGE);
218
+ for (const line of lines) expect(line).not.toContain(".darkf-tmp");
219
+ });
220
+
221
+ test("sync: a foreign skill dir is never read or written", () => {
222
+ const d = deps();
223
+ const dir = seedSkillsDir(d.home);
224
+ putSkill(dir, "my-own-skill", "mine, not darkf's\n");
225
+ const { lines } = capturedLog();
226
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(0);
227
+ expect(readFileSync(join(dir, "my-own-skill", "SKILL.md"), "utf8")).toBe("mine, not darkf's\n");
228
+ for (const line of lines) expect(line).not.toContain("my-own-skill");
229
+ });
230
+
231
+ test("sync: dir absent + binary absent — harness skipped, nothing created", () => {
232
+ const d = deps({ existsBinary: () => false });
233
+ const { lines } = capturedLog();
234
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(0);
235
+ expect(lines).toContain("host claude — harness not present");
236
+ expect(existsSync(join(d.home, ".claude"))).toBe(false);
237
+ expect(existsSync(join(d.home, ".opencode"))).toBe(false);
238
+ });
239
+
240
+ test("sync: dir absent + binary present — dir created 0755, skill copied", () => {
241
+ const umask = process.umask();
242
+ const d = deps({ existsBinary: (b) => b === "gemini" });
243
+ expect(syncAll(d)).toBe(0);
244
+ const dir = join(d.home, ".gemini", "skills");
245
+ expect(statSync(dir).mode & 0o777).toBe(0o755 & ~umask);
246
+ expect(readFileSync(join(dir, "darkf-usage", "SKILL.md"), "utf8")).toBe(USAGE);
247
+ });
248
+
249
+ test("sync: one table row per known harness — every row syncs through the same loop", () => {
250
+ const d = deps({ existsBinary: (b) => KNOWN_HOSTS.some((h) => h.binary === b) });
251
+ expect(syncAll(d)).toBe(0);
252
+ for (const host of KNOWN_HOSTS) {
253
+ const installed = join(d.home, host.dir, "darkf-usage", "SKILL.md");
254
+ expect(readFileSync(installed, "utf8")).toBe(USAGE);
255
+ }
256
+ });
257
+
258
+ test("sync: state reporting — ok, installed, and updated (was stale)", () => {
259
+ const d = deps();
260
+ const dir = seedSkillsDir(d.home);
261
+ seedOk(dir, d.bundledDir, "darkf-usage"); // stays ok
262
+ putSkill(dir, "darkf-writing-workflows", "stale\n"); // differs
263
+ const { lines } = capturedLog();
264
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(0);
265
+ expect(lines).toContain("host claude (~/.claude/skills)");
266
+ expect(lines.some((l) => l.startsWith(" darkf-usage") && l.trimEnd().endsWith("ok"))).toBe(true);
267
+ expect(
268
+ lines.some(
269
+ (l) => l.startsWith(" darkf-writing-workflows") && l.endsWith("updated (was stale)"),
270
+ ),
271
+ ).toBe(true);
272
+ // And a second run is a no-op: everything ok.
273
+ const again: string[] = [];
274
+ expect(syncAll({ ...d, log: again.push.bind(again) })).toBe(0);
275
+ expect(
276
+ again.filter((l) => l.startsWith(" darkf-")).every((l) => l.trimEnd().endsWith("ok")),
277
+ ).toBe(true);
278
+ });
279
+
280
+ test("sync: a fresh install reports installed", () => {
281
+ const d = deps({ existsBinary: (b) => b === "claude" });
282
+ const { lines } = capturedLog();
283
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(0);
284
+ expect(
285
+ lines.some((l) => l.startsWith(" darkf-usage") && l.trimEnd().endsWith("installed")),
286
+ ).toBe(true);
287
+ });
288
+
289
+ test("sync: exit 1 when a present host still ends missing/differs", () => {
290
+ const d = deps({ existsBinary: (b) => b === "claude" });
291
+ // The host skills "dir" is a file — every copy op fails, nothing crashes.
292
+ mkdirSync(join(d.home, ".claude"));
293
+ writeFileSync(join(d.home, ".claude", "skills"), "a file, not a dir");
294
+ const { lines } = capturedLog();
295
+ expect(syncAll({ ...d, log: lines.push.bind(lines) })).toBe(1);
296
+ expect(lines.some((l) => l.includes("failed ("))).toBe(true);
297
+ });
298
+
299
+ // --- daily probe ---
300
+
301
+ const TODAY = new Date(2026, 10, 9, 13, 0, 0); // local 2026-11-09 13:00
302
+
303
+ test("todayLocal renders the local calendar date, not UTC", () => {
304
+ // 23:30 local in a UTC+13 zone is already tomorrow in UTC.
305
+ expect(todayLocal(new Date(2026, 10, 9, 23, 30))).toBe("2026-11-09");
306
+ expect(todayLocal(TODAY)).toBe("2026-11-09");
307
+ });
308
+
309
+ test("probe state: absent and corrupt files read as never probed; writes round-trip", () => {
310
+ expect(readProbeState(join(tempDir(), "absent.json"))).toEqual({});
311
+ const corrupt = join(tempDir(), "corrupt.json");
312
+ writeFileSync(corrupt, "{not json");
313
+ expect(readProbeState(corrupt)).toEqual({});
314
+ const wrongType = join(tempDir(), "wrong.json");
315
+ writeFileSync(wrongType, JSON.stringify({ lastProbe: 42 }));
316
+ expect(readProbeState(wrongType)).toEqual({});
317
+ const file = join(tempDir(), "state", "darkf", "last-skills-check.json");
318
+ writeProbeState(file, { lastProbe: "2026-11-09" });
319
+ expect(readProbeState(file)).toEqual({ lastProbe: "2026-11-09" });
320
+ });
321
+
322
+ test("probeBlock: silent when every present harness is ok or absent", () => {
323
+ const d = deps();
324
+ seedOk(seedSkillsDir(d.home), d.bundledDir, "darkf-usage");
325
+ seedOk(seedSkillsDir(d.home), d.bundledDir, "darkf-writing-workflows");
326
+ expect(probeBlock(skillsCheck(d))).toBeNull();
327
+ });
328
+
329
+ test("probeBlock: failing lines plus the fix hint, one line per failing harness", () => {
330
+ const d = deps();
331
+ const dir = seedSkillsDir(d.home);
332
+ putSkill(dir, "darkf-usage", "edited locally\n");
333
+ seedOk(dir, d.bundledDir, "darkf-writing-workflows");
334
+ const block = probeBlock(skillsCheck(d))!;
335
+ expect(block).toEqual([
336
+ "skills (claude): darkf-usage differs from bundled",
337
+ "fix: run darkf setup",
338
+ ]);
339
+ });
340
+
341
+ async function capturedProbe(d: ProbeDeps): Promise<{ lines: string[] }> {
342
+ const lines: string[] = [];
343
+ await skillsProbeGate("status", { ...d, log: lines.push.bind(lines) });
344
+ return { lines };
345
+ }
346
+
347
+ test("probe: first invocation of a day runs and stamps; same-day skips silently", async () => {
348
+ const d = deps();
349
+ const dir = seedSkillsDir(d.home);
350
+ seedOk(dir, d.bundledDir, "darkf-usage");
351
+ seedOk(dir, d.bundledDir, "darkf-writing-workflows");
352
+ const first = await capturedProbe({ ...d, today: () => "2026-11-09" });
353
+ expect(first.lines).toEqual([]); // all ok — silent by contract
354
+ expect(readProbeState(d.stateFile).lastProbe).toBe("2026-11-09");
355
+ // Same-day: skipped even when the state changed under the probe.
356
+ rmSync(join(dir, "darkf-usage"), { recursive: true });
357
+ rmSync(join(dir, "darkf-writing-workflows"), { recursive: true });
358
+ const second = await capturedProbe({ ...d, today: () => "2026-11-09" });
359
+ expect(second.lines).toEqual([]);
360
+ // Next day: runs again — only darkf-usage is drifted, so one named line.
361
+ seedOk(dir, d.bundledDir, "darkf-writing-workflows");
362
+ const nextDay = await capturedProbe({ ...d, today: () => "2026-11-10" });
363
+ expect(nextDay.lines).toEqual(["skills (claude): darkf-usage missing", "fix: run darkf setup"]);
364
+ });
365
+
366
+ test("probe: a corrupt state file counts as never probed", async () => {
367
+ const d = deps();
368
+ putSkill(seedSkillsDir(d.home), "darkf-usage", "edited locally\n"); // a present harness with drift
369
+ mkdirSync(d.stateFile.slice(0, d.stateFile.lastIndexOf("/")), { recursive: true });
370
+ writeFileSync(d.stateFile, "{corrupt");
371
+ const { lines } = await capturedProbe({ ...d, today: () => "2026-11-09" });
372
+ expect(lines).toContain("fix: run darkf setup"); // probed despite the corrupt file
373
+ expect(readProbeState(d.stateFile).lastProbe).toBe("2026-11-09"); // and stamped
374
+ });
375
+
376
+ test("probe: exempt commands skip the probe and refresh the state file", async () => {
377
+ const d = deps(); // nothing installed — a probe would loudly report missing
378
+ for (const cmd of ["setup", "upgrade"]) {
379
+ const lines: string[] = [];
380
+ await skillsProbeGate(cmd, { ...d, today: () => "2026-11-09", log: lines.push.bind(lines) });
381
+ expect(lines).toEqual([]);
382
+ expect(readProbeState(d.stateFile)).toEqual({ lastProbe: "2026-11-09" });
383
+ }
384
+ });
@@ -0,0 +1,286 @@
1
+ // Skill setup (docs/specs/skill-setup): the shared skills-check core, the
2
+ // `darkf setup` sync, and the daily first-invocation probe. The bundled
3
+ // darkf-* skills ship inside the package (darkf/skills/); every dependency
4
+ // arrives via deps objects, so the whole module runs in tests without a real
5
+ // HOME, PATH, or the packaged skills dir. No module-level mutable state.
6
+ import {
7
+ cpSync,
8
+ type Dirent,
9
+ existsSync,
10
+ mkdirSync,
11
+ readdirSync,
12
+ readFileSync,
13
+ renameSync,
14
+ rmSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+
19
+ // The known harnesses are a table in code — adding one is a row plus a test
20
+ // fixture, not a feature (spec: Host detection). `dir` is relative to HOME;
21
+ // a host is detected when its skills dir exists OR its binary is on PATH.
22
+ // A harness whose skills support or path cannot be confirmed drops from the
23
+ // table rather than creating dirs nothing reads.
24
+ export interface KnownHost {
25
+ name: string;
26
+ dir: string; // relative to HOME
27
+ binary: string;
28
+ }
29
+
30
+ export const KNOWN_HOSTS: KnownHost[] = [
31
+ { name: "claude", dir: ".claude/skills", binary: "claude" },
32
+ { name: "opencode", dir: ".opencode/skills", binary: "opencode" },
33
+ { name: "codex", dir: ".codex/skills", binary: "codex" },
34
+ { name: "gemini", dir: ".gemini/skills", binary: "gemini" },
35
+ { name: "cursor", dir: ".cursor/skills", binary: "cursor-agent" },
36
+ ];
37
+
38
+ export type SkillState = "missing" | "ok" | "differs";
39
+
40
+ export interface SkillsDeps {
41
+ home: string; // expands the table's ~/. paths
42
+ bundledDir: string; // the package's skills/ dir
43
+ existsBinary(name: string): boolean;
44
+ }
45
+
46
+ export interface SyncDeps extends SkillsDeps {
47
+ log?(line: string): void;
48
+ }
49
+
50
+ export interface ProbeDeps extends SkillsDeps {
51
+ stateFile: string; // injectable last-skills-check location
52
+ today?(): string; // injectable local calendar date
53
+ log?(line: string): void;
54
+ }
55
+
56
+ /** Bundled skill names: subdirs of bundledDir containing a SKILL.md, sorted. */
57
+ export function bundledSkills(bundledDir: string): string[] {
58
+ try {
59
+ return readdirSync(bundledDir, { withFileTypes: true })
60
+ .filter((e) => e.isDirectory() && existsSync(join(bundledDir, e.name, "SKILL.md")))
61
+ .map((e) => e.name)
62
+ .sort();
63
+ } catch {
64
+ return [];
65
+ }
66
+ }
67
+
68
+ /**
69
+ * The three per-skill states, by byte equality on SKILL.md — the only file
70
+ * either skill has. A dir without SKILL.md is a partial install: missing.
71
+ */
72
+ export function skillState(skillsDir: string, skill: string, bundledDir: string): SkillState {
73
+ try {
74
+ const installed = readFileSync(join(skillsDir, skill, "SKILL.md"));
75
+ const bundled = readFileSync(join(bundledDir, skill, "SKILL.md"));
76
+ return installed.equals(bundled) ? "ok" : "differs";
77
+ } catch {
78
+ return "missing";
79
+ }
80
+ }
81
+
82
+ export interface HostSkills {
83
+ host: string;
84
+ dir: string; // absolute, HOME-expanded
85
+ display: string; // the ~/. form for output lines
86
+ present: boolean;
87
+ /** Per bundled skill; empty for an absent host. */
88
+ states: Record<string, SkillState>;
89
+ }
90
+
91
+ /**
92
+ * The read-only skills check every consumer shares (doctor's skills section,
93
+ * the daily probe, setup's state model): one entry per known harness, every
94
+ * harness always named. Reads nothing outside darkf-* skill dirs; writes
95
+ * nothing.
96
+ */
97
+ export function skillsCheck(deps: SkillsDeps): HostSkills[] {
98
+ const skills = bundledSkills(deps.bundledDir);
99
+ return KNOWN_HOSTS.map((host) => {
100
+ const dir = join(deps.home, host.dir);
101
+ const present = existsSync(dir) || deps.existsBinary(host.binary);
102
+ const states: Record<string, SkillState> = {};
103
+ if (present) {
104
+ for (const skill of skills) states[skill] = skillState(dir, skill, deps.bundledDir);
105
+ }
106
+ return { host: host.name, dir, display: `~/${host.dir}`, present, states };
107
+ });
108
+ }
109
+
110
+ /** Per-skill failing names for a checked host, in reporting order. */
111
+ export function failingSkills(h: HostSkills): Array<[string, SkillState]> {
112
+ return Object.entries(h.states).filter(([, state]) => state !== "ok") as Array<
113
+ [string, SkillState]
114
+ >;
115
+ }
116
+
117
+ /** "darkf-usage differs from bundled" / "darkf-usage missing". */
118
+ export function describeFailure(skill: string, state: SkillState): string {
119
+ return state === "missing" ? `${skill} missing` : `${skill} differs from bundled`;
120
+ }
121
+
122
+ // The write itself is dir replacement, not a file-by-file merge: copy the
123
+ // bundled dir to a dot-prefixed temp dir inside the skills dir (hosts ignore
124
+ // dot-dirs when listing skills), remove the installed dir, rename the temp
125
+ // into place. The swap is one rename; a crash mid-copy at worst leaves a
126
+ // temp dir that the next sync replaces. The destination is an exact mirror
127
+ // of the bundled dir after every sync.
128
+ const TEMP_PREFIX = ".darkf-tmp-";
129
+
130
+ function copySkill(skillsDir: string, skill: string, bundledDir: string): void {
131
+ const temp = join(skillsDir, `${TEMP_PREFIX}${skill}`);
132
+ rmSync(temp, { recursive: true, force: true });
133
+ cpSync(join(bundledDir, skill), temp, { recursive: true });
134
+ rmSync(join(skillsDir, skill), { recursive: true, force: true });
135
+ renameSync(temp, join(skillsDir, skill));
136
+ }
137
+
138
+ /** Dot-prefixed temp dirs are darkf's namespace too — the next sync replaces them. */
139
+ function clearTempDirs(skillsDir: string): void {
140
+ let entries: Dirent[];
141
+ try {
142
+ entries = readdirSync(skillsDir, { withFileTypes: true });
143
+ } catch {
144
+ return;
145
+ }
146
+ for (const e of entries) {
147
+ if (e.isDirectory() && e.name.startsWith(TEMP_PREFIX)) {
148
+ rmSync(join(skillsDir, e.name), { recursive: true, force: true });
149
+ }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Sync every bundled darkf-* skill into every detected host: copy when
155
+ * missing, replace when differs, no-op when ok. One host-detection line, then
156
+ * one line per host per skill. An undetected host is skipped without creating
157
+ * anything. Foreign skill dirs (no darkf- prefix) are never read or written.
158
+ * Returns 0 on success; 1 when a present host still ends missing/differs
159
+ * after the sync attempt.
160
+ */
161
+ export function syncAll(deps: SyncDeps): number {
162
+ const log = deps.log ?? ((line: string) => console.log(line));
163
+ const skills = bundledSkills(deps.bundledDir);
164
+ const width = Math.max(...skills.map((s) => s.length), 0);
165
+ let failed = false;
166
+ for (const host of KNOWN_HOSTS) {
167
+ const dir = join(deps.home, host.dir);
168
+ if (!existsSync(dir) && !deps.existsBinary(host.binary)) {
169
+ log(`host ${host.name} — harness not present`);
170
+ continue;
171
+ }
172
+ log(`host ${host.name} (~/${host.dir})`);
173
+ try {
174
+ mkdirSync(dir, { recursive: true, mode: 0o755 });
175
+ clearTempDirs(dir);
176
+ for (const skill of skills) {
177
+ const before = skillState(dir, skill, deps.bundledDir);
178
+ let after = before;
179
+ if (before !== "ok") {
180
+ try {
181
+ copySkill(dir, skill, deps.bundledDir);
182
+ after = skillState(dir, skill, deps.bundledDir);
183
+ } catch (err) {
184
+ log(
185
+ ` ${skill.padEnd(width)} failed (${err instanceof Error ? err.message : String(err)})`,
186
+ );
187
+ failed = true;
188
+ continue;
189
+ }
190
+ }
191
+ const label =
192
+ after === "ok"
193
+ ? before === "missing"
194
+ ? "installed"
195
+ : before === "differs"
196
+ ? "updated (was stale)"
197
+ : "ok"
198
+ : after;
199
+ if (after !== "ok") failed = true;
200
+ log(` ${skill.padEnd(width)} ${label}`);
201
+ }
202
+ } catch (err) {
203
+ log(` failed (${err instanceof Error ? err.message : String(err)})`);
204
+ failed = true;
205
+ }
206
+ }
207
+ return failed ? 1 : 0;
208
+ }
209
+
210
+ // --- daily probe (spec: Daily probe on first invocation) ---
211
+
212
+ export interface ProbeState {
213
+ lastProbe?: string; // local calendar date YYYY-MM-DD of the last probe attempt
214
+ }
215
+
216
+ /** Absent or corrupt file returns {}. Never throws. */
217
+ export function readProbeState(file: string): ProbeState {
218
+ try {
219
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
220
+ if (typeof parsed !== "object" || parsed === null) return {};
221
+ const rec = (parsed as Record<string, unknown>).lastProbe;
222
+ return typeof rec === "string" ? { lastProbe: rec } : {};
223
+ } catch {
224
+ return {};
225
+ }
226
+ }
227
+
228
+ /** mkdir -p on the parent; best-effort — swallow write errors. */
229
+ export function writeProbeState(file: string, state: ProbeState): void {
230
+ try {
231
+ mkdirSync(dirname(file), { recursive: true });
232
+ writeFileSync(file, JSON.stringify(state));
233
+ } catch {
234
+ // An unwritable state location degrades to re-probing next invocation.
235
+ }
236
+ }
237
+
238
+ /** The local calendar date — the day a probe compares against, not UTC. */
239
+ export function todayLocal(now: Date = new Date()): string {
240
+ const y = now.getFullYear();
241
+ const m = String(now.getMonth() + 1).padStart(2, "0");
242
+ const d = String(now.getDate()).padStart(2, "0");
243
+ return `${y}-${m}-${d}`;
244
+ }
245
+
246
+ /**
247
+ * One compact block for the failing harnesses plus the fix hint; null when
248
+ * every present harness is ok (and for absent ones — silent by contract).
249
+ */
250
+ export function probeBlock(checks: HostSkills[]): string[] | null {
251
+ const lines: string[] = [];
252
+ for (const h of checks) {
253
+ if (!h.present) continue;
254
+ const failing = failingSkills(h).map(([skill, state]) => describeFailure(skill, state));
255
+ if (failing.length > 0) lines.push(`skills (${h.host}): ${failing.join(", ")}`);
256
+ }
257
+ if (lines.length === 0) return null;
258
+ lines.push("fix: run darkf setup");
259
+ return lines;
260
+ }
261
+
262
+ /**
263
+ * The startup path, called from main() after the update gate. First
264
+ * invocation of a local calendar day probes; same-day invocations skip
265
+ * silently. Missing or corrupt state counts as never probed. `setup` and
266
+ * `upgrade` skip the probe and refresh the state file so the next command
267
+ * starts a fresh day window. Never fatal: a slow or erroring probe is
268
+ * swallowed and never changes the invoking command's exit code.
269
+ */
270
+ export async function skillsProbeGate(cmd: string | undefined, deps: ProbeDeps): Promise<void> {
271
+ const today = deps.today ?? (() => todayLocal());
272
+ const stamp = () => writeProbeState(deps.stateFile, { lastProbe: today() });
273
+ if (cmd === "setup" || cmd === "upgrade") {
274
+ stamp();
275
+ return;
276
+ }
277
+ const state = readProbeState(deps.stateFile);
278
+ if (state.lastProbe === today()) return;
279
+ try {
280
+ const block = probeBlock(skillsCheck(deps));
281
+ if (block) for (const line of block) (deps.log ?? console.log)(line);
282
+ } catch {
283
+ // swallowed — today's run matters more than the report
284
+ }
285
+ stamp();
286
+ }