@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/core/types.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import type { WorkflowValidationError } from "./graph.ts";
2
3
 
3
4
  // What a leaf node's dispatch produces when it succeeds. This is also the
@@ -18,17 +19,20 @@ export interface NodeResult {
18
19
  agentSessionId?: string;
19
20
  }
20
21
 
22
+ // Same shape as the NodeResult interface above, one level of runtime
23
+ // checking added. Non-strict on purpose: extra fields pass, the same as the
24
+ // hand-rolled check this replaced. One deliberate behavior change: an array
25
+ // now fails, where the hand-rolled check let it through
26
+ // (docs/specs/output-validation/spec.md, "Extending `isNodeResult` to the
27
+ // same pattern").
28
+ const NodeResultSchema = z.object({
29
+ event: z.string().optional(),
30
+ output: z.unknown().optional(),
31
+ agentSessionId: z.string().optional(),
32
+ });
33
+
21
34
  export function isNodeResult(value: unknown): value is NodeResult {
22
- if (typeof value !== "object" || value === null) return false;
23
- const v = value as Record<string, unknown>;
24
- if ("event" in v && v.event !== undefined && typeof v.event !== "string") return false;
25
- if (
26
- "agentSessionId" in v &&
27
- v.agentSessionId !== undefined &&
28
- typeof v.agentSessionId !== "string"
29
- )
30
- return false;
31
- return true;
35
+ return NodeResultSchema.safeParse(value).success;
32
36
  }
33
37
 
34
38
  // Sentinel target meaning "the whole workflow completed its work". Renders
@@ -39,7 +43,7 @@ export const DONE = "[*]" as const;
39
43
  // since `[-]` has no built-in meaning to stateDiagram-v2 the way `[*]` does.
40
44
  export const FAILED = "[-]" as const;
41
45
  // Deprecated alias — kept only for a consumer repo's give-up edges, which still
42
- // route to EXIT on its own schedule (docs/specs/failed-terminal/spec.md).
46
+ // route to EXIT on its own schedule (docs/specs/_built/failed-terminal/spec.md).
43
47
  // Removed in the same change that lands the `run_failure` node + retarget
44
48
  // table there; any surviving `EXIT` import then fails to compile.
45
49
  export { DONE as EXIT };
@@ -53,6 +57,10 @@ export interface BaseLeafDef {
53
57
  retries?: number;
54
58
  /** Engine-enforced ceiling on one dispatch attempt. Default 1h. */
55
59
  timeoutMs?: number;
60
+ /** Fixed interval between usage-limit re-probes after a provider quota wall. Default 30 min. See docs/specs/_built/usage-limit-backoff/spec.md. */
61
+ usageLimitRetryMs?: number;
62
+ /** Total wait budget per node visit for usage-limit backoff. At the cap the run crashes with the last usage-limit reason. Default 24h. */
63
+ usageLimitMaxWaitMs?: number;
56
64
  /**
57
65
  * Plain code check run against a well-formed NodeResult before it's accepted
58
66
  * as `succeeded`. Return a failure message to reject it, or undefined to
@@ -65,6 +73,11 @@ export interface AgentStateDef extends BaseLeafDef {
65
73
  type: "agent";
66
74
  prompt: string;
67
75
  agent?: Record<string, unknown>;
76
+ outputType?: OutputSchema; // checks result.output, before `validate` runs
77
+ }
78
+
79
+ export interface OutputSchema {
80
+ safeParse(value: unknown): { success: true } | { success: false; message: string };
68
81
  }
69
82
 
70
83
  export interface ScriptStateDef extends BaseLeafDef {
@@ -146,7 +159,7 @@ export type AgentRunnerKind = "claude-code" | "opencode" | (string & {});
146
159
  /**
147
160
  * Incremental liveness signal a runner may report via `AgentRunner.run`'s
148
161
  * optional `onProgress` callback, throttled to roughly once per 30s —
149
- * see docs/specs/agent-liveness/spec.md. The engine owns the journal: a
162
+ * see docs/specs/_built/agent-liveness/spec.md. The engine owns the journal: a
150
163
  * runner only ever reports its latest snapshot, never writes anything
151
164
  * itself.
152
165
  */
@@ -202,7 +215,7 @@ export type NodeStatus =
202
215
  agentSessionId?: string;
203
216
  /** Latest step count from the agent's own event stream, when the
204
217
  * runner reports progress (`AgentRunner.run`'s optional
205
- * `onProgress`) — see docs/specs/agent-liveness/spec.md. Absent for
218
+ * `onProgress`) — see docs/specs/_built/agent-liveness/spec.md. Absent for
206
219
  * script dispatches or runners that don't report progress. */
207
220
  agentStepCount?: number;
208
221
  /** Milliseconds since the last agent-reported progress event, as of
@@ -212,10 +225,13 @@ export type NodeStatus =
212
225
  * conditions as `agentStepCount`. */
213
226
  agentIdleMs?: number;
214
227
  /** Set only while the engine is nudging this attempt (1..3) — see
215
- * docs/specs/session-nudge/spec.md. Absent on an ordinary dispatch. */
228
+ * docs/specs/_built/session-nudge/spec.md. Absent on an ordinary dispatch. */
216
229
  nudgeAttempt?: number;
217
230
  /** The nudgeable `CrashReason` kind that triggered this nudge. */
218
231
  nudgeReason?: CrashReason["kind"];
232
+ /** Present only while the engine is waiting out a provider usage-limit
233
+ * backoff for this attempt — see docs/specs/_built/usage-limit-backoff/spec.md. */
234
+ limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number };
219
235
  }
220
236
  | { phase: "succeeded"; result: NodeResult }
221
237
  | { phase: "failed"; result: NodeResult }
@@ -223,6 +239,7 @@ export type NodeStatus =
223
239
 
224
240
  export type CrashReason =
225
241
  | { kind: "runner-error"; error: string }
242
+ | { kind: "usage-limit"; detail: string }
226
243
  | { kind: "timeout"; elapsedMs: number }
227
244
  | { kind: "handoff-missing" }
228
245
  | { kind: "handoff-unparseable"; parseError: string }
@@ -241,7 +258,7 @@ export type CrashReason =
241
258
  * `Error` can't: the session id to resume, and which `CrashReason` kind this
242
259
  * is — so the engine can route the correct nudge template without
243
260
  * inspecting the error message string. See
244
- * docs/specs/session-nudge/spec.md.
261
+ * docs/specs/_built/session-nudge/spec.md.
245
262
  */
246
263
  export class AgentFailure extends Error {
247
264
  agentSessionId?: string;
@@ -280,7 +297,7 @@ export interface RunResult {
280
297
 
281
298
  // --- Task lists ---
282
299
  //
283
- // One shared vocabulary for plan/dispatch task lists (docs/specs/task-list-json/spec.md):
300
+ // One shared vocabulary for plan/dispatch task lists (docs/specs/_built/task-list-json/spec.md):
284
301
  // workflows write it, `parseTaskList` narrows it, the OpenCode plugin renders it.
285
302
  // Lowercase MoSCoW and `satisfies` are the locked names — the validator has no
286
303
  // tolerance for the legacy shapes (`moscow`, task-side `requirements`).
@@ -580,7 +580,7 @@ test("crashes with validation-failed after exhausting retries", async () => {
580
580
  }
581
581
  });
582
582
 
583
- test("threads agentSessionId and previousFailure into DispatchInfo across retries", async () => {
583
+ test("threads agentSessionId and previousFailure into DispatchInfo across nudges and retries", async () => {
584
584
  const workflow: WorkflowDef = {
585
585
  initial: "Agentic",
586
586
  states: {
@@ -611,7 +611,20 @@ test("threads agentSessionId and previousFailure into DispatchInfo across retrie
611
611
  agentSessionId: undefined,
612
612
  previousFailure: undefined,
613
613
  });
614
- expect(infos[1]).toMatchObject({
614
+ // A validate rejection with a session nudges in-session (up to three,
615
+ // docs/specs/output-validation): the attempt stays 1 while previousFailure
616
+ // and the carried session id thread through every nudge dispatch.
617
+ expect(infos).toHaveLength(5); // fresh + 3 nudges + the capped fallback
618
+ for (const info of infos.slice(1, 4)) {
619
+ expect(info).toMatchObject({
620
+ attempt: 1,
621
+ agentSessionId: "sess-123",
622
+ previousFailure: { kind: "validation-failed", message: "expected event 'ok'" },
623
+ });
624
+ }
625
+ // Only after the three-nudge cap does the fresh attempt run, still
626
+ // threaded with the failure and the session id.
627
+ expect(infos[4]).toMatchObject({
615
628
  attempt: 2,
616
629
  agentSessionId: "sess-123",
617
630
  previousFailure: { kind: "validation-failed", message: "expected event 'ok'" },
@@ -836,7 +849,7 @@ test("open dispatches heartbeat the journal (live runtime)", async () => {
836
849
  rmSync(rootDir, { recursive: true, force: true });
837
850
  });
838
851
 
839
- // --- session-nudge (docs/specs/session-nudge/spec.md) ---
852
+ // --- session-nudge (docs/specs/_built/session-nudge/spec.md) ---
840
853
 
841
854
  test("nudges a handoff-missing AgentFailure in-session, consuming no retry", async () => {
842
855
  const workflow: WorkflowDef = {
@@ -1027,6 +1040,162 @@ test("a shared per-attempt deadline bounds the whole nudge sequence, not a fresh
1027
1040
  }
1028
1041
  });
1029
1042
 
1043
+ // --- output-validation (docs/specs/output-validation/spec.md) ---
1044
+
1045
+ test("a failing outputType nudges in-session with the message in previousFailure, capped at three before the fresh retry", async () => {
1046
+ const workflow: WorkflowDef = {
1047
+ initial: "Shaped",
1048
+ states: {
1049
+ Shaped: {
1050
+ type: "agent",
1051
+ prompt: "shape it",
1052
+ retries: 1,
1053
+ on: { ok: EXIT },
1054
+ outputType: {
1055
+ safeParse: (value) =>
1056
+ value === "fixed"
1057
+ ? { success: true }
1058
+ : { success: false, message: "output: expected the string 'fixed'" },
1059
+ },
1060
+ },
1061
+ },
1062
+ };
1063
+
1064
+ const infos: DispatchInfo[] = [];
1065
+ const agentRunner: AgentRunner = {
1066
+ run: async (_id, _def, _handoff, info) => {
1067
+ infos.push(info);
1068
+ return infos.length <= 4
1069
+ ? { event: "retry_me", output: "bad", agentSessionId: "sess-shape" }
1070
+ : { event: "ok", output: "fixed" };
1071
+ },
1072
+ };
1073
+
1074
+ const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
1075
+
1076
+ expect(result.node.phase).toBe("succeeded");
1077
+ // 1 fresh + exactly 3 nudges, all inside outer attempt 1; the 5th call is
1078
+ // the capped fallback to a fresh attempt (retries: 1 affords exactly one).
1079
+ expect(infos).toHaveLength(5);
1080
+ expect(infos.slice(0, 4).map((i) => i.attempt)).toEqual([1, 1, 1, 1]);
1081
+ expect(infos[4]).toMatchObject({ attempt: 2 });
1082
+ // The first dispatch is not a nudge. Each nudge dispatch carries the
1083
+ // outputType message in previousFailure — the text the corrective prompt
1084
+ // quotes (nudgeMessage's job, covered in kit/agents/handoff.test.ts;
1085
+ // engine/ must not import kit/ — engine-does-not-import-harness).
1086
+ expect(infos[0]).toMatchObject({ previousFailure: undefined });
1087
+ for (const info of infos.slice(1, 4)) {
1088
+ expect(info).toMatchObject({
1089
+ agentSessionId: "sess-shape",
1090
+ previousFailure: {
1091
+ kind: "validation-failed",
1092
+ message: "output: expected the string 'fixed'",
1093
+ },
1094
+ });
1095
+ }
1096
+ });
1097
+
1098
+ test("a failing validate nudges in-session with the script's message in previousFailure, capped at three before the fresh retry", async () => {
1099
+ const workflow: WorkflowDef = {
1100
+ initial: "Picky",
1101
+ states: {
1102
+ Picky: {
1103
+ type: "agent",
1104
+ prompt: "be good",
1105
+ retries: 1,
1106
+ on: { ok: EXIT },
1107
+ validate: (result) =>
1108
+ result.output === "good" ? undefined : "output must be the string 'good'",
1109
+ },
1110
+ },
1111
+ };
1112
+
1113
+ const infos: DispatchInfo[] = [];
1114
+ const agentRunner: AgentRunner = {
1115
+ run: async (_id, _def, _handoff, info) => {
1116
+ infos.push(info);
1117
+ return infos.length <= 4
1118
+ ? { event: "retry_me", output: "bad", agentSessionId: "sess-picky" }
1119
+ : { event: "ok", output: "good" };
1120
+ },
1121
+ };
1122
+
1123
+ const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
1124
+
1125
+ expect(result.node.phase).toBe("succeeded");
1126
+ // 1 fresh + exactly 3 nudges, then the capped fresh retry — the nudge
1127
+ // count stops at three, and no retry was spent on the nudges themselves.
1128
+ expect(infos).toHaveLength(5);
1129
+ expect(infos[0]).toMatchObject({ previousFailure: undefined });
1130
+ for (const info of infos.slice(1, 4)) {
1131
+ expect(info).toMatchObject({
1132
+ agentSessionId: "sess-picky",
1133
+ previousFailure: {
1134
+ kind: "validation-failed",
1135
+ message: "output must be the string 'good'",
1136
+ },
1137
+ });
1138
+ }
1139
+ });
1140
+
1141
+ test("regression: a validate-only leaf still rejects the same inputs, now nudging before it retries", async () => {
1142
+ // The Compatibility contract, checked directly
1143
+ // (docs/specs/output-validation/spec.md): a leaf with `validate` and no
1144
+ // `outputType` — the pre-spec shape — rejects the same inputs with the
1145
+ // same message and ends in the same `validation-failed` crash shape as
1146
+ // before. Only the path there changed: with a session, up to three
1147
+ // same-session nudges run before the fresh retry spends its
1148
+ // `def.retries` slot.
1149
+ const MESSAGE = "rejected: output was not 'good'";
1150
+ const workflow: WorkflowDef = {
1151
+ initial: "Picky",
1152
+ states: {
1153
+ Picky: {
1154
+ type: "agent",
1155
+ prompt: "be good",
1156
+ retries: 1,
1157
+ on: { ok: EXIT },
1158
+ validate: (result) => (result.output === "good" ? undefined : MESSAGE),
1159
+ },
1160
+ },
1161
+ };
1162
+
1163
+ const infos: DispatchInfo[] = [];
1164
+ const agentRunner: AgentRunner = {
1165
+ run: async (_id, _def, _handoff, info) => {
1166
+ infos.push(info);
1167
+ // The same bad input every time — what the leaf rejected before the
1168
+ // feature, it must keep rejecting now.
1169
+ return { event: "retry_me", output: "bad", agentSessionId: "sess-regress" };
1170
+ },
1171
+ };
1172
+
1173
+ const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
1174
+
1175
+ // Same rejection as before, end to end: the identical crash shape the
1176
+ // no-session test above asserts, reached only after the fresh retry
1177
+ // spent the one retries: 1 slot (the nudges spent none).
1178
+ expect(result.node.phase).toBe("crashed");
1179
+ if (result.node.phase === "crashed") {
1180
+ expect(result.node.reason).toEqual({ kind: "validation-failed", message: MESSAGE });
1181
+ expect(result.node.attempt).toBe(2);
1182
+ }
1183
+ // Nudges before it retries: fresh + 3 in-session nudges on attempt 1,
1184
+ // then the fresh attempt 2 — which nudges again within its own attempt
1185
+ // (the per-attempt budget the other nudgeable kinds share) before the
1186
+ // crash. Every dispatch after the first threads the same rejection
1187
+ // message and the carried session id.
1188
+ expect(infos).toHaveLength(8);
1189
+ expect(infos.map((i) => i.attempt)).toEqual([1, 1, 1, 1, 2, 2, 2, 2]);
1190
+ expect(infos[0]).toMatchObject({ previousFailure: undefined });
1191
+ for (const info of infos.slice(1)) {
1192
+ expect(info).toMatchObject({
1193
+ agentSessionId: "sess-regress",
1194
+ previousFailure: { kind: "validation-failed", message: MESSAGE },
1195
+ });
1196
+ }
1197
+ });
1198
+
1030
1199
  test("a workflow routing to FAILED ends with phase 'failed', never crashed/unresolved-target", async () => {
1031
1200
  const workflow: WorkflowDef = {
1032
1201
  initial: "RunFailure",
@@ -1066,3 +1235,293 @@ test("FAILED's terminal journal entry carries the failing node's result as its e
1066
1235
  expect(last.status.result.output).toEqual({ kind: "cap_exceeded" });
1067
1236
  }
1068
1237
  });
1238
+
1239
+ // --- usage-limit-backoff (docs/specs/_built/usage-limit-backoff/spec.md) ---
1240
+
1241
+ const usageLimitFailure = () =>
1242
+ new AgentFailure("Usage limit reached for 5 hour.", {
1243
+ agentSessionId: "sess-limit",
1244
+ crashReason: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
1245
+ });
1246
+
1247
+ test("a usage-limit failure waits the interval, then re-dispatches the SAME attempt without consuming a retry", async () => {
1248
+ const workflow: WorkflowDef = {
1249
+ initial: "Agentic",
1250
+ states: {
1251
+ Agentic: { type: "agent", prompt: "do it", usageLimitRetryMs: 100, on: { ok: EXIT } },
1252
+ },
1253
+ };
1254
+
1255
+ const infos: DispatchInfo[] = [];
1256
+ const dispatchTimes: number[] = [];
1257
+ const agentRunner: AgentRunner = {
1258
+ run: async (_id, _def, _handoff, info) => {
1259
+ infos.push(info);
1260
+ dispatchTimes.push(Date.now());
1261
+ if (infos.length === 1) throw usageLimitFailure();
1262
+ return { event: "ok" };
1263
+ },
1264
+ };
1265
+
1266
+ const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
1267
+
1268
+ expect(result.node.phase).toBe("succeeded");
1269
+ expect(infos.length).toBe(2);
1270
+ // Same outer attempt (retries: 0 default — success itself proves none was
1271
+ // consumed), with the session id and the wall forwarded unchanged.
1272
+ expect(infos[1]).toMatchObject({
1273
+ attempt: 1,
1274
+ agentSessionId: "sess-limit",
1275
+ previousFailure: { kind: "usage-limit", detail: "Usage limit reached for 5 hour." },
1276
+ });
1277
+ // The retry fired after the shortened interval — not the 30-min default.
1278
+ const waited = dispatchTimes[1]! - dispatchTimes[0]!;
1279
+ expect(waited).toBeGreaterThanOrEqual(90);
1280
+ expect(waited).toBeLessThan(2000);
1281
+ });
1282
+
1283
+ test("while waiting, running heartbeats carry limitBackoff (probe, nextAttemptAt, waitedMs)", async () => {
1284
+ const workflow: WorkflowDef = {
1285
+ initial: "Agentic",
1286
+ states: {
1287
+ Agentic: { type: "agent", prompt: "do it", usageLimitRetryMs: 100, on: { ok: EXIT } },
1288
+ },
1289
+ };
1290
+
1291
+ let calls = 0;
1292
+ const agentRunner: AgentRunner = {
1293
+ run: async () => {
1294
+ calls++;
1295
+ if (calls === 1) throw usageLimitFailure();
1296
+ return { event: "ok" };
1297
+ },
1298
+ };
1299
+
1300
+ const result = await run({
1301
+ workflow,
1302
+ agentRunner,
1303
+ scriptRunner: noopScript,
1304
+ heartbeatMs: 20,
1305
+ });
1306
+ expect(result.node.phase).toBe("succeeded");
1307
+
1308
+ const journalPath = join(testRootDir, ".darkf", "run", result.runId, "journal.jsonl");
1309
+ const events = readFileSync(journalPath, "utf8")
1310
+ .trim()
1311
+ .split("\n")
1312
+ .map((l) => JSON.parse(l) as NodeEvent);
1313
+ const waiting = events.filter(
1314
+ (e) => e.status.phase === "running" && e.status.limitBackoff !== undefined,
1315
+ );
1316
+ // Wait-start emit (immediate, nudge-start precedent) + interval heartbeats
1317
+ // during the 100ms sleep at 20ms cadence.
1318
+ expect(waiting.length).toBeGreaterThanOrEqual(2);
1319
+ const first = waiting[0]!;
1320
+ if (first.status.phase === "running") {
1321
+ expect(first.status.limitBackoff).toEqual({
1322
+ probe: 1,
1323
+ nextAttemptAt: expect.any(Number),
1324
+ waitedMs: 100,
1325
+ });
1326
+ expect(first.status.limitBackoff!.nextAttemptAt).toBeGreaterThan(first.status.lastHeartbeat);
1327
+ }
1328
+ });
1329
+
1330
+ test("exhausting usageLimitMaxWaitMs crashes with the last usage-limit reason; probe count and total wait journaled", async () => {
1331
+ const workflow: WorkflowDef = {
1332
+ initial: "Agentic",
1333
+ states: {
1334
+ Agentic: {
1335
+ type: "agent",
1336
+ prompt: "do it",
1337
+ usageLimitRetryMs: 50,
1338
+ usageLimitMaxWaitMs: 120,
1339
+ on: { ok: EXIT },
1340
+ },
1341
+ },
1342
+ };
1343
+
1344
+ let calls = 0;
1345
+ const agentRunner: AgentRunner = {
1346
+ run: async () => {
1347
+ calls++;
1348
+ throw usageLimitFailure();
1349
+ },
1350
+ };
1351
+
1352
+ const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
1353
+
1354
+ // Waits: 50 (probe 1), then 100 <= 120 (probe 2); the third failure sees
1355
+ // 100 + 50 > 120 and takes the crashed() path. Never a fourth dispatch.
1356
+ expect(calls).toBe(3);
1357
+ expect(result.node.phase).toBe("crashed");
1358
+ if (result.node.phase === "crashed") {
1359
+ expect(result.node.reason).toEqual({
1360
+ kind: "usage-limit",
1361
+ detail: "Usage limit reached for 5 hour.",
1362
+ });
1363
+ }
1364
+
1365
+ const journalPath = join(testRootDir, ".darkf", "run", result.runId, "journal.jsonl");
1366
+ const events = readFileSync(journalPath, "utf8")
1367
+ .trim()
1368
+ .split("\n")
1369
+ .map((l) => JSON.parse(l) as NodeEvent);
1370
+ const lastWait = events
1371
+ .filter((e) => e.status.phase === "running" && e.status.limitBackoff !== undefined)
1372
+ .at(-1);
1373
+ expect(lastWait).toBeDefined();
1374
+ if (lastWait!.status.phase === "running") {
1375
+ expect(lastWait!.status.limitBackoff).toEqual({
1376
+ probe: 2,
1377
+ nextAttemptAt: expect.any(Number),
1378
+ waitedMs: 100,
1379
+ });
1380
+ }
1381
+ });
1382
+
1383
+ test("the attempt deadline is recomputed after each usage-limit wait, so a slept interval never eats the next dispatch's timeout", async () => {
1384
+ const workflow: WorkflowDef = {
1385
+ initial: "Agentic",
1386
+ states: {
1387
+ Agentic: {
1388
+ type: "agent",
1389
+ prompt: "do it",
1390
+ timeoutMs: 80,
1391
+ usageLimitRetryMs: 50,
1392
+ on: { ok: EXIT },
1393
+ },
1394
+ },
1395
+ };
1396
+
1397
+ let calls = 0;
1398
+ const agentRunner: AgentRunner = {
1399
+ run: async () => {
1400
+ calls++;
1401
+ if (calls === 1) throw usageLimitFailure();
1402
+ // Longer than the ORIGINAL budget's remainder (80ms - ~50ms slept) but
1403
+ // shorter than a recomputed one — without the recompute this surfaces
1404
+ // as `timeout`, with it the dispatch succeeds.
1405
+ await new Promise((r) => setTimeout(r, 60));
1406
+ return { event: "ok" };
1407
+ },
1408
+ };
1409
+
1410
+ const result = await run({ workflow, agentRunner, scriptRunner: noopScript });
1411
+
1412
+ expect(calls).toBe(2);
1413
+ expect(result.node.phase).toBe("succeeded");
1414
+ });
1415
+
1416
+ // Bare-payload coercion (run 0a1b2ca3): an agent result without an `event`
1417
+ // field is a payload, not an envelope — the engine wraps it so the payload
1418
+ // always rides `handoff.output` and a payload-internal `output` key can
1419
+ // never hijack the channel downstream.
1420
+
1421
+ test("wraps an event-less agent result as { output: payload }", async () => {
1422
+ const workflow: WorkflowDef = {
1423
+ initial: "Work",
1424
+ states: {
1425
+ Work: { type: "agent", prompt: "work", next: "Gate" },
1426
+ Gate: { type: "script", file: "gate.ts", next: EXIT },
1427
+ },
1428
+ };
1429
+ let seen: NodeResult | undefined;
1430
+ const scriptRunner: ScriptRunner = {
1431
+ run: async (_id, _def, handoff) => {
1432
+ seen = handoff;
1433
+ return { event: undefined };
1434
+ },
1435
+ };
1436
+ const agentRunner: AgentRunner = {
1437
+ run: async () => ({ behavior_ok: true, gaps: [] }) as unknown as NodeResult,
1438
+ };
1439
+
1440
+ const result = await run({ workflow, agentRunner, scriptRunner });
1441
+
1442
+ expect(result.node.phase).toBe("succeeded");
1443
+ expect(seen?.output).toEqual({ behavior_ok: true, gaps: [] });
1444
+ });
1445
+
1446
+ test("hybrid payload: flat claim plus nested output survives to handoff.output", async () => {
1447
+ // The exact run 0a1b2ca3 shape: the nested summary used to shadow the
1448
+ // passing verdict when the raw object rode the handoff unwrapped.
1449
+ const workflow: WorkflowDef = {
1450
+ initial: "Verify",
1451
+ states: {
1452
+ Verify: { type: "agent", prompt: "verify", next: "Gate" },
1453
+ Gate: { type: "script", file: "gate.ts", next: EXIT },
1454
+ },
1455
+ };
1456
+ let seen: NodeResult | undefined;
1457
+ const scriptRunner: ScriptRunner = {
1458
+ run: async (_id, _def, handoff) => {
1459
+ seen = handoff;
1460
+ return { event: undefined };
1461
+ },
1462
+ };
1463
+ const agentRunner: AgentRunner = {
1464
+ run: async () =>
1465
+ ({
1466
+ behavior_ok: true,
1467
+ gaps: [],
1468
+ output: { summary: "All 7 MUST requirements verified" },
1469
+ }) as unknown as NodeResult,
1470
+ };
1471
+
1472
+ const result = await run({ workflow, agentRunner, scriptRunner });
1473
+
1474
+ expect(result.node.phase).toBe("succeeded");
1475
+ const output = seen?.output as { behavior_ok?: boolean; output?: { summary?: string } };
1476
+ expect(output.behavior_ok).toBe(true);
1477
+ expect(output.output?.summary).toBe("All 7 MUST requirements verified");
1478
+ });
1479
+
1480
+ test("envelope results (event present) are passed through untouched", async () => {
1481
+ const workflow: WorkflowDef = {
1482
+ initial: "Work",
1483
+ states: {
1484
+ Work: { type: "agent", prompt: "work", on: { done: "Gate" } },
1485
+ Gate: { type: "script", file: "gate.ts", next: EXIT },
1486
+ },
1487
+ };
1488
+ let seen: NodeResult | undefined;
1489
+ const scriptRunner: ScriptRunner = {
1490
+ run: async (_id, _def, handoff) => {
1491
+ seen = handoff;
1492
+ return { event: undefined };
1493
+ },
1494
+ };
1495
+ const payload = { verdict: "clean" };
1496
+ const agentRunner: AgentRunner = {
1497
+ run: async () => ({ event: "done", output: payload }),
1498
+ };
1499
+
1500
+ const result = await run({ workflow, agentRunner, scriptRunner });
1501
+
1502
+ expect(result.node.phase).toBe("succeeded");
1503
+ expect(seen?.output).toEqual(payload);
1504
+ });
1505
+
1506
+ test("script results are never coerced", async () => {
1507
+ const workflow: WorkflowDef = {
1508
+ initial: "Prep",
1509
+ states: {
1510
+ Prep: { type: "script", file: "prep.ts", next: "Gate" },
1511
+ Gate: { type: "script", file: "gate.ts", next: EXIT },
1512
+ },
1513
+ };
1514
+ let seen: unknown; // asserted as a raw shape, not a typed envelope
1515
+ const scriptRunner: ScriptRunner = {
1516
+ run: async (id, _def, handoff) => {
1517
+ if (id === "Prep") return { probe: 1 } as unknown as NodeResult; // no event, no output
1518
+ seen = handoff;
1519
+ return { event: undefined };
1520
+ },
1521
+ };
1522
+
1523
+ const result = await run({ workflow, agentRunner: noopAgent, scriptRunner });
1524
+
1525
+ expect(result.node.phase).toBe("succeeded");
1526
+ expect(seen).toEqual({ probe: 1 }); // raw handoff, not wrapped
1527
+ });