@psimona/darkf 0.6.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 (39) hide show
  1. package/docs/concepts/failure-modes.md +18 -5
  2. package/docs/concepts/node-types.md +4 -2
  3. package/docs/guides/plan-with-a-task-queue.md +6 -5
  4. package/docs/guides/write-your-first-workflow.md +8 -2
  5. package/docs/index.mdx +4 -0
  6. package/docs/reference/core-types.md +5 -0
  7. package/docs/reference/package-map.md +12 -8
  8. package/docs/start-here/quickstart.md +12 -5
  9. package/package.json +9 -2
  10. package/skills/darkf-writing-workflows/SKILL.md +131 -6
  11. package/src/cli/doctor.test.ts +1 -1
  12. package/src/cli/index.ts +25 -15
  13. package/src/cli/setup.ts +4 -9
  14. package/src/cli/state-file.ts +14 -0
  15. package/src/cli/tarball.test.ts +3 -1
  16. package/src/cli/update.ts +4 -9
  17. package/src/core/tasks.ts +1 -1
  18. package/src/core/types.test.ts +52 -0
  19. package/src/core/types.ts +27 -18
  20. package/src/engine/run.test.ts +286 -4
  21. package/src/engine/run.ts +51 -9
  22. package/src/exports.ts +4 -0
  23. package/src/kit/agents/claude-code.ts +4 -34
  24. package/src/kit/agents/handoff.test.ts +12 -0
  25. package/src/kit/agents/handoff.ts +32 -8
  26. package/src/kit/agents/opencode.test.ts +1 -1
  27. package/src/kit/agents/opencode.ts +14 -28
  28. package/src/kit/specs.test.ts +247 -0
  29. package/src/kit/specs.ts +344 -0
  30. package/src/kit/status.ts +6 -6
  31. package/src/kit/validation/zod.test.ts +42 -0
  32. package/src/kit/validation/zod.ts +20 -0
  33. package/workflows/dev-loop/scripts/begin.ts +9 -6
  34. package/workflows/dev-loop/scripts/dispatch.ts +50 -0
  35. package/workflows/dev-loop/scripts/finish.ts +23 -21
  36. package/workflows/dev-loop/scripts/mark-done.ts +22 -0
  37. package/workflows/dev-loop/scripts/validate-plan.ts +30 -0
  38. package/workflows/dev-loop/workflow.ts +164 -68
  39. /package/workflows/dev-loop/scripts/{check.ts → test.ts} +0 -0
package/src/core/tasks.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Task, TaskList, TaskPriority, TaskRequirement, TaskStatus } from "./types.ts";
2
2
 
3
- // Hand-written narrowing of unknown JSON to a TaskList (docs/specs/task-list-json/spec.md,
3
+ // Hand-written narrowing of unknown JSON to a TaskList (docs/specs/_built/task-list-json/spec.md,
4
4
  // Decisions: Validation) — zero deps, no dual-schema tolerance: the legacy
5
5
  // names (`moscow`, task-side `requirements`) are simply not read, and the
6
6
  // result is either a TaskList or `{ error }`. The item-loop path and the
@@ -0,0 +1,52 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { isNodeResult } from "./types.ts";
3
+
4
+ describe("isNodeResult", () => {
5
+ test("accepts the full envelope: typed event, output, agentSessionId", () => {
6
+ expect(isNodeResult({ event: "done", output: { ok: true }, agentSessionId: "ses_1" })).toBe(
7
+ true,
8
+ );
9
+ });
10
+
11
+ test("accepts a bare object with no fields at all — everything is optional", () => {
12
+ expect(isNodeResult({})).toBe(true);
13
+ });
14
+
15
+ test("accepts partial envelopes: event only, output only, agentSessionId only", () => {
16
+ expect(isNodeResult({ event: "planned" })).toBe(true);
17
+ expect(isNodeResult({ output: [1, 2, 3] })).toBe(true);
18
+ expect(isNodeResult({ agentSessionId: "ses_abc" })).toBe(true);
19
+ });
20
+
21
+ test("accepts extra fields — the check is non-strict", () => {
22
+ expect(isNodeResult({ event: "done", agentSessionId: "ses_1", extra: "ignored" })).toBe(true);
23
+ });
24
+
25
+ test("rejects null", () => {
26
+ expect(isNodeResult(null)).toBe(false);
27
+ });
28
+
29
+ test("rejects other non-object values", () => {
30
+ expect(isNodeResult(undefined)).toBe(false);
31
+ expect(isNodeResult("done")).toBe(false);
32
+ expect(isNodeResult(42)).toBe(false);
33
+ expect(isNodeResult(true)).toBe(false);
34
+ });
35
+
36
+ test("rejects a wrong-typed event", () => {
37
+ expect(isNodeResult({ event: 7 })).toBe(false);
38
+ expect(isNodeResult({ event: null })).toBe(false);
39
+ });
40
+
41
+ test("rejects a wrong-typed agentSessionId", () => {
42
+ expect(isNodeResult({ agentSessionId: 42 })).toBe(false);
43
+ expect(isNodeResult({ agentSessionId: null })).toBe(false);
44
+ });
45
+
46
+ test("rejects an array — new behavior; the hand-rolled check let it through", () => {
47
+ expect(isNodeResult(["done"])).toBe(false);
48
+ expect(isNodeResult([])).toBe(false);
49
+ // An array carrying the right keys on its elements still is not a NodeResult.
50
+ expect(isNodeResult([{ event: "done", agentSessionId: "ses_1" }])).toBe(false);
51
+ });
52
+ });
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,7 +57,7 @@ export interface BaseLeafDef {
53
57
  retries?: number;
54
58
  /** Engine-enforced ceiling on one dispatch attempt. Default 1h. */
55
59
  timeoutMs?: number;
56
- /** Fixed interval between usage-limit re-probes after a provider quota wall. Default 30 min. See docs/specs/usage-limit-backoff/spec.md. */
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. */
57
61
  usageLimitRetryMs?: number;
58
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. */
59
63
  usageLimitMaxWaitMs?: number;
@@ -69,6 +73,11 @@ export interface AgentStateDef extends BaseLeafDef {
69
73
  type: "agent";
70
74
  prompt: string;
71
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 };
72
81
  }
73
82
 
74
83
  export interface ScriptStateDef extends BaseLeafDef {
@@ -150,7 +159,7 @@ export type AgentRunnerKind = "claude-code" | "opencode" | (string & {});
150
159
  /**
151
160
  * Incremental liveness signal a runner may report via `AgentRunner.run`'s
152
161
  * optional `onProgress` callback, throttled to roughly once per 30s —
153
- * 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
154
163
  * runner only ever reports its latest snapshot, never writes anything
155
164
  * itself.
156
165
  */
@@ -206,7 +215,7 @@ export type NodeStatus =
206
215
  agentSessionId?: string;
207
216
  /** Latest step count from the agent's own event stream, when the
208
217
  * runner reports progress (`AgentRunner.run`'s optional
209
- * `onProgress`) — see docs/specs/agent-liveness/spec.md. Absent for
218
+ * `onProgress`) — see docs/specs/_built/agent-liveness/spec.md. Absent for
210
219
  * script dispatches or runners that don't report progress. */
211
220
  agentStepCount?: number;
212
221
  /** Milliseconds since the last agent-reported progress event, as of
@@ -216,12 +225,12 @@ export type NodeStatus =
216
225
  * conditions as `agentStepCount`. */
217
226
  agentIdleMs?: number;
218
227
  /** Set only while the engine is nudging this attempt (1..3) — see
219
- * docs/specs/session-nudge/spec.md. Absent on an ordinary dispatch. */
228
+ * docs/specs/_built/session-nudge/spec.md. Absent on an ordinary dispatch. */
220
229
  nudgeAttempt?: number;
221
230
  /** The nudgeable `CrashReason` kind that triggered this nudge. */
222
231
  nudgeReason?: CrashReason["kind"];
223
232
  /** Present only while the engine is waiting out a provider usage-limit
224
- * backoff for this attempt — see docs/specs/usage-limit-backoff/spec.md. */
233
+ * backoff for this attempt — see docs/specs/_built/usage-limit-backoff/spec.md. */
225
234
  limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number };
226
235
  }
227
236
  | { phase: "succeeded"; result: NodeResult }
@@ -249,7 +258,7 @@ export type CrashReason =
249
258
  * `Error` can't: the session id to resume, and which `CrashReason` kind this
250
259
  * is — so the engine can route the correct nudge template without
251
260
  * inspecting the error message string. See
252
- * docs/specs/session-nudge/spec.md.
261
+ * docs/specs/_built/session-nudge/spec.md.
253
262
  */
254
263
  export class AgentFailure extends Error {
255
264
  agentSessionId?: string;
@@ -288,7 +297,7 @@ export interface RunResult {
288
297
 
289
298
  // --- Task lists ---
290
299
  //
291
- // 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):
292
301
  // workflows write it, `parseTaskList` narrows it, the OpenCode plugin renders it.
293
302
  // Lowercase MoSCoW and `satisfies` are the locked names — the validator has no
294
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",
@@ -1067,7 +1236,7 @@ test("FAILED's terminal journal entry carries the failing node's result as its e
1067
1236
  }
1068
1237
  });
1069
1238
 
1070
- // --- usage-limit-backoff (docs/specs/usage-limit-backoff/spec.md) ---
1239
+ // --- usage-limit-backoff (docs/specs/_built/usage-limit-backoff/spec.md) ---
1071
1240
 
1072
1241
  const usageLimitFailure = () =>
1073
1242
  new AgentFailure("Usage limit reached for 5 hour.", {
@@ -1243,3 +1412,116 @@ test("the attempt deadline is recomputed after each usage-limit wait, so a slept
1243
1412
  expect(calls).toBe(2);
1244
1413
  expect(result.node.phase).toBe("succeeded");
1245
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
+ });
package/src/engine/run.ts CHANGED
@@ -29,7 +29,7 @@ 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/usage-limit-backoff/spec.md) —
32
+ // Usage-limit backoff defaults (docs/specs/_built/usage-limit-backoff/spec.md) —
33
33
  // the leaf-config fields on BaseLeafDef fall back to these. Fixed 30-min
34
34
  // probe interval, deliberately not the provider message's quoted reset time
35
35
  // (its timezone is not the supervisor's); 24h bounds the total wait per
@@ -37,13 +37,14 @@ const DEFAULT_MAX_STEPS = 1000;
37
37
  const DEFAULT_USAGE_LIMIT_RETRY_MS = 30 * 60 * 1000;
38
38
  const DEFAULT_USAGE_LIMIT_MAX_WAIT_MS = 24 * 60 * 60 * 1000;
39
39
  // Bounded in-session repair attempts per outer attempt (see
40
- // 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
41
41
  // knob, deliberately fixed.
42
42
  const NUDGE_LIMIT = 3;
43
43
  const NUDGEABLE_KINDS = new Set<CrashReason["kind"]>([
44
44
  "handoff-missing",
45
45
  "handoff-unparseable",
46
46
  "no-transition",
47
+ "validation-failed",
47
48
  ]);
48
49
  function isNudgeable(reason: CrashReason): boolean {
49
50
  return NUDGEABLE_KINDS.has(reason.kind);
@@ -216,7 +217,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
216
217
  let attempt = 0;
217
218
  // Usage-limit wait bookkeeping — per node visit, never per attempt:
218
219
  // waits consume no retry, so the wait budget spans every attempt of
219
- // this visit (docs/specs/usage-limit-backoff/spec.md).
220
+ // this visit (docs/specs/_built/usage-limit-backoff/spec.md).
220
221
  let limitWaitedMs = 0;
221
222
  let limitProbes = 0;
222
223
 
@@ -224,7 +225,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
224
225
  // Fixed once per outer attempt: every dispatch this attempt makes — the
225
226
  // first call and up to NUDGE_LIMIT nudges after it — spends down the
226
227
  // SAME remaining budget, so a nudge sequence can't multiply the
227
- // configured per-attempt timeout (docs/specs/session-nudge/spec.md,
228
+ // configured per-attempt timeout (docs/specs/_built/session-nudge/spec.md,
228
229
  // "Dispatch loop change").
229
230
  //
230
231
  // Usage-limit exception (same spec family, usage-limit-backoff D-7):
@@ -249,7 +250,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
249
250
  const startedAt = Date.now();
250
251
  // Reset fresh per dispatch attempt (including each nudge) — a new
251
252
  // process gets a new progress snapshot, never carried over from a
252
- // previous attempt. See docs/specs/agent-liveness/spec.md.
253
+ // previous attempt. See docs/specs/_built/agent-liveness/spec.md.
253
254
  let latestProgress: AgentProgress | undefined;
254
255
  const onProgress = (p: AgentProgress) => {
255
256
  latestProgress = p;
@@ -275,7 +276,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
275
276
  emit(runningStatus(startedAt), current, scopePath);
276
277
  // Live-runtime heartbeats: journal a refreshed `running` status while the
277
278
  // dispatch is open, so status/monitor can advance runtime and prove
278
- // liveness (spec: darkf-cli/docs/specs/live-runtime). unref'd — a pending
279
+ // liveness (spec: docs/specs/_built/live-runtime). unref'd — a pending
279
280
  // timer must never keep the process alive past the run's own exit.
280
281
  const heartbeat =
281
282
  heartbeatMs > 0
@@ -296,9 +297,50 @@ export async function run(opts: RunOptions): Promise<RunResult> {
296
297
  continue attemptLoop;
297
298
  }
298
299
  agentSessionId = raw.agentSessionId ?? agentSessionId;
299
- 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);
300
331
  if (validationError !== undefined) {
301
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
+ }
302
344
  continue attemptLoop;
303
345
  }
304
346
  const resolved = resolveTarget(def, raw.event);
@@ -311,7 +353,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
311
353
  continue attemptLoop;
312
354
  }
313
355
 
314
- result = raw;
356
+ result = result_;
315
357
  target = resolved;
316
358
  reason = undefined;
317
359
  break attemptLoop;
@@ -334,7 +376,7 @@ export async function run(opts: RunOptions): Promise<RunResult> {
334
376
  nudgeAttempt++;
335
377
  continue;
336
378
  }
337
- // Usage-limit (docs/specs/usage-limit-backoff/spec.md, Wait and
379
+ // Usage-limit (docs/specs/_built/usage-limit-backoff/spec.md, Wait and
338
380
  // resume): a quota wall is not a failed attempt — it consumes no
339
381
  // retry. Sleep usageLimitRetryMs (heartbeating the wait), then
340
382
  // re-dispatch this same attempt; the existing
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";