@psimona/darkf 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,10 +35,10 @@ export interface StepFinishScan {
35
35
  // mid-turn death) all surfaced as `exit 0` + missing handoff → a bare
36
36
  // ENOENT minutes after the real failure. Capture the reason and make a
37
37
  // missing handoff fail loudly with it, so retries and RCA start from facts.
38
- // NB: the type discriminator is hyphenated ("step-finish"), confirmed against
39
- // both @opencode-ai/sdk's generated types and strings pulled from the
40
- // installed opencode binary — matching on "step_finish" (underscore) here
41
- // silently never matched, so this capture never actually fired.
38
+ // NB: the stream's outer `type` is `step_finish` (underscore). The
39
+ // hyphenated "step-finish" appears only one level down, in `part.type`
40
+ // (captured from opencode 2.3.0, 2026-11-28). The SDK's part types use the
41
+ // hyphen, which is not what `run --format json` puts on the outer event.
42
42
  //
43
43
  // Extended (docs/specs/_built/session-nudge/spec.md) to also pull `part.sessionID`
44
44
  // and a count of step-finish events seen, in the same single pass:
@@ -58,7 +58,7 @@ export function scanStepFinish(stdout: string): StepFinishScan {
58
58
  type?: string;
59
59
  part?: { reason?: string; sessionID?: string };
60
60
  };
61
- if (event.type === "step-finish") {
61
+ if (event.type === "step_finish") {
62
62
  stepCount++;
63
63
  if (event.part?.reason) reason = event.part.reason;
64
64
  if (event.part?.sessionID) sessionId = event.part.sessionID;
@@ -170,6 +170,65 @@ export function matchUsageLimit(stderr: string, stdout: string): string | undefi
170
170
  return undefined;
171
171
  }
172
172
 
173
+ // Provider errors (docs/roadmap/run-resilience/tickets/opencode-provider-error-lost.md):
174
+ // with `--format json`, opencode reports a provider failure as a top-level
175
+ // `error` event on stdout, exits 1 and writes nothing to stderr. The event is
176
+ // opencode's own, not agent-authored, so reading it does not reopen the
177
+ // false-positive hazard `matchUsageLimit` guards against. Re-check the type
178
+ // table against opencode's source (core/src/session/to-session-error.ts)
179
+ // when upgrading the supported version.
180
+ export interface ProviderError {
181
+ type?: string;
182
+ message?: string;
183
+ status?: number;
184
+ }
185
+
186
+ const WAITING_ERROR_TYPES = new Set([
187
+ "provider.quota",
188
+ "provider.rate-limit",
189
+ "provider.go-limit",
190
+ "provider.chatgpt-limit",
191
+ "provider.chatgpt-workspace-limit",
192
+ "provider.budget-limit",
193
+ ]);
194
+
195
+ /** The last top-level `error` event on stdout, if any. */
196
+ export function scanProviderError(stdout: string): ProviderError | undefined {
197
+ let found: ProviderError | undefined;
198
+ for (const line of stdout.split("\n")) {
199
+ if (!line.trim()) continue;
200
+ try {
201
+ const event = JSON.parse(line) as { type?: unknown; error?: unknown };
202
+ if (event.type !== "error" || event.error === null || typeof event.error !== "object") {
203
+ continue;
204
+ }
205
+ const err = event.error as Record<string, unknown>;
206
+ found = {
207
+ type: typeof err.type === "string" ? err.type : undefined,
208
+ message: typeof err.message === "string" ? err.message : undefined,
209
+ status: typeof err.status === "number" ? err.status : undefined,
210
+ };
211
+ } catch {
212
+ // ignore: not every line is guaranteed parseable
213
+ }
214
+ }
215
+ return found;
216
+ }
217
+
218
+ function describeProviderError(err: ProviderError): string {
219
+ const head = `${err.type ?? "error"}${err.status !== undefined ? ` (${err.status})` : ""}`;
220
+ return err.message ? `${head}: ${err.message}` : head;
221
+ }
222
+
223
+ /** A waiting limit: a known waiting type, or an untyped error whose message
224
+ * holds one of the plain-text markers. Everything else is not waited on. */
225
+ function providerLimitDetail(err: ProviderError): string | undefined {
226
+ const text = err.message ?? describeProviderError(err);
227
+ if (err.type !== undefined) return WAITING_ERROR_TYPES.has(err.type) ? text : undefined;
228
+ const lowered = text.toLowerCase();
229
+ return USAGE_LIMIT_MARKERS.some((marker) => lowered.includes(marker)) ? text : undefined;
230
+ }
231
+
173
232
  // `opencode models` answers in about a second; this only bounds a hung one.
174
233
  const MODEL_LIST_TIMEOUT_MS = 20_000;
175
234
 
@@ -329,7 +388,7 @@ export const opencodeRunner: AgentRunner = {
329
388
  try {
330
389
  const event = JSON.parse(line) as { type?: string };
331
390
  if (event.type) lastEvent = event.type;
332
- if (event.type === "step-finish") stepCount++;
391
+ if (event.type === "step_finish") stepCount++;
333
392
  } catch {
334
393
  // ignore: not every line is guaranteed parseable (same tolerance
335
394
  // scanStepFinish's final pass already has)
@@ -348,7 +407,11 @@ export const opencodeRunner: AgentRunner = {
348
407
 
349
408
  if (exitCode !== 0) {
350
409
  const stderr = await new Response(proc.stderr).text();
351
- const reason = `opencode exited ${exitCode}: ${stderr.trim().slice(-400)}`;
410
+ const providerError = scanProviderError(stdout);
411
+ const detailText = [stderr.trim(), providerError ? describeProviderError(providerError) : ""]
412
+ .filter(Boolean)
413
+ .join("\n");
414
+ const reason = `opencode exited ${exitCode}: ${detailText.slice(-400)}`;
352
415
  lastFailures.set(dispatchKey, reason);
353
416
  const scan = scanStepFinish(stdout);
354
417
  // Usage-limit classification (docs/specs/_built/usage-limit-backoff/spec.md):
@@ -357,7 +420,9 @@ export const opencodeRunner: AgentRunner = {
357
420
  // waits it out instead of burning retries against it. The session id
358
421
  // stays evidence-gated (stepCount > 0) exactly as below. No match
359
422
  // keeps the existing runner-error throw unchanged.
360
- const limitLine = matchUsageLimit(stderr, stdout);
423
+ const limitLine =
424
+ matchUsageLimit(stderr, stdout) ??
425
+ (providerError ? providerLimitDetail(providerError) : undefined);
361
426
  if (limitLine !== undefined) {
362
427
  throw new AgentFailure(reason, {
363
428
  agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
@@ -0,0 +1,11 @@
1
+ import type { OutputSchema } from "../core/index.ts";
2
+
3
+ // The minimal schema every test fixture's agent leaf declares once
4
+ // validateWorkflow rejects a missing outputType
5
+ // (docs/specs/mandatory-agent-output-types/). Fixtures exercise routing,
6
+ // retries, nudges, and the journal — never their output shape — so the
7
+ // declaration is deliberately the most permissive one the rule accepts
8
+ // (a schema that rejects nothing). A test-local convenience, not kit API.
9
+ export const okOutputType: OutputSchema = {
10
+ safeParse: () => ({ success: true }),
11
+ };
@@ -0,0 +1,43 @@
1
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
2
+ import { z } from "zod";
3
+
4
+ // Plan's handoff output is the one dev-loop claim a consumer actually
5
+ // reads: ValidatePlan runs parseTaskList on it and persists tasks.json.
6
+ // This schema mirrors that narrowing
7
+ // (docs/specs/_built/task-list-json/spec.md), so a malformed list costs an
8
+ // in-session nudge instead of a full Plan/ValidatePlan loop round.
9
+ const priority = z.enum(["must", "should", "could", "won't"]);
10
+ const taskList = z.object({
11
+ id: z.string(),
12
+ spec: z.object({ prd: z.string().optional(), design: z.string().optional() }).optional(),
13
+ requirements: z
14
+ .array(
15
+ z.object({
16
+ id: z.string(),
17
+ kind: z.enum(["req", "nfr", "ng"]),
18
+ text: z.string(),
19
+ priority: priority.optional(),
20
+ }),
21
+ )
22
+ .optional(),
23
+ tasks: z.array(
24
+ z.object({
25
+ id: z.string(),
26
+ title: z.string(),
27
+ status: z.enum(["pending", "in-progress", "done", "failed"]),
28
+ satisfies: z.array(z.string()).optional(),
29
+ priority: priority.optional(),
30
+ }),
31
+ ),
32
+ });
33
+ export const planOutput = zodOutputType(taskList);
34
+
35
+ // The other agent leaves route by event; their consumers (Test, MarkDone,
36
+ // Finish) read the working tree and tasks.json, never the handoff output.
37
+ // Their declarations stay permissive — the rule guarantees a declaration,
38
+ // not a good one (docs/specs/mandatory-agent-output-types/, NG-1).
39
+ export const implementOutput = zodOutputType(z.unknown());
40
+ export const fixOutput = zodOutputType(z.unknown());
41
+ export const reviewOutput = zodOutputType(z.unknown());
42
+ export const documentOutput = zodOutputType(z.unknown());
43
+ export const feedbackOutput = zodOutputType(z.unknown());
@@ -1,11 +1,11 @@
1
1
  import type { DispatchInfo } from "@psimona/darkf/src/core/index.ts";
2
2
 
3
- // Ported from blueprint's build-backend create_branch: cut feature/<slug>
3
+ // Ported from a sibling project's build-backend create_branch: cut feature/<slug>
4
4
  // from the current tree. Uncommitted work (the feature under construction)
5
5
  // rides along on the branch — Finish commits it there before the squash.
6
6
  // The slug is a workflow-file constant for the pilot; editing this file per
7
7
  // feature is the contract until engine-side input plumbing exists.
8
- const FEATURE = "opencode-overlay-tiles";
8
+ const FEATURE = "mandatory-agent-output-types";
9
9
 
10
10
  function sh(cwd: string, ...args: string[]): [string, number] {
11
11
  const proc = Bun.spawnSync(args, { cwd, stdout: "pipe", stderr: "pipe" });
@@ -1,32 +1,16 @@
1
1
  import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts";
2
2
 
3
- // Ported from blueprint's build-backend finish_branch (node 4): commit the
3
+ // Ported from a sibling project's build-backend finish_branch (node 4): commit the
4
4
  // loop's work on the feature branch, squash-merge onto master as one commit
5
5
  // (subject from the prd H1), delete the branch. The run ends with the work
6
6
  // merged; no supervisor merge.
7
7
  //
8
8
  // Safety rails:
9
9
  // - only runs on feature/<slug>;
10
- // - refuses when the dirty tree touches paths outside the loop's known
11
- // surface (the anti-sweep rail — a blind `git add -A` once wiped a
12
- // repo's .darkf state in the registry-lifecycle incident);
13
10
  // - refuses unless master is an ancestor of the branch (master must not
14
11
  // have moved mid-run — the only case where the squash could conflict);
15
12
  // - rolls back (reset --hard + checkout back) on any git failure.
16
- const FEATURE = "opencode-overlay-tiles";
17
- const ALLOWED = [
18
- "docs/",
19
- "darkf/src/",
20
- "darkf/skills/",
21
- "darkf/docs/",
22
- "darkf/package.json",
23
- "bun.lock",
24
- "darkf-opencode-plugin/",
25
- "ROADMAP.md",
26
- "README.md",
27
- "site/",
28
- "darkf/workflows/",
29
- ];
13
+ const FEATURE = "mandatory-agent-output-types";
30
14
 
31
15
  function sh(cwd: string, ...args: string[]): [string, number] {
32
16
  const proc = Bun.spawnSync(args, { cwd, stdout: "pipe", stderr: "pipe" });
@@ -52,24 +36,6 @@ export default function finishBranch(_handoff: NodeResult, info: DispatchInfo):
52
36
  };
53
37
  }
54
38
 
55
- const [status, statusRc] = sh(rootDir, "git", "status", "--porcelain");
56
- if (statusRc !== 0) {
57
- return { event: "merge_failed", output: { failure: "git status failed" } };
58
- }
59
- const dirty = status
60
- .split("\n")
61
- .map((l) => l.slice(3).trim())
62
- .filter(Boolean);
63
- const foreign = dirty.filter((p) => !ALLOWED.some((prefix) => p.startsWith(prefix)));
64
- if (foreign.length > 0) {
65
- return {
66
- event: "merge_failed",
67
- output: {
68
- failure: `dirty paths outside the loop's surface — human decision:\n${foreign.join("\n")}`,
69
- },
70
- };
71
- }
72
-
73
39
  const title = prdTitle(rootDir) ?? FEATURE;
74
40
  const subject = `feat: ${title} (${FEATURE})`;
75
41
  const add = sh(rootDir, "git", "add", "-A");
@@ -1,5 +1,13 @@
1
1
  import { DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
2
2
  import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
3
+ import {
4
+ documentOutput,
5
+ feedbackOutput,
6
+ fixOutput,
7
+ implementOutput,
8
+ planOutput,
9
+ reviewOutput,
10
+ } from "./output-types.ts";
3
11
 
4
12
  // dev-loop — begin → PlanPhase{plan → validate} → (dispatch →
5
13
  // Task{implement → test → [fix → test]* → review → mark done})* →
@@ -7,8 +15,8 @@ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
7
15
  //
8
16
  // The darkf-on-darkf pilot, expanded after its first real run built the CLI
9
17
  // self-update feature (docs/specs/_built/self-update/). Shape ported from
10
- // blueprint's build-backend: Begin cuts the feature branch, Finish
11
- // squash-merges onto master with blueprint's rails, Feedback writes the run
18
+ // a sibling project's build-backend: Begin cuts the feature branch, Finish
19
+ // squash-merges onto master with a sibling project's rails, Feedback writes the run
12
20
  // retrospective under darkf/feedback/.
13
21
  //
14
22
  // Run from the target repo root with the released engine from the npm
@@ -98,8 +106,8 @@ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
98
106
  export const agentRunner = opencodeRunner;
99
107
 
100
108
  const MODEL = "zai-coding-plan/glm-5.3-flash";
101
- const RUN_DATE = "2026-11-19";
102
- const FEATURE = "opencode-overlay-tiles";
109
+ const RUN_DATE = "2026-12-03";
110
+ const FEATURE = "mandatory-agent-output-types";
103
111
 
104
112
  export const workflow: WorkflowDef = {
105
113
  initial: "Begin",
@@ -119,6 +127,7 @@ export const workflow: WorkflowDef = {
119
127
  states: {
120
128
  Plan: {
121
129
  type: "agent",
130
+ outputType: planOutput,
122
131
  agent: { model: MODEL },
123
132
  retries: 1,
124
133
  prompt: `You are planning the ${FEATURE} run. Do not write or modify any code.
@@ -161,6 +170,7 @@ Finish with event "planned". If the contract is missing, contradictory, or too v
161
170
  states: {
162
171
  Implement: {
163
172
  type: "agent",
173
+ outputType: implementOutput,
164
174
  agent: { model: MODEL },
165
175
  retries: 1,
166
176
  prompt: `Implement exactly the one task you were handed for the ${FEATURE} feature — see "Input from the previous step" below for its id, title, and which requirements it satisfies. Nothing else.
@@ -182,6 +192,7 @@ Finish with event "implemented". If the task cannot be implemented as specified,
182
192
  },
183
193
  Fix: {
184
194
  type: "agent",
195
+ outputType: fixOutput,
185
196
  agent: { model: MODEL },
186
197
  retries: 1,
187
198
  prompt: `You are repairing the ${FEATURE} implementation after a failed gate.
@@ -193,6 +204,7 @@ Finish with event "fixed". If the failure exposes a spec defect you cannot resol
193
204
  },
194
205
  Review: {
195
206
  type: "agent",
207
+ outputType: reviewOutput,
196
208
  agent: { model: MODEL },
197
209
  retries: 1,
198
210
  prompt: `You are an independent reviewer. Do not modify any files.
@@ -218,6 +230,7 @@ Finish with event "approved" or event "changes_requested".`,
218
230
  },
219
231
  Document: {
220
232
  type: "agent",
233
+ outputType: documentOutput,
221
234
  agent: { model: MODEL },
222
235
  retries: 1,
223
236
  prompt: `You are updating user-facing documentation for the ${FEATURE} feature, after every task in its plan was implemented and independently reviewed. Do not modify code or tests.
@@ -245,6 +258,7 @@ If nothing user-facing changed and no doc drifted, finish with event "skipped" a
245
258
  },
246
259
  Feedback: {
247
260
  type: "agent",
261
+ outputType: feedbackOutput,
248
262
  agent: { model: MODEL },
249
263
  retries: 1,
250
264
  prompt: `Write the run retrospective for the ${FEATURE} dev-loop run, in the style of a post-run feedback note.
@@ -0,0 +1,9 @@
1
+ import { zodOutputType } from "@psimona/darkf/src/kit/validation/zod.ts";
2
+ import { z } from "zod";
3
+
4
+ // Verify runs Gradle against the working tree; nothing reads the handoff
5
+ // output. The declarations stay permissive — the rule guarantees a
6
+ // declaration, not a good one
7
+ // (docs/specs/mandatory-agent-output-types/, NG-1).
8
+ export const implementOutput = zodOutputType(z.unknown());
9
+ export const reviewOutput = zodOutputType(z.unknown());
@@ -9,6 +9,7 @@
9
9
  // darkf start <this dir> "<bug id>"
10
10
  import { type AgentRunner, DONE, type WorkflowDef } from "@psimona/darkf/src/core/index.ts";
11
11
  import { claudeCodeRunner } from "@psimona/darkf/src/kit/agents/claude-code.ts";
12
+ import { implementOutput, reviewOutput } from "./output-types.ts";
12
13
 
13
14
  export const agentRunner: AgentRunner = claudeCodeRunner;
14
15
 
@@ -60,6 +61,7 @@ export const workflow: WorkflowDef = {
60
61
  states: {
61
62
  Implement: {
62
63
  type: "agent",
64
+ outputType: implementOutput,
63
65
  retries: 1,
64
66
  prompt: IMPLEMENT_PROMPT,
65
67
  on: { implemented: "Verify", blocked: DONE, disputed: DONE },
@@ -73,6 +75,7 @@ export const workflow: WorkflowDef = {
73
75
  },
74
76
  Review: {
75
77
  type: "agent",
78
+ outputType: reviewOutput,
76
79
  retries: 1,
77
80
  prompt: REVIEW_PROMPT,
78
81
  on: { done: DONE, changes_requested: "Implement" },