my-durable 0.0.44 → 0.0.45
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/apps/dpi-backend/src/graph-cli.ts +446 -0
- package/apps/dpi-backend/src/graphs.ts +960 -0
- package/apps/dpi-backend/src/notify-cli.ts +8 -1
- package/apps/dpi-backend/src/routes.ts +18 -1
- package/apps/dpi-backend/src/store.ts +143 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/{index-BDY9dgTQ.js → index-CIMZq9MU.js} +4 -4
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-Dp-HJ4Vs.css +1 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/GraphPanel.vue +309 -0
- package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +4 -0
- package/apps/dpi-sdk/src/api.ts +38 -0
- package/apps/dpi-sdk/src/client.ts +19 -0
- package/apps/dpi-sdk/src/protocol/rest-routes.ts +7 -0
- package/bin/dpi.mjs +7 -0
- package/docs/host-project-checklist.md +2 -2
- package/package.json +1 -1
- package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CraiQho0.css +0 -1
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `dpi graph` — task-graph orchestration from the CLI (checklist Wave 3, the
|
|
3
|
+
* last SHOULD: "Task-graph orchestration").
|
|
4
|
+
*
|
|
5
|
+
* The records live in `<home>/backend/graphs.json`, so list/show/add/archive/
|
|
6
|
+
* unarchive edit that file directly through `GraphRegistry` (atomic, 0600, with
|
|
7
|
+
* a `.bak`) — the same "the file is the contract" stance as the other
|
|
8
|
+
* registries. Two commands additionally talk to the RUNNING device daemon over
|
|
9
|
+
* its API, because only the device executes:
|
|
10
|
+
*
|
|
11
|
+
* - `run` POST /v1/graphs/:id/run (body `{}`) — the store drives the
|
|
12
|
+
* DAG: each task, once its deps finished ok, runs as a fresh session.
|
|
13
|
+
* - `remove` DELETE /v1/graphs/:id — the record is gone from the file
|
|
14
|
+
* either way; the DELETE tells a running daemon to drop it now.
|
|
15
|
+
*
|
|
16
|
+
* Those REST routes land in a later build of the daemon, so a 404 (or an
|
|
17
|
+
* allowlist refusal) is translated to "this device is on an older build" rather
|
|
18
|
+
* than a raw error. Endpoint + token resolution is doctor.ts's
|
|
19
|
+
* `deviceEndpoint`/`authHeaders`, exactly like `dpi schedule`.
|
|
20
|
+
*
|
|
21
|
+
* CLI io is injected (print/printErr/env/homedir/fetch/exists/readFile/
|
|
22
|
+
* readStdin), so tests fake one object. Exit codes: 0 ok, 1 graph/daemon error,
|
|
23
|
+
* 2 usage error; nothing is ever thrown out of `graphCli`. `argv` is what
|
|
24
|
+
* follows the `graph` word (`graphCli({ argv: ["list"] })`).
|
|
25
|
+
*/
|
|
26
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
27
|
+
import { homedir } from "node:os";
|
|
28
|
+
import { join, resolve } from "node:path";
|
|
29
|
+
import { GraphError, GraphRegistry, type GraphRecord, type GraphRunRecord, type TaskRunState } from "./graphs.js";
|
|
30
|
+
import { authHeaders, defaultDoctorIo, deviceEndpoint, expand, readEnvFile, type FetchLike } from "./doctor.js";
|
|
31
|
+
|
|
32
|
+
export const GRAPH_HELP = `dpi graph — task-graph orchestration (a run = a fresh session per task)
|
|
33
|
+
|
|
34
|
+
dpi graph list [--all]
|
|
35
|
+
dpi graph show <id-prefix> [--runs]
|
|
36
|
+
dpi graph add --file graph.json | --file -
|
|
37
|
+
dpi graph run <id-prefix>
|
|
38
|
+
dpi graph remove <id-prefix>
|
|
39
|
+
dpi graph archive|unarchive <id-prefix>
|
|
40
|
+
|
|
41
|
+
list graphs (active only; --all includes archived)
|
|
42
|
+
show the tasks with their last-run statuses; --runs adds the history
|
|
43
|
+
add read a { name, cwd, tasks: [...] } JSON document from --file
|
|
44
|
+
(or STDIN with --file -), print the created id
|
|
45
|
+
run ask the running device daemon to start a run
|
|
46
|
+
(POST /v1/graphs/<id>/run; each task runs as a fresh session
|
|
47
|
+
once every dependency finished ok)
|
|
48
|
+
remove delete the record (and its run history) and tell the daemon
|
|
49
|
+
archive soft delete: keeps tasks and run history, hides the graph
|
|
50
|
+
|
|
51
|
+
--home DIR device home (default: $DPI_HOME, else ~/.dpi); the registry is
|
|
52
|
+
<home>/backend/graphs.json
|
|
53
|
+
|
|
54
|
+
A 404 from the daemon on run/remove means an older build without the graph
|
|
55
|
+
routes — update the device and restart it.
|
|
56
|
+
Exit codes: 0 ok, 1 graph/daemon error, 2 usage error.`;
|
|
57
|
+
|
|
58
|
+
export interface GraphCliArgs {
|
|
59
|
+
argv: readonly string[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Everything the CLI touches is injectable; the default io is the real machine. */
|
|
63
|
+
export interface GraphCliIo {
|
|
64
|
+
print: (line: string) => void;
|
|
65
|
+
printErr: (line: string) => void;
|
|
66
|
+
env: Record<string, string | undefined>;
|
|
67
|
+
homedir: () => string;
|
|
68
|
+
/** doctor's narrow fetch surface, so a fake httpd is three lines in tests. */
|
|
69
|
+
fetch: FetchLike;
|
|
70
|
+
/** Timeout for the daemon calls (`run` may kick off sessions). */
|
|
71
|
+
fetchTimeoutMs: number;
|
|
72
|
+
exists: (path: string) => boolean;
|
|
73
|
+
/** Sync text read: the --file document and the env file (doctor.ts shape). */
|
|
74
|
+
readFile: (path: string) => string;
|
|
75
|
+
/** The add document when `--file -` is used. */
|
|
76
|
+
readStdin: () => Promise<string>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const readAllStdin = async (): Promise<string> => {
|
|
80
|
+
const chunks: Buffer[] = [];
|
|
81
|
+
for await (const chunk of process.stdin) chunks.push(chunk as Buffer);
|
|
82
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export const defaultGraphCliIo = (): GraphCliIo => ({
|
|
86
|
+
print: (line) => process.stdout.write(`${line}\n`),
|
|
87
|
+
printErr: (line) => process.stderr.write(`${line}\n`),
|
|
88
|
+
env: process.env as Record<string, string | undefined>,
|
|
89
|
+
homedir,
|
|
90
|
+
fetch: async (url, init) => fetch(url, init as RequestInit),
|
|
91
|
+
fetchTimeoutMs: 30_000,
|
|
92
|
+
exists: existsSync,
|
|
93
|
+
readFile: (path) => readFileSync(path, "utf8"),
|
|
94
|
+
readStdin: readAllStdin,
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
/** Flags that consume the next argument. */
|
|
98
|
+
const VALUE_FLAGS = new Set(["--home", "--file"]);
|
|
99
|
+
/** Flags each subcommand accepts; anything else `--`-shaped is a usage error. */
|
|
100
|
+
const SUB_FLAGS: Record<string, Set<string>> = {
|
|
101
|
+
list: new Set(["--all"]),
|
|
102
|
+
show: new Set(["--runs"]),
|
|
103
|
+
add: new Set(["--file"]),
|
|
104
|
+
run: new Set(),
|
|
105
|
+
remove: new Set(),
|
|
106
|
+
archive: new Set(),
|
|
107
|
+
unarchive: new Set(),
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const flagValue = (argv: readonly string[], name: string): string | undefined => {
|
|
111
|
+
const i = argv.indexOf(name);
|
|
112
|
+
return i >= 0 && argv[i + 1] ? argv[i + 1] : undefined;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** Positional args, skipping flags and the value --home/--file consume. */
|
|
116
|
+
const positional = (argv: readonly string[]): string[] => {
|
|
117
|
+
const out: string[] = [];
|
|
118
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
119
|
+
if (VALUE_FLAGS.has(argv[i])) i += 1;
|
|
120
|
+
else if (!argv[i].startsWith("-")) out.push(argv[i]);
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** env wins over the env file, like doctor.ts's `deviceEndpoint`. */
|
|
126
|
+
function envValues(io: GraphCliIo): (key: string) => string | undefined {
|
|
127
|
+
const envFile = io.env.DPI_ENV_FILE;
|
|
128
|
+
let fileEnv: Record<string, string> = {};
|
|
129
|
+
if (envFile) {
|
|
130
|
+
try {
|
|
131
|
+
fileEnv = readEnvFile(io.readFile(resolve(expand(envFile, io.homedir()))));
|
|
132
|
+
} catch {
|
|
133
|
+
/* unreadable env file: fall back to process env, like doctor.ts */
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return (key) => io.env[key] ?? (typeof fileEnv[key] === "string" ? fileEnv[key] : undefined);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** `--home` wins, then $DPI_HOME (env file included), then ~/.dpi — the backup-cli rule. */
|
|
140
|
+
function resolveHome(homeFlag: string | undefined, io: GraphCliIo): string {
|
|
141
|
+
const value = envValues(io);
|
|
142
|
+
const home = homeFlag ?? value("DPI_HOME") ?? join(io.homedir(), ".dpi");
|
|
143
|
+
return resolve(expand(home, io.homedir()));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The registry the device loop reads: <home>/backend/graphs.json (the store's dataDir). */
|
|
147
|
+
function registryPath(home: string): string {
|
|
148
|
+
return join(home, "backend", "graphs.json");
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function openRegistry(home: string, io: GraphCliIo): Promise<GraphRegistry> {
|
|
152
|
+
return GraphRegistry.open(registryPath(home), {
|
|
153
|
+
warn: (message, error) => io.printErr(`[graphs] ${message}${error === undefined ? "" : ` (${error})`}`),
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Resolve an id prefix the way a human types it (`dpi graph show 3f2a`). */
|
|
158
|
+
export function matchGraph(list: readonly GraphRecord[], prefix: string): GraphRecord[] {
|
|
159
|
+
const needle = prefix.toLowerCase();
|
|
160
|
+
return list.filter((graph) => graph.id.toLowerCase().startsWith(needle));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
type Resolved = { record: GraphRecord } | { error: number; message: string };
|
|
164
|
+
|
|
165
|
+
function resolveTarget(list: readonly GraphRecord[], prefix: string, io: GraphCliIo): Resolved {
|
|
166
|
+
const matches = matchGraph(list, prefix);
|
|
167
|
+
if (!matches.length) return { error: 1, message: `no graph starts with '${prefix}'` };
|
|
168
|
+
if (matches.length > 1) {
|
|
169
|
+
io.printErr(`dpi graph: '${prefix}' matches ${matches.length} graphs — be more specific:`);
|
|
170
|
+
for (const match of matches) io.printErr(` ${match.id} ${match.name}`);
|
|
171
|
+
return { error: 2, message: `prefix '${prefix}' is ambiguous` };
|
|
172
|
+
}
|
|
173
|
+
return { record: matches[0] };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The last-run marker a task shows: `ok` / `pending` / `✗ failed: <err>` / `– skipped`. */
|
|
177
|
+
export function taskMarker(state: TaskRunState | undefined): string {
|
|
178
|
+
if (!state) return "–"; // never ran
|
|
179
|
+
switch (state.status) {
|
|
180
|
+
case "ok":
|
|
181
|
+
return "ok";
|
|
182
|
+
case "pending":
|
|
183
|
+
return "pending";
|
|
184
|
+
case "running":
|
|
185
|
+
return "running";
|
|
186
|
+
case "failed":
|
|
187
|
+
return `✗ failed: ${(state.error ?? "").slice(0, 40) || "no error recorded"}`;
|
|
188
|
+
case "skipped":
|
|
189
|
+
return "– skipped";
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** A graph with its tasks and their last-run statuses. */
|
|
194
|
+
export function formatGraph(graph: GraphRecord, lastRun?: GraphRunRecord): string[] {
|
|
195
|
+
const head = `${graph.id} ${graph.name}${graph.archivedAt ? " (archived)" : ""} — ${graph.tasks.length} task(s), ${graph.cwd}`;
|
|
196
|
+
const tasks = graph.tasks.map((task) => {
|
|
197
|
+
const deps = task.dependsOn.length ? ` [needs ${task.dependsOn.join(", ")}]` : "";
|
|
198
|
+
return ` ${taskMarker(lastRun?.tasks[task.id]).padEnd(18)} ${task.id.padEnd(12)} ${task.name}${deps}`;
|
|
199
|
+
});
|
|
200
|
+
return [head, ...tasks];
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** One run as a summary line per task plus the counts — what `run` prints back. */
|
|
204
|
+
export function formatRun(run: GraphRunRecord): string[] {
|
|
205
|
+
const states = Object.values(run.tasks);
|
|
206
|
+
const count = (status: TaskRunState["status"]) => states.filter((state) => state.status === status).length;
|
|
207
|
+
const toGo = count("pending") + count("running");
|
|
208
|
+
const head = `${run.id} ${run.status} — ${count("ok")} ok, ${count("failed")} failed, ${count("skipped")} skipped, ${toGo} to go`;
|
|
209
|
+
return [
|
|
210
|
+
head,
|
|
211
|
+
...Object.entries(run.tasks).map(([id, state]) => ` ${taskMarker(state).padEnd(18)} ${id}`),
|
|
212
|
+
];
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Run-history lines for `show --runs`. */
|
|
216
|
+
export function formatRuns(runs: readonly GraphRunRecord[]): string[] {
|
|
217
|
+
return runs.map(
|
|
218
|
+
(run) =>
|
|
219
|
+
` ${run.id} ${run.status.padEnd(11)} started ${run.startedAt}${run.finishedAt ? `, finished ${run.finishedAt}` : ""}`,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* One daemon call. The token is looked up in the same home the CLI is editing
|
|
225
|
+
* (`DPI_HOME` is overridden with the resolved home), so the graph and the
|
|
226
|
+
* credential can never come from two different devices.
|
|
227
|
+
*/
|
|
228
|
+
async function callDevice(
|
|
229
|
+
io: GraphCliIo,
|
|
230
|
+
home: string,
|
|
231
|
+
method: string,
|
|
232
|
+
path: string,
|
|
233
|
+
body?: unknown,
|
|
234
|
+
): Promise<{ ok: true; status: number; body: Record<string, unknown> } | { ok: false; status?: number; error: string }> {
|
|
235
|
+
const doctorIo = {
|
|
236
|
+
...defaultDoctorIo(),
|
|
237
|
+
env: { ...io.env, DPI_HOME: home },
|
|
238
|
+
homedir: io.homedir,
|
|
239
|
+
exists: io.exists,
|
|
240
|
+
readFile: io.readFile,
|
|
241
|
+
fetchImpl: io.fetch,
|
|
242
|
+
};
|
|
243
|
+
const cfg = deviceEndpoint(doctorIo);
|
|
244
|
+
if (!cfg.token) return { ok: false, error: `no DPI_TOKEN (looked in ${cfg.envFile})` };
|
|
245
|
+
try {
|
|
246
|
+
const res = await io.fetch(`${cfg.baseUrl}${path}`, {
|
|
247
|
+
method,
|
|
248
|
+
headers: {
|
|
249
|
+
...authHeaders(cfg.token),
|
|
250
|
+
...(body === undefined ? {} : { "content-type": "application/json" }),
|
|
251
|
+
},
|
|
252
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
253
|
+
signal: AbortSignal.timeout(io.fetchTimeoutMs),
|
|
254
|
+
});
|
|
255
|
+
const parsed = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
|
256
|
+
if (!res.ok) {
|
|
257
|
+
const message = (parsed as { error?: { message?: string } })?.error?.message ?? "";
|
|
258
|
+
return { ok: false, status: res.status, error: message };
|
|
259
|
+
}
|
|
260
|
+
return { ok: true, status: res.status, body: parsed };
|
|
261
|
+
} catch (error) {
|
|
262
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
263
|
+
return { ok: false, error: `${message} (is the device running? "dpi device start")` };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** A non-ok daemon answer in words; a 404 on the graph routes is an older build, not a bug. */
|
|
268
|
+
function daemonError(result: { status?: number; error: string }, action: string): string {
|
|
269
|
+
if (result.status === 404) {
|
|
270
|
+
return `the device answered 404 — this device is on an older build without the /v1/graphs routes (update it, then "dpi device start")`;
|
|
271
|
+
}
|
|
272
|
+
const detail = result.status ? `${result.status} ` : "";
|
|
273
|
+
return `could not ${action} on the device: ${detail}${result.error}`.trim();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export async function graphCli(args: GraphCliArgs, io: GraphCliIo = defaultGraphCliIo()): Promise<number> {
|
|
277
|
+
try {
|
|
278
|
+
return await run(args.argv, io);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
// The CLI contract is an exit code, never a stack trace (backupCli's rule).
|
|
281
|
+
io.printErr(`dpi graph: ${error instanceof Error ? error.message : String(error)}`);
|
|
282
|
+
return 1;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async function run(argv: readonly string[], io: GraphCliIo): Promise<number> {
|
|
287
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
288
|
+
io.print(GRAPH_HELP);
|
|
289
|
+
return 0;
|
|
290
|
+
}
|
|
291
|
+
// `--home` is global: peel it out wherever it sits, so both
|
|
292
|
+
// `dpi graph list --home D` and `dpi graph --home D list` parse.
|
|
293
|
+
const homeFlag = flagValue(argv, "--home");
|
|
294
|
+
const peeled: string[] = [];
|
|
295
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
296
|
+
if (argv[i] === "--home") {
|
|
297
|
+
i += 1;
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
peeled.push(argv[i]);
|
|
301
|
+
}
|
|
302
|
+
const [sub = "list", ...rest] = peeled;
|
|
303
|
+
if (!SUB_FLAGS[sub]) {
|
|
304
|
+
io.printErr(`dpi graph: unknown subcommand '${sub}'\n\n${GRAPH_HELP}`);
|
|
305
|
+
return 2;
|
|
306
|
+
}
|
|
307
|
+
// Every other --flag must be known to the subcommand; a flag's VALUE (the
|
|
308
|
+
// "-" STDIN marker, a dir) is skipped, not validated.
|
|
309
|
+
for (let i = 0; i < rest.length; i += 1) {
|
|
310
|
+
if (VALUE_FLAGS.has(rest[i])) {
|
|
311
|
+
i += 1;
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
if (rest[i].startsWith("-") && !SUB_FLAGS[sub].has(rest[i])) {
|
|
315
|
+
io.printErr(`dpi graph ${sub}: unknown flag '${rest[i]}'\n\n${GRAPH_HELP}`);
|
|
316
|
+
return 2;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
if (sub === "add") return addCmd(rest, homeFlag, io);
|
|
320
|
+
if (sub === "list") return listCmd(rest, homeFlag, io);
|
|
321
|
+
|
|
322
|
+
// Everything else needs a graph id prefix.
|
|
323
|
+
const home = resolveHome(homeFlag, io);
|
|
324
|
+
const registry = await openRegistry(home, io);
|
|
325
|
+
const prefix = positional(rest)[0];
|
|
326
|
+
if (!prefix) {
|
|
327
|
+
io.printErr(`dpi graph ${sub}: an id prefix is required\n\n${GRAPH_HELP}`);
|
|
328
|
+
return 2;
|
|
329
|
+
}
|
|
330
|
+
const resolved = resolveTarget(registry.list({ includeArchived: true }), prefix, io);
|
|
331
|
+
if ("error" in resolved) {
|
|
332
|
+
if (resolved.error === 1) io.printErr(`dpi graph: ${resolved.message}`);
|
|
333
|
+
return resolved.error;
|
|
334
|
+
}
|
|
335
|
+
const graph = resolved.record;
|
|
336
|
+
|
|
337
|
+
if (sub === "show") return showCmd(registry, graph, rest.includes("--runs"), io);
|
|
338
|
+
if (sub === "run") return runCmd(home, graph, io);
|
|
339
|
+
if (sub === "remove") return removeCmd(home, registry, graph, io);
|
|
340
|
+
if (sub === "archive" || sub === "unarchive") {
|
|
341
|
+
const updated = sub === "archive" ? await registry.archive(graph.id) : await registry.unarchive(graph.id);
|
|
342
|
+
io.print(`${sub}d ${updated.id} — ${updated.name}`);
|
|
343
|
+
return 0;
|
|
344
|
+
}
|
|
345
|
+
io.printErr(`dpi graph: unknown subcommand '${sub}'\n\n${GRAPH_HELP}`);
|
|
346
|
+
return 2;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function listCmd(rest: readonly string[], homeFlag: string | undefined, io: GraphCliIo): Promise<number> {
|
|
350
|
+
const registry = await openRegistry(resolveHome(homeFlag, io), io);
|
|
351
|
+
const graphs = registry.list({ includeArchived: rest.includes("--all") });
|
|
352
|
+
if (!graphs.length) {
|
|
353
|
+
io.print("no graphs yet. Add one with `dpi graph add --file graph.json`.");
|
|
354
|
+
return 0;
|
|
355
|
+
}
|
|
356
|
+
for (const graph of graphs) {
|
|
357
|
+
io.print(`${graph.id} ${graph.name}${graph.archivedAt ? " (archived)" : ""} — ${graph.tasks.length} task(s), ${graph.cwd}`);
|
|
358
|
+
}
|
|
359
|
+
return 0;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async function showCmd(registry: GraphRegistry, graph: GraphRecord, withRuns: boolean, io: GraphCliIo): Promise<number> {
|
|
363
|
+
for (const line of formatGraph(graph, registry.lastRun(graph.id))) io.print(line);
|
|
364
|
+
if (withRuns) {
|
|
365
|
+
const runs = registry.runs(graph.id);
|
|
366
|
+
io.print(runs.length ? "runs:" : "runs: none yet");
|
|
367
|
+
for (const line of formatRuns(runs)) io.print(line);
|
|
368
|
+
}
|
|
369
|
+
return 0;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async function addCmd(rest: readonly string[], homeFlag: string | undefined, io: GraphCliIo): Promise<number> {
|
|
373
|
+
const file = flagValue(rest, "--file");
|
|
374
|
+
if (!file) {
|
|
375
|
+
io.printErr(`dpi graph add: --file <graph.json> (or --file - for STDIN) is required\n\n${GRAPH_HELP}`);
|
|
376
|
+
return 2;
|
|
377
|
+
}
|
|
378
|
+
let text: string;
|
|
379
|
+
if (file === "-") {
|
|
380
|
+
text = await io.readStdin();
|
|
381
|
+
} else {
|
|
382
|
+
try {
|
|
383
|
+
text = io.readFile(resolve(expand(file, io.homedir())));
|
|
384
|
+
} catch (error) {
|
|
385
|
+
io.printErr(`dpi graph add: could not read ${file} — ${error instanceof Error ? error.message : String(error)}`);
|
|
386
|
+
return 1;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
let document: unknown;
|
|
390
|
+
try {
|
|
391
|
+
document = JSON.parse(text);
|
|
392
|
+
} catch (error) {
|
|
393
|
+
io.printErr(`dpi graph add: ${file === "-" ? "STDIN" : file} is not valid JSON — ${error instanceof Error ? error.message : String(error)}`);
|
|
394
|
+
return 1;
|
|
395
|
+
}
|
|
396
|
+
if (!document || typeof document !== "object" || Array.isArray(document)) {
|
|
397
|
+
io.printErr(`dpi graph add: the document must be a { name, cwd, tasks } JSON object`);
|
|
398
|
+
return 1;
|
|
399
|
+
}
|
|
400
|
+
const home = resolveHome(homeFlag, io);
|
|
401
|
+
const registry = await openRegistry(home, io);
|
|
402
|
+
try {
|
|
403
|
+
const created = await registry.create(document as { name: string; cwd: string; tasks: never[] });
|
|
404
|
+
io.print(`created ${created.id} — ${created.name} (${created.tasks.length} task(s))`);
|
|
405
|
+
return 0;
|
|
406
|
+
} catch (error) {
|
|
407
|
+
if (error instanceof GraphError && error.code === "invalid") {
|
|
408
|
+
io.printErr(`dpi graph add: ${error.message}`);
|
|
409
|
+
return 1;
|
|
410
|
+
}
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function runCmd(home: string, graph: GraphRecord, io: GraphCliIo): Promise<number> {
|
|
416
|
+
io.print(`asking the device to run ${graph.name} (${graph.tasks.length} task(s))…`);
|
|
417
|
+
const result = await callDevice(io, home, "POST", `/v1/graphs/${graph.id}/run`, {});
|
|
418
|
+
if (!result.ok) {
|
|
419
|
+
io.printErr(`dpi graph run: ${daemonError(result, "start the run")}`);
|
|
420
|
+
return 1;
|
|
421
|
+
}
|
|
422
|
+
const body = result.body;
|
|
423
|
+
const candidate =
|
|
424
|
+
body.run && typeof body.run === "object" ? (body.run as Record<string, unknown>) : body;
|
|
425
|
+
if (typeof candidate.id !== "string" || !candidate.tasks || typeof candidate.tasks !== "object") {
|
|
426
|
+
io.print(`the device accepted the run for ${graph.id}`);
|
|
427
|
+
return 0;
|
|
428
|
+
}
|
|
429
|
+
const run = candidate as unknown as GraphRunRecord;
|
|
430
|
+
for (const line of formatRun(run)) io.print(line);
|
|
431
|
+
return run.status === "failed" || run.status === "interrupted" ? 1 : 0;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async function removeCmd(home: string, registry: GraphRegistry, graph: GraphRecord, io: GraphCliIo): Promise<number> {
|
|
435
|
+
if (!(await registry.remove(graph.id))) {
|
|
436
|
+
io.printErr(`dpi graph: no graph ${graph.id}`);
|
|
437
|
+
return 1;
|
|
438
|
+
}
|
|
439
|
+
io.print(`removed ${graph.id} — ${graph.name}`);
|
|
440
|
+
// The file is the durable fact; the DELETE tells a RUNNING daemon to drop it
|
|
441
|
+
// now. An older build or a stopped daemon is a note, not a failure — the next
|
|
442
|
+
// boot reads the file without the record.
|
|
443
|
+
const result = await callDevice(io, home, "DELETE", `/v1/graphs/${graph.id}`);
|
|
444
|
+
if (!result.ok) io.printErr(`note: ${daemonError(result, "remove it")} — it will forget the graph on its next start`);
|
|
445
|
+
return 0;
|
|
446
|
+
}
|