@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/engine/run.ts CHANGED
@@ -29,14 +29,22 @@ import { createJsonlEventLogger } from "./eventLog.ts";
29
29
  const DEFAULT_HEARTBEAT_MS = 30_000;
30
30
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000; // 1h — high default ceiling, not a tuning knob
31
31
  const DEFAULT_MAX_STEPS = 1000;
32
+ // Usage-limit backoff defaults (docs/specs/_built/usage-limit-backoff/spec.md) —
33
+ // the leaf-config fields on BaseLeafDef fall back to these. Fixed 30-min
34
+ // probe interval, deliberately not the provider message's quoted reset time
35
+ // (its timezone is not the supervisor's); 24h bounds the total wait per
36
+ // node visit before the run crashes with the last usage-limit reason.
37
+ const DEFAULT_USAGE_LIMIT_RETRY_MS = 30 * 60 * 1000;
38
+ const DEFAULT_USAGE_LIMIT_MAX_WAIT_MS = 24 * 60 * 60 * 1000;
32
39
  // Bounded in-session repair attempts per outer attempt (see
33
- // docs/specs/session-nudge/spec.md) — not a `def.retries`-style tuning
40
+ // docs/specs/_built/session-nudge/spec.md) — not a `def.retries`-style tuning
34
41
  // knob, deliberately fixed.
35
42
  const NUDGE_LIMIT = 3;
36
43
  const NUDGEABLE_KINDS = new Set<CrashReason["kind"]>([
37
44
  "handoff-missing",
38
45
  "handoff-unparseable",
39
46
  "no-transition",
47
+ "validation-failed",
40
48
  ]);
41
49
  function isNudgeable(reason: CrashReason): boolean {
42
50
  return NUDGEABLE_KINDS.has(reason.kind);
@@ -63,6 +71,10 @@ function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
63
71
  });
64
72
  }
65
73
 
74
+ function sleep(ms: number): Promise<void> {
75
+ return new Promise((r) => setTimeout(r, ms));
76
+ }
77
+
66
78
  const defaultScriptRunner: ScriptRunner = {
67
79
  async run(_id, def, handoff, baseDir, info) {
68
80
  const url = pathToFileURL(`${baseDir}/${def.file}`).href;
@@ -203,14 +215,24 @@ export async function run(opts: RunOptions): Promise<RunResult> {
203
215
  let reason: CrashReason | undefined;
204
216
  let agentSessionId: string | undefined;
205
217
  let attempt = 0;
218
+ // Usage-limit wait bookkeeping — per node visit, never per attempt:
219
+ // waits consume no retry, so the wait budget spans every attempt of
220
+ // this visit (docs/specs/_built/usage-limit-backoff/spec.md).
221
+ let limitWaitedMs = 0;
222
+ let limitProbes = 0;
206
223
 
207
224
  attemptLoop: for (attempt = 1; attempt <= maxAttempts; attempt++) {
208
225
  // Fixed once per outer attempt: every dispatch this attempt makes — the
209
226
  // first call and up to NUDGE_LIMIT nudges after it — spends down the
210
227
  // SAME remaining budget, so a nudge sequence can't multiply the
211
- // configured per-attempt timeout (docs/specs/session-nudge/spec.md,
228
+ // configured per-attempt timeout (docs/specs/_built/session-nudge/spec.md,
212
229
  // "Dispatch loop change").
213
- const deadline = Date.now() + timeoutMs;
230
+ //
231
+ // Usage-limit exception (same spec family, usage-limit-backoff D-7):
232
+ // recomputed after every usage-limit wait, so a slept interval never
233
+ // eats into the next dispatch's timeout — `timeoutMs` bounds a single
234
+ // dispatch, never a wait.
235
+ let deadline = Date.now() + timeoutMs;
214
236
  let nudgeAttempt = 0;
215
237
 
216
238
  for (;;) {
@@ -228,12 +250,15 @@ export async function run(opts: RunOptions): Promise<RunResult> {
228
250
  const startedAt = Date.now();
229
251
  // Reset fresh per dispatch attempt (including each nudge) — a new
230
252
  // process gets a new progress snapshot, never carried over from a
231
- // previous attempt. See docs/specs/agent-liveness/spec.md.
253
+ // previous attempt. See docs/specs/_built/agent-liveness/spec.md.
232
254
  let latestProgress: AgentProgress | undefined;
233
255
  const onProgress = (p: AgentProgress) => {
234
256
  latestProgress = p;
235
257
  };
236
- const runningStatus = (lastHeartbeat: number): NodeStatus => ({
258
+ const runningStatus = (
259
+ lastHeartbeat: number,
260
+ limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number },
261
+ ): NodeStatus => ({
237
262
  phase: "running",
238
263
  attempt,
239
264
  startedAt,
@@ -246,11 +271,12 @@ export async function run(opts: RunOptions): Promise<RunResult> {
246
271
  }
247
272
  : {}),
248
273
  ...(nudgeAttempt > 0 ? { nudgeAttempt, nudgeReason } : {}),
274
+ ...(limitBackoff ? { limitBackoff } : {}),
249
275
  });
250
276
  emit(runningStatus(startedAt), current, scopePath);
251
277
  // Live-runtime heartbeats: journal a refreshed `running` status while the
252
278
  // dispatch is open, so status/monitor can advance runtime and prove
253
- // liveness (spec: darkf-cli/docs/specs/live-runtime). unref'd — a pending
279
+ // liveness (spec: docs/specs/_built/live-runtime). unref'd — a pending
254
280
  // timer must never keep the process alive past the run's own exit.
255
281
  const heartbeat =
256
282
  heartbeatMs > 0
@@ -271,9 +297,50 @@ export async function run(opts: RunOptions): Promise<RunResult> {
271
297
  continue attemptLoop;
272
298
  }
273
299
  agentSessionId = raw.agentSessionId ?? agentSessionId;
274
- const validationError = def.validate?.(raw, handoff);
300
+ // Bare-payload coercion (agent nodes only). A result without an
301
+ // `event` field is the agent's raw payload, not an envelope —
302
+ // wrap it so the payload always rides the reserved `output`
303
+ // channel. Without this, a payload that itself carries an
304
+ // `output` key hijacks the channel downstream (run 0a1b2ca3: a
305
+ // hybrid `{behavior_ok, gaps, output: {summary}}` shipped the
306
+ // summary as the payload and shadowed the passing verdict).
307
+ // Routing is untouched: `resolveTarget` still reads `raw.event`,
308
+ // and event-less results keep falling through `def.next`.
309
+ const result_ =
310
+ def.type === "agent" && raw.event === undefined ? ({ output: raw } as NodeResult) : raw;
311
+ // outputType (agent leaves only) — a shape check on the payload,
312
+ // run before `validate` so a validate script can read the output
313
+ // without re-checking its shape
314
+ // (docs/specs/output-validation/spec.md, "Order"). Same inline
315
+ // nudge form as no-transition below: this reason comes from a
316
+ // return value, not a thrown AgentFailure, so the catch block's
317
+ // isNudgeable path never sees it.
318
+ const typeResult =
319
+ def.type === "agent" && def.outputType
320
+ ? def.outputType.safeParse(result_.output)
321
+ : undefined;
322
+ if (typeResult && !typeResult.success) {
323
+ reason = { kind: "validation-failed", message: typeResult.message };
324
+ if (agentSessionId && nudgeAttempt < NUDGE_LIMIT) {
325
+ nudgeAttempt++;
326
+ continue;
327
+ }
328
+ continue attemptLoop;
329
+ }
330
+ const validationError = def.validate?.(result_, handoff);
275
331
  if (validationError !== undefined) {
276
332
  reason = { kind: "validation-failed", message: validationError };
333
+ // A validate rejection now nudges in-session first, same inline
334
+ // form as the checks beside it — a return-value reason, so the
335
+ // catch block's isNudgeable path never sees it. Up to
336
+ // NUDGE_LIMIT nudges consume no retry; only the fallback to a
337
+ // fresh attempt does
338
+ // (docs/specs/output-validation/spec.md, "Where this plugs
339
+ // into the dispatch loop").
340
+ if (agentSessionId && nudgeAttempt < NUDGE_LIMIT) {
341
+ nudgeAttempt++;
342
+ continue;
343
+ }
277
344
  continue attemptLoop;
278
345
  }
279
346
  const resolved = resolveTarget(def, raw.event);
@@ -286,7 +353,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
286
353
  continue attemptLoop;
287
354
  }
288
355
 
289
- result = raw;
356
+ result = result_;
290
357
  target = resolved;
291
358
  reason = undefined;
292
359
  break attemptLoop;
@@ -309,6 +376,45 @@ export async function run(opts: RunOptions): Promise<RunResult> {
309
376
  nudgeAttempt++;
310
377
  continue;
311
378
  }
379
+ // Usage-limit (docs/specs/_built/usage-limit-backoff/spec.md, Wait and
380
+ // resume): a quota wall is not a failed attempt — it consumes no
381
+ // retry. Sleep usageLimitRetryMs (heartbeating the wait), then
382
+ // re-dispatch this same attempt; the existing
383
+ // previousFailure/agentSessionId threading below is what makes the
384
+ // runner resume the interrupted session. At the cap, the existing
385
+ // crashed() path after the attempt loop records the last
386
+ // usage-limit reason — attempt untouched, so the crash shows no
387
+ // retry consumed.
388
+ if (reason.kind === "usage-limit") {
389
+ const retryMs = def.usageLimitRetryMs ?? DEFAULT_USAGE_LIMIT_RETRY_MS;
390
+ const maxWaitMs = def.usageLimitMaxWaitMs ?? DEFAULT_USAGE_LIMIT_MAX_WAIT_MS;
391
+ if (limitWaitedMs + retryMs > maxWaitMs) {
392
+ break attemptLoop;
393
+ }
394
+ limitWaitedMs += retryMs;
395
+ limitProbes++;
396
+ const limitBackoff = {
397
+ probe: limitProbes,
398
+ nextAttemptAt: Date.now() + retryMs,
399
+ waitedMs: limitWaitedMs,
400
+ };
401
+ // Journal the wait immediately (nudge-start precedent: not gated
402
+ // behind a heartbeat cadence), then heartbeat it for as long as
403
+ // it lasts, so status/monitor show the wait instead of silence.
404
+ emit(runningStatus(Date.now(), limitBackoff), current, scopePath);
405
+ const waitHeartbeat =
406
+ heartbeatMs > 0
407
+ ? setInterval(
408
+ () => emit(runningStatus(Date.now(), limitBackoff), current, scopePath),
409
+ heartbeatMs,
410
+ )
411
+ : undefined;
412
+ waitHeartbeat?.unref?.();
413
+ await sleep(retryMs);
414
+ waitHeartbeat && clearInterval(waitHeartbeat);
415
+ deadline = Date.now() + timeoutMs;
416
+ continue;
417
+ }
312
418
  continue attemptLoop;
313
419
  }
314
420
  }
package/src/exports.ts CHANGED
@@ -1,2 +1,6 @@
1
+ // Workflow discovery (opencode-overlay-tabs r9): the same two-root scan
2
+ // `darkf run`/`render` resolve against, reused instead of re-scanned.
3
+ export { listWorkflows, type WorkflowListing } from "./cli/index.ts";
1
4
  export * from "./kit/registry.ts";
5
+ export * from "./kit/specs.ts";
2
6
  export * from "./kit/status.ts";
@@ -1,44 +1,14 @@
1
1
  import { mkdir } from "node:fs/promises";
2
2
  import { dirname } from "node:path";
3
- import {
4
- AgentFailure,
5
- type AgentRunner,
6
- type AgentStateDef,
7
- type NodeResult,
8
- } from "../../core/index.ts";
9
- import {
10
- handoffContractText,
11
- handoffPath,
12
- nudgeMessage,
13
- readHandoff,
14
- usagePath,
15
- } from "./handoff.ts";
3
+ import { AgentFailure, type AgentRunner, type NodeResult } from "../../core/index.ts";
4
+ import { buildPrompt, handoffPath, nudgeMessage, readHandoff, usagePath } from "./handoff.ts";
16
5
 
17
6
  // Mirrors darkf-engine's own DEFAULT_TIMEOUT_MS (run.ts) so this runner can
18
7
  // kill its own subprocess in step with the engine's timeout instead of
19
8
  // leaving it running past the point where the engine has moved on — see
20
- // docs/specs/agent-handoff/spec.md's retry-overwrite race note.
9
+ // docs/specs/_built/agent-handoff/spec.md's retry-overwrite race note.
21
10
  const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000;
22
11
 
23
- function buildPrompt(
24
- def: AgentStateDef,
25
- handoff: NodeResult,
26
- info: { validEvents: string[]; hasFallback: boolean },
27
- path: string,
28
- ): string {
29
- const parts = [def.prompt, `Input from the previous step:\n${JSON.stringify(handoff)}`];
30
-
31
- if (info.validEvents.length > 0) {
32
- const fallbackNote = info.hasFallback ? ` If none apply, you may omit "event" instead.` : "";
33
- parts.push(
34
- `Your "event" must be exactly one of: ${info.validEvents.join(", ")}.${fallbackNote}`,
35
- );
36
- }
37
-
38
- parts.push(handoffContractText(path));
39
- return parts.join("\n\n");
40
- }
41
-
42
12
  interface ClaudeCodeStdout {
43
13
  session_id?: string;
44
14
  total_cost_usd?: number;
@@ -102,7 +72,7 @@ export const claudeCodeRunner: AgentRunner = {
102
72
  const permissionMode =
103
73
  (agentConfig.permissionMode as string | undefined) ?? "bypassPermissions";
104
74
  const model = agentConfig.model as string | undefined;
105
- // Same-session nudge (docs/specs/session-nudge/spec.md): when the
75
+ // Same-session nudge (docs/specs/_built/session-nudge/spec.md): when the
106
76
  // previous attempt failed in a repairable way and we have its session
107
77
  // id, send a short corrective message into that session instead of
108
78
  // replaying the full prompt. `--resume` itself is unconditional on
@@ -126,3 +126,15 @@ test("nudgeMessage builds the no-transition repair text, naming the bad event an
126
126
  expect(msg).toContain("ok, changes_requested");
127
127
  expect(msg).toContain("routable event");
128
128
  });
129
+
130
+ test("nudgeMessage builds the validation-failed repair text, quoting the message", () => {
131
+ const info = baseInfo({
132
+ agentSessionId: "sess-1",
133
+ previousFailure: { kind: "validation-failed", message: "tasks[2].title: required" },
134
+ });
135
+ const msg = nudgeMessage(info, "/root/.darkf/run/run-1/handoff/0001-Plan.json")!;
136
+ expect(msg).toContain("failed validation");
137
+ expect(msg).toContain("tasks[2].title: required");
138
+ expect(msg).toContain('Rewrite the handoff\'s "output" field');
139
+ expect(msg).toContain("/root/.darkf/run/run-1/handoff/0001-Plan.json");
140
+ });
@@ -1,9 +1,9 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import type { DispatchInfo } from "../../core/index.ts";
3
+ import type { AgentStateDef, DispatchInfo, NodeResult } from "../../core/index.ts";
4
4
 
5
5
  // Shared, harness-agnostic half of the agent-handoff contract. See
6
- // docs/specs/agent-handoff/spec.md. Per-harness runners own everything else
6
+ // docs/specs/_built/agent-handoff/spec.md. Per-harness runners own everything else
7
7
  // (invocation, native structured-output vs. prompt fallback, agentSessionId,
8
8
  // subprocess lifecycle).
9
9
 
@@ -35,13 +35,35 @@ export async function readHandoff(path: string): Promise<unknown> {
35
35
  return JSON.parse(text);
36
36
  }
37
37
 
38
+ /** Builds one agent's prompt from its state def, the previous step's
39
+ * handoff, and the valid outgoing events — identical for every harness,
40
+ * so each runner calls this instead of building its own. */
41
+ export function buildPrompt(
42
+ def: AgentStateDef,
43
+ handoff: NodeResult,
44
+ info: { validEvents: string[]; hasFallback: boolean },
45
+ path: string,
46
+ ): string {
47
+ const parts = [def.prompt, `Input from the previous step:\n${JSON.stringify(handoff)}`];
48
+
49
+ if (info.validEvents.length > 0) {
50
+ const fallbackNote = info.hasFallback ? ` If none apply, you may omit "event" instead.` : "";
51
+ parts.push(
52
+ `Your "event" must be exactly one of: ${info.validEvents.join(", ")}.${fallbackNote}`,
53
+ );
54
+ }
55
+
56
+ parts.push(handoffContractText(path));
57
+ return parts.join("\n\n");
58
+ }
59
+
38
60
  /**
39
- * Shared same-session repair text for the three nudgeable `CrashReason`
40
- * kinds (docs/specs/session-nudge/spec.md). `undefined` means "don't
41
- * nudge" — either there's no `previousFailure`, no `agentSessionId` to
42
- * resume, or the failure isn't one of the three repairable kinds. Both
43
- * runners call this identically; only the CLI invocation that sends the
44
- * message differs per harness.
61
+ * Shared same-session repair text for the nudgeable `CrashReason` kinds
62
+ * (docs/specs/_built/session-nudge/spec.md, docs/specs/output-validation/spec.md).
63
+ * `undefined` means "don't nudge" — either there's no `previousFailure`, no
64
+ * `agentSessionId` to resume, or the failure isn't one of the repairable
65
+ * kinds. Both runners call this identically; only the CLI invocation that
66
+ * sends the message differs per harness.
45
67
  */
46
68
  export function nudgeMessage(info: DispatchInfo, path: string): string | undefined {
47
69
  const failure = info.previousFailure;
@@ -54,6 +76,8 @@ export function nudgeMessage(info: DispatchInfo, path: string): string | undefin
54
76
  return `The JSON at ${path} failed to parse (${failure.parseError}). Rewrite it as a single valid JSON object with the contract fields.`;
55
77
  case "no-transition":
56
78
  return `You reported event ${failure.event}; this state only routes ${validEvents}. Re-issue the handoff with a routable event.`;
79
+ case "validation-failed":
80
+ return `Your output failed validation: ${failure.message}\n\nRewrite the handoff's "output" field to fix this and write it again to ${path}.`;
57
81
  default:
58
82
  return undefined;
59
83
  }
@@ -1,5 +1,10 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { readIncrementally, scanStepFinish } from "./opencode.ts";
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { AgentFailure, type AgentStateDef, type DispatchInfo } from "../../core/index.ts";
6
+ import { handoffPath } from "./handoff.ts";
7
+ import { matchUsageLimit, opencodeRunner, readIncrementally, scanStepFinish } from "./opencode.ts";
3
8
 
4
9
  function ndjson(events: unknown[]): string {
5
10
  return events.map((e) => JSON.stringify(e)).join("\n");
@@ -134,3 +139,228 @@ describe("readIncrementally", () => {
134
139
  expect(seen).toEqual(["café"]);
135
140
  });
136
141
  });
142
+
143
+ // --- usage-limit-backoff (docs/specs/_built/usage-limit-backoff/spec.md) ---
144
+
145
+ describe("matchUsageLimit", () => {
146
+ test("matches the captured usage-limit line, case-insensitively, returning the line itself", () => {
147
+ const captured = "Usage limit reached for 5 hour. Your limit will reset at 2026-11-01 06:58:19";
148
+ expect(matchUsageLimit(`${captured}\n`, "")).toBe(captured);
149
+ expect(matchUsageLimit("", "USAGE LIMIT EXHAUSTED — retry later\n")).toBe(
150
+ "USAGE LIMIT EXHAUSTED — retry later",
151
+ );
152
+ });
153
+
154
+ test("matches the full conservative marker set: rate limit, limit exceeded, 429", () => {
155
+ expect(matchUsageLimit("rate limit exceeded for org\n", "")).toBe(
156
+ "rate limit exceeded for org",
157
+ );
158
+ expect(matchUsageLimit("", "limit exceeded: reduce your request rate\n")).toBe(
159
+ "limit exceeded: reduce your request rate",
160
+ );
161
+ expect(matchUsageLimit("HTTP 429: too many requests\n", "")).toBe(
162
+ "HTTP 429: too many requests",
163
+ );
164
+ });
165
+
166
+ test("scans stderr first, then stdout, returning the first matched line", () => {
167
+ expect(matchUsageLimit("first stderr rate limit\n", "second stdout usage limit\n")).toBe(
168
+ "first stderr rate limit",
169
+ );
170
+ expect(matchUsageLimit("", "stdout usage limit\n")).toBe("stdout usage limit");
171
+ });
172
+
173
+ test("never matches an agent-authored JSON line, even when its text contains a marker", () => {
174
+ const json = JSON.stringify({
175
+ type: "message",
176
+ part: { text: "the agent mused about the usage limit" },
177
+ });
178
+ expect(matchUsageLimit("", json)).toBeUndefined();
179
+ expect(matchUsageLimit(`${json}\nplain usage limit line\n`, "")).toBe("plain usage limit line");
180
+ });
181
+
182
+ test("an ordinary non-limit API error does not match", () => {
183
+ expect(matchUsageLimit("opencode: API error 500: backend exploded\n", "")).toBeUndefined();
184
+ expect(matchUsageLimit("", '{"type":"step-finish","part":{"reason":"stop"}}')).toBeUndefined();
185
+ });
186
+ });
187
+
188
+ // Runner-level classification and resume paths. A fake `opencode` binary
189
+ // stands in for the real CLI: it records argv (NUL-separated, prompts contain
190
+ // newlines), emits NDJSON, optionally writes the handoff file, and exits with
191
+ // a scripted code — so `Bun.spawn` runs unmocked. `Bun.which` is mocked to
192
+ // resolve it: it snapshots PATH at process start, so mutating the env at
193
+ // test time has no effect.
194
+ describe("opencodeRunner usage-limit classification + resume", () => {
195
+ let fakeDir: string;
196
+ let realWhich: typeof Bun.which;
197
+
198
+ beforeAll(() => {
199
+ fakeDir = mkdtempSync(join(tmpdir(), "darkf-opencode-fake-"));
200
+ realWhich = Bun.which;
201
+ Bun.which = ((bin: string) =>
202
+ bin === "opencode" ? join(fakeDir, "opencode") : realWhich(bin)) as typeof Bun.which;
203
+ });
204
+
205
+ afterAll(() => {
206
+ Bun.which = realWhich;
207
+ rmSync(fakeDir, { recursive: true, force: true });
208
+ });
209
+
210
+ const RUN_ID = "f1e2d3c4-1111-4222-8333-444455556666";
211
+ const def: AgentStateDef = {
212
+ type: "agent",
213
+ prompt: "FRESH-PROMPT-MARKER do the task",
214
+ agent: { model: "test-model" },
215
+ };
216
+
217
+ /** Installs a scripted fake binary and a per-test scratch rootDir. The
218
+ * builder receives the rootDir and the argv log path, both baked into the
219
+ * script text. */
220
+ function install(build: (rootDir: string, argvFile: string) => string): {
221
+ rootDir: string;
222
+ argvFile: string;
223
+ } {
224
+ const rootDir = mkdtempSync(join(tmpdir(), "darkf-opencode-run-"));
225
+ const argvFile = join(rootDir, "argv.bin");
226
+ writeFileSync(join(fakeDir, "opencode"), `#!/bin/sh\n${build(rootDir, argvFile)}\n`);
227
+ chmodSync(join(fakeDir, "opencode"), 0o755);
228
+ return { rootDir, argvFile };
229
+ }
230
+
231
+ function readArgv(argvFile: string): string[] {
232
+ return readFileSync(argvFile, "utf8")
233
+ .split("\0")
234
+ .filter((arg) => arg.length > 0);
235
+ }
236
+
237
+ function info(rootDir: string, over: Partial<DispatchInfo> = {}): DispatchInfo {
238
+ return {
239
+ runId: RUN_ID,
240
+ validEvents: ["ok"],
241
+ hasFallback: false,
242
+ attempt: 1,
243
+ step: 1,
244
+ rootDir,
245
+ ...over,
246
+ };
247
+ }
248
+
249
+ function successScript(rootDir: string, argvFile: string, sessionId: string): string {
250
+ const handoffFile = handoffPath(rootDir, RUN_ID, 1, "N");
251
+ return [
252
+ `printf '%s\\0' "$@" > "${argvFile}"`,
253
+ `echo '{"type":"step-finish","part":{"reason":"stop","sessionID":"${sessionId}"}}'`,
254
+ `mkdir -p "$(dirname "${handoffFile}")"`,
255
+ `echo '{"event":"ok"}' > "${handoffFile}"`,
256
+ ].join("\n");
257
+ }
258
+
259
+ test("a non-zero exit with the captured limit message classifies usage-limit, with the evidence-gated session id", async () => {
260
+ const { rootDir } = install((_rootDir, _argvFile) =>
261
+ [
262
+ `echo 'Usage limit reached for 5 hour. Your limit will reset at 2026-11-01 06:58:19' 1>&2`,
263
+ `echo '{"type":"step-finish","part":{"reason":"stop","sessionID":"sess-wall"}}'`,
264
+ `exit 3`,
265
+ ].join("\n"),
266
+ );
267
+
268
+ let thrown: unknown;
269
+ try {
270
+ await opencodeRunner.run("N", def, {}, info(rootDir));
271
+ } catch (err) {
272
+ thrown = err;
273
+ }
274
+
275
+ expect(thrown).toBeInstanceOf(AgentFailure);
276
+ const failure = thrown as AgentFailure;
277
+ expect(failure.crashReason).toEqual({
278
+ kind: "usage-limit",
279
+ detail: "Usage limit reached for 5 hour. Your limit will reset at 2026-11-01 06:58:19",
280
+ });
281
+ expect(failure.agentSessionId).toBe("sess-wall");
282
+ rmSync(rootDir, { recursive: true, force: true });
283
+ });
284
+
285
+ test("a non-zero exit with a non-limit API error stays runner-error", async () => {
286
+ const { rootDir } = install((_rootDir, _argvFile) =>
287
+ [`echo 'API error: 500 backend exploded' 1>&2`, `exit 1`].join("\n"),
288
+ );
289
+
290
+ let thrown: unknown;
291
+ try {
292
+ await opencodeRunner.run("N", def, {}, info(rootDir));
293
+ } catch (err) {
294
+ thrown = err;
295
+ }
296
+
297
+ expect(thrown).toBeInstanceOf(AgentFailure);
298
+ const failure = thrown as AgentFailure;
299
+ expect(failure.crashReason).toEqual({
300
+ kind: "runner-error",
301
+ error: expect.stringContaining("500 backend exploded"),
302
+ });
303
+ rmSync(rootDir, { recursive: true, force: true });
304
+ });
305
+
306
+ test("an exit-0 + missing-handoff output with a limit string inside an agent JSON line stays handoff-missing", async () => {
307
+ const { rootDir } = install((_rootDir, _argvFile) =>
308
+ [
309
+ `echo '{"type":"message","part":{"text":"note to self: mind the usage limit"}}'`,
310
+ `exit 0`,
311
+ ].join("\n"),
312
+ );
313
+
314
+ let thrown: unknown;
315
+ try {
316
+ await opencodeRunner.run("N", def, {}, info(rootDir));
317
+ } catch (err) {
318
+ thrown = err;
319
+ }
320
+
321
+ expect(thrown).toBeInstanceOf(AgentFailure);
322
+ expect((thrown as AgentFailure).crashReason).toEqual({ kind: "handoff-missing" });
323
+ rmSync(rootDir, { recursive: true, force: true });
324
+ });
325
+
326
+ test("resume: previousFailure usage-limit + agentSessionId dispatches -s and the continuation prompt, not the fresh prompt", async () => {
327
+ const { rootDir, argvFile } = install((dir, argv) => successScript(dir, argv, "sess-9"));
328
+
329
+ const result = await opencodeRunner.run("N", def, {}, {
330
+ ...info(rootDir),
331
+ previousFailure: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
332
+ agentSessionId: "sess-9",
333
+ } as DispatchInfo);
334
+
335
+ expect(result).toEqual({ event: "ok", agentSessionId: "sess-9" });
336
+ const argv = readArgv(argvFile);
337
+ expect(argv).toContain("-s");
338
+ expect(argv).toContain("sess-9");
339
+ const prompt = argv.at(-1)!;
340
+ expect(prompt).toContain("A provider usage limit interrupted your previous turn.");
341
+ expect(prompt).toContain("Continue where you left off.");
342
+ // The handoff contract text still closes the continuation prompt...
343
+ expect(prompt).toContain("write your result as JSON to this exact path");
344
+ // ...and the full fresh prompt is NOT replayed.
345
+ expect(prompt).not.toContain("FRESH-PROMPT-MARKER");
346
+ rmSync(rootDir, { recursive: true, force: true });
347
+ });
348
+
349
+ test("resume without a session id (no persisted evidence) dispatches fresh, without -s", async () => {
350
+ const { rootDir, argvFile } = install((dir, argv) => successScript(dir, argv, "sess-unused"));
351
+
352
+ const result = await opencodeRunner.run("N", def, {}, {
353
+ ...info(rootDir),
354
+ previousFailure: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
355
+ } as DispatchInfo);
356
+
357
+ expect(result).toEqual({ event: "ok", agentSessionId: "sess-unused" });
358
+ const argv = readArgv(argvFile);
359
+ expect(argv).not.toContain("-s");
360
+ const prompt = argv.at(-1)!;
361
+ // The fresh prompt path, unchanged.
362
+ expect(prompt).toContain("FRESH-PROMPT-MARKER");
363
+ expect(prompt).not.toContain("Continue where you left off");
364
+ rmSync(rootDir, { recursive: true, force: true });
365
+ });
366
+ });