@psimona/darkf 0.5.0 → 0.6.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.
- package/docs/concepts/failure-modes.md +164 -0
- package/docs/concepts/handoff.md +91 -0
- package/docs/concepts/journal.md +92 -0
- package/docs/concepts/node-types.md +175 -0
- package/docs/guides/pick-an-agent-runner.md +57 -0
- package/docs/guides/plan-with-a-task-queue.md +410 -0
- package/docs/guides/render-to-mermaid.md +22 -0
- package/docs/guides/run-detached-and-monitor.md +76 -0
- package/docs/guides/test-your-workflow.md +20 -0
- package/docs/guides/write-your-first-workflow.md +95 -0
- package/docs/index.mdx +64 -0
- package/docs/reference/cli-commands.md +105 -0
- package/docs/reference/core-types.md +123 -0
- package/docs/reference/package-map.md +35 -0
- package/docs/start-here/install.md +71 -0
- package/docs/start-here/quickstart.md +241 -0
- package/package.json +7 -1
- package/skills/darkf-usage/SKILL.md +92 -0
- package/skills/darkf-writing-workflows/SKILL.md +88 -0
- package/src/cli/doctor.test.ts +338 -0
- package/src/cli/index.ts +123 -9
- package/src/cli/setup.test.ts +384 -0
- package/src/cli/setup.ts +286 -0
- package/src/cli/tarball.test.ts +125 -0
- package/src/cli/update.test.ts +82 -0
- package/src/cli/update.ts +20 -0
- package/src/core/types.ts +8 -0
- package/src/engine/run.test.ts +177 -0
- package/src/engine/run.ts +66 -2
- package/src/kit/agents/opencode.test.ts +232 -2
- package/src/kit/agents/opencode.ts +69 -6
- package/src/kit/status.test.ts +67 -0
- package/src/kit/status.ts +25 -0
- package/workflows/dev-loop/scripts/begin.ts +1 -1
- package/workflows/dev-loop/scripts/finish.ts +4 -1
- package/workflows/dev-loop/workflow.ts +30 -19
- package/bunfig.toml +0 -13
- package/examples/article-classifier/data/articles.ts +0 -38
- package/examples/article-classifier/scripts/next.ts +0 -7
- package/examples/article-classifier/scripts/queue.ts +0 -33
- package/examples/article-classifier/scripts/record.ts +0 -9
- package/examples/article-classifier/workflow.ts +0 -44
- package/examples/haiku-commit/scripts/check.ts +0 -24
- package/examples/haiku-commit/workflow.ts +0 -28
- package/examples/haiku-readme/scripts/test.ts +0 -13
- package/examples/haiku-readme/scripts/write.ts +0 -10
- package/examples/haiku-readme/workflow.ts +0 -41
- package/examples/task-queue/scripts/next.ts +0 -20
- package/examples/task-queue/scripts/record.ts +0 -20
- package/examples/task-queue/supervise.ts +0 -57
- package/examples/task-queue/workflow.ts +0 -33
- package/feedback/2026-10-30-self-update.md +0 -29
- package/feedback/2026-10-31-task-list-json.md +0 -26
- package/tsconfig.json +0 -4
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
import { describe, expect, test } from "bun:test";
|
|
2
|
-
import {
|
|
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/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
|
+
});
|
|
@@ -152,6 +152,38 @@ function contextBlock(rootDir: string, runId: string): string {
|
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
+
// Usage-limit detection (docs/specs/usage-limit-backoff/spec.md, Detection):
|
|
156
|
+
// a provider quota wall surfaces as an API-level error — opencode exits
|
|
157
|
+
// non-zero with the provider's message in its output. Scan stderr and
|
|
158
|
+
// non-JSON stdout lines ONLY: stdout's NDJSON lines are event objects, i.e.
|
|
159
|
+
// agent-authored content — a limit-shaped string inside one must never match
|
|
160
|
+
// (a false positive turns a real crash into a silent hours-long wait; the
|
|
161
|
+
// worse error). Markers, case-insensitive, from the 2026-11-01 live capture
|
|
162
|
+
// ("Usage limit reached for 5 hour. Your limit will reset at ..."): the
|
|
163
|
+
// quoted reset time is display text darkf never parses — see the spec's Wait
|
|
164
|
+
// section for why a fixed interval is the honest response. Returns the first
|
|
165
|
+
// matched line; callers consult this on the non-zero-exit branch only, so a
|
|
166
|
+
// limit-shaped string on the exit-0 + missing-handoff path stays a
|
|
167
|
+
// `handoff-missing` on its existing nudge/repair path.
|
|
168
|
+
const USAGE_LIMIT_MARKERS = ["usage limit", "rate limit", "limit exceeded", "429"];
|
|
169
|
+
|
|
170
|
+
export function matchUsageLimit(stderr: string, stdout: string): string | undefined {
|
|
171
|
+
for (const text of [stderr, stdout]) {
|
|
172
|
+
for (const line of text.split("\n")) {
|
|
173
|
+
if (!line.trim()) continue;
|
|
174
|
+
try {
|
|
175
|
+
JSON.parse(line);
|
|
176
|
+
continue; // event object — agent-authored, never matched
|
|
177
|
+
} catch {
|
|
178
|
+
// not JSON — runner/provider output
|
|
179
|
+
}
|
|
180
|
+
const lowered = line.toLowerCase();
|
|
181
|
+
if (USAGE_LIMIT_MARKERS.some((marker) => lowered.includes(marker))) return line;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
|
|
155
187
|
export const opencodeRunner: AgentRunner = {
|
|
156
188
|
kind: "opencode",
|
|
157
189
|
async run(id, def, handoff, info: DispatchInfo, onProgress?: (p: AgentProgress) => void) {
|
|
@@ -186,9 +218,26 @@ export const opencodeRunner: AgentRunner = {
|
|
|
186
218
|
// "No -s outside a nudge" note below.
|
|
187
219
|
const nudge = nudgeMessage(info, path);
|
|
188
220
|
|
|
221
|
+
// Post-limit continuation (docs/specs/usage-limit-backoff/spec.md, Wait
|
|
222
|
+
// and resume): when the engine re-dispatches this attempt after waiting
|
|
223
|
+
// out a usage limit, resume the interrupted session with a short
|
|
224
|
+
// continuation prompt instead of replaying the full fresh prompt — the
|
|
225
|
+
// dispatch itself doubles as the limit probe (a still-limited provider
|
|
226
|
+
// rejects it before processing; a lifted limit continues mid-flight with
|
|
227
|
+
// all pre-wall work intact). A present agentSessionId IS the evidence
|
|
228
|
+
// gate: the runner only ever attaches one when `scanStepFinish` counted
|
|
229
|
+
// step events (stepCount > 0), the same bar that makes `-s` safe for
|
|
230
|
+
// nudges. Without a session id the dispatch is fresh, exactly as before.
|
|
231
|
+
const continuation =
|
|
232
|
+
info.previousFailure?.kind === "usage-limit" && info.agentSessionId !== undefined
|
|
233
|
+
? `A provider usage limit interrupted your previous turn. Continue where you left off.\n\n${handoffContractText(path)}`
|
|
234
|
+
: undefined;
|
|
235
|
+
|
|
189
236
|
let prompt: string;
|
|
190
237
|
if (nudge) {
|
|
191
238
|
prompt = nudge;
|
|
239
|
+
} else if (continuation) {
|
|
240
|
+
prompt = continuation;
|
|
192
241
|
} else {
|
|
193
242
|
const promptParts: string[] = [];
|
|
194
243
|
|
|
@@ -225,16 +274,17 @@ export const opencodeRunner: AgentRunner = {
|
|
|
225
274
|
// terminal runner crash. `scanStepFinish`'s `stepCount` guard (above) is
|
|
226
275
|
// what makes `-s` safe again — the hang's root cause was resuming a
|
|
227
276
|
// session with no evidence it had done anything, not resuming as such —
|
|
228
|
-
// but it's deliberately only ever used for
|
|
229
|
-
//
|
|
230
|
-
//
|
|
231
|
-
//
|
|
232
|
-
//
|
|
277
|
+
// but it's deliberately only ever used for two explicitly-scoped cases:
|
|
278
|
+
// a nudge (immediately after a nudgeable failure in the same outer
|
|
279
|
+
// attempt) and the post-limit continuation (usage-limit-backoff spec —
|
|
280
|
+
// same evidence gate, same reasoning). A fresh or exhausted-nudge
|
|
281
|
+
// dispatch always starts a brand-new session, exactly as today, even
|
|
282
|
+
// when `info.agentSessionId` happens to be set.
|
|
233
283
|
const bin = Bun.which("opencode") ?? "opencode";
|
|
234
284
|
const args = [
|
|
235
285
|
bin,
|
|
236
286
|
"run",
|
|
237
|
-
...(nudge ? ["-s", info.agentSessionId!] : []),
|
|
287
|
+
...(nudge || continuation ? ["-s", info.agentSessionId!] : []),
|
|
238
288
|
...(auto ? ["--auto"] : []),
|
|
239
289
|
"-m",
|
|
240
290
|
model,
|
|
@@ -285,6 +335,19 @@ export const opencodeRunner: AgentRunner = {
|
|
|
285
335
|
const reason = `opencode exited ${exitCode}: ${stderr.trim().slice(-400)}`;
|
|
286
336
|
lastFailures.set(dispatchKey, reason);
|
|
287
337
|
const scan = scanStepFinish(stdout);
|
|
338
|
+
// Usage-limit classification (docs/specs/usage-limit-backoff/spec.md):
|
|
339
|
+
// consulted on this non-zero-exit branch ONLY, before the generic
|
|
340
|
+
// throw — a quota wall is a known temporary condition, and the engine
|
|
341
|
+
// waits it out instead of burning retries against it. The session id
|
|
342
|
+
// stays evidence-gated (stepCount > 0) exactly as below. No match
|
|
343
|
+
// keeps the existing runner-error throw unchanged.
|
|
344
|
+
const limitLine = matchUsageLimit(stderr, stdout);
|
|
345
|
+
if (limitLine !== undefined) {
|
|
346
|
+
throw new AgentFailure(reason, {
|
|
347
|
+
agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
|
|
348
|
+
crashReason: { kind: "usage-limit", detail: limitLine },
|
|
349
|
+
});
|
|
350
|
+
}
|
|
288
351
|
throw new AgentFailure(reason, {
|
|
289
352
|
agentSessionId: scan.stepCount > 0 ? scan.sessionId : undefined,
|
|
290
353
|
crashReason: { kind: "runner-error", error: reason },
|
package/src/kit/status.test.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
foldJournal,
|
|
14
14
|
foldReport,
|
|
15
15
|
foldTaskList,
|
|
16
|
+
limitWarning,
|
|
16
17
|
nudgeWarning,
|
|
17
18
|
stallWarning,
|
|
18
19
|
} from "./status.ts";
|
|
@@ -296,6 +297,72 @@ test("nudgeWarning fires only for a running node with an active nudge", () => {
|
|
|
296
297
|
expect(nudgeWarning(done)).toBeNull();
|
|
297
298
|
});
|
|
298
299
|
|
|
300
|
+
function runningWithLimitBackoff(
|
|
301
|
+
state: string,
|
|
302
|
+
heartbeatTs: number,
|
|
303
|
+
backoff: { probe: number; nextAttemptAt: number; waitedMs: number },
|
|
304
|
+
): NodeEvent {
|
|
305
|
+
return {
|
|
306
|
+
runId: R,
|
|
307
|
+
state,
|
|
308
|
+
scopePath: [],
|
|
309
|
+
status: {
|
|
310
|
+
phase: "running",
|
|
311
|
+
attempt: 1,
|
|
312
|
+
startedAt: heartbeatTs,
|
|
313
|
+
lastHeartbeat: heartbeatTs,
|
|
314
|
+
limitBackoff: backoff,
|
|
315
|
+
},
|
|
316
|
+
timestamp: heartbeatTs,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
test("foldJournal surfaces a running node's limitBackoff, omits it when absent", () => {
|
|
321
|
+
const waiting = foldJournal(
|
|
322
|
+
journalText([
|
|
323
|
+
begin(),
|
|
324
|
+
runningWithLimitBackoff("Write", 2000, { probe: 1, nextAttemptAt: 2600, waitedMs: 600 }),
|
|
325
|
+
]),
|
|
326
|
+
);
|
|
327
|
+
expect(waiting.current?.limitBackoff).toEqual({ probe: 1, nextAttemptAt: 2600, waitedMs: 600 });
|
|
328
|
+
|
|
329
|
+
const plain = foldJournal(journalText([begin(), running("Write", 2000)]));
|
|
330
|
+
expect(plain.current?.limitBackoff).toBeUndefined();
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
test("limitWarning renders the probe countdown from the latest waiting heartbeat", () => {
|
|
334
|
+
const NOW = 3_600_000;
|
|
335
|
+
// 22 minutes until the next attempt; defaults give a 24h/30min = 48 total.
|
|
336
|
+
const digest = foldJournal(
|
|
337
|
+
journalText([
|
|
338
|
+
begin(),
|
|
339
|
+
running("Write", NOW - 8 * 60_000),
|
|
340
|
+
runningWithLimitBackoff("Write", NOW - 1_000, {
|
|
341
|
+
probe: 3,
|
|
342
|
+
nextAttemptAt: NOW + 22 * 60_000,
|
|
343
|
+
waitedMs: 90 * 60_000,
|
|
344
|
+
}),
|
|
345
|
+
]),
|
|
346
|
+
);
|
|
347
|
+
expect(limitWarning(digest, NOW)).toBe("usage limit — probe 3/48, next attempt in 22m");
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
test("limitWarning is null for a plain running heartbeat, and once the wait ends (latest running status has no limitBackoff)", () => {
|
|
351
|
+
const plain = foldJournal(journalText([begin(), running("Write", 2000)]));
|
|
352
|
+
expect(limitWarning(plain)).toBeNull();
|
|
353
|
+
|
|
354
|
+
// The post-wait re-dispatch's running status carries no limitBackoff — the
|
|
355
|
+
// warning must clear while the probe dispatch itself is running.
|
|
356
|
+
const probing = foldJournal(
|
|
357
|
+
journalText([
|
|
358
|
+
begin(),
|
|
359
|
+
runningWithLimitBackoff("Write", 2000, { probe: 1, nextAttemptAt: 2600, waitedMs: 600 }),
|
|
360
|
+
running("Write", 2600),
|
|
361
|
+
]),
|
|
362
|
+
);
|
|
363
|
+
expect(limitWarning(probing)).toBeNull();
|
|
364
|
+
});
|
|
365
|
+
|
|
299
366
|
test("foldJournal counts distinct visits, not retry attempts", () => {
|
|
300
367
|
// Write visited once (two attempts), then Test visited once
|
|
301
368
|
const events = [
|
package/src/kit/status.ts
CHANGED
|
@@ -31,6 +31,10 @@ export interface JournalDigest {
|
|
|
31
31
|
agentStepCount?: number;
|
|
32
32
|
/** Milliseconds idle as of the last heartbeat — see `agentStallWarning`. */
|
|
33
33
|
agentIdleMs?: number;
|
|
34
|
+
/** Present while the engine is waiting out a provider usage-limit
|
|
35
|
+
* backoff for the current attempt — see `limitWarning` and
|
|
36
|
+
* docs/specs/usage-limit-backoff/spec.md. */
|
|
37
|
+
limitBackoff?: { probe: number; nextAttemptAt: number; waitedMs: number };
|
|
34
38
|
} | null;
|
|
35
39
|
crash?: { attempt: number; reason: CrashReason };
|
|
36
40
|
visits: Record<string, number>;
|
|
@@ -88,6 +92,7 @@ export function foldJournal(journalText: string): JournalDigest {
|
|
|
88
92
|
nudgeReason: lastStatus.nudgeReason,
|
|
89
93
|
agentStepCount: lastStatus.agentStepCount,
|
|
90
94
|
agentIdleMs: lastStatus.agentIdleMs,
|
|
95
|
+
limitBackoff: lastStatus.limitBackoff,
|
|
91
96
|
}
|
|
92
97
|
: {}),
|
|
93
98
|
};
|
|
@@ -321,3 +326,23 @@ export function nudgeWarning(digest: JournalDigest): string | null {
|
|
|
321
326
|
if (digest.current?.phase !== "running" || nudgeAttempt === undefined) return null;
|
|
322
327
|
return `nudging attempt ${nudgeAttempt}/3 (${nudgeReason}) — supervisor decides`;
|
|
323
328
|
}
|
|
329
|
+
|
|
330
|
+
// Display-only usage-limit config defaults (docs/specs/usage-limit-backoff/
|
|
331
|
+
// spec.md), mirroring how this module already treats other engine constants
|
|
332
|
+
// as display knowledge, not a shared dependency. The denominator assumes the
|
|
333
|
+
// defaults; a leaf overriding usageLimitRetryMs/usageLimitMaxWaitMs renders
|
|
334
|
+
// a best-effort total until leaf config is recorded in the journal.
|
|
335
|
+
const USAGE_LIMIT_RETRY_MS = 30 * 60_000;
|
|
336
|
+
const USAGE_LIMIT_MAX_WAIT_MS = 24 * 60 * 60_000;
|
|
337
|
+
|
|
338
|
+
/** Warn-only usage-limit wait note, same contract as `stallWarning`: folded
|
|
339
|
+
* from the latest running status's `limitBackoff` — present only while the
|
|
340
|
+
* engine sleeps between usage-limit re-probes, so the supervisor sees the
|
|
341
|
+
* wait instead of silence. Purely a display string, never acts. */
|
|
342
|
+
export function limitWarning(digest: JournalDigest, now: number = Date.now()): string | null {
|
|
343
|
+
const backoff = digest.current?.limitBackoff;
|
|
344
|
+
if (digest.current?.phase !== "running" || backoff === undefined) return null;
|
|
345
|
+
const totalProbes = Math.ceil(USAGE_LIMIT_MAX_WAIT_MS / USAGE_LIMIT_RETRY_MS);
|
|
346
|
+
const minutes = Math.max(0, Math.round((backoff.nextAttemptAt - now) / 60_000));
|
|
347
|
+
return `usage limit — probe ${backoff.probe}/${totalProbes}, next attempt in ${minutes}m`;
|
|
348
|
+
}
|
|
@@ -5,7 +5,7 @@ import type { DispatchInfo } from "@psimona/darkf/src/core/index.ts";
|
|
|
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 = "
|
|
8
|
+
const FEATURE = "skill-setup";
|
|
9
9
|
|
|
10
10
|
function sh(...args: string[]): [string, number] {
|
|
11
11
|
const proc = Bun.spawnSync(args, { stdout: "pipe", stderr: "pipe" });
|
|
@@ -13,10 +13,13 @@ import type { DispatchInfo, NodeResult } from "@psimona/darkf/src/core/index.ts"
|
|
|
13
13
|
// - refuses unless master is an ancestor of the branch (master must not
|
|
14
14
|
// have moved mid-run — the only case where the squash could conflict);
|
|
15
15
|
// - rolls back (reset --hard + checkout back) on any git failure.
|
|
16
|
-
const FEATURE = "
|
|
16
|
+
const FEATURE = "skill-setup";
|
|
17
17
|
const ALLOWED = [
|
|
18
18
|
"docs/",
|
|
19
19
|
"darkf/src/",
|
|
20
|
+
"darkf/skills/",
|
|
21
|
+
"darkf/docs/",
|
|
22
|
+
"darkf/package.json",
|
|
20
23
|
"darkf-opencode-plugin/",
|
|
21
24
|
"ROADMAP.md",
|
|
22
25
|
"README.md",
|
|
@@ -15,7 +15,7 @@ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
|
|
|
15
15
|
// workspace symlink — doctor's selfRoot guard fails inside the checkout):
|
|
16
16
|
//
|
|
17
17
|
// bun run install:global # once, to refresh the global binary
|
|
18
|
-
// darkf
|
|
18
|
+
// darkf validate darkf/workflows/dev-loop
|
|
19
19
|
// darkf start darkf/workflows/dev-loop "message" --allow-dirty-workflow
|
|
20
20
|
//
|
|
21
21
|
// Editing the FEATURE / RUN_DATE constants at the top of the begin/finish
|
|
@@ -34,8 +34,8 @@ import { opencodeRunner } from "@psimona/darkf/src/kit/agents/opencode.ts";
|
|
|
34
34
|
export const agentRunner = opencodeRunner;
|
|
35
35
|
|
|
36
36
|
const MODEL = "zai-coding-plan/glm-5.3-flash";
|
|
37
|
-
const RUN_DATE = "2026-
|
|
38
|
-
const FEATURE = "
|
|
37
|
+
const RUN_DATE = "2026-11-09";
|
|
38
|
+
const FEATURE = "skill-setup";
|
|
39
39
|
|
|
40
40
|
export const workflow: WorkflowDef = {
|
|
41
41
|
initial: "Begin",
|
|
@@ -60,18 +60,20 @@ export const workflow: WorkflowDef = {
|
|
|
60
60
|
retries: 1,
|
|
61
61
|
prompt: `Implement the ${FEATURE} feature in this repository.
|
|
62
62
|
|
|
63
|
-
First read docs/specs/${FEATURE}/spec.md. It is the contract: its
|
|
63
|
+
First read docs/specs/${FEATURE}/spec.md. It is the contract: its Decisions and Non-goals sections are locked — implement exactly what they specify, nothing more. The spec is the only contract artifact; no design.md exists for this feature.
|
|
64
64
|
|
|
65
|
-
Resume semantics: if the working tree already implements the spec, verify that instead of re-implementing
|
|
65
|
+
Resume semantics: if the working tree already implements part of the spec, verify that part instead of re-implementing. The bundled skills already exist and are final content — darkf/skills/darkf-usage/SKILL.md and darkf/skills/darkf-writing-workflows/SKILL.md. Do not rewrite them. Wire them into setup, doctor, packaging, and the docs move as the spec specifies.
|
|
66
66
|
|
|
67
67
|
Deliverables (when not already present):
|
|
68
|
-
-
|
|
69
|
-
-
|
|
70
|
-
-
|
|
71
|
-
-
|
|
72
|
-
-
|
|
68
|
+
- darkf/src/cli/setup.ts (new): \`darkf setup\` — sync both bundled skills into every detected host's skills dir. Hosts are a table in code per the spec: claude code (~/.claude/skills, binary claude), opencode (~/.opencode/skills, opencode), codex cli (~/.codex/skills, codex), gemini cli (~/.gemini/skills, gemini), cursor (~/.cursor/skills, cursor-agent); a host is detected when its skills dir exists OR its binary is on PATH. Write policy: darkf-* is darkf's namespace — copy when missing; when present, replace the whole dir (copy bundled to a dot-prefixed temp dir inside the skills dir, remove the installed dir, rename into place) so the destination is an exact mirror. States missing/ok/differs per skill. Output: one host-detection line, then one line per host per skill. Creates a missing skills dir (mode 0755) for a detected host; skips an undetected host without creating anything. Exits non-zero when a present host still ends missing/differs after the sync attempt. Takes no flags and no positional args; never prompts.
|
|
69
|
+
- \`darkf upgrade\` (darkf/src/cli/update.ts) runs the same sync after self-update, under a "skills:" header, best-effort: a sync failure is reported and exits non-zero but never masks the upgrade itself.
|
|
70
|
+
- doctor/validate split in darkf/src/cli/index.ts: \`darkf doctor\` with no ref checks the environment only — agent binaries, cwd sanity, skills section. \`darkf validate <ref>\` inherits the workflow checks doctor has today (resolves, loads, exports, structure), unchanged lines and exit codes. Back-compat: \`darkf doctor <ref>\` prints the new usage and exits 1. The skills section names every known harness: per skill ok/missing/differs for a present harness, \`harness not present\` for an absent one; it writes nothing and exits non-zero only for missing/differs on a present harness, with \`run darkf setup\` as the fix hint. All three (doctor skills section, validate checks, setup sync) share one skills-check function. Fix doctor's stale runner hint while there: "built-ins live in src/agents/" — the real location is src/kit/agents/.
|
|
71
|
+
- Daily probe: once per calendar day, the first darkf invocation after the update gate runs a skills-only check via the same shared function. State file per the spec (XDG state semantics like updateStateFile) stores the last probe date; missing or corrupt counts as never probed. Silent when every present harness is ok. On missing/differs, print one compact block (the failing lines plus "fix: run darkf setup") before the invoked command's own output. Never fatal — the probe never changes the invoking command's exit code. \`setup\` and \`upgrade\` skip the probe and refresh the state file.
|
|
72
|
+
- Packaging: darkf/package.json gains "files": ["src", "workflows", "skills", "docs"].
|
|
73
|
+
- Docs move: move site/src/content/docs/** to darkf/docs/** and rebase the site's content loading onto darkf/docs/ (site/src/content.config.ts, starlight docsLoader — rebase it, or if the loader cannot rebase, a prepack copy with a drift check per the spec). bun run build in site/ must still succeed.
|
|
74
|
+
- Tests per the spec's Testing section: setup tests with deps injected like update.ts's UpdateDeps (home, bundledDir, existsBinary) covering host detection by dir alone / by binary / absent, copy and mirror semantics including leftover-file wipe and crashed-temp-dir replacement, state reporting, and exit codes; doctor/validate split tests; daily-probe tests (first-of-day runs, same-day skip, corrupt state file, silent-ok, block-on-failure, exemptions); the tarball smoke check (npm pack, temp-prefix install, run setup/doctor/render and the skill-referenced docs paths).
|
|
73
75
|
|
|
74
|
-
Follow the existing code style of darkf/src/
|
|
76
|
+
Follow the existing code style of darkf/src/cli/index.ts and darkf/src/cli/update.ts. Do not commit. Do not touch files outside darkf/src/, darkf/package.json, darkf/skills/, darkf/docs/, site/, and docs/specs/${FEATURE}/.
|
|
75
77
|
|
|
76
78
|
Finish with event "implemented". If the spec cannot be implemented as written, finish with event "blocked" and put the reason in the output. If a review demand contradicts the spec, finish with event "disputed" and ground the objection in the spec text.`,
|
|
77
79
|
on: { implemented: "Check", blocked: DONE, disputed: DONE },
|
|
@@ -88,7 +90,7 @@ Finish with event "implemented". If the spec cannot be implemented as written, f
|
|
|
88
90
|
retries: 1,
|
|
89
91
|
prompt: `You are repairing the ${FEATURE} implementation after a failed gate.
|
|
90
92
|
|
|
91
|
-
The handoff you received carries either the failing tail of "bun run check" or the reviewer's change list. Read docs/specs/${FEATURE}/spec.md for the contract. Fix the code minimally. Do not redesign. Do not commit. Do not touch files outside darkf/src/
|
|
93
|
+
The handoff you received carries either the failing tail of "bun run check" or the reviewer's change list. Read docs/specs/${FEATURE}/spec.md for the contract. Fix the code minimally. Do not redesign. Do not commit. Do not touch files outside darkf/src/, darkf/package.json, darkf/skills/, darkf/docs/, and site/.
|
|
92
94
|
|
|
93
95
|
Finish with event "fixed". If the failure exposes a spec defect you cannot resolve in code, finish with event "blocked" and the reason. If the demand contradicts the spec, finish with event "disputed" and ground the objection in the spec text.`,
|
|
94
96
|
on: { fixed: "Check", blocked: DONE, disputed: DONE },
|
|
@@ -101,9 +103,15 @@ Finish with event "fixed". If the failure exposes a spec defect you cannot resol
|
|
|
101
103
|
|
|
102
104
|
Verify the working tree against docs/specs/${FEATURE}/spec.md:
|
|
103
105
|
- inspect git status --porcelain in addition to git diff — agent-authored new files are invisible to git diff alone
|
|
104
|
-
- check the
|
|
105
|
-
- check the
|
|
106
|
-
-
|
|
106
|
+
- check the host table matches the spec exactly: five harnesses (claude code, opencode, codex cli, gemini cli, cursor), their skills dirs and binary names, and dir-exists OR binary-on-PATH detection
|
|
107
|
+
- check the write policy: darkf-* namespace only, dir replacement not file merge (temp-dir copy, remove, rename), exact-mirror destinations, no flags, no prompts, undetected hosts skipped without dir creation
|
|
108
|
+
- check the upgrade sync: runs after self-update under a "skills:" header, best-effort, same code path as setup
|
|
109
|
+
- check the doctor/validate split: doctor with no ref = environment only (binaries, cwd sanity, skills section); validate <ref> inherits the workflow checks with unchanged lines and exit codes; doctor <ref> back-compat prints usage and exits 1; the skills section names every known harness with the spec's states and exit rules; the stale "src/agents/" hint is fixed to src/kit/agents/
|
|
110
|
+
- check the daily probe: once per calendar day on first invocation after the update gate, skills-only via the shared function, spec state file with missing/corrupt treated as never probed, silent on ok, compact block plus fix hint on missing/differs, never fatal, setup/upgrade exempt and refreshing the state file
|
|
111
|
+
- check packaging: package.json files allowlist exactly ["src", "workflows", "skills", "docs"]; docs moved to darkf/docs/; the site still builds from the moved docs (loader rebase or prepack copy with drift check)
|
|
112
|
+
- check the bundled skills are byte-unchanged: darkf/skills/darkf-usage/SKILL.md and darkf/skills/darkf-writing-workflows/SKILL.md
|
|
113
|
+
- check the tests cover the spec's Testing section: setup deps-injection fixtures, mirror semantics, doctor/validate split, daily probe behaviors, tarball smoke check
|
|
114
|
+
- you may run "bun test darkf/src" and "bun run lint" yourself
|
|
107
115
|
|
|
108
116
|
Approve only if the implementation fulfills the spec. Otherwise list every required change concretely in the output.
|
|
109
117
|
|
|
@@ -118,14 +126,17 @@ Finish with event "approved" or event "changes_requested".`,
|
|
|
118
126
|
|
|
119
127
|
Read docs/specs/${FEATURE}/spec.md (or prd.md/design.md when present) for what the feature does, and run git diff master plus git status --porcelain to see what shipped.
|
|
120
128
|
|
|
121
|
-
|
|
129
|
+
Docs must match the spec when this run lands — drift accumulates one stale page at a time. Update everything the feature's surface touches:
|
|
122
130
|
- README.md — CLI flags/commands, plugin behavior, setup steps that changed
|
|
123
|
-
- docs
|
|
124
|
-
-
|
|
131
|
+
- packaged docs under darkf/docs/ — the site renders from these files, so they are the docs:
|
|
132
|
+
- reference/cli-commands.md for any CLI surface change (new command, flag, exit code, default)
|
|
133
|
+
- the guides and concepts pages the feature's surface touches — re-read them and fix stale paths, stale command names, and claims the feature made wrong
|
|
134
|
+
- start-here/install.md when setup, packaging, or install steps changed
|
|
135
|
+
- cross-references anywhere in darkf/docs/ or README.md that now point at moved or renamed paths
|
|
125
136
|
|
|
126
137
|
Do NOT touch: ROADMAP.md, darkf/feedback/, docs/specs/ (the spec archive move and roadmap entry are post-merge human curation), any file under darkf/src/ or darkf-opencode-plugin/.
|
|
127
138
|
|
|
128
|
-
If nothing user-facing changed
|
|
139
|
+
If nothing user-facing changed and no doc drifted, finish with event "skipped" and put the one-line reason in the output. Otherwise make the edits and finish with event "documented". If the docs cannot be updated (for example the site is broken), finish with event "blocked" and the reason.`,
|
|
129
140
|
on: { documented: "Finish", skipped: "Finish", blocked: DONE },
|
|
130
141
|
},
|
|
131
142
|
},
|
package/bunfig.toml
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
# One merged suite, one threshold. `darkf-core`, `darkf-engine`, and the
|
|
2
|
-
# old `darkf-cli` coverage configs (0.85/0.80 engine, 0.30/0.30 cli) died
|
|
3
|
-
# with the package merge — the package-boundaries spec moved all sources
|
|
4
|
-
# under one roof, so coverage is measured once, across the whole tree.
|
|
5
|
-
#
|
|
6
|
-
# kit/agents is excluded because the runners' real code paths execute
|
|
7
|
-
# inside spawned worker subprocesses (see src/cli/detached.test.ts), which
|
|
8
|
-
# the in-process profiler cannot see; their harness-side logic is still
|
|
9
|
-
# covered in-process (handoff, registry, status).
|
|
10
|
-
[test]
|
|
11
|
-
coverage = true
|
|
12
|
-
coveragePathIgnorePatterns = ["src/kit/agents/**"]
|
|
13
|
-
coverageThreshold = { lines = 0.30, functions = 0.30 }
|