@psimona/darkf 0.0.0-stage → 0.4.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/README.md +28 -2
- package/bunfig.toml +13 -0
- package/examples/article-classifier/data/articles.ts +38 -0
- package/examples/article-classifier/scripts/next.ts +7 -0
- package/examples/article-classifier/scripts/queue.ts +33 -0
- package/examples/article-classifier/scripts/record.ts +9 -0
- package/examples/article-classifier/workflow.ts +44 -0
- package/examples/haiku-commit/scripts/check.ts +24 -0
- package/examples/haiku-commit/workflow.ts +28 -0
- package/examples/haiku-readme/scripts/test.ts +13 -0
- package/examples/haiku-readme/scripts/write.ts +10 -0
- package/examples/haiku-readme/workflow.ts +41 -0
- package/examples/task-queue/scripts/next.ts +20 -0
- package/examples/task-queue/scripts/record.ts +20 -0
- package/examples/task-queue/supervise.ts +57 -0
- package/examples/task-queue/workflow.ts +33 -0
- package/feedback/2026-10-30-self-update.md +29 -0
- package/package.json +30 -4
- package/src/cli/detached.test.ts +560 -0
- package/src/cli/index.ts +1040 -0
- package/src/cli/update.test.ts +486 -0
- package/src/cli/update.ts +191 -0
- package/src/core/graph.test.ts +172 -0
- package/src/core/graph.ts +148 -0
- package/src/core/index.ts +4 -0
- package/src/core/journal.ts +21 -0
- package/src/core/mermaid.test.ts +34 -0
- package/src/core/mermaid.ts +95 -0
- package/src/core/types.ts +279 -0
- package/src/engine/eventLog.ts +17 -0
- package/src/engine/index.ts +2 -0
- package/src/engine/run.test.ts +1068 -0
- package/src/engine/run.ts +359 -0
- package/src/exports.ts +2 -0
- package/src/kit/agents/claude-code.test.ts +37 -0
- package/src/kit/agents/claude-code.ts +180 -0
- package/src/kit/agents/handoff.test.ts +128 -0
- package/src/kit/agents/handoff.ts +69 -0
- package/src/kit/agents/opencode.test.ts +136 -0
- package/src/kit/agents/opencode.ts +327 -0
- package/src/kit/registry.test.ts +386 -0
- package/src/kit/registry.ts +296 -0
- package/src/kit/status.test.ts +423 -0
- package/src/kit/status.ts +282 -0
- package/tsconfig.json +4 -0
- package/workflows/dev-loop/scripts/begin.ts +22 -0
- package/workflows/dev-loop/scripts/check.ts +19 -0
- package/workflows/dev-loop/scripts/finish.ts +114 -0
- package/workflows/dev-loop/workflow.ts +135 -0
- package/workflows/series-ordering/scripts/verify.ts +18 -0
- package/workflows/series-ordering/workflow.ts +80 -0
package/src/cli/index.ts
ADDED
|
@@ -0,0 +1,1040 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { closeSync, existsSync, openSync, readdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import packageJson from "../../package.json";
|
|
8
|
+
import {
|
|
9
|
+
type AgentRunner,
|
|
10
|
+
buildRegistry,
|
|
11
|
+
DONE,
|
|
12
|
+
type NodeEvent,
|
|
13
|
+
type NodeResult,
|
|
14
|
+
parseEventLog,
|
|
15
|
+
renderActive,
|
|
16
|
+
renderMermaid,
|
|
17
|
+
type ScriptRunner,
|
|
18
|
+
validateWorkflow,
|
|
19
|
+
type WorkflowDef,
|
|
20
|
+
type WorkflowValidationError,
|
|
21
|
+
} from "../core/index.ts";
|
|
22
|
+
import { run } from "../engine/index.ts";
|
|
23
|
+
import {
|
|
24
|
+
currentBootId,
|
|
25
|
+
detectSupervisorSignal,
|
|
26
|
+
hostDiedSince,
|
|
27
|
+
isPidAlive,
|
|
28
|
+
journalPathFor,
|
|
29
|
+
projectRoot,
|
|
30
|
+
type RegistryEntry,
|
|
31
|
+
type RegistryStatus,
|
|
32
|
+
readEntry,
|
|
33
|
+
readJournalText,
|
|
34
|
+
readyPath,
|
|
35
|
+
resolveRun,
|
|
36
|
+
runArtifactsDir,
|
|
37
|
+
SCHEMA_VERSION,
|
|
38
|
+
workerLogPath,
|
|
39
|
+
writeEntry,
|
|
40
|
+
} from "../kit/registry.ts";
|
|
41
|
+
import {
|
|
42
|
+
AGENT_STALL_MS,
|
|
43
|
+
agentStallWarning,
|
|
44
|
+
classifyTerminal,
|
|
45
|
+
foldJournal,
|
|
46
|
+
foldReport,
|
|
47
|
+
nudgeWarning,
|
|
48
|
+
stallWarning,
|
|
49
|
+
type TerminalState,
|
|
50
|
+
} from "../kit/status.ts";
|
|
51
|
+
import { type UpdateDeps, updateGate, upgradeCmd } from "./update.ts";
|
|
52
|
+
|
|
53
|
+
const INDEX_PATH = fileURLToPath(import.meta.url);
|
|
54
|
+
// Fixed, not yet measured against a cold `bun` import on real hosts — see
|
|
55
|
+
// docs/specs/_built/registry-lifecycle/spec.md's open questions.
|
|
56
|
+
const READY_TIMEOUT_MS = 10_000;
|
|
57
|
+
const READY_POLL_MS = 100;
|
|
58
|
+
const MONITOR_SUB_POLL_MS = 500;
|
|
59
|
+
const DEFAULT_MONITOR_WINDOW_S = 30;
|
|
60
|
+
const MESSAGE_MAX_LEN = 2048;
|
|
61
|
+
const WORKER_LOG_TAIL_CHARS = 2000;
|
|
62
|
+
|
|
63
|
+
interface WorkflowModule {
|
|
64
|
+
workflow: WorkflowDef;
|
|
65
|
+
input?: NodeResult;
|
|
66
|
+
agentRunner?: AgentRunner;
|
|
67
|
+
/** Opt-in override for run-aware script dispatch — e.g. a script needing
|
|
68
|
+
* `.darkf/run/<runId>/...` for its own artifacts (see DispatchInfo's own
|
|
69
|
+
* docs in darkf-core). Omitted: falls back to darkf-engine's default,
|
|
70
|
+
* which only ever passes a script's default export the plain `handoff`. */
|
|
71
|
+
scriptRunner?: ScriptRunner;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function loadWorkflow(dir: string): Promise<WorkflowModule> {
|
|
75
|
+
const url = pathToFileURL(resolve(dir, "workflow.ts")).href;
|
|
76
|
+
const mod = await import(url);
|
|
77
|
+
return mod as WorkflowModule;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Workflow reference resolution. A ref with a path separator (or an existing
|
|
82
|
+
* relative path) is a filesystem path. A bare name is looked up in:
|
|
83
|
+
* 1. `<cwd>/darkf/<name>` — project workspace
|
|
84
|
+
* 2. `<darkf>/workflows/<name>` — shipped with darkf
|
|
85
|
+
* A candidate counts only if it contains a workflow.ts.
|
|
86
|
+
*
|
|
87
|
+
* `<cwd>/.darkf/workflows/<name>` was the original location and is no
|
|
88
|
+
* longer resolved at all (see docs/specs/_built/registry-lifecycle/spec.md):
|
|
89
|
+
* `.darkf/` is darkf's own runtime/run-storage directory, meant to be
|
|
90
|
+
* gitignored wholesale, which was never possible while committed workflow
|
|
91
|
+
* config lived inside it too.
|
|
92
|
+
*/
|
|
93
|
+
function selfRoot(): string {
|
|
94
|
+
// src/cli/index.ts → the package root (where examples/ and workflows/ live).
|
|
95
|
+
return resolve(dirname(INDEX_PATH), "..", "..");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function workflowCandidates(ref: string): string[] {
|
|
99
|
+
if (ref.includes("/") || ref.includes("\\") || ref === "." || ref === "..") return [resolve(ref)];
|
|
100
|
+
// Back-compat: a bare name that names a dir relative to cwd stays a path
|
|
101
|
+
// (the pre-resolution behavior). Otherwise it is a workflow reference:
|
|
102
|
+
// project workspace first, then workflows shipped with darkf.
|
|
103
|
+
return [
|
|
104
|
+
resolve(ref),
|
|
105
|
+
resolve(process.cwd(), "darkf", ref),
|
|
106
|
+
resolve(selfRoot(), "workflows", ref),
|
|
107
|
+
];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function resolveWorkflowDir(ref: string): string {
|
|
111
|
+
const candidates = workflowCandidates(ref);
|
|
112
|
+
for (const candidate of candidates) {
|
|
113
|
+
if (existsSync(join(candidate, "workflow.ts"))) return candidate;
|
|
114
|
+
}
|
|
115
|
+
const available = listWorkflows()
|
|
116
|
+
.map((w) => `${w.name} (${w.source})`)
|
|
117
|
+
.join(", ");
|
|
118
|
+
console.error(`no workflow for '${ref}' — tried:`);
|
|
119
|
+
for (const candidate of candidates) console.error(` ${candidate}`);
|
|
120
|
+
console.error(
|
|
121
|
+
`available: ${available || "(none)"} — or pass a path to a dir containing workflow.ts`,
|
|
122
|
+
);
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
interface WorkflowListing {
|
|
127
|
+
name: string;
|
|
128
|
+
source: "workspace" | "built-in";
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function listWorkflows(): WorkflowListing[] {
|
|
132
|
+
const roots: Array<[string, WorkflowListing["source"]]> = [
|
|
133
|
+
[resolve(process.cwd(), "darkf"), "workspace"],
|
|
134
|
+
[resolve(selfRoot(), "workflows"), "built-in"],
|
|
135
|
+
];
|
|
136
|
+
const out: WorkflowListing[] = [];
|
|
137
|
+
for (const [root, source] of roots) {
|
|
138
|
+
if (!existsSync(root)) continue;
|
|
139
|
+
for (const entry of readdirSync(root)) {
|
|
140
|
+
if (existsSync(join(root, entry, "workflow.ts"))) out.push({ name: entry, source });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function reportCmd(args: string[]): Promise<void> {
|
|
147
|
+
const { runId } = parseFlags(args);
|
|
148
|
+
const res = resolveRun(projectRoot(), runId);
|
|
149
|
+
// Report works on ANY resolvable run — finished runs (terminal/orphaned)
|
|
150
|
+
// are the primary subject, not an error.
|
|
151
|
+
const entry = "entry" in res && res.entry ? res.entry : undefined;
|
|
152
|
+
const journalPath = "journalPath" in res ? res.journalPath : undefined;
|
|
153
|
+
if (!entry || !journalPath) {
|
|
154
|
+
console.error(`no run for '${runId ?? "(latest)"}' (${res.kind})`);
|
|
155
|
+
process.exit(1);
|
|
156
|
+
}
|
|
157
|
+
const journalText = readJournalText(journalPath);
|
|
158
|
+
if (!journalText) {
|
|
159
|
+
console.error("journal is empty or missing");
|
|
160
|
+
process.exit(1);
|
|
161
|
+
}
|
|
162
|
+
const report = foldReport(journalText);
|
|
163
|
+
const seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s`;
|
|
164
|
+
console.log(`run: ${entry.runId}`);
|
|
165
|
+
console.log(`message: ${entry.message ?? "(none)"}`);
|
|
166
|
+
console.log(`span: ${seconds(report.spanMs)}, ${report.dispatches.length} dispatches`);
|
|
167
|
+
const visits = Object.entries(report.visits);
|
|
168
|
+
if (visits.length) console.log(`visits: ${JSON.stringify(Object.fromEntries(visits))}`);
|
|
169
|
+
|
|
170
|
+
console.log("\ndispatches:");
|
|
171
|
+
for (const d of report.dispatches) {
|
|
172
|
+
const outcome =
|
|
173
|
+
d.phase === "succeeded"
|
|
174
|
+
? `-> ${d.event ?? "(no event)"}`
|
|
175
|
+
: d.phase === "failed"
|
|
176
|
+
? `-> FAILED${d.event ? ` ${d.event}` : ""}`
|
|
177
|
+
: `-> CRASHED ${d.reason ? JSON.stringify(d.reason) : ""}`;
|
|
178
|
+
console.log(` ${d.state.padEnd(12)} ${seconds(d.durationMs).padStart(9)} ${outcome}`);
|
|
179
|
+
}
|
|
180
|
+
if (report.crashReasons.length) {
|
|
181
|
+
console.log(`crashes: ${report.crashReasons.length}`);
|
|
182
|
+
for (const r of new Set(report.crashReasons)) console.log(` ${r}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const usage = await readUsageSummary(entry.rootDir, entry.runId);
|
|
186
|
+
if (usage) console.log(usage);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function readUsageSummary(rootDir: string, runId: string): Promise<string | null> {
|
|
190
|
+
const dir = join(rootDir, ".darkf", "run", runId, "usage");
|
|
191
|
+
if (!existsSync(dir)) return null;
|
|
192
|
+
let cost = 0;
|
|
193
|
+
let hasCost = false;
|
|
194
|
+
let input = 0,
|
|
195
|
+
cacheRead = 0,
|
|
196
|
+
cacheCreation = 0,
|
|
197
|
+
output = 0,
|
|
198
|
+
count = 0;
|
|
199
|
+
for (const file of readdirSync(dir)) {
|
|
200
|
+
try {
|
|
201
|
+
const u = JSON.parse(readFileSync(join(dir, file), "utf8"));
|
|
202
|
+
count += 1;
|
|
203
|
+
if (typeof u.costUsd === "number") {
|
|
204
|
+
cost += u.costUsd;
|
|
205
|
+
hasCost = true;
|
|
206
|
+
}
|
|
207
|
+
input += u.inputTokens ?? 0;
|
|
208
|
+
cacheRead += u.cacheReadTokens ?? 0;
|
|
209
|
+
cacheCreation += u.cacheCreationTokens ?? 0;
|
|
210
|
+
output += u.outputTokens ?? 0;
|
|
211
|
+
} catch {
|
|
212
|
+
/* skip unreadable sidecars */
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (count === 0) return null;
|
|
216
|
+
const costPart = hasCost ? ` $${cost.toFixed(2)},` : "";
|
|
217
|
+
return `usage (${count} agent dispatches):${costPart} ${input + cacheRead + cacheCreation} in (${cacheRead} cache-read, ${cacheCreation} cache-write), ${output} out`;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function describeValidationError(err: WorkflowValidationError): string {
|
|
221
|
+
switch (err.kind) {
|
|
222
|
+
case "unresolved-target":
|
|
223
|
+
return `${err.from ?? "<top-level initial>"} -> "${err.target}": no such state`;
|
|
224
|
+
case "initial-cycle":
|
|
225
|
+
return `initial cycle: ${err.cycle.join(" -> ")} -> ${err.cycle[0]}`;
|
|
226
|
+
case "dead-end-leaf":
|
|
227
|
+
return `"${err.state}": dead end, no on/next`;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function doctorCmd(args: string[]): Promise<number> {
|
|
232
|
+
const ref = args[0];
|
|
233
|
+
let fail = false;
|
|
234
|
+
const check = (label: string, ok: boolean, detail?: string) => {
|
|
235
|
+
console.log(`${ok ? "ok " : "FAIL"} ${label}${detail ? ` — ${detail}` : ""}`);
|
|
236
|
+
if (!ok) fail = true;
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// 1. workflow resolution
|
|
240
|
+
if (ref === undefined) {
|
|
241
|
+
check("workflow ref", false, "usage: darkf doctor <workflow-ref-or-path>");
|
|
242
|
+
return Promise.resolve(1);
|
|
243
|
+
}
|
|
244
|
+
const candidates = workflowCandidates(ref);
|
|
245
|
+
let resolved: string | null = null;
|
|
246
|
+
for (const candidate of candidates) {
|
|
247
|
+
if (existsSync(join(candidate, "workflow.ts"))) {
|
|
248
|
+
resolved = candidate;
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
check("workflow resolves", resolved !== null, resolved ?? candidates.join(", "));
|
|
253
|
+
|
|
254
|
+
// 2. module loads + exports
|
|
255
|
+
if (resolved) {
|
|
256
|
+
try {
|
|
257
|
+
const mod = await loadWorkflow(resolved);
|
|
258
|
+
check("workflow.ts loads", true);
|
|
259
|
+
check(
|
|
260
|
+
"exports `workflow`",
|
|
261
|
+
typeof mod.workflow?.states === "object" && typeof mod.workflow?.initial === "string",
|
|
262
|
+
);
|
|
263
|
+
check(
|
|
264
|
+
"exports `agentRunner`",
|
|
265
|
+
typeof mod.agentRunner?.run === "function",
|
|
266
|
+
"agent states need a runner; built-ins live in src/agents/",
|
|
267
|
+
);
|
|
268
|
+
if (typeof mod.workflow?.states === "object" && typeof mod.workflow?.initial === "string") {
|
|
269
|
+
try {
|
|
270
|
+
const registry = buildRegistry(mod.workflow);
|
|
271
|
+
const errors = validateWorkflow(registry, mod.workflow.initial);
|
|
272
|
+
if (errors.length === 0) {
|
|
273
|
+
check("workflow structure", true);
|
|
274
|
+
} else {
|
|
275
|
+
for (const err of errors) {
|
|
276
|
+
check("workflow structure", false, describeValidationError(err));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
} catch (err) {
|
|
280
|
+
check("workflow structure", false, err instanceof Error ? err.message : String(err));
|
|
281
|
+
}
|
|
282
|
+
} else {
|
|
283
|
+
check("workflow structure", false, "skipped — invalid or missing `workflow` export");
|
|
284
|
+
}
|
|
285
|
+
} catch (err) {
|
|
286
|
+
check("workflow.ts loads", false, err instanceof Error ? err.message : String(err));
|
|
287
|
+
check("exports `workflow`", false, "skipped — module failed to load");
|
|
288
|
+
check("exports `agentRunner`", false, "skipped — module failed to load");
|
|
289
|
+
check("workflow structure", false, "skipped — module failed to load");
|
|
290
|
+
}
|
|
291
|
+
} else {
|
|
292
|
+
check("workflow.ts loads", false, "skipped — no resolved workflow");
|
|
293
|
+
check("exports `workflow`", false, "skipped — no resolved workflow");
|
|
294
|
+
check("exports `agentRunner`", false, "skipped — no resolved workflow");
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// 3. agent binaries
|
|
298
|
+
for (const bin of ["claude", "opencode"]) {
|
|
299
|
+
check(`agent binary '${bin}'`, Bun.which(bin) !== null);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// 4. cwd sanity — the run-1 mistake: targeting a repo while sitting in the darkf checkout
|
|
303
|
+
const cwd = process.cwd();
|
|
304
|
+
const insideSelf = cwd.startsWith(selfRoot());
|
|
305
|
+
check(
|
|
306
|
+
"cwd is not inside the darkf checkout",
|
|
307
|
+
!insideSelf,
|
|
308
|
+
insideSelf ? `${cwd} is inside ${selfRoot()} — agent cwd follows rootDir (= this cwd)` : cwd,
|
|
309
|
+
);
|
|
310
|
+
const gitRoot = projectRoot();
|
|
311
|
+
check("cwd is inside a git repo", existsSync(join(gitRoot, ".git")), gitRoot);
|
|
312
|
+
|
|
313
|
+
return Promise.resolve(fail ? 1 : 0);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function workflowsCmd(): void {
|
|
317
|
+
const workflows = listWorkflows();
|
|
318
|
+
if (workflows.length === 0) {
|
|
319
|
+
console.log(
|
|
320
|
+
"no workflows found — add <repo>/darkf/<name>/workflow.ts or darkf/workflows/<name>/workflow.ts",
|
|
321
|
+
);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
for (const w of workflows) console.log(`${w.name.padEnd(24)} ${w.source}`);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async function renderCmd(dir: string): Promise<void> {
|
|
328
|
+
const { workflow } = await loadWorkflow(dir);
|
|
329
|
+
console.log(renderMermaid(workflow));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// The one arg parser `run` and `start` share so the two can't drift: a `<dir>`
|
|
333
|
+
// and an optional `[message]`. A given `message` overrides the workflow
|
|
334
|
+
// module's own `input` export; omitted, the module's `input` (or `{}`) is used.
|
|
335
|
+
function parseRunArgs(args: string[]): {
|
|
336
|
+
dir: string;
|
|
337
|
+
message?: string;
|
|
338
|
+
allowDirtyWorkflow: boolean;
|
|
339
|
+
} {
|
|
340
|
+
const allowDirtyWorkflow = args.includes("--allow-dirty-workflow");
|
|
341
|
+
const positional = args.filter((a) => a !== "--allow-dirty-workflow");
|
|
342
|
+
return { dir: positional[0] ?? ".", message: positional[1], allowDirtyWorkflow };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Start-time config guard (registry-lifecycle, lesson-2 companion): a
|
|
346
|
+
// workflow config edit left uncommitted *will* be swept into a run commit or
|
|
347
|
+
// reset away by the run itself — a consumer repo lost config edits both ways.
|
|
348
|
+
// Scoped to the bare `darkf/` directory — the user/consumer-repo convention
|
|
349
|
+
// for versioned workflow config — never `.darkf` (dot-prefixed), which is
|
|
350
|
+
// darkf's own runtime/run-storage directory (registry, journals, this very
|
|
351
|
+
// `ready`/`worker.log` pair) and is expected to be gitignored entirely, not
|
|
352
|
+
// checked for "config drift."
|
|
353
|
+
// Fails OPEN (returns null) on anything that isn't a clean, unambiguous
|
|
354
|
+
// "yes, these files are dirty": not a git repo, git not installed, or no
|
|
355
|
+
// `darkf/` directory at all — never blocks a run over something this check
|
|
356
|
+
// can't actually verify.
|
|
357
|
+
function dirtyWorkflowConfigFiles(rootDir: string): string[] | null {
|
|
358
|
+
if (!existsSync(join(rootDir, "darkf"))) return null;
|
|
359
|
+
let out: { exitCode: number; stdout: Buffer };
|
|
360
|
+
try {
|
|
361
|
+
out = Bun.spawnSync(["git", "status", "--porcelain", "--", "darkf"], {
|
|
362
|
+
cwd: rootDir,
|
|
363
|
+
});
|
|
364
|
+
} catch {
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
if (out.exitCode !== 0) return null;
|
|
368
|
+
const text = new TextDecoder().decode(out.stdout).trim();
|
|
369
|
+
return text.length > 0 ? text.split("\n") : null;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function inputFor(
|
|
373
|
+
message: string | undefined,
|
|
374
|
+
moduleInput: NodeResult | undefined,
|
|
375
|
+
): NodeResult | undefined {
|
|
376
|
+
return message !== undefined ? { output: { message } } : moduleInput;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function runCmd(dir: string, message?: string): Promise<void> {
|
|
380
|
+
const { workflow, input, agentRunner, scriptRunner } = await loadWorkflow(dir);
|
|
381
|
+
|
|
382
|
+
// Pre-generated (rather than left to `run()`'s own default) and written to
|
|
383
|
+
// the registry *before* dispatch starts, mirroring `startCmd`'s own
|
|
384
|
+
// sequencing — this is the blocking-run path's equivalent of a detached
|
|
385
|
+
// run's worker entry, so a live run started via `darkf run` is just as
|
|
386
|
+
// discoverable (e.g. by a visualizer) as one started via `darkf start`,
|
|
387
|
+
// not only visible after the fact via the final `journal:` line below.
|
|
388
|
+
const runId = randomUUID();
|
|
389
|
+
const root = projectRoot();
|
|
390
|
+
const rootDir = process.cwd();
|
|
391
|
+
writeEntry(root, {
|
|
392
|
+
schemaVersion: SCHEMA_VERSION,
|
|
393
|
+
runId,
|
|
394
|
+
pid: process.pid,
|
|
395
|
+
rootDir,
|
|
396
|
+
workflowDir: dir,
|
|
397
|
+
startedAt: Date.now(),
|
|
398
|
+
message: message !== undefined ? truncateMessage(message) : undefined,
|
|
399
|
+
status: "running",
|
|
400
|
+
finishedAt: null,
|
|
401
|
+
agentRunnerKind: agentRunner?.kind,
|
|
402
|
+
...detectSupervisorSignal(),
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
const result = await run({
|
|
406
|
+
workflow,
|
|
407
|
+
input: inputFor(message, input),
|
|
408
|
+
agentRunner,
|
|
409
|
+
scriptRunner,
|
|
410
|
+
baseDir: resolve(dir, "scripts"),
|
|
411
|
+
// Run artifacts live under the invocation cwd (RunOptions' documented
|
|
412
|
+
// default), NOT the workflow dir — repo-targeting workflows are invoked
|
|
413
|
+
// from their target repo, and agent runners use rootDir as their cwd.
|
|
414
|
+
rootDir,
|
|
415
|
+
runId,
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
const finalStatus: RegistryStatus =
|
|
419
|
+
result.node.phase === "succeeded"
|
|
420
|
+
? "succeeded"
|
|
421
|
+
: result.node.phase === "failed"
|
|
422
|
+
? "failed"
|
|
423
|
+
: "crashed";
|
|
424
|
+
try {
|
|
425
|
+
const entry = readEntry(root, runId);
|
|
426
|
+
if (entry) writeEntry(root, { ...entry, status: finalStatus, finishedAt: Date.now() });
|
|
427
|
+
} catch {
|
|
428
|
+
// best-effort, same as workerCmd — the journal already records the outcome
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
for (const step of result.trace) {
|
|
432
|
+
const scope = step.scopePath.length ? `${step.scopePath.join(">")} > ` : "";
|
|
433
|
+
console.log(`${scope}${step.state} -> event=${step.result.event ?? "(none)"}`);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
console.log(`\nstatus: ${result.node.phase}`);
|
|
437
|
+
if (result.node.phase === "crashed") {
|
|
438
|
+
console.log(`reason: ${JSON.stringify(result.node.reason)} (attempt ${result.node.attempt})`);
|
|
439
|
+
}
|
|
440
|
+
if (result.node.phase === "succeeded" || result.node.phase === "failed") {
|
|
441
|
+
console.log("output:", result.node.result.output);
|
|
442
|
+
}
|
|
443
|
+
console.log(`journal: ${join(rootDir, ".darkf", "run", result.runId, "journal.jsonl")}`);
|
|
444
|
+
|
|
445
|
+
const lastState = result.trace.at(-1)?.state;
|
|
446
|
+
if (lastState) {
|
|
447
|
+
await mkdir(`${dir}/.darkf`, { recursive: true });
|
|
448
|
+
await writeFile(`${dir}/.darkf/last-run.mmd`, renderActive(workflow, lastState));
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function sleep(ms: number): Promise<void> {
|
|
453
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function truncateMessage(message: string): string {
|
|
457
|
+
return message.length > MESSAGE_MAX_LEN ? message.slice(0, MESSAGE_MAX_LEN) : message;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async function startCmd(
|
|
461
|
+
dir: string,
|
|
462
|
+
message?: string,
|
|
463
|
+
allowDirtyWorkflow = false,
|
|
464
|
+
): Promise<number> {
|
|
465
|
+
const rootDir = process.cwd();
|
|
466
|
+
const root = projectRoot();
|
|
467
|
+
|
|
468
|
+
if (!allowDirtyWorkflow) {
|
|
469
|
+
const dirty = dirtyWorkflowConfigFiles(rootDir);
|
|
470
|
+
if (dirty) {
|
|
471
|
+
console.error(
|
|
472
|
+
`darkf start: darkf/ has uncommitted changes — a run can sweep them into a ` +
|
|
473
|
+
`commit or reset them away:\n${dirty.map((f) => ` ${f}`).join("\n")}\n` +
|
|
474
|
+
`Commit or stash first, or pass --allow-dirty-workflow to proceed anyway.`,
|
|
475
|
+
);
|
|
476
|
+
return 1;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const runId = randomUUID();
|
|
481
|
+
const startedAt = Date.now();
|
|
482
|
+
const bootId = currentBootId();
|
|
483
|
+
|
|
484
|
+
await mkdir(runArtifactsDir(rootDir, runId), { recursive: true });
|
|
485
|
+
const workerLogFd = openSync(workerLogPath(rootDir, runId), "w");
|
|
486
|
+
|
|
487
|
+
const workerArgs = [INDEX_PATH, "__worker", dir, runId];
|
|
488
|
+
if (message !== undefined) workerArgs.push(message);
|
|
489
|
+
const child = Bun.spawn([process.execPath, ...workerArgs], {
|
|
490
|
+
detached: true,
|
|
491
|
+
// stdout stays discarded (never the failure signal this guards
|
|
492
|
+
// against); stderr goes to worker.log instead of `ignore` — see
|
|
493
|
+
// docs/specs/_built/registry-lifecycle/spec.md.
|
|
494
|
+
stdio: ["ignore", "ignore", workerLogFd],
|
|
495
|
+
});
|
|
496
|
+
closeSync(workerLogFd); // the child keeps its own fd; the parent's copy is done
|
|
497
|
+
child.unref();
|
|
498
|
+
const pid = child.pid;
|
|
499
|
+
|
|
500
|
+
// Wait for positive evidence the workflow module actually loaded (the
|
|
501
|
+
// `ready` file `workerCmd` writes), not just "the pid still exists at some
|
|
502
|
+
// arbitrary moment" — a live pid at +250ms proved nothing about whether the
|
|
503
|
+
// module import had even finished, let alone succeeded.
|
|
504
|
+
const deadline = Date.now() + READY_TIMEOUT_MS;
|
|
505
|
+
let ready = false;
|
|
506
|
+
for (;;) {
|
|
507
|
+
if (existsSync(readyPath(rootDir, runId))) {
|
|
508
|
+
ready = true;
|
|
509
|
+
break;
|
|
510
|
+
}
|
|
511
|
+
if (!isPidAlive(pid)) break; // died before ever signaling ready
|
|
512
|
+
if (Date.now() >= deadline) break; // timed out — still alive, see below
|
|
513
|
+
await sleep(READY_POLL_MS);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
if (!ready && !isPidAlive(pid)) {
|
|
517
|
+
// Confirmed dead before ever loading the workflow module — the one
|
|
518
|
+
// case `failed-start` exists for. No fake "running" identity printed.
|
|
519
|
+
const tail = readFileSync(workerLogPath(rootDir, runId), "utf8")
|
|
520
|
+
.trim()
|
|
521
|
+
.slice(-WORKER_LOG_TAIL_CHARS);
|
|
522
|
+
console.error(
|
|
523
|
+
`darkf start: worker (pid ${pid}) exited during startup, before loading the workflow:\n${tail}`,
|
|
524
|
+
);
|
|
525
|
+
writeEntry(root, {
|
|
526
|
+
schemaVersion: SCHEMA_VERSION,
|
|
527
|
+
runId,
|
|
528
|
+
pid,
|
|
529
|
+
rootDir,
|
|
530
|
+
workflowDir: dir,
|
|
531
|
+
startedAt,
|
|
532
|
+
message: message !== undefined ? truncateMessage(message) : undefined,
|
|
533
|
+
status: "failed-start",
|
|
534
|
+
finishedAt: Date.now(),
|
|
535
|
+
startFailureDetail: tail,
|
|
536
|
+
bootId,
|
|
537
|
+
...detectSupervisorSignal(),
|
|
538
|
+
});
|
|
539
|
+
return 1;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (!ready) {
|
|
543
|
+
// Timed out but still alive: a slow module import, not a failure. Proceed
|
|
544
|
+
// optimistically — the alternative (killing a live, legitimately-working
|
|
545
|
+
// process) is worse than occasionally missing a slow-but-real success
|
|
546
|
+
// within this window. See spec's open question on the timeout value.
|
|
547
|
+
console.error(
|
|
548
|
+
`darkf start: worker (pid ${pid}) had not signaled ready after ${READY_TIMEOUT_MS}ms but is still alive; proceeding`,
|
|
549
|
+
);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// `agentRunnerKind` isn't known here — this process never loads the
|
|
553
|
+
// workflow module, only spawns the worker that does — so `workerCmd`
|
|
554
|
+
// merges it in once it has (see there).
|
|
555
|
+
writeEntry(root, {
|
|
556
|
+
schemaVersion: SCHEMA_VERSION,
|
|
557
|
+
runId,
|
|
558
|
+
pid,
|
|
559
|
+
rootDir,
|
|
560
|
+
workflowDir: dir,
|
|
561
|
+
startedAt,
|
|
562
|
+
message: message !== undefined ? truncateMessage(message) : undefined,
|
|
563
|
+
status: "running",
|
|
564
|
+
finishedAt: null,
|
|
565
|
+
bootId,
|
|
566
|
+
...detectSupervisorSignal(),
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
console.log(JSON.stringify({ runId, pid }));
|
|
570
|
+
return 0;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// The detached worker: the process that actually calls run(), then best-effort
|
|
574
|
+
// updates the registry. Its own exit code is not the point — the journal is the
|
|
575
|
+
// one durable record — so a registry-update failure is swallowed, not fatal.
|
|
576
|
+
async function workerCmd(dir: string, runId: string, message?: string): Promise<void> {
|
|
577
|
+
const rootDir = process.cwd();
|
|
578
|
+
const { workflow, input, agentRunner, scriptRunner } = await loadWorkflow(dir);
|
|
579
|
+
|
|
580
|
+
// The one piece of positive evidence `startCmd`'s readiness wait is
|
|
581
|
+
// watching for — written only once the workflow module has actually
|
|
582
|
+
// loaded (if `loadWorkflow` above throws, this line never runs, and
|
|
583
|
+
// `startCmd` reports `failed-start` instead of a fake `running`).
|
|
584
|
+
await mkdir(runArtifactsDir(rootDir, runId), { recursive: true });
|
|
585
|
+
await writeFile(readyPath(rootDir, runId), "");
|
|
586
|
+
|
|
587
|
+
// `startCmd` wrote the entry before this worker loaded the workflow module,
|
|
588
|
+
// so it couldn't know the runner's `kind` yet — merge it in now, best-effort
|
|
589
|
+
// like every other registry update here (the journal stays authoritative).
|
|
590
|
+
if (agentRunner?.kind !== undefined) {
|
|
591
|
+
try {
|
|
592
|
+
const entry = readEntry(projectRoot(), runId);
|
|
593
|
+
if (entry) writeEntry(projectRoot(), { ...entry, agentRunnerKind: agentRunner.kind });
|
|
594
|
+
} catch {
|
|
595
|
+
// best-effort, same as the final status update below
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const result = await run({
|
|
600
|
+
workflow,
|
|
601
|
+
input: inputFor(message, input),
|
|
602
|
+
agentRunner,
|
|
603
|
+
scriptRunner,
|
|
604
|
+
baseDir: resolve(dir, "scripts"),
|
|
605
|
+
rootDir,
|
|
606
|
+
runId,
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
const status: RegistryStatus =
|
|
610
|
+
result.node.phase === "succeeded"
|
|
611
|
+
? "succeeded"
|
|
612
|
+
: result.node.phase === "failed"
|
|
613
|
+
? "failed"
|
|
614
|
+
: "crashed";
|
|
615
|
+
try {
|
|
616
|
+
const entry = readEntry(projectRoot(), runId);
|
|
617
|
+
if (entry) writeEntry(projectRoot(), { ...entry, status, finishedAt: Date.now() });
|
|
618
|
+
} catch {
|
|
619
|
+
// best-effort: the journal already records the outcome; never fatal here
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function parseFlags(args: string[]): { runId?: string; window?: number; once?: boolean } {
|
|
624
|
+
let runId: string | undefined;
|
|
625
|
+
let window: number | undefined;
|
|
626
|
+
let once = false;
|
|
627
|
+
for (let i = 0; i < args.length; i++) {
|
|
628
|
+
const arg = args[i]!;
|
|
629
|
+
if (arg === "--run") runId = args[++i];
|
|
630
|
+
else if (arg === "--window") window = Number(args[++i]);
|
|
631
|
+
else if (arg === "--once") once = true;
|
|
632
|
+
}
|
|
633
|
+
return { runId, window, once };
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function statusExit(state: TerminalState): number {
|
|
637
|
+
switch (state) {
|
|
638
|
+
case "succeeded":
|
|
639
|
+
return 0;
|
|
640
|
+
case "crashed":
|
|
641
|
+
return 1;
|
|
642
|
+
case "orphaned":
|
|
643
|
+
return 2;
|
|
644
|
+
case "running":
|
|
645
|
+
return 3;
|
|
646
|
+
case "failed":
|
|
647
|
+
return 4;
|
|
648
|
+
case "host-died":
|
|
649
|
+
return 5;
|
|
650
|
+
case "failed-start":
|
|
651
|
+
return 6;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
function formatMs(ms: number): string {
|
|
656
|
+
if (ms < 1000) return `${ms}ms`;
|
|
657
|
+
const s = ms / 1000;
|
|
658
|
+
if (s < 60) return `${s.toFixed(1)}s`;
|
|
659
|
+
const m = Math.floor(s / 60);
|
|
660
|
+
return `${m}m ${Math.round(s % 60)}s`;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function printDigest(entry: RegistryEntry, state: TerminalState, journalText: string): void {
|
|
664
|
+
const digest = foldJournal(journalText);
|
|
665
|
+
console.log(`run: ${entry.runId}`);
|
|
666
|
+
console.log(`root: ${entry.rootDir}`);
|
|
667
|
+
if (entry.message) console.log(`message: ${entry.message}`);
|
|
668
|
+
console.log(`state: ${state}`);
|
|
669
|
+
if (digest.current) {
|
|
670
|
+
console.log(`current node: ${digest.current.state} (${digest.current.phase})`);
|
|
671
|
+
}
|
|
672
|
+
if (digest.crash) {
|
|
673
|
+
console.log(
|
|
674
|
+
`crash: attempt=${digest.crash.attempt} reason=${JSON.stringify(digest.crash.reason)}`,
|
|
675
|
+
);
|
|
676
|
+
}
|
|
677
|
+
if (Object.keys(digest.visits).length > 0) {
|
|
678
|
+
console.log(`visits: ${JSON.stringify(digest.visits)}`);
|
|
679
|
+
const [node, count] = Object.entries(digest.visits).sort((a, b) => b[1] - a[1])[0] ?? [];
|
|
680
|
+
if (count !== undefined && count >= 4) {
|
|
681
|
+
console.log(
|
|
682
|
+
`warn: ${node} visited ${count}x — possible review/thrash cycling (check the journal, or wrap the loop in a composite with maxCycles)`,
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (digest.current?.phase === "running" && digest.current.startedAt !== undefined) {
|
|
687
|
+
// Live elapsed, computed at print time — journal-frozen runtime goes stale
|
|
688
|
+
// during long nodes (spec: docs/specs/live-runtime).
|
|
689
|
+
console.log(
|
|
690
|
+
`elapsed: ${formatMs(Date.now() - digest.current.startedAt)} (node ${digest.current.state})`,
|
|
691
|
+
);
|
|
692
|
+
const stall = stallWarning(digest);
|
|
693
|
+
if (stall) console.log(`warn: ${stall}`);
|
|
694
|
+
const agentStall = agentStallWarning(digest);
|
|
695
|
+
if (agentStall) console.log(`warn: ${agentStall}`);
|
|
696
|
+
const nudge = nudgeWarning(digest);
|
|
697
|
+
if (nudge) console.log(`warn: ${nudge}`);
|
|
698
|
+
}
|
|
699
|
+
if (digest.runtimeMs !== null) console.log(`runtime: ${formatMs(digest.runtimeMs)}`);
|
|
700
|
+
if (state === "orphaned") console.log("orphaned: true");
|
|
701
|
+
if (state === "host-died") {
|
|
702
|
+
const lastTs = parseEventLog(journalText).at(-1)?.timestamp;
|
|
703
|
+
const since =
|
|
704
|
+
lastTs !== undefined ? ` (last journal event ${new Date(lastTs).toISOString()})` : "";
|
|
705
|
+
console.log(`host-died: true${since}`);
|
|
706
|
+
}
|
|
707
|
+
if (state === "failed-start") {
|
|
708
|
+
console.log("failed-start: true");
|
|
709
|
+
if (entry.startFailureDetail) console.log(`worker log tail:\n${entry.startFailureDetail}`);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
async function statusCmd(args: string[]): Promise<number> {
|
|
714
|
+
const { runId } = parseFlags(args);
|
|
715
|
+
const res = resolveRun(projectRoot(), runId);
|
|
716
|
+
|
|
717
|
+
switch (res.kind) {
|
|
718
|
+
case "none":
|
|
719
|
+
console.log(
|
|
720
|
+
res.recentFinished
|
|
721
|
+
? `nothing to monitor (most recent finished run: ${res.recentFinished.runId})`
|
|
722
|
+
: "nothing to monitor",
|
|
723
|
+
);
|
|
724
|
+
return 7;
|
|
725
|
+
case "noSuchRun":
|
|
726
|
+
console.error(`no such run: ${runId}`);
|
|
727
|
+
return 4;
|
|
728
|
+
case "ambiguous": {
|
|
729
|
+
console.error(`ambiguous: multiple runs are cached "running"; use --run <runId>`);
|
|
730
|
+
for (const e of res.entries) console.error(` ${e.runId} ${e.rootDir}`);
|
|
731
|
+
return 5;
|
|
732
|
+
}
|
|
733
|
+
default: {
|
|
734
|
+
const journalText = readJournalText(res.journalPath);
|
|
735
|
+
const state = classifyTerminal(journalText, isPidAlive(res.entry.pid), {
|
|
736
|
+
cachedStatus: res.entry.status,
|
|
737
|
+
hostDied: hostDiedSince(res.entry),
|
|
738
|
+
});
|
|
739
|
+
printDigest(res.entry, state, journalText);
|
|
740
|
+
return statusExit(state);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
function printTransition(e: NodeEvent, prevTs: number | null, isHeartbeat = false): void {
|
|
746
|
+
const dwell = prevTs !== null ? ` (dwell ${e.timestamp - prevTs}ms)` : "";
|
|
747
|
+
const status = e.status;
|
|
748
|
+
if (isHeartbeat) {
|
|
749
|
+
// A heartbeat is a liveness pulse on an open dispatch, not a transition —
|
|
750
|
+
// one compact line, or it drowns the monitor every 30s.
|
|
751
|
+
const startedAt = status.phase === "running" ? status.startedAt : undefined;
|
|
752
|
+
const idle = startedAt !== undefined ? e.timestamp - startedAt : 0;
|
|
753
|
+
let line = `${e.state} still running — ${(idle / 1000).toFixed(0)}s elapsed`;
|
|
754
|
+
// Agent-level liveness, distinct from the engine-heartbeat idle above —
|
|
755
|
+
// see docs/specs/agent-liveness/spec.md. Absent for script dispatches or
|
|
756
|
+
// runners that don't report progress.
|
|
757
|
+
if (status.phase === "running" && status.agentIdleMs !== undefined) {
|
|
758
|
+
const agentIdleSec = Math.round(status.agentIdleMs / 1000);
|
|
759
|
+
line += `, agent step ${status.agentStepCount ?? 0}, idle ${agentIdleSec}s`;
|
|
760
|
+
if (status.agentIdleMs > AGENT_STALL_MS) line += " — warn: agent stall suspected";
|
|
761
|
+
}
|
|
762
|
+
console.log(line);
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
let line = `${e.state} ${status.phase}`;
|
|
766
|
+
if (status.phase === "running") line += ` attempt=${status.attempt}`;
|
|
767
|
+
else if (status.phase === "succeeded" && status.result?.event)
|
|
768
|
+
line += ` event=${status.result.event}`;
|
|
769
|
+
console.log(`${line}${dwell}`);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/** A `running` event whose dispatch is already open is a heartbeat, not a
|
|
773
|
+
* transition: same state+attempt seen running in the previous event window. */
|
|
774
|
+
function isHeartbeatEvent(events: NodeEvent[], index: number): boolean {
|
|
775
|
+
const e = events[index]!;
|
|
776
|
+
if (e.state === DONE || e.status.phase !== "running") return false;
|
|
777
|
+
for (let i = index - 1; i >= 0; i--) {
|
|
778
|
+
const prev = events[i]!;
|
|
779
|
+
if (
|
|
780
|
+
prev.state === e.state &&
|
|
781
|
+
(prev.scopePath ?? []).join(">") === (e.scopePath ?? []).join(">")
|
|
782
|
+
) {
|
|
783
|
+
return prev.status.phase === "running" && prev.status.attempt === e.status.attempt;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
return false;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// Dwell hint (P2): flag an open dispatch whose elapsed time exceeds 3× the
|
|
790
|
+
// median of that node's completed visits (floor 2 min) — the supervisor's
|
|
791
|
+
// cue to inspect or `steer`, printed once per visit. An unattended run: a
|
|
792
|
+
// GREEN agent thrashed for 35 minutes before anyone looked; a hint at
|
|
793
|
+
// minute 10 would have surfaced it. Purely advisory — never exits.
|
|
794
|
+
function dwellHint(events: NodeEvent[], runId: string, hinted: Set<string>): void {
|
|
795
|
+
const durations: Record<string, number[]> = {};
|
|
796
|
+
let open: { state: string; startedAt: number } | null = null;
|
|
797
|
+
for (const e of events) {
|
|
798
|
+
if (e.state === DONE) continue;
|
|
799
|
+
const phase = e.status.phase;
|
|
800
|
+
if (phase === "running") {
|
|
801
|
+
if (open === null || open.state !== e.state) {
|
|
802
|
+
open = { state: e.state, startedAt: e.status.startedAt ?? e.timestamp };
|
|
803
|
+
}
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
if ((phase === "succeeded" || phase === "crashed") && open && open.state === e.state) {
|
|
807
|
+
durations[e.state] ??= [];
|
|
808
|
+
durations[e.state]!.push(Math.max(0, e.timestamp - open.startedAt));
|
|
809
|
+
open = null;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
if (!open) return;
|
|
813
|
+
const ds = durations[open.state] ?? [];
|
|
814
|
+
if (ds.length === 0) return;
|
|
815
|
+
const sorted = [...ds].sort((a, b) => a - b);
|
|
816
|
+
const median = sorted[Math.floor(sorted.length / 2)]!;
|
|
817
|
+
const dwell = Date.now() - open.startedAt;
|
|
818
|
+
const threshold = Math.max(median * 3, 120_000);
|
|
819
|
+
const key = `${open.state}:${open.startedAt}`;
|
|
820
|
+
if (dwell > threshold && !hinted.has(key)) {
|
|
821
|
+
hinted.add(key);
|
|
822
|
+
const mins = (ms: number) => Math.round(ms / 60_000);
|
|
823
|
+
console.log(
|
|
824
|
+
`hint: ${open.state} running ${mins(dwell)}m (median ${mins(median)}m) — inspect with darkf recent/status, or nudge: darkf steer ${runId} "<message>"`,
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
async function monitorRun(entry: RegistryEntry, windowSec: number, once: boolean): Promise<number> {
|
|
830
|
+
const journalPath = journalPathFor(entry);
|
|
831
|
+
const pid = entry.pid;
|
|
832
|
+
const deadline = Date.now() + windowSec * 1000;
|
|
833
|
+
const hinted = new Set<string>();
|
|
834
|
+
|
|
835
|
+
// Open the window: if the begin marker is already there, print it once as
|
|
836
|
+
// context (not a transition) and tail only lines added from this point on.
|
|
837
|
+
let text = readJournalText(journalPath);
|
|
838
|
+
let events = parseEventLog(text);
|
|
839
|
+
const begin = events[0];
|
|
840
|
+
if (begin && begin.state === DONE && begin.status.phase === "succeeded") {
|
|
841
|
+
console.log(`started with: ${JSON.stringify(begin.status.result)}`);
|
|
842
|
+
}
|
|
843
|
+
let lastSeen = events.length;
|
|
844
|
+
let lastTs = events.at(-1)?.timestamp ?? null;
|
|
845
|
+
|
|
846
|
+
for (;;) {
|
|
847
|
+
text = readJournalText(journalPath);
|
|
848
|
+
events = parseEventLog(text);
|
|
849
|
+
for (let i = lastSeen; i < events.length; i++) {
|
|
850
|
+
const e = events[i]!;
|
|
851
|
+
printTransition(e, lastTs, isHeartbeatEvent(events, i));
|
|
852
|
+
lastTs = e.timestamp;
|
|
853
|
+
}
|
|
854
|
+
lastSeen = events.length;
|
|
855
|
+
dwellHint(events, entry.runId, hinted);
|
|
856
|
+
|
|
857
|
+
// Re-check liveness every sub-poll: the journal's last line is authoritative
|
|
858
|
+
// for succeeded/crashed, and a dead PID with no terminal marker is
|
|
859
|
+
// orphaned/host-died.
|
|
860
|
+
const state = classifyTerminal(text, isPidAlive(pid), {
|
|
861
|
+
cachedStatus: entry.status,
|
|
862
|
+
hostDied: hostDiedSince(entry),
|
|
863
|
+
});
|
|
864
|
+
if (state === "succeeded") {
|
|
865
|
+
console.log("succeeded");
|
|
866
|
+
return 0;
|
|
867
|
+
}
|
|
868
|
+
if (state === "failed") {
|
|
869
|
+
const digest = foldJournal(text);
|
|
870
|
+
console.log(
|
|
871
|
+
`failed: ${digest.finalResult ? JSON.stringify(digest.finalResult) : "(no result)"}`,
|
|
872
|
+
);
|
|
873
|
+
return 3;
|
|
874
|
+
}
|
|
875
|
+
if (state === "crashed") {
|
|
876
|
+
const digest = foldJournal(text);
|
|
877
|
+
console.log(`crashed: ${digest.crash ? JSON.stringify(digest.crash.reason) : "(no reason)"}`);
|
|
878
|
+
return 1;
|
|
879
|
+
}
|
|
880
|
+
if (state === "host-died") {
|
|
881
|
+
const lastTs = parseEventLog(text).at(-1)?.timestamp;
|
|
882
|
+
const since =
|
|
883
|
+
lastTs !== undefined ? ` (last journal event ${new Date(lastTs).toISOString()})` : "";
|
|
884
|
+
console.log(`host-died: true${since}`);
|
|
885
|
+
return 4;
|
|
886
|
+
}
|
|
887
|
+
if (state === "failed-start") {
|
|
888
|
+
console.log("failed-start: true");
|
|
889
|
+
if (entry.startFailureDetail) console.log(`worker log tail:\n${entry.startFailureDetail}`);
|
|
890
|
+
return 5;
|
|
891
|
+
}
|
|
892
|
+
if (state === "orphaned") {
|
|
893
|
+
console.log("orphaned: worker PID is gone and the journal has no terminal marker");
|
|
894
|
+
return 2;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
if (Date.now() >= deadline) {
|
|
898
|
+
console.log(`window of ${windowSec}s elapsed, still running`);
|
|
899
|
+
return 6;
|
|
900
|
+
}
|
|
901
|
+
if (once) {
|
|
902
|
+
console.log("still running");
|
|
903
|
+
return 6;
|
|
904
|
+
}
|
|
905
|
+
await sleep(MONITOR_SUB_POLL_MS);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async function monitorCmd(args: string[]): Promise<number> {
|
|
910
|
+
const { runId, window, once } = parseFlags(args);
|
|
911
|
+
const windowSec = window ?? DEFAULT_MONITOR_WINDOW_S;
|
|
912
|
+
const res = resolveRun(projectRoot(), runId);
|
|
913
|
+
|
|
914
|
+
switch (res.kind) {
|
|
915
|
+
case "none":
|
|
916
|
+
console.log("nothing to monitor");
|
|
917
|
+
return 7;
|
|
918
|
+
case "noSuchRun":
|
|
919
|
+
console.error(`no such run: ${runId}`);
|
|
920
|
+
return 4;
|
|
921
|
+
case "ambiguous": {
|
|
922
|
+
console.error(`ambiguous: multiple runs are cached "running"; use --run <runId>`);
|
|
923
|
+
for (const e of res.entries) console.error(` ${e.runId} ${e.rootDir}`);
|
|
924
|
+
return 5;
|
|
925
|
+
}
|
|
926
|
+
case "terminal": {
|
|
927
|
+
const digest = foldJournal(readJournalText(res.journalPath));
|
|
928
|
+
if (res.outcome === "succeeded") {
|
|
929
|
+
console.log("succeeded");
|
|
930
|
+
return 0;
|
|
931
|
+
}
|
|
932
|
+
if (res.outcome === "failed") {
|
|
933
|
+
console.log(
|
|
934
|
+
`failed: ${digest.finalResult ? JSON.stringify(digest.finalResult) : "(no result)"}`,
|
|
935
|
+
);
|
|
936
|
+
return 3;
|
|
937
|
+
}
|
|
938
|
+
console.log(`crashed: ${digest.crash ? JSON.stringify(digest.crash.reason) : "(no reason)"}`);
|
|
939
|
+
return 1;
|
|
940
|
+
}
|
|
941
|
+
case "orphaned": {
|
|
942
|
+
const journalText = readJournalText(res.journalPath);
|
|
943
|
+
const state = classifyTerminal(journalText, false, {
|
|
944
|
+
cachedStatus: res.entry.status,
|
|
945
|
+
hostDied: hostDiedSince(res.entry),
|
|
946
|
+
});
|
|
947
|
+
if (state === "host-died") {
|
|
948
|
+
const lastTs = parseEventLog(journalText).at(-1)?.timestamp;
|
|
949
|
+
const since =
|
|
950
|
+
lastTs !== undefined ? ` (last journal event ${new Date(lastTs).toISOString()})` : "";
|
|
951
|
+
console.log(`host-died: true${since}`);
|
|
952
|
+
return 4;
|
|
953
|
+
}
|
|
954
|
+
if (state === "failed-start") {
|
|
955
|
+
console.log("failed-start: true");
|
|
956
|
+
if (res.entry.startFailureDetail) {
|
|
957
|
+
console.log(`worker log tail:\n${res.entry.startFailureDetail}`);
|
|
958
|
+
}
|
|
959
|
+
return 5;
|
|
960
|
+
}
|
|
961
|
+
console.log("orphaned: worker PID is gone and the journal has no terminal marker");
|
|
962
|
+
return 2;
|
|
963
|
+
}
|
|
964
|
+
case "resolved":
|
|
965
|
+
return await monitorRun(res.entry, windowSec, once ?? false);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
// Per-install state location for the self-update feature (self-update D-2):
|
|
970
|
+
// XDG state semantics, not `.darkf/` (NG-5 — nothing per-project). The first
|
|
971
|
+
// candidate whose defining environment variable exists wins; tests point
|
|
972
|
+
// elsewhere by injecting `stateFile` through UpdateDeps.
|
|
973
|
+
function updateStateFile(): string {
|
|
974
|
+
const xdg = process.env.XDG_STATE_HOME;
|
|
975
|
+
if (xdg) return join(xdg, "darkf", "last-update-check.json");
|
|
976
|
+
return join(process.env.HOME ?? "", ".local", "state", "darkf", "last-update-check.json");
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
async function main(): Promise<void> {
|
|
980
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
981
|
+
|
|
982
|
+
// Self-update gate (REQ-1..REQ-5, REQ-11): runs before every dispatch, so
|
|
983
|
+
// its notice is the first line of stdout (NFR-3). The gate itself skips
|
|
984
|
+
// `upgrade`, which fetches on its own. Silent by contract (REQ-4).
|
|
985
|
+
const updateDeps: UpdateDeps = {
|
|
986
|
+
now: () => Date.now(),
|
|
987
|
+
fetchImpl: fetch,
|
|
988
|
+
spawnImpl: Bun.spawnSync,
|
|
989
|
+
stateFile: updateStateFile(),
|
|
990
|
+
installed: packageJson.version,
|
|
991
|
+
};
|
|
992
|
+
await updateGate(cmd, updateDeps);
|
|
993
|
+
|
|
994
|
+
if (cmd === "upgrade") {
|
|
995
|
+
process.exit(await upgradeCmd(updateDeps));
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
if (cmd === "workflows") {
|
|
999
|
+
workflowsCmd();
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
if (cmd === "report") {
|
|
1003
|
+
await reportCmd(rest);
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
if (cmd === "doctor") {
|
|
1007
|
+
process.exit(await doctorCmd(rest));
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
if (cmd === "render") {
|
|
1011
|
+
await renderCmd(resolveWorkflowDir(rest[0] ?? "."));
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
if (cmd === "run") {
|
|
1015
|
+
const { dir, message } = parseRunArgs(rest);
|
|
1016
|
+
await runCmd(resolveWorkflowDir(dir), message);
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
1019
|
+
if (cmd === "start") {
|
|
1020
|
+
const { dir, message, allowDirtyWorkflow } = parseRunArgs(rest);
|
|
1021
|
+
process.exit(await startCmd(resolveWorkflowDir(dir), message, allowDirtyWorkflow));
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
if (cmd === "status") {
|
|
1025
|
+
process.exit(await statusCmd(rest));
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
if (cmd === "monitor") {
|
|
1029
|
+
process.exit(await monitorCmd(rest));
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
if (cmd === "__worker") {
|
|
1033
|
+
await workerCmd(rest[0] ?? ".", rest[1] ?? "", rest[2]);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
// back-compat: `darkf <dir>` defaults to run
|
|
1037
|
+
await runCmd(resolveWorkflowDir(cmd ?? "."), undefined);
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
main();
|