@psimona/darkf 0.5.0 → 0.7.1

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 (69) hide show
  1. package/docs/concepts/failure-modes.md +177 -0
  2. package/docs/concepts/handoff.md +91 -0
  3. package/docs/concepts/journal.md +92 -0
  4. package/docs/concepts/node-types.md +177 -0
  5. package/docs/guides/pick-an-agent-runner.md +57 -0
  6. package/docs/guides/plan-with-a-task-queue.md +411 -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 +101 -0
  11. package/docs/index.mdx +68 -0
  12. package/docs/reference/cli-commands.md +105 -0
  13. package/docs/reference/core-types.md +128 -0
  14. package/docs/reference/package-map.md +39 -0
  15. package/docs/start-here/install.md +71 -0
  16. package/docs/start-here/quickstart.md +248 -0
  17. package/package.json +15 -2
  18. package/skills/darkf-usage/SKILL.md +92 -0
  19. package/skills/darkf-writing-workflows/SKILL.md +213 -0
  20. package/src/cli/doctor.test.ts +338 -0
  21. package/src/cli/index.ts +139 -15
  22. package/src/cli/setup.test.ts +384 -0
  23. package/src/cli/setup.ts +281 -0
  24. package/src/cli/state-file.ts +14 -0
  25. package/src/cli/tarball.test.ts +127 -0
  26. package/src/cli/update.test.ts +82 -0
  27. package/src/cli/update.ts +24 -9
  28. package/src/core/tasks.ts +1 -1
  29. package/src/core/types.test.ts +52 -0
  30. package/src/core/types.ts +33 -16
  31. package/src/engine/run.test.ts +462 -3
  32. package/src/engine/run.ts +114 -8
  33. package/src/exports.ts +4 -0
  34. package/src/kit/agents/claude-code.ts +4 -34
  35. package/src/kit/agents/handoff.test.ts +12 -0
  36. package/src/kit/agents/handoff.ts +32 -8
  37. package/src/kit/agents/opencode.test.ts +232 -2
  38. package/src/kit/agents/opencode.ts +80 -31
  39. package/src/kit/specs.test.ts +247 -0
  40. package/src/kit/specs.ts +344 -0
  41. package/src/kit/status.test.ts +67 -0
  42. package/src/kit/status.ts +29 -4
  43. package/src/kit/validation/zod.test.ts +42 -0
  44. package/src/kit/validation/zod.ts +20 -0
  45. package/workflows/dev-loop/scripts/begin.ts +9 -6
  46. package/workflows/dev-loop/scripts/dispatch.ts +50 -0
  47. package/workflows/dev-loop/scripts/finish.ts +26 -21
  48. package/workflows/dev-loop/scripts/mark-done.ts +22 -0
  49. package/workflows/dev-loop/scripts/validate-plan.ts +30 -0
  50. package/workflows/dev-loop/workflow.ts +171 -64
  51. package/bunfig.toml +0 -13
  52. package/examples/article-classifier/data/articles.ts +0 -38
  53. package/examples/article-classifier/scripts/next.ts +0 -7
  54. package/examples/article-classifier/scripts/queue.ts +0 -33
  55. package/examples/article-classifier/scripts/record.ts +0 -9
  56. package/examples/article-classifier/workflow.ts +0 -44
  57. package/examples/haiku-commit/scripts/check.ts +0 -24
  58. package/examples/haiku-commit/workflow.ts +0 -28
  59. package/examples/haiku-readme/scripts/test.ts +0 -13
  60. package/examples/haiku-readme/scripts/write.ts +0 -10
  61. package/examples/haiku-readme/workflow.ts +0 -41
  62. package/examples/task-queue/scripts/next.ts +0 -20
  63. package/examples/task-queue/scripts/record.ts +0 -20
  64. package/examples/task-queue/supervise.ts +0 -57
  65. package/examples/task-queue/workflow.ts +0 -33
  66. package/feedback/2026-10-30-self-update.md +0 -29
  67. package/feedback/2026-10-31-task-list-json.md +0 -26
  68. package/tsconfig.json +0 -4
  69. /package/workflows/dev-loop/scripts/{check.ts → test.ts} +0 -0
package/src/cli/index.ts CHANGED
@@ -44,11 +44,21 @@ import {
44
44
  classifyTerminal,
45
45
  foldJournal,
46
46
  foldReport,
47
+ limitWarning,
47
48
  nudgeWarning,
48
49
  stallWarning,
49
50
  type TerminalState,
50
51
  } from "../kit/status.ts";
51
- import { type UpdateDeps, updateGate, upgradeCmd } from "./update.ts";
52
+ import {
53
+ describeFailure,
54
+ failingSkills,
55
+ type ProbeDeps,
56
+ type SkillsDeps,
57
+ skillsCheck,
58
+ skillsProbeGate,
59
+ syncAll,
60
+ } from "./setup.ts";
61
+ import { type UpdateDeps, updateGate, upgradeWithSkills } from "./update.ts";
52
62
 
53
63
  const INDEX_PATH = fileURLToPath(import.meta.url);
54
64
  // Fixed, not yet measured against a cold `bun` import on real hosts — see
@@ -123,12 +133,12 @@ function resolveWorkflowDir(ref: string): string {
123
133
  process.exit(1);
124
134
  }
125
135
 
126
- interface WorkflowListing {
136
+ export interface WorkflowListing {
127
137
  name: string;
128
138
  source: "workspace" | "built-in";
129
139
  }
130
140
 
131
- function listWorkflows(): WorkflowListing[] {
141
+ export function listWorkflows(): WorkflowListing[] {
132
142
  const roots: Array<[string, WorkflowListing["source"]]> = [
133
143
  [resolve(process.cwd(), "darkf"), "workspace"],
134
144
  [resolve(selfRoot(), "workflows"), "built-in"],
@@ -228,17 +238,34 @@ function describeValidationError(err: WorkflowValidationError): string {
228
238
  }
229
239
  }
230
240
 
231
- async function doctorCmd(args: string[]): Promise<number> {
232
- const ref = args[0];
241
+ /**
242
+ * Workflow checks (skill-setup spec: command split). `darkf validate <ref>`
243
+ * inherits doctor's artifact-level checks unchanged: workflow resolution,
244
+ * module load, exports, structure validation. Skill state is deliberately
245
+ * not checked here — a workflow can be sound on a machine whose skills are
246
+ * stale; the two verdicts stay independent.
247
+ */
248
+ /** Shared ok/FAIL line printer for `validate` and `doctor`: logs each check
249
+ * as it runs and remembers whether any of them failed. */
250
+ function makeChecker(): {
251
+ check: (label: string, ok: boolean, detail?: string) => void;
252
+ failed: () => boolean;
253
+ } {
233
254
  let fail = false;
234
255
  const check = (label: string, ok: boolean, detail?: string) => {
235
256
  console.log(`${ok ? "ok " : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
236
257
  if (!ok) fail = true;
237
258
  };
259
+ return { check, failed: () => fail };
260
+ }
261
+
262
+ async function validateCmd(args: string[]): Promise<number> {
263
+ const ref = args[0];
264
+ const { check, failed } = makeChecker();
238
265
 
239
266
  // 1. workflow resolution
240
267
  if (ref === undefined) {
241
- check("workflow ref", false, "usage: darkf doctor <workflow-ref-or-path>");
268
+ check("workflow ref", false, "usage: darkf validate <ref-or-path>");
242
269
  return Promise.resolve(1);
243
270
  }
244
271
  const candidates = workflowCandidates(ref);
@@ -263,7 +290,7 @@ async function doctorCmd(args: string[]): Promise<number> {
263
290
  check(
264
291
  "exports `agentRunner`",
265
292
  typeof mod.agentRunner?.run === "function",
266
- "agent states need a runner; built-ins live in src/agents/",
293
+ "agent states need a runner; built-ins live in src/kit/agents/",
267
294
  );
268
295
  if (typeof mod.workflow?.states === "object" && typeof mod.workflow?.initial === "string") {
269
296
  try {
@@ -294,12 +321,28 @@ async function doctorCmd(args: string[]): Promise<number> {
294
321
  check("exports `agentRunner`", false, "skipped — no resolved workflow");
295
322
  }
296
323
 
297
- // 3. agent binaries
324
+ return Promise.resolve(failed() ? 1 : 0);
325
+ }
326
+
327
+ /**
328
+ * Environment checks (skill-setup spec: command split). `darkf doctor` takes
329
+ * no ref and is strictly machine-level: agent binaries, cwd sanity, and the
330
+ * skills section. Read-only — fixing skill drift is always `darkf setup`.
331
+ */
332
+ function doctorCmd(args: string[]): number {
333
+ if (args[0] !== undefined) {
334
+ // The command is young; no silent compatibility shim.
335
+ console.log("usage: darkf doctor takes no ref — darkf validate <ref> for workflow checks");
336
+ return 1;
337
+ }
338
+ const { check, failed } = makeChecker();
339
+
340
+ // 1. agent binaries
298
341
  for (const bin of ["claude", "opencode"]) {
299
342
  check(`agent binary '${bin}'`, Bun.which(bin) !== null);
300
343
  }
301
344
 
302
- // 4. cwd sanity — the run-1 mistake: targeting a repo while sitting in the darkf checkout
345
+ // 2. cwd sanity — the run-1 mistake: targeting a repo while sitting in the darkf checkout
303
346
  const cwd = process.cwd();
304
347
  const insideSelf = cwd.startsWith(selfRoot());
305
348
  check(
@@ -310,7 +353,29 @@ async function doctorCmd(args: string[]): Promise<number> {
310
353
  const gitRoot = projectRoot();
311
354
  check("cwd is inside a git repo", existsSync(join(gitRoot, ".git")), gitRoot);
312
355
 
313
- return Promise.resolve(fail ? 1 : 0);
356
+ // 3. skills — every known harness always named; `harness not present` is
357
+ // informational and always passes (the binaries check above is the failure
358
+ // signal for an absent binary).
359
+ for (const h of skillsCheck(skillsDeps())) {
360
+ const label = `skills (${h.host})`;
361
+ if (!h.present) {
362
+ check(label, true, "harness not present");
363
+ continue;
364
+ }
365
+ const failing = failingSkills(h);
366
+ if (failing.length === 0) {
367
+ const total = Object.keys(h.states).length;
368
+ check(label, true, `${total}/${total} installed`);
369
+ } else {
370
+ check(
371
+ label,
372
+ false,
373
+ `${failing.map(([skill, state]) => describeFailure(skill, state)).join("; ")} — run: darkf setup`,
374
+ );
375
+ }
376
+ }
377
+
378
+ return failed() ? 1 : 0;
314
379
  }
315
380
 
316
381
  function workflowsCmd(): void {
@@ -685,7 +750,7 @@ function printDigest(entry: RegistryEntry, state: TerminalState, journalText: st
685
750
  }
686
751
  if (digest.current?.phase === "running" && digest.current.startedAt !== undefined) {
687
752
  // Live elapsed, computed at print time — journal-frozen runtime goes stale
688
- // during long nodes (spec: docs/specs/live-runtime).
753
+ // during long nodes (spec: docs/specs/_built/live-runtime).
689
754
  console.log(
690
755
  `elapsed: ${formatMs(Date.now() - digest.current.startedAt)} (node ${digest.current.state})`,
691
756
  );
@@ -695,6 +760,8 @@ function printDigest(entry: RegistryEntry, state: TerminalState, journalText: st
695
760
  if (agentStall) console.log(`warn: ${agentStall}`);
696
761
  const nudge = nudgeWarning(digest);
697
762
  if (nudge) console.log(`warn: ${nudge}`);
763
+ const limit = limitWarning(digest);
764
+ if (limit) console.log(`warn: ${limit}`);
698
765
  }
699
766
  if (digest.runtimeMs !== null) console.log(`runtime: ${formatMs(digest.runtimeMs)}`);
700
767
  if (state === "orphaned") console.log("orphaned: true");
@@ -752,7 +819,7 @@ function printTransition(e: NodeEvent, prevTs: number | null, isHeartbeat = fals
752
819
  const idle = startedAt !== undefined ? e.timestamp - startedAt : 0;
753
820
  let line = `${e.state} still running — ${(idle / 1000).toFixed(0)}s elapsed`;
754
821
  // Agent-level liveness, distinct from the engine-heartbeat idle above —
755
- // see docs/specs/agent-liveness/spec.md. Absent for script dispatches or
822
+ // see docs/specs/_built/agent-liveness/spec.md. Absent for script dispatches or
756
823
  // runners that don't report progress.
757
824
  if (status.phase === "running" && status.agentIdleMs !== undefined) {
758
825
  const agentIdleSec = Math.round(status.agentIdleMs / 1000);
@@ -831,6 +898,7 @@ async function monitorRun(entry: RegistryEntry, windowSec: number, once: boolean
831
898
  const pid = entry.pid;
832
899
  const deadline = Date.now() + windowSec * 1000;
833
900
  const hinted = new Set<string>();
901
+ let lastLimitProbe = 0;
834
902
 
835
903
  // Open the window: if the begin marker is already there, print it once as
836
904
  // context (not a transition) and tail only lines added from this point on.
@@ -854,6 +922,18 @@ async function monitorRun(entry: RegistryEntry, windowSec: number, once: boolean
854
922
  lastSeen = events.length;
855
923
  dwellHint(events, entry.runId, hinted);
856
924
 
925
+ // Usage-limit wait (docs/specs/_built/usage-limit-backoff/spec.md): re-render
926
+ // the wait line when the probe advances, so a monitored wait shows the
927
+ // countdown instead of silence — same one-line warn style as the status
928
+ // digest's stallWarning/nudgeWarning.
929
+ const limitDigest = foldJournal(text);
930
+ const backoff = limitDigest.current?.limitBackoff;
931
+ if (limitDigest.current?.phase === "running" && backoff && backoff.probe !== lastLimitProbe) {
932
+ const warning = limitWarning(limitDigest);
933
+ if (warning) console.log(`warn: ${warning}`);
934
+ lastLimitProbe = backoff.probe;
935
+ }
936
+
857
937
  // Re-check liveness every sub-poll: the journal's last line is authoritative
858
938
  // for succeeded/crashed, and a dead PID with no terminal marker is
859
939
  // orphaned/host-died.
@@ -976,6 +1056,28 @@ function updateStateFile(): string {
976
1056
  return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-update-check.json");
977
1057
  }
978
1058
 
1059
+ // Same XDG state scheme, for the daily skills probe (skill-setup spec).
1060
+ function skillsProbeStateFile(): string {
1061
+ const xdg = process.env.XDG_STATE_HOME;
1062
+ if (xdg) return join(xdg, "darkf", "last-skills-check.json");
1063
+ return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-skills-check.json");
1064
+ }
1065
+
1066
+ // The bundled skills dir is package-relative (sibling of workflows/), so a
1067
+ // global install and a sibling checkout both work — the same selfRoot()
1068
+ // mechanism workflows/ resolution already uses.
1069
+ function skillsDeps(): SkillsDeps {
1070
+ return {
1071
+ home: process.env.HOME ?? "",
1072
+ bundledDir: resolve(dirname(INDEX_PATH), "..", "..", "skills"),
1073
+ existsBinary: (name: string) => Bun.which(name) !== null,
1074
+ };
1075
+ }
1076
+
1077
+ function probeDeps(): ProbeDeps {
1078
+ return { ...skillsDeps(), stateFile: skillsProbeStateFile() };
1079
+ }
1080
+
979
1081
  async function main(): Promise<void> {
980
1082
  const [cmd, ...rest] = process.argv.slice(2);
981
1083
 
@@ -991,8 +1093,22 @@ async function main(): Promise<void> {
991
1093
  };
992
1094
  await updateGate(cmd, updateDeps);
993
1095
 
1096
+ // Daily skills probe (skill-setup spec): after the update gate, before the
1097
+ // command's own output. setup and upgrade are exempt (they sync the skills
1098
+ // themselves) and refresh the probe stamp. Never fatal — the outcome never
1099
+ // changes the invoking command's exit code.
1100
+ await skillsProbeGate(cmd, probeDeps());
1101
+
994
1102
  if (cmd === "upgrade") {
995
- process.exit(await upgradeCmd(updateDeps));
1103
+ // Skill sync after the install (skill-setup spec): the new package may
1104
+ // ship new skill content, and the running process resolves the new
1105
+ // bundled copies on disk. Best-effort: a sync failure is reported and
1106
+ // exits non-zero, but never masks the upgrade itself.
1107
+ process.exit(await upgradeWithSkills(updateDeps, skillsDeps()));
1108
+ return;
1109
+ }
1110
+ if (cmd === "setup") {
1111
+ process.exit(syncAll(skillsDeps()));
996
1112
  return;
997
1113
  }
998
1114
  if (cmd === "workflows") {
@@ -1004,7 +1120,11 @@ async function main(): Promise<void> {
1004
1120
  return;
1005
1121
  }
1006
1122
  if (cmd === "doctor") {
1007
- process.exit(await doctorCmd(rest));
1123
+ process.exit(doctorCmd(rest));
1124
+ return;
1125
+ }
1126
+ if (cmd === "validate") {
1127
+ process.exit(await validateCmd(rest));
1008
1128
  return;
1009
1129
  }
1010
1130
  if (cmd === "render") {
@@ -1037,4 +1157,8 @@ async function main(): Promise<void> {
1037
1157
  await runCmd(resolveWorkflowDir(cmd ?? "."), undefined);
1038
1158
  }
1039
1159
 
1040
- main();
1160
+ // Dispatch only when this file is the process entry point — the `darkf` bin,
1161
+ // or the spawned `__worker` (startCmd spawns this same file directly). The
1162
+ // package public surface (src/exports.ts) re-exports `listWorkflows` from
1163
+ // here; importing it must not execute the CLI against the host's own argv.
1164
+ if (import.meta.main) main();
@@ -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
+ });