@loka1/pi-orchestra 0.0.0-stage → 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/CHANGELOG.md +313 -0
- package/LICENSE +21 -0
- package/README.md +662 -2
- package/assets/preview.html +226 -0
- package/assets/preview.png +0 -0
- package/config/orchestra.json.example +35 -0
- package/config/templates/review-squad.md +11 -0
- package/extensions/lib/agents.ts +110 -0
- package/extensions/lib/chat.ts +171 -0
- package/extensions/lib/commands.ts +118 -0
- package/extensions/lib/config.ts +236 -0
- package/extensions/lib/format.ts +663 -0
- package/extensions/lib/git.ts +99 -0
- package/extensions/lib/log.ts +233 -0
- package/extensions/lib/mail.ts +115 -0
- package/extensions/lib/metrics.ts +365 -0
- package/extensions/lib/providers.ts +355 -0
- package/extensions/lib/redact.ts +57 -0
- package/extensions/lib/retry.ts +61 -0
- package/extensions/lib/state.ts +694 -0
- package/extensions/lib/templates.ts +153 -0
- package/extensions/lib/types.ts +171 -0
- package/extensions/lib/worker.ts +450 -0
- package/extensions/orchestra.ts +3043 -0
- package/extensions/ui/browse.ts +497 -0
- package/extensions/ui/join.ts +289 -0
- package/package.json +56 -4
- package/skills/orchestra/SKILL.md +86 -0
|
@@ -0,0 +1,694 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable orchestration state.
|
|
3
|
+
*
|
|
4
|
+
* One JSON document per project under `.pi/orchestra/state.json`, written
|
|
5
|
+
* atomically (tmp + rename). The coordinator session is the only writer; worker
|
|
6
|
+
* processes never touch this file, they only exchange mail (see `mail.ts`).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
existsSync,
|
|
11
|
+
mkdirSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
readdirSync,
|
|
14
|
+
renameSync,
|
|
15
|
+
rmSync,
|
|
16
|
+
statSync,
|
|
17
|
+
writeFileSync,
|
|
18
|
+
} from "node:fs";
|
|
19
|
+
import { join } from "node:path";
|
|
20
|
+
import { randomUUID } from "node:crypto";
|
|
21
|
+
import {
|
|
22
|
+
type Dispatch,
|
|
23
|
+
type DispatchStatus,
|
|
24
|
+
type OrchestraState,
|
|
25
|
+
type Run,
|
|
26
|
+
type Task,
|
|
27
|
+
emptyState,
|
|
28
|
+
emptyUsage,
|
|
29
|
+
} from "./types.ts";
|
|
30
|
+
|
|
31
|
+
export interface StorePaths {
|
|
32
|
+
root: string;
|
|
33
|
+
stateFile: string;
|
|
34
|
+
logsDir: string;
|
|
35
|
+
mailDir: string;
|
|
36
|
+
promptsDir: string;
|
|
37
|
+
archiveDir: string;
|
|
38
|
+
exportsDir: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function storePaths(root: string): StorePaths {
|
|
42
|
+
return {
|
|
43
|
+
root,
|
|
44
|
+
stateFile: join(root, "state.json"),
|
|
45
|
+
logsDir: join(root, "logs"),
|
|
46
|
+
mailDir: join(root, "mail"),
|
|
47
|
+
promptsDir: join(root, "prompts"),
|
|
48
|
+
archiveDir: join(root, "archive"),
|
|
49
|
+
exportsDir: join(root, "exports"),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function ensureStore(root: string): StorePaths {
|
|
54
|
+
const paths = storePaths(root);
|
|
55
|
+
mkdirSync(paths.root, { recursive: true });
|
|
56
|
+
mkdirSync(paths.logsDir, { recursive: true });
|
|
57
|
+
mkdirSync(paths.mailDir, { recursive: true });
|
|
58
|
+
const ignore = join(paths.root, ".gitignore");
|
|
59
|
+
if (!existsSync(ignore)) {
|
|
60
|
+
// Keep run artifacts out of the user's git index without asking them to edit .gitignore.
|
|
61
|
+
writeFileSync(ignore, "*\n", "utf8");
|
|
62
|
+
}
|
|
63
|
+
return paths;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function loadState(root: string): OrchestraState {
|
|
67
|
+
const { stateFile } = storePaths(root);
|
|
68
|
+
if (!existsSync(stateFile)) return emptyState();
|
|
69
|
+
try {
|
|
70
|
+
const parsed = JSON.parse(readFileSync(stateFile, "utf8")) as OrchestraState;
|
|
71
|
+
if (!parsed || parsed.version !== 1) return emptyState();
|
|
72
|
+
parsed.runs ??= {};
|
|
73
|
+
parsed.tasks ??= {};
|
|
74
|
+
parsed.dispatches ??= {};
|
|
75
|
+
parsed.gates ??= {};
|
|
76
|
+
parsed.seq ??= 0;
|
|
77
|
+
parsed.ui ??= {};
|
|
78
|
+
return parsed;
|
|
79
|
+
} catch {
|
|
80
|
+
return emptyState();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function saveState(root: string, state: OrchestraState): void {
|
|
85
|
+
const { stateFile } = storePaths(root);
|
|
86
|
+
mkdirSync(root, { recursive: true });
|
|
87
|
+
const tmp = `${stateFile}.${process.pid}.tmp`;
|
|
88
|
+
writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
89
|
+
renameSync(tmp, stateFile);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function newId(prefix: string): string {
|
|
93
|
+
return `${prefix}_${randomUUID().replace(/-/g, "").slice(0, 10)}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function nowIso(): string {
|
|
97
|
+
return new Date().toISOString();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface ActiveRunOptions {
|
|
101
|
+
/**
|
|
102
|
+
* Hide a run whose work is finished once nothing in it has moved for this long
|
|
103
|
+
* (0 = never; every finished run stays current). See `staleRunHours`.
|
|
104
|
+
*/
|
|
105
|
+
staleAfterMs?: number;
|
|
106
|
+
/** Clock override for tests. */
|
|
107
|
+
now?: number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The newest timestamp anything in `run` *did* (creation alone does not count). */
|
|
111
|
+
export function runLastActivity(state: OrchestraState, run: Run): number {
|
|
112
|
+
const stamps: Array<string | undefined> = [run.updatedAt];
|
|
113
|
+
for (const dispatch of listDispatches(state, run.id)) {
|
|
114
|
+
// A finished dispatch last did something when it ended; only a live one moves.
|
|
115
|
+
const ended = dispatch.endedAt ?? dispatch.settledAt;
|
|
116
|
+
if (ended) stamps.push(ended);
|
|
117
|
+
else stamps.push(dispatch.startedAt, dispatch.lastEventAt);
|
|
118
|
+
}
|
|
119
|
+
for (const task of listTasks(state, run.id)) stamps.push(task.updatedAt);
|
|
120
|
+
let newest = 0;
|
|
121
|
+
for (const stamp of stamps) {
|
|
122
|
+
if (!stamp) continue;
|
|
123
|
+
const value = Date.parse(stamp);
|
|
124
|
+
if (Number.isFinite(value) && value > newest) newest = value;
|
|
125
|
+
}
|
|
126
|
+
return newest;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A run is stale when it can no longer make progress on its own — every worker is
|
|
131
|
+
* terminal (note: `orphaned` is not, its process may still be alive) and no task
|
|
132
|
+
* is waiting to run — and its last activity is older than the window.
|
|
133
|
+
*
|
|
134
|
+
* Staleness only affects *visibility*: the run and its history stay in the state
|
|
135
|
+
* and in `/orchestra runs`; it is simply not treated as this session's work.
|
|
136
|
+
*/
|
|
137
|
+
export function isRunStale(
|
|
138
|
+
state: OrchestraState,
|
|
139
|
+
run: Run,
|
|
140
|
+
staleAfterMs: number,
|
|
141
|
+
now = Date.now(),
|
|
142
|
+
): boolean {
|
|
143
|
+
if (!(staleAfterMs > 0)) return false;
|
|
144
|
+
const live = listDispatches(state, run.id).some((dispatch) => !isTerminalStatus(dispatch.status));
|
|
145
|
+
if (live) return false;
|
|
146
|
+
const waiting = listTasks(state, run.id).some(
|
|
147
|
+
(task) => task.status === "pending" || task.status === "ready" || task.status === "running" || task.status === "blocked",
|
|
148
|
+
);
|
|
149
|
+
if (waiting) return false;
|
|
150
|
+
const last = runLastActivity(state, run);
|
|
151
|
+
return last > 0 && now - last >= staleAfterMs;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The run a session should treat as current.
|
|
156
|
+
*
|
|
157
|
+
* Explicit wins: `state.activeRunId` is honoured even when the run is stale if it
|
|
158
|
+
* was pinned by `/orchestra use`, so an old run can be reopened on purpose. Otherwise
|
|
159
|
+
* stale runs are skipped and a fresh session starts with no run at all.
|
|
160
|
+
*/
|
|
161
|
+
export function activeRun(state: OrchestraState, options: ActiveRunOptions = {}): Run | undefined {
|
|
162
|
+
const staleAfterMs = options.staleAfterMs ?? 0;
|
|
163
|
+
const now = options.now ?? Date.now();
|
|
164
|
+
const pinned = state.ui?.pinnedRunId;
|
|
165
|
+
const usable = (run: Run): boolean => run.id === pinned || !isRunStale(state, run, staleAfterMs, now);
|
|
166
|
+
|
|
167
|
+
const explicit = state.activeRunId ? state.runs[state.activeRunId] : undefined;
|
|
168
|
+
if (explicit && usable(explicit)) return explicit;
|
|
169
|
+
|
|
170
|
+
const runs = Object.values(state.runs).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
171
|
+
for (let index = runs.length - 1; index >= 0; index -= 1) {
|
|
172
|
+
if (usable(runs[index])) return runs[index];
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function runOf(state: OrchestraState, options: ActiveRunOptions = {}): Run {
|
|
178
|
+
const run = activeRun(state, options);
|
|
179
|
+
if (!run) {
|
|
180
|
+
const created = createRun(state, { name: "main" });
|
|
181
|
+
state.activeRunId = created.id;
|
|
182
|
+
return created;
|
|
183
|
+
}
|
|
184
|
+
return run;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function createRun(
|
|
188
|
+
state: OrchestraState,
|
|
189
|
+
input: { name?: string; goal?: string; budgetUsd?: number; template?: string },
|
|
190
|
+
): Run {
|
|
191
|
+
const now = nowIso();
|
|
192
|
+
const seq = ++state.seq;
|
|
193
|
+
const run: Run = {
|
|
194
|
+
id: newId("run"),
|
|
195
|
+
name: input.name?.trim() || `run-${seq}`,
|
|
196
|
+
goal: input.goal,
|
|
197
|
+
budgetUsd: input.budgetUsd,
|
|
198
|
+
template: input.template,
|
|
199
|
+
status: "active",
|
|
200
|
+
createdAt: now,
|
|
201
|
+
updatedAt: now,
|
|
202
|
+
};
|
|
203
|
+
state.runs[run.id] = run;
|
|
204
|
+
state.activeRunId = run.id;
|
|
205
|
+
// A new run is the current one; drop the `/orchestra use` pin of an older run.
|
|
206
|
+
state.ui = { ...state.ui, pinnedRunId: undefined };
|
|
207
|
+
return run;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Follow `deps` from one task and return the path back to it when they loop.
|
|
212
|
+
* Returns undefined when the graph under `taskId` is acyclic.
|
|
213
|
+
*/
|
|
214
|
+
export function findDependencyCycle(state: OrchestraState, taskId: string): string[] | undefined {
|
|
215
|
+
const path: string[] = [];
|
|
216
|
+
const seen = new Set<string>();
|
|
217
|
+
const walk = (id: string): string[] | undefined => {
|
|
218
|
+
if (seen.has(id)) return undefined;
|
|
219
|
+
seen.add(id);
|
|
220
|
+
path.push(id);
|
|
221
|
+
for (const dep of state.tasks[id]?.deps ?? []) {
|
|
222
|
+
if (dep === taskId) return [...path, taskId];
|
|
223
|
+
const found = walk(dep);
|
|
224
|
+
if (found) return found;
|
|
225
|
+
}
|
|
226
|
+
path.pop();
|
|
227
|
+
return undefined;
|
|
228
|
+
};
|
|
229
|
+
return walk(taskId);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Throw when setting `deps` on `taskId` would create a dependency loop. */
|
|
233
|
+
export function assertNoCycle(state: OrchestraState, taskId: string, deps: string[]): void {
|
|
234
|
+
const clone: OrchestraState = { ...state, tasks: { ...state.tasks } };
|
|
235
|
+
if (clone.tasks[taskId]) clone.tasks[taskId] = { ...(clone.tasks[taskId] as Task), deps };
|
|
236
|
+
for (const dep of deps) {
|
|
237
|
+
if (dep === taskId) throw new Error(`Task ${taskId} cannot depend on itself.`);
|
|
238
|
+
if (!clone.tasks[dep]) throw new Error(`Unknown dependency ${dep}.`);
|
|
239
|
+
}
|
|
240
|
+
const cycle = findDependencyCycle(clone, taskId);
|
|
241
|
+
if (cycle) {
|
|
242
|
+
const titles = cycle.map((id) => clone.tasks[id]?.title ?? id);
|
|
243
|
+
throw new Error(`Dependency cycle: ${titles.join(" -> ")}.`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Tasks that are part of a loop, mapped to their path, for load-time repair. */
|
|
248
|
+
export function cyclicTasks(state: OrchestraState): Map<string, string[]> {
|
|
249
|
+
const found = new Map<string, string[]>();
|
|
250
|
+
for (const task of Object.values(state.tasks)) {
|
|
251
|
+
if (task.deps.length === 0) continue;
|
|
252
|
+
const cycle = findDependencyCycle(state, task.id);
|
|
253
|
+
if (cycle) found.set(task.id, cycle);
|
|
254
|
+
}
|
|
255
|
+
return found;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function setTaskDeps(state: OrchestraState, taskId: string, deps: string[]): Task {
|
|
259
|
+
const task = state.tasks[taskId];
|
|
260
|
+
if (!task) throw new Error(`Unknown task ${taskId}.`);
|
|
261
|
+
assertNoCycle(state, taskId, deps);
|
|
262
|
+
task.deps = [...new Set(deps)];
|
|
263
|
+
task.updatedAt = nowIso();
|
|
264
|
+
refreshTaskReadiness(state);
|
|
265
|
+
return task;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function createTask(
|
|
269
|
+
state: OrchestraState,
|
|
270
|
+
input: { runId: string; title: string; description?: string; agent?: string; deps?: string[] },
|
|
271
|
+
): Task {
|
|
272
|
+
const now = nowIso();
|
|
273
|
+
const task: Task = {
|
|
274
|
+
id: newId("task"),
|
|
275
|
+
runId: input.runId,
|
|
276
|
+
title: input.title.trim(),
|
|
277
|
+
description: input.description,
|
|
278
|
+
agent: input.agent,
|
|
279
|
+
status: "pending",
|
|
280
|
+
deps: input.deps ?? [],
|
|
281
|
+
createdAt: now,
|
|
282
|
+
updatedAt: now,
|
|
283
|
+
};
|
|
284
|
+
for (const dep of task.deps) {
|
|
285
|
+
if (!state.tasks[dep]) throw new Error(`Unknown dependency ${dep}.`);
|
|
286
|
+
if (dep === task.id) throw new Error("A task cannot depend on itself.");
|
|
287
|
+
}
|
|
288
|
+
state.tasks[task.id] = task;
|
|
289
|
+
refreshTaskReadiness(state);
|
|
290
|
+
return task;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function createDispatch(
|
|
294
|
+
state: OrchestraState,
|
|
295
|
+
input: {
|
|
296
|
+
runId: string;
|
|
297
|
+
taskId?: string;
|
|
298
|
+
agent: string;
|
|
299
|
+
spec: string;
|
|
300
|
+
model?: string;
|
|
301
|
+
provider?: string;
|
|
302
|
+
modelNote?: string;
|
|
303
|
+
thinking?: string;
|
|
304
|
+
tools?: string[];
|
|
305
|
+
budgetUsd?: number;
|
|
306
|
+
budgetMs?: number;
|
|
307
|
+
timeoutMs?: number;
|
|
308
|
+
timeoutMode?: "total" | "idle";
|
|
309
|
+
sessionId?: string;
|
|
310
|
+
resumedFrom?: string;
|
|
311
|
+
retryOf?: string;
|
|
312
|
+
baseCommit?: string;
|
|
313
|
+
attempt?: number;
|
|
314
|
+
retries?: number;
|
|
315
|
+
keepOpen: boolean;
|
|
316
|
+
},
|
|
317
|
+
): Dispatch {
|
|
318
|
+
const dispatch: Dispatch = {
|
|
319
|
+
id: newId("dispatch"),
|
|
320
|
+
runId: input.runId,
|
|
321
|
+
taskId: input.taskId,
|
|
322
|
+
agent: input.agent,
|
|
323
|
+
spec: input.spec,
|
|
324
|
+
status: "starting",
|
|
325
|
+
model: input.model,
|
|
326
|
+
provider: input.provider,
|
|
327
|
+
modelNote: input.modelNote,
|
|
328
|
+
budgetUsd: input.budgetUsd,
|
|
329
|
+
budgetMs: input.budgetMs,
|
|
330
|
+
timeoutMs: input.timeoutMs,
|
|
331
|
+
timeoutMode: input.timeoutMode,
|
|
332
|
+
sessionId: input.sessionId,
|
|
333
|
+
resumedFrom: input.resumedFrom,
|
|
334
|
+
retryOf: input.retryOf,
|
|
335
|
+
baseCommit: input.baseCommit,
|
|
336
|
+
attempt: input.attempt ?? 1,
|
|
337
|
+
retries: input.retries,
|
|
338
|
+
lastEventAt: nowIso(),
|
|
339
|
+
thinking: input.thinking,
|
|
340
|
+
tools: input.tools,
|
|
341
|
+
keepOpen: input.keepOpen,
|
|
342
|
+
startedAt: nowIso(),
|
|
343
|
+
usage: emptyUsage(),
|
|
344
|
+
};
|
|
345
|
+
state.dispatches[dispatch.id] = dispatch;
|
|
346
|
+
if (input.taskId && state.tasks[input.taskId]) {
|
|
347
|
+
const task = state.tasks[input.taskId];
|
|
348
|
+
task.status = "running";
|
|
349
|
+
task.dispatchId = dispatch.id;
|
|
350
|
+
task.updatedAt = nowIso();
|
|
351
|
+
}
|
|
352
|
+
return dispatch;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export function listTasks(state: OrchestraState, runId?: string): Task[] {
|
|
356
|
+
const run = runId ?? activeRun(state)?.id;
|
|
357
|
+
return Object.values(state.tasks)
|
|
358
|
+
.filter((task) => !run || task.runId === run)
|
|
359
|
+
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export function listDispatches(state: OrchestraState, runId?: string): Dispatch[] {
|
|
363
|
+
const run = runId ?? activeRun(state)?.id;
|
|
364
|
+
return Object.values(state.dispatches)
|
|
365
|
+
.filter((dispatch) => !run || dispatch.runId === run)
|
|
366
|
+
.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export function refreshTaskReadiness(state: OrchestraState): void {
|
|
370
|
+
const cycles = cyclicTasks(state);
|
|
371
|
+
for (const [taskId, cycle] of cycles) {
|
|
372
|
+
const task = state.tasks[taskId];
|
|
373
|
+
if (!task || task.status === "running" || task.status === "done") continue;
|
|
374
|
+
const note = `dependency cycle: ${cycle.map((id) => state.tasks[id]?.title ?? id).join(" -> ")}`;
|
|
375
|
+
if (task.status !== "blocked" || task.error !== note) {
|
|
376
|
+
task.status = "blocked";
|
|
377
|
+
task.error = note;
|
|
378
|
+
task.updatedAt = nowIso();
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
for (const task of Object.values(state.tasks)) {
|
|
382
|
+
if (task.status !== "pending" && task.status !== "ready" && task.status !== "blocked") continue;
|
|
383
|
+
if (cycles.has(task.id)) continue;
|
|
384
|
+
const deps = task.deps.map((dep) => state.tasks[dep]).filter(Boolean);
|
|
385
|
+
if (deps.some((dep) => dep.status === "failed")) {
|
|
386
|
+
if (task.status !== "blocked") {
|
|
387
|
+
task.status = "blocked";
|
|
388
|
+
task.updatedAt = nowIso();
|
|
389
|
+
}
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
const ready = deps.every((dep) => dep.status === "done");
|
|
393
|
+
const next = ready ? "ready" : "pending";
|
|
394
|
+
if (task.status !== next) {
|
|
395
|
+
task.status = next;
|
|
396
|
+
task.updatedAt = nowIso();
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
export function totalUsage(state: OrchestraState, runId?: string) {
|
|
402
|
+
const totals = emptyUsage();
|
|
403
|
+
for (const dispatch of listDispatches(state, runId)) {
|
|
404
|
+
totals.turns += dispatch.usage.turns;
|
|
405
|
+
totals.input += dispatch.usage.input;
|
|
406
|
+
totals.output += dispatch.usage.output;
|
|
407
|
+
totals.cacheRead += dispatch.usage.cacheRead;
|
|
408
|
+
totals.cacheWrite += dispatch.usage.cacheWrite;
|
|
409
|
+
totals.cost += dispatch.usage.cost;
|
|
410
|
+
totals.toolCalls += dispatch.usage.toolCalls;
|
|
411
|
+
}
|
|
412
|
+
return totals;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export function isTerminalStatus(status: DispatchStatus): boolean {
|
|
416
|
+
return status !== "starting" && status !== "running" && status !== "question" && status !== "orphaned";
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** True when the pid belongs to a live process we can still signal. */
|
|
420
|
+
export function pidAlive(pid: number | undefined): boolean {
|
|
421
|
+
if (!pid || pid <= 0) return false;
|
|
422
|
+
try {
|
|
423
|
+
process.kill(pid, 0);
|
|
424
|
+
return true;
|
|
425
|
+
} catch (error) {
|
|
426
|
+
// EPERM means the process exists but belongs to someone else.
|
|
427
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Classify dispatches that a previous coordinator left non-terminal: a live pid
|
|
433
|
+
* becomes `orphaned` (stoppable, resumable), a dead one `lost`.
|
|
434
|
+
*/
|
|
435
|
+
export function reconcileOrphans(
|
|
436
|
+
state: OrchestraState,
|
|
437
|
+
options: { isAlive?: (pid: number | undefined) => boolean } = {},
|
|
438
|
+
): { orphaned: string[]; lost: string[] } {
|
|
439
|
+
const alive = options.isAlive ?? pidAlive;
|
|
440
|
+
const result: { orphaned: string[]; lost: string[] } = { orphaned: [], lost: [] };
|
|
441
|
+
for (const dispatch of Object.values(state.dispatches)) {
|
|
442
|
+
if (isTerminalStatus(dispatch.status)) continue;
|
|
443
|
+
if (alive(dispatch.pid)) {
|
|
444
|
+
dispatch.status = "orphaned";
|
|
445
|
+
dispatch.error = `Process ${dispatch.pid} is still running, but it belongs to a previous coordinator session. Stop it with worker_stop (SIGTERM) or resume the work with worker_resume.`;
|
|
446
|
+
dispatch.stalledAt = undefined;
|
|
447
|
+
dispatch.lastEventAt = dispatch.lastEventAt ?? dispatch.startedAt;
|
|
448
|
+
result.orphaned.push(dispatch.id);
|
|
449
|
+
} else {
|
|
450
|
+
dispatch.status = "lost";
|
|
451
|
+
dispatch.endedAt = nowIso();
|
|
452
|
+
dispatch.error = "Coordinator restarted; the worker process is gone.";
|
|
453
|
+
result.lost.push(dispatch.id);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return result;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Signal a pid, politely first. Returns true when a signal was delivered. */
|
|
460
|
+
export function killPid(pid: number | undefined, signal: NodeJS.Signals = "SIGTERM"): boolean {
|
|
461
|
+
if (!pid || pid <= 0) return false;
|
|
462
|
+
try {
|
|
463
|
+
process.kill(pid, signal);
|
|
464
|
+
return true;
|
|
465
|
+
} catch {
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
// ---------------------------------------------------------------------------
|
|
472
|
+
// retention: delete data that archiving only moved aside
|
|
473
|
+
// ---------------------------------------------------------------------------
|
|
474
|
+
|
|
475
|
+
export interface PruneOptions {
|
|
476
|
+
/** Delete things older than this many days (default 30). */
|
|
477
|
+
days?: number;
|
|
478
|
+
/** Report what would go without deleting anything. */
|
|
479
|
+
dryRun?: boolean;
|
|
480
|
+
/** Reference time, for tests. */
|
|
481
|
+
now?: number;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
export interface PruneResult {
|
|
485
|
+
files: string[];
|
|
486
|
+
bytes: number;
|
|
487
|
+
/** Directories removed (archived runs). */
|
|
488
|
+
runs: string[];
|
|
489
|
+
dryRun: boolean;
|
|
490
|
+
days: number;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function directorySize(dir: string): number {
|
|
494
|
+
let total = 0;
|
|
495
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
496
|
+
const full = join(dir, entry.name);
|
|
497
|
+
if (entry.isDirectory()) total += directorySize(full);
|
|
498
|
+
else if (entry.isFile()) {
|
|
499
|
+
try {
|
|
500
|
+
total += statSync(full).size;
|
|
501
|
+
} catch {
|
|
502
|
+
// vanished while we walked; ignore
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return total;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Newest content mtime under a path. A directory is judged by the newest thing
|
|
511
|
+
* inside it (not by its own mtime, which changes when anything is written), so
|
|
512
|
+
* an archived run expires N days after its last file was touched.
|
|
513
|
+
*/
|
|
514
|
+
function newestMtime(target: string): number {
|
|
515
|
+
let stats;
|
|
516
|
+
try {
|
|
517
|
+
stats = statSync(target);
|
|
518
|
+
} catch {
|
|
519
|
+
return 0;
|
|
520
|
+
}
|
|
521
|
+
if (!stats.isDirectory()) return stats.mtimeMs;
|
|
522
|
+
let newest = 0;
|
|
523
|
+
let entries = 0;
|
|
524
|
+
for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
525
|
+
entries += 1;
|
|
526
|
+
newest = Math.max(newest, newestMtime(join(target, entry.name)));
|
|
527
|
+
}
|
|
528
|
+
return entries === 0 ? stats.mtimeMs : newest;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Remove archived runs and orphaned files older than a window. Live state is
|
|
533
|
+
* never touched: archived runs are already out of `state.json`, and an orphan is
|
|
534
|
+
* a log/prompt/mail/export whose dispatch no longer exists.
|
|
535
|
+
*/
|
|
536
|
+
export function pruneStore(root: string, state: OrchestraState, options: PruneOptions = {}): PruneResult {
|
|
537
|
+
const paths = storePaths(root);
|
|
538
|
+
const days = options.days && options.days > 0 ? options.days : 30;
|
|
539
|
+
const now = options.now ?? Date.now();
|
|
540
|
+
const cutoff = now - days * 86_400_000;
|
|
541
|
+
const result: PruneResult = { files: [], bytes: 0, runs: [], dryRun: Boolean(options.dryRun), days };
|
|
542
|
+
|
|
543
|
+
const old = (file: string): boolean => {
|
|
544
|
+
const mtime = newestMtime(file);
|
|
545
|
+
return mtime > 0 && mtime < cutoff;
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
// Archived runs: whole directories, judged by their newest file.
|
|
549
|
+
if (existsSync(paths.archiveDir)) {
|
|
550
|
+
for (const entry of readdirSync(paths.archiveDir, { withFileTypes: true })) {
|
|
551
|
+
if (!entry.isDirectory()) continue;
|
|
552
|
+
const dir = join(paths.archiveDir, entry.name);
|
|
553
|
+
if (!old(dir)) continue;
|
|
554
|
+
result.runs.push(entry.name);
|
|
555
|
+
result.files.push(dir);
|
|
556
|
+
result.bytes += directorySize(dir);
|
|
557
|
+
if (!options.dryRun) rmSync(dir, { recursive: true, force: true });
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Orphans: data whose dispatch or run no longer exists in the live state.
|
|
562
|
+
const knownDispatches = new Set(Object.keys(state.dispatches));
|
|
563
|
+
const knownRuns = new Set(Object.keys(state.runs));
|
|
564
|
+
const sweep = (dir: string, keep: (name: string) => boolean) => {
|
|
565
|
+
if (!existsSync(dir)) return;
|
|
566
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
567
|
+
const name = entry.name;
|
|
568
|
+
if (keep(name)) continue;
|
|
569
|
+
const full = join(dir, name);
|
|
570
|
+
if (!old(full)) continue;
|
|
571
|
+
result.files.push(full);
|
|
572
|
+
result.bytes += entry.isDirectory() ? directorySize(full) : statSync(full).size;
|
|
573
|
+
if (!options.dryRun) rmSync(full, { recursive: true, force: true });
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
|
|
577
|
+
sweep(paths.logsDir, (name) => knownDispatches.has(name.replace(/\.jsonl$/, "")));
|
|
578
|
+
sweep(paths.promptsDir, (name) => knownDispatches.has(name.replace(/\.md$/, "")));
|
|
579
|
+
sweep(paths.mailDir, (name) => knownDispatches.has(name));
|
|
580
|
+
sweep(paths.exportsDir, (name) => knownRuns.has(name.replace(/\.(jsonl|json|md)$/, "")));
|
|
581
|
+
|
|
582
|
+
return result;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// ---------------------------------------------------------------------------
|
|
586
|
+
// archiving: keep state.json small without losing history
|
|
587
|
+
// ---------------------------------------------------------------------------
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* The blunt instrument behind `action=reset` and `/orchestra reset`: copy the whole
|
|
591
|
+
* store aside, then empty the live state in place so the coordinator keeps its reference.
|
|
592
|
+
*
|
|
593
|
+
* Logs, prompts, mail and the archive stay on disk (use `prune` to reclaim them).
|
|
594
|
+
* The project's *UI preference* survives — hiding the widget is a choice about the
|
|
595
|
+
* terminal, not about the data — while the `/orchestra use` pin does not.
|
|
596
|
+
*/
|
|
597
|
+
export function archiveAndClearState(root: string, state: OrchestraState): { archive?: string } {
|
|
598
|
+
const paths = storePaths(root);
|
|
599
|
+
let archive: string | undefined;
|
|
600
|
+
if (existsSync(paths.stateFile)) {
|
|
601
|
+
archive = join(root, `state.${Date.now()}.bak.json`);
|
|
602
|
+
try {
|
|
603
|
+
writeFileSync(archive, readFileSync(paths.stateFile));
|
|
604
|
+
} catch {
|
|
605
|
+
// Archiving is best effort: a reset must still clear the state.
|
|
606
|
+
archive = undefined;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
for (const bucket of [state.runs, state.tasks, state.dispatches, state.gates] as Array<Record<string, unknown>>) {
|
|
610
|
+
for (const key of Object.keys(bucket)) delete bucket[key];
|
|
611
|
+
}
|
|
612
|
+
state.seq = 0;
|
|
613
|
+
state.activeRunId = undefined;
|
|
614
|
+
state.ui = { widget: state.ui?.widget };
|
|
615
|
+
return { archive };
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
export interface ArchiveResult {
|
|
619
|
+
/** Runs moved out of the live state. */
|
|
620
|
+
archived: string[];
|
|
621
|
+
/** Where each run was written, keyed by run id. */
|
|
622
|
+
dirs: Record<string, string>;
|
|
623
|
+
/** Runs still live afterwards. */
|
|
624
|
+
kept: string[];
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
export interface ArchiveOptions {
|
|
628
|
+
/** Keep this many of the most recent runs; everything older is archived. */
|
|
629
|
+
keep?: number;
|
|
630
|
+
/** Archive exactly these runs, whatever `keep` says. */
|
|
631
|
+
runIds?: string[];
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Move whole runs (tasks, dispatches, gates, logs, prompts, mail) into
|
|
636
|
+
* `archive/<runId>/`. The live `state.json` keeps only what is still useful.
|
|
637
|
+
*/
|
|
638
|
+
export function archiveRuns(root: string, state: OrchestraState, options: ArchiveOptions = {}): ArchiveResult {
|
|
639
|
+
const paths = storePaths(root);
|
|
640
|
+
const runs = Object.values(state.runs).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
641
|
+
const keep = Math.max(0, options.keep ?? 5);
|
|
642
|
+
const explicit = options.runIds?.length ? options.runIds : undefined;
|
|
643
|
+
|
|
644
|
+
const targets = explicit
|
|
645
|
+
? runs.filter((run) => explicit.includes(run.id))
|
|
646
|
+
: runs.filter((run, index) => index >= keep && run.id !== state.activeRunId);
|
|
647
|
+
|
|
648
|
+
const result: ArchiveResult = { archived: [], dirs: {}, kept: [] };
|
|
649
|
+
if (targets.length === 0) {
|
|
650
|
+
result.kept = runs.map((run) => run.id);
|
|
651
|
+
return result;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
mkdirSync(paths.archiveDir, { recursive: true });
|
|
655
|
+
for (const run of targets) {
|
|
656
|
+
const dir = join(paths.archiveDir, run.id);
|
|
657
|
+
mkdirSync(join(dir, "logs"), { recursive: true });
|
|
658
|
+
mkdirSync(join(dir, "prompts"), { recursive: true });
|
|
659
|
+
mkdirSync(join(dir, "mail"), { recursive: true });
|
|
660
|
+
|
|
661
|
+
const tasks = listTasks(state, run.id);
|
|
662
|
+
const dispatches = listDispatches(state, run.id);
|
|
663
|
+
const gates = Object.values(state.gates).filter((gate) => gate.runId === run.id);
|
|
664
|
+
|
|
665
|
+
for (const dispatch of dispatches) {
|
|
666
|
+
const logFile = join(paths.logsDir, `${dispatch.id}.jsonl`);
|
|
667
|
+
if (existsSync(logFile)) renameSync(logFile, join(dir, "logs", `${dispatch.id}.jsonl`));
|
|
668
|
+
const promptFile = join(paths.promptsDir, `${dispatch.id}.md`);
|
|
669
|
+
if (existsSync(promptFile)) renameSync(promptFile, join(dir, "prompts", `${dispatch.id}.md`));
|
|
670
|
+
const mail = join(paths.mailDir, dispatch.id);
|
|
671
|
+
if (existsSync(mail)) renameSync(mail, join(dir, "mail", dispatch.id));
|
|
672
|
+
delete state.dispatches[dispatch.id];
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
writeFileSync(
|
|
676
|
+
join(dir, "run.json"),
|
|
677
|
+
`${JSON.stringify({ run, tasks, dispatches, gates, archivedAt: nowIso() }, null, 2)}\n`,
|
|
678
|
+
"utf8",
|
|
679
|
+
);
|
|
680
|
+
|
|
681
|
+
for (const task of tasks) delete state.tasks[task.id];
|
|
682
|
+
for (const gate of gates) delete state.gates[gate.id];
|
|
683
|
+
delete state.runs[run.id];
|
|
684
|
+
result.archived.push(run.id);
|
|
685
|
+
result.dirs[run.id] = dir;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
if (state.activeRunId && !state.runs[state.activeRunId]) {
|
|
689
|
+
const next = Object.values(state.runs).sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
|
|
690
|
+
state.activeRunId = next?.id;
|
|
691
|
+
}
|
|
692
|
+
result.kept = Object.keys(state.runs);
|
|
693
|
+
return result;
|
|
694
|
+
}
|