@galaxy-stack/blackhole-cli 3.0.21 → 3.0.22
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/package.json +4 -3
- package/web/brand/app-icon-192.png +0 -0
- package/web/brand/app-icon-512.png +0 -0
- package/web/brand/client.template.js +1259 -0
- package/web/brand/dsh-locale-keys.json +8659 -0
- package/web/brand/favicon.png +0 -0
- package/web/brand/favicon.svg +12 -0
- package/web/brand/lib/app-icons.js +3 -0
- package/web/brand/lib/client.js +5161 -0
- package/web/brand/lib/favicon.js +1 -0
- package/web/brand/lib/index.d.ts +3 -0
- package/web/brand/lib/index.js +1068 -0
- package/web/brand/lib/journey-host.js +288 -0
- package/web/brand/lib/journey-run.d.ts +70 -0
- package/web/brand/lib/journey-run.js +344 -0
- package/web/brand/lib/journey-store.d.ts +61 -0
- package/web/brand/lib/journey-store.js +183 -0
- package/web/brand/lib/session-store.d.ts +54 -0
- package/web/brand/lib/session-store.js +288 -0
- package/web/brand/logo.png +0 -0
- package/web/brand/logo.svg +20 -0
- package/web/brand/package.json +35 -0
- package/web/brand/panel/journey-panel.js +1037 -0
- package/web/brand/vi-same-by-design.json +112 -0
- package/web/brand/vi.locales.json +2867 -0
- package/web/brand/zalo.jpg +0 -0
- package/web/patches/gbh-brand.patch.yml +13 -0
- package/web/patches/gbh-ui.patch.yml +7 -0
- package/web/patches/gbh-web.patch.yml +124 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
//#region gbh journey run engine
|
|
2
|
+
/**
|
|
3
|
+
* Run engine for the Galaxy delivery journey.
|
|
4
|
+
*
|
|
5
|
+
* A run is one attempt to move a feature through the blueprint: it walks the graph
|
|
6
|
+
* in dependency order, executes each node through a declared adapter, and keeps a
|
|
7
|
+
* per-node state plus evidence. Everything is fail-closed and resumable — a node
|
|
8
|
+
* that cannot run is marked blocked/awaiting instead of being skipped silently,
|
|
9
|
+
* and every transition is written to the run file before the next node starts.
|
|
10
|
+
*
|
|
11
|
+
* Runs live under \`<DSH_HOME>/journey/runs\` because a run belongs to the session
|
|
12
|
+
* that drove it, while the blueprint belongs to the workspace (and to git).
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
|
|
18
|
+
/** Per-node states a canvas renders. */
|
|
19
|
+
export const JOURNEY_RUN_STATES = ["pending", "running", "awaiting_approval", "blocked", "done", "failed", "skipped"];
|
|
20
|
+
/** Whole-run states. */
|
|
21
|
+
export const JOURNEY_RUN_STATUSES = ["running", "awaiting_approval", "blocked", "completed", "failed", "cancelled"];
|
|
22
|
+
/** Adapters the engine can execute today; the rest report a missing adapter. */
|
|
23
|
+
const EXECUTABLE_ACTIONS = ["command", "manual"];
|
|
24
|
+
const DEFAULT_COMMAND_TIMEOUT_MS = 120_000;
|
|
25
|
+
const OUTPUT_TAIL_CHARS = 4_000;
|
|
26
|
+
|
|
27
|
+
/** Runs directory inside the harness home. */
|
|
28
|
+
export function runsDirectory(home) {
|
|
29
|
+
return join(home, "journey", "runs");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Absolute path of one run record. */
|
|
33
|
+
export function runPath(home, runId) {
|
|
34
|
+
return join(runsDirectory(home), runId + ".json");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function nowIso(now) {
|
|
38
|
+
return (now instanceof Date ? now : new Date()).toISOString();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function incomingEdges(document, nodeId) {
|
|
42
|
+
return (document.edges || []).filter(edge => edge.to === nodeId);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Whether one edge lets its target run, given the source's state. */
|
|
46
|
+
export function edgeIsActive(edge, sourceState) {
|
|
47
|
+
const when = edge.when || "success";
|
|
48
|
+
if (when === "always") return ["done", "failed", "skipped"].includes(sourceState);
|
|
49
|
+
if (when === "failure") return sourceState === "failed";
|
|
50
|
+
return sourceState === "done";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Nodes whose dependencies are satisfied and that may run next. */
|
|
54
|
+
export function eligibleNodes(document, run) {
|
|
55
|
+
const eligible = [];
|
|
56
|
+
for (const node of document.nodes || []) {
|
|
57
|
+
const state = run.nodes[node.id]?.state ?? "pending";
|
|
58
|
+
if (state !== "pending") continue;
|
|
59
|
+
const incoming = incomingEdges(document, node.id);
|
|
60
|
+
if (incoming.length === 0) {
|
|
61
|
+
eligible.push(node);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (incoming.some(edge => edgeIsActive(edge, run.nodes[edge.from]?.state ?? "pending"))) eligible.push(node);
|
|
65
|
+
}
|
|
66
|
+
return eligible;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function boundOutput(value) {
|
|
70
|
+
const text = String(value ?? "");
|
|
71
|
+
return text.length > OUTPUT_TAIL_CHARS ? "…" + text.slice(-OUTPUT_TAIL_CHARS) : text;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The shell one command string runs in: cmd.exe on Windows (there is no /bin/sh there), /bin/sh
|
|
76
|
+
* everywhere else. Same argv shape on both sides, so callers never build a command differently.
|
|
77
|
+
*/
|
|
78
|
+
function shellFor(command) {
|
|
79
|
+
if (process.platform === "win32") {
|
|
80
|
+
return { command: process.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", command] };
|
|
81
|
+
}
|
|
82
|
+
return { command: "/bin/sh", args: ["-c", command] };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Run one shell command in the workspace, bounded and cancellable. */
|
|
86
|
+
export function runCommand(command, options = {}) {
|
|
87
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_COMMAND_TIMEOUT_MS;
|
|
88
|
+
return new Promise(resolve => {
|
|
89
|
+
const shell = shellFor(command);
|
|
90
|
+
const child = spawn(shell.command, shell.args, {
|
|
91
|
+
cwd: options.cwd,
|
|
92
|
+
env: { ...process.env, ...(options.env || {}) },
|
|
93
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
94
|
+
});
|
|
95
|
+
let stdout = "";
|
|
96
|
+
let stderr = "";
|
|
97
|
+
let settled = false;
|
|
98
|
+
const timer = setTimeout(() => {
|
|
99
|
+
if (settled) return;
|
|
100
|
+
try { child.kill("SIGKILL"); } catch { /* already gone */ }
|
|
101
|
+
}, timeoutMs);
|
|
102
|
+
const finish = result => {
|
|
103
|
+
if (settled) return;
|
|
104
|
+
settled = true;
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
resolve(result);
|
|
107
|
+
};
|
|
108
|
+
child.stdout?.on("data", chunk => { stdout += chunk.toString("utf8"); });
|
|
109
|
+
child.stderr?.on("data", chunk => { stderr += chunk.toString("utf8"); });
|
|
110
|
+
child.on("error", error => finish({ exitCode: null, error: String(error), stdout, stderr }));
|
|
111
|
+
child.on("close", code => finish({ exitCode: code, stdout: boundOutput(stdout), stderr: boundOutput(stderr) }));
|
|
112
|
+
if (options.signal !== undefined) {
|
|
113
|
+
options.signal.addEventListener("abort", () => {
|
|
114
|
+
try { child.kill("SIGTERM"); } catch { /* already gone */ }
|
|
115
|
+
finish({ exitCode: null, error: "cancelled", stdout, stderr });
|
|
116
|
+
}, { once: true });
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Create one run for a blueprint; triggers start done so the first real node can run. */
|
|
122
|
+
export function createRun(input) {
|
|
123
|
+
const document = input.document;
|
|
124
|
+
const nodes = {};
|
|
125
|
+
for (const node of document.nodes || []) {
|
|
126
|
+
/* The frozen blueprint travels with the run: whoever drives it (or reads the
|
|
127
|
+
evidence later) sees the label and description the author wrote for that step. */
|
|
128
|
+
nodes[node.id] = {
|
|
129
|
+
state: node.kind === "trigger" ? "done" : "pending",
|
|
130
|
+
attempts: 0,
|
|
131
|
+
kind: typeof node.kind === "string" ? node.kind : "action",
|
|
132
|
+
label: typeof node.label === "string" && node.label.length > 0 ? node.label : node.id,
|
|
133
|
+
description: typeof node.description === "string" ? node.description : "",
|
|
134
|
+
evidence: [],
|
|
135
|
+
};
|
|
136
|
+
if (node.kind === "trigger") {
|
|
137
|
+
nodes[node.id].evidence.push({ at: nowIso(input.now), status: "done", note: "trigger", description: nodes[node.id].description });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const createdAt = nowIso(input.now);
|
|
141
|
+
return {
|
|
142
|
+
id: input.runId,
|
|
143
|
+
sessionId: input.sessionId,
|
|
144
|
+
blueprintPath: input.blueprintPath,
|
|
145
|
+
blueprintRevision: typeof document.revision === "number" ? document.revision : 0,
|
|
146
|
+
workspaceRoot: input.workspaceRoot,
|
|
147
|
+
feature: typeof input.feature === "string" && input.feature.length > 0 ? input.feature : "(không đặt tên)",
|
|
148
|
+
status: "running",
|
|
149
|
+
createdAt,
|
|
150
|
+
updatedAt: createdAt,
|
|
151
|
+
nodes,
|
|
152
|
+
log: [{ at: createdAt, event: "run/created", note: input.feature ?? "" }],
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Persist one run atomically. */
|
|
157
|
+
export function writeRun(home, run) {
|
|
158
|
+
mkdirSync(runsDirectory(home), { recursive: true });
|
|
159
|
+
const path = runPath(home, run.id);
|
|
160
|
+
const temporary = path + ".tmp-" + process.pid;
|
|
161
|
+
writeFileSync(temporary, JSON.stringify(run, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
|
|
162
|
+
renameSync(temporary, path);
|
|
163
|
+
return path;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Read one run record, or undefined. */
|
|
167
|
+
export function readRun(home, runId) {
|
|
168
|
+
const path = runPath(home, runId);
|
|
169
|
+
if (!existsSync(path)) return undefined;
|
|
170
|
+
try {
|
|
171
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
172
|
+
} catch {
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Every run of one session, newest first. */
|
|
178
|
+
export function listRuns(home, sessionId) {
|
|
179
|
+
const directory = runsDirectory(home);
|
|
180
|
+
if (!existsSync(directory)) return [];
|
|
181
|
+
const rows = [];
|
|
182
|
+
for (const file of readdirSync(directory)) {
|
|
183
|
+
if (!file.endsWith(".json")) continue;
|
|
184
|
+
const run = readRun(home, file.slice(0, -5));
|
|
185
|
+
if (run === undefined) continue;
|
|
186
|
+
if (sessionId !== undefined && run.sessionId !== sessionId) continue;
|
|
187
|
+
rows.push(run);
|
|
188
|
+
}
|
|
189
|
+
return rows.sort((left, right) => String(right.updatedAt).localeCompare(String(left.updatedAt)));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function record(run, nodeId, entry, now) {
|
|
193
|
+
const state = run.nodes[nodeId];
|
|
194
|
+
state.evidence.push({ at: nowIso(now), ...entry });
|
|
195
|
+
run.updatedAt = nowIso(now);
|
|
196
|
+
run.log.push({ at: nowIso(now), event: "node/" + entry.status, nodeId, note: entry.note ?? "" });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Recompute the whole-run status from the node states. */
|
|
200
|
+
export function refreshRunStatus(run) {
|
|
201
|
+
const states = Object.values(run.nodes).map(node => node.state);
|
|
202
|
+
if (states.includes("running")) return "running";
|
|
203
|
+
if (states.includes("awaiting_approval")) return "awaiting_approval";
|
|
204
|
+
/* A node the engine cannot execute must surface as blocked, never as completed. */
|
|
205
|
+
if (states.includes("blocked")) return "blocked";
|
|
206
|
+
if (states.includes("pending")) return "blocked";
|
|
207
|
+
if (states.includes("failed")) return "failed";
|
|
208
|
+
return "completed";
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Execute the next eligible nodes, one at a time, persisting after each.
|
|
213
|
+
*
|
|
214
|
+
* @param run - the run record (mutated and returned).
|
|
215
|
+
* @param document - the blueprint the run was created from.
|
|
216
|
+
* @param options.cwd - workspace root every command runs in.
|
|
217
|
+
* @param options.now - injectable clock.
|
|
218
|
+
* @param options.adapters - optional override adapters, for tests.
|
|
219
|
+
*/
|
|
220
|
+
export async function advanceRun(run, document, options = {}) {
|
|
221
|
+
const now = () => (options.now instanceof Date ? options.now : new Date());
|
|
222
|
+
const executed = [];
|
|
223
|
+
if (run.status === "cancelled" || run.status === "completed" || run.status === "failed") return { run, executed };
|
|
224
|
+
for (let guard = 0; guard < 200; guard += 1) {
|
|
225
|
+
const eligible = eligibleNodes(document, run);
|
|
226
|
+
if (eligible.length === 0) break;
|
|
227
|
+
const node = eligible[0];
|
|
228
|
+
const state = run.nodes[node.id];
|
|
229
|
+
state.state = "running";
|
|
230
|
+
state.attempts += 1;
|
|
231
|
+
run.status = "running";
|
|
232
|
+
let outcome = { status: "done" };
|
|
233
|
+
if (node.kind === "approval") {
|
|
234
|
+
outcome = { status: "awaiting_approval", note: "Cần người/agent duyệt" };
|
|
235
|
+
} else if (node.kind === "gate") {
|
|
236
|
+
const gateKind = node.gate?.kind ?? "manual";
|
|
237
|
+
if (gateKind === "command" && typeof node.gate?.run === "string") {
|
|
238
|
+
const result = await runCommand(node.gate.run, { cwd: options.cwd, signal: options.signal });
|
|
239
|
+
outcome = result.exitCode === 0
|
|
240
|
+
? { status: "done", exitCode: 0, output: result.stdout }
|
|
241
|
+
: { status: "failed", exitCode: result.exitCode, output: result.stdout, error: result.stderr || result.error };
|
|
242
|
+
} else {
|
|
243
|
+
outcome = { status: "awaiting_approval", note: gateKind === "ci" ? "Xác nhận CI xanh (adapter CI ở P4)" : "Cần xác nhận" };
|
|
244
|
+
}
|
|
245
|
+
} else if (node.kind === "action") {
|
|
246
|
+
const actions = Array.isArray(node.actions) ? node.actions : [];
|
|
247
|
+
let blocked;
|
|
248
|
+
let failure;
|
|
249
|
+
const evidence = [];
|
|
250
|
+
for (const action of actions) {
|
|
251
|
+
if (!EXECUTABLE_ACTIONS.includes(action.kind)) { blocked = action.kind; break; }
|
|
252
|
+
if (action.kind === "manual") { blocked = "manual"; break; }
|
|
253
|
+
const result = await runCommand(String(action.run ?? ""), { cwd: options.cwd, signal: options.signal, timeoutMs: action.timeoutMs });
|
|
254
|
+
evidence.push({ at: nowIso(now()), status: result.exitCode === 0 ? "done" : "failed", action: action.kind, command: action.run, exitCode: result.exitCode, output: result.stdout, error: boundOutput(result.stderr || result.error || "") });
|
|
255
|
+
if (result.exitCode !== 0) { failure = evidence[evidence.length - 1]; break; }
|
|
256
|
+
}
|
|
257
|
+
for (const entry of evidence) state.evidence.push(entry);
|
|
258
|
+
if (failure !== undefined) outcome = { status: "failed", exitCode: failure.exitCode, note: "Lệnh thất bại: " + String(failure.command) };
|
|
259
|
+
else if (blocked !== undefined) outcome = { status: blocked === "manual" ? "awaiting_approval" : "blocked", note: blocked === "manual" ? "Bước thủ công cần xác nhận" : "Chưa có adapter: " + blocked };
|
|
260
|
+
else outcome = { status: "done" };
|
|
261
|
+
} else if (node.kind === "join") {
|
|
262
|
+
const mode = node.join?.mode ?? "all";
|
|
263
|
+
const states = incomingEdges(document, node.id).map(edge => run.nodes[edge.from]?.state);
|
|
264
|
+
const ok = mode === "any" ? states.includes("done") : states.length > 0 && states.every(state => state === "done");
|
|
265
|
+
outcome = ok ? { status: "done" } : { status: "failed", note: "Nhánh gộp không đạt" };
|
|
266
|
+
} else if (node.kind === "notify") {
|
|
267
|
+
outcome = { status: "done", note: "Thông báo ghi vào log (adapter ngoài ở P4)" };
|
|
268
|
+
} else if (node.kind === "rollback") {
|
|
269
|
+
const actions = Array.isArray(node.actions) ? node.actions : [];
|
|
270
|
+
const command = actions.find(action => action.kind === "command");
|
|
271
|
+
if (command === undefined) outcome = { status: "awaiting_approval", note: "Cần xác nhận hoàn tác" };
|
|
272
|
+
else {
|
|
273
|
+
const result = await runCommand(String(command.run), { cwd: options.cwd, signal: options.signal });
|
|
274
|
+
outcome = result.exitCode === 0 ? { status: "done", exitCode: 0, output: result.stdout } : { status: "failed", exitCode: result.exitCode, error: result.stderr };
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
state.state = outcome.status;
|
|
278
|
+
record(run, node.id, outcome, now());
|
|
279
|
+
executed.push({ nodeId: node.id, status: outcome.status });
|
|
280
|
+
if (outcome.status === "awaiting_approval" || outcome.status === "blocked") continue;
|
|
281
|
+
}
|
|
282
|
+
run.status = refreshRunStatus(run);
|
|
283
|
+
return { run, executed };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Approve, reject, or manually complete one node; returns the updated run. */
|
|
287
|
+
export function decideRun(run, nodeId, decision, note, now = new Date()) {
|
|
288
|
+
const state = run.nodes[nodeId];
|
|
289
|
+
if (state === undefined) return { ok: false, code: "journey/unknown-node", message: "Node " + nodeId + " is not part of this run." };
|
|
290
|
+
if (!["awaiting_approval", "blocked"].includes(state.state) && decision !== "reset") {
|
|
291
|
+
return { ok: false, code: "journey/not-decidable", message: "Node " + nodeId + " is " + state.state + "." };
|
|
292
|
+
}
|
|
293
|
+
const by = typeof note?.by === "string" ? note.by : "human";
|
|
294
|
+
if (decision === "approve") {
|
|
295
|
+
state.state = "done";
|
|
296
|
+
record(run, nodeId, { status: "done", note: note?.text ?? "Đã duyệt", by }, now);
|
|
297
|
+
} else if (decision === "reject") {
|
|
298
|
+
state.state = "failed";
|
|
299
|
+
record(run, nodeId, { status: "failed", note: note?.text ?? "Bị từ chối", by }, now);
|
|
300
|
+
} else if (decision === "retry") {
|
|
301
|
+
state.state = "pending";
|
|
302
|
+
record(run, nodeId, { status: "pending", note: note?.text ?? "Chạy lại", by }, now);
|
|
303
|
+
} else {
|
|
304
|
+
return { ok: false, code: "journey/unknown-decision", message: "Unknown decision " + String(decision) };
|
|
305
|
+
}
|
|
306
|
+
run.status = refreshRunStatus(run);
|
|
307
|
+
run.updatedAt = nowIso(now);
|
|
308
|
+
return { ok: true, run };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Cancel a run: running and pending nodes stop; finished evidence stays. */
|
|
312
|
+
export function cancelRun(run, note, now = new Date()) {
|
|
313
|
+
for (const [nodeId, state] of Object.entries(run.nodes)) {
|
|
314
|
+
if (state.state === "done" || state.state === "failed") continue;
|
|
315
|
+
state.state = "skipped";
|
|
316
|
+
record(run, nodeId, { status: "skipped", note: note?.text ?? "Đã huỷ" }, now);
|
|
317
|
+
}
|
|
318
|
+
run.status = "cancelled";
|
|
319
|
+
run.updatedAt = nowIso(now);
|
|
320
|
+
return run;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Compact status a canvas, a tool, or a chat command can print. */
|
|
324
|
+
export function summarizeRun(run) {
|
|
325
|
+
const counts = {};
|
|
326
|
+
for (const state of Object.values(run.nodes)) counts[state.state] = (counts[state.state] ?? 0) + 1;
|
|
327
|
+
return {
|
|
328
|
+
id: run.id,
|
|
329
|
+
feature: run.feature,
|
|
330
|
+
status: run.status,
|
|
331
|
+
blueprintRevision: run.blueprintRevision,
|
|
332
|
+
counts,
|
|
333
|
+
nodes: Object.entries(run.nodes).map(([nodeId, state]) => ({
|
|
334
|
+
nodeId,
|
|
335
|
+
state: state.state,
|
|
336
|
+
attempts: state.attempts,
|
|
337
|
+
kind: state.kind,
|
|
338
|
+
label: state.label,
|
|
339
|
+
description: state.description,
|
|
340
|
+
last: state.evidence[state.evidence.length - 1] ?? null,
|
|
341
|
+
})),
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
//#endregion
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** Types for the gbh journey blueprint store (see journey-store.js). */
|
|
2
|
+
|
|
3
|
+
export interface JourneyNode {
|
|
4
|
+
id: string;
|
|
5
|
+
kind: string;
|
|
6
|
+
label?: string;
|
|
7
|
+
x?: number;
|
|
8
|
+
y?: number;
|
|
9
|
+
gate?: Record<string, unknown>;
|
|
10
|
+
actions?: Record<string, unknown>[];
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface JourneyEdge {
|
|
15
|
+
id?: string;
|
|
16
|
+
from: string;
|
|
17
|
+
to: string;
|
|
18
|
+
when?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface JourneyDocument {
|
|
22
|
+
version?: number;
|
|
23
|
+
revision?: number;
|
|
24
|
+
updatedAt?: string;
|
|
25
|
+
updatedBy?: string;
|
|
26
|
+
variables?: Record<string, unknown>;
|
|
27
|
+
nodes: JourneyNode[];
|
|
28
|
+
edges: JourneyEdge[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface JourneyIssue {
|
|
32
|
+
code: string;
|
|
33
|
+
message: string;
|
|
34
|
+
nodeId?: string;
|
|
35
|
+
edgeId?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type JourneyWriteResult =
|
|
39
|
+
| { ok: true; revision: number; hash: string; path: string }
|
|
40
|
+
| { ok: false; code: string; issues?: JourneyIssue[]; current?: { revision: number; document: JourneyDocument } };
|
|
41
|
+
|
|
42
|
+
export declare const BLUEPRINT_FILE: string;
|
|
43
|
+
export declare const JOURNEY_NODE_KINDS: readonly string[];
|
|
44
|
+
export declare const JOURNEY_EDGE_WHENS: readonly string[];
|
|
45
|
+
export declare const JOURNEY_ACTION_KINDS: readonly string[];
|
|
46
|
+
export declare function canonicalJson(value: unknown): string;
|
|
47
|
+
export declare function defaultBlueprint(now?: string): JourneyDocument;
|
|
48
|
+
export declare function blueprintPathFor(workspaceRoot: string): string;
|
|
49
|
+
export declare function validateBlueprint(document: unknown): JourneyIssue[];
|
|
50
|
+
export declare function readBlueprint(workspaceRoot: string): {
|
|
51
|
+
path: string;
|
|
52
|
+
exists: boolean;
|
|
53
|
+
document?: JourneyDocument;
|
|
54
|
+
hash?: string;
|
|
55
|
+
parseError?: string;
|
|
56
|
+
};
|
|
57
|
+
export declare function writeBlueprint(
|
|
58
|
+
root: string,
|
|
59
|
+
document: unknown,
|
|
60
|
+
options?: { expectedRevision?: number; updatedBy?: string },
|
|
61
|
+
): JourneyWriteResult;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
//#region gbh journey blueprint store
|
|
2
|
+
/**
|
|
3
|
+
* Blueprint storage for the Galaxy delivery journey.
|
|
4
|
+
*
|
|
5
|
+
* One blueprint per workspace root: \`<workspace>/journey.json\`. When the workspace
|
|
6
|
+
* is a repository that file is tracked by git, so both the panel and the agent edit
|
|
7
|
+
* a reviewable document instead of hidden UI state.
|
|
8
|
+
*
|
|
9
|
+
* The host owns every filesystem touch: the browser sends a session id and a
|
|
10
|
+
* document, never a path. The workspace root is resolved from the trusted session
|
|
11
|
+
* record, and every write is compare-and-swap on the document revision plus an
|
|
12
|
+
* atomic replace, so two writers can never silently overwrite each other.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
17
|
+
|
|
18
|
+
/** Blueprint file name at the workspace root. */
|
|
19
|
+
export const BLUEPRINT_FILE = "journey.json";
|
|
20
|
+
/** Node kinds the canvas and the validator understand. */
|
|
21
|
+
export const JOURNEY_NODE_KINDS = ["trigger", "gate", "action", "approval", "join", "notify", "rollback"];
|
|
22
|
+
/** Edge conditions a branch may carry. */
|
|
23
|
+
export const JOURNEY_EDGE_WHENS = ["success", "failure", "always"];
|
|
24
|
+
|
|
25
|
+
/** Action adapters the host may execute; only declared kinds are ever run. */
|
|
26
|
+
export const JOURNEY_ACTION_KINDS = ["command", "npm", "git", "http", "ci", "mcp", "manual"];
|
|
27
|
+
|
|
28
|
+
function sha256(value) {
|
|
29
|
+
return "sha256:" + createHash("sha256").update(value).digest("hex");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Canonical JSON: sorted keys, so a hash never depends on property order. */
|
|
33
|
+
export function canonicalJson(value) {
|
|
34
|
+
if (Array.isArray(value)) return "[" + value.map(canonicalJson).join(",") + "]";
|
|
35
|
+
if (value !== null && typeof value === "object") {
|
|
36
|
+
const keys = Object.keys(value).sort();
|
|
37
|
+
return "{" + keys.map(key => JSON.stringify(key) + ":" + canonicalJson(value[key])).join(",") + "}";
|
|
38
|
+
}
|
|
39
|
+
return JSON.stringify(value ?? null);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The blueprint a workspace starts from.
|
|
44
|
+
*
|
|
45
|
+
* Every node carries a `description`: the panel shows it on the card and the agent
|
|
46
|
+
* reads it (with the label and kind) before running that step, so the copy is part of
|
|
47
|
+
* the contract, not decoration.
|
|
48
|
+
*/
|
|
49
|
+
export function defaultBlueprint(now = new Date().toISOString()) {
|
|
50
|
+
return {
|
|
51
|
+
version: 1,
|
|
52
|
+
revision: 0,
|
|
53
|
+
updatedAt: now,
|
|
54
|
+
updatedBy: "template",
|
|
55
|
+
variables: {},
|
|
56
|
+
nodes: [
|
|
57
|
+
{ id: "dev", kind: "trigger", label: "Dev xong", description: "Việc trong workspace đã xong: mã nguồn đã commit, sẵn sàng đi tiếp.", x: 120, y: 80 },
|
|
58
|
+
{ id: "ci", kind: "gate", label: "CI xanh", description: "Cổng kiểm: pipeline CI phải xanh trên nhánh main trước khi đóng gói.", x: 360, y: 80, gate: { kind: "ci", workflow: "ci.yml", ref: "main" } },
|
|
59
|
+
{ id: "uat", kind: "action", label: "UAT", description: "Đóng gói bản alpha để người dùng thử (npm dist-tag alpha).", x: 600, y: 80, actions: [{ kind: "npm", distTag: "alpha" }] },
|
|
60
|
+
{ id: "approve", kind: "approval", label: "Duyệt UAT", description: "Người duyệt xác nhận bản alpha đạt yêu cầu trước khi lên PROD.", x: 840, y: 80 },
|
|
61
|
+
{ id: "prod", kind: "action", label: "PROD", description: "Phát hành bản chính thức (npm dist-tag latest).", x: 1080, y: 80, actions: [{ kind: "npm", distTag: "latest" }] },
|
|
62
|
+
{ id: "notify", kind: "notify", label: "Thông báo", description: "Thông báo kết quả hành trình cho người theo dõi.", x: 1320, y: 80 },
|
|
63
|
+
],
|
|
64
|
+
edges: [
|
|
65
|
+
{ id: "e1", from: "dev", to: "ci", when: "always" },
|
|
66
|
+
{ id: "e2", from: "ci", to: "uat", when: "success" },
|
|
67
|
+
{ id: "e3", from: "uat", to: "approve", when: "success" },
|
|
68
|
+
{ id: "e4", from: "approve", to: "prod", when: "success" },
|
|
69
|
+
{ id: "e5", from: "prod", to: "notify", when: "success" },
|
|
70
|
+
],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Workspace root a blueprint belongs to, from a trusted session directory. */
|
|
75
|
+
export function blueprintPathFor(workspaceRoot) {
|
|
76
|
+
if (typeof workspaceRoot !== "string" || workspaceRoot.trim().length === 0) {
|
|
77
|
+
throw new Error("journey: the session has no workspace directory");
|
|
78
|
+
}
|
|
79
|
+
const root = resolve(workspaceRoot.trim());
|
|
80
|
+
const path = join(root, BLUEPRINT_FILE);
|
|
81
|
+
if (!(path === join(root, BLUEPRINT_FILE) && resolve(path).startsWith(root + sep))) {
|
|
82
|
+
throw new Error("journey: refusing a blueprint outside the workspace root");
|
|
83
|
+
}
|
|
84
|
+
return path;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Structural validation shared by the panel route and the agent tools. */
|
|
88
|
+
export function validateBlueprint(document) {
|
|
89
|
+
const issues = [];
|
|
90
|
+
if (document === null || typeof document !== "object" || Array.isArray(document)) {
|
|
91
|
+
return [{ code: "document", message: "Blueprint must be a JSON object." }];
|
|
92
|
+
}
|
|
93
|
+
if (!Array.isArray(document.nodes) || document.nodes.length === 0) {
|
|
94
|
+
issues.push({ code: "nodes", message: "Blueprint needs at least one node." });
|
|
95
|
+
}
|
|
96
|
+
const ids = new Set();
|
|
97
|
+
for (const node of Array.isArray(document.nodes) ? document.nodes : []) {
|
|
98
|
+
if (node === null || typeof node !== "object") {
|
|
99
|
+
issues.push({ code: "node", message: "Every node must be an object." });
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (typeof node.id !== "string" || node.id.length === 0) issues.push({ code: "node.id", message: "Node id is required." });
|
|
103
|
+
else if (ids.has(node.id)) issues.push({ code: "node.id", message: "Duplicate node id: " + node.id, nodeId: node.id });
|
|
104
|
+
else ids.add(node.id);
|
|
105
|
+
if (!JOURNEY_NODE_KINDS.includes(node.kind)) {
|
|
106
|
+
issues.push({ code: "node.kind", message: "Unknown node kind: " + String(node.kind), nodeId: node.id });
|
|
107
|
+
}
|
|
108
|
+
if (node.kind === "action" && (!Array.isArray(node.actions) || node.actions.length === 0)) {
|
|
109
|
+
issues.push({ code: "node.actions", message: "An action node needs at least one action.", nodeId: node.id });
|
|
110
|
+
}
|
|
111
|
+
for (const action of Array.isArray(node.actions) ? node.actions : []) {
|
|
112
|
+
if (!JOURNEY_ACTION_KINDS.includes(action?.kind)) {
|
|
113
|
+
issues.push({ code: "action.kind", message: "Unknown action kind: " + String(action?.kind), nodeId: node.id });
|
|
114
|
+
}
|
|
115
|
+
if (typeof action?.secret === "string") {
|
|
116
|
+
issues.push({ code: "action.secret", message: "Secrets must be referenced as secretRef, never inlined.", nodeId: node.id });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const edge of Array.isArray(document.edges) ? document.edges : []) {
|
|
121
|
+
if (!ids.has(edge?.from) || !ids.has(edge?.to)) {
|
|
122
|
+
issues.push({ code: "edge.endpoint", message: "Edge refers to a missing node.", edgeId: edge?.id });
|
|
123
|
+
}
|
|
124
|
+
if (edge?.from === edge?.to) issues.push({ code: "edge.loop", message: "Edge cannot loop on one node.", edgeId: edge?.id });
|
|
125
|
+
if (edge?.when !== undefined && !JOURNEY_EDGE_WHENS.includes(edge.when)) {
|
|
126
|
+
issues.push({ code: "edge.when", message: "Unknown edge condition: " + String(edge.when), edgeId: edge?.id });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return issues;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Read a workspace blueprint; a missing file reports the default document. */
|
|
133
|
+
export function readBlueprint(workspaceRoot) {
|
|
134
|
+
const path = blueprintPathFor(workspaceRoot);
|
|
135
|
+
if (!existsSync(path)) {
|
|
136
|
+
return { path, exists: false, document: defaultBlueprint(), hash: undefined };
|
|
137
|
+
}
|
|
138
|
+
const raw = readFileSync(path, "utf8");
|
|
139
|
+
let document;
|
|
140
|
+
try {
|
|
141
|
+
document = JSON.parse(raw);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
return { path, exists: true, document: undefined, hash: sha256(raw), parseError: error instanceof Error ? error.message : String(error) };
|
|
144
|
+
}
|
|
145
|
+
return { path, exists: true, document, hash: sha256(canonicalJson(document)) };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Write a workspace blueprint under compare-and-swap.
|
|
150
|
+
*
|
|
151
|
+
* @param root - workspace root from the trusted session record.
|
|
152
|
+
* @param document - the blueprint the caller edited.
|
|
153
|
+
* @param options.expectedRevision - revision the caller read; a mismatch refuses.
|
|
154
|
+
* @param options.updatedBy - "human" for the panel, "agent" for tooling.
|
|
155
|
+
* @returns the stored revision and hash.
|
|
156
|
+
*/
|
|
157
|
+
export function writeBlueprint(root, document, options = {}) {
|
|
158
|
+
const issues = validateBlueprint(document);
|
|
159
|
+
if (issues.length > 0) return { ok: false, code: "journey/invalid", issues };
|
|
160
|
+
const path = blueprintPathFor(root);
|
|
161
|
+
const current = readBlueprint(root);
|
|
162
|
+
const expected = options.expectedRevision;
|
|
163
|
+
if (typeof expected === "number" && current.exists && current.document !== undefined) {
|
|
164
|
+
const live = typeof current.document.revision === "number" ? current.document.revision : 0;
|
|
165
|
+
if (live !== expected) {
|
|
166
|
+
return { ok: false, code: "journey/conflict", current: { revision: live, document: current.document } };
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const revision = (current.exists && typeof current.document?.revision === "number" ? current.document.revision : 0) + 1;
|
|
170
|
+
const stored = {
|
|
171
|
+
...document,
|
|
172
|
+
version: typeof document.version === "number" ? document.version : 1,
|
|
173
|
+
revision,
|
|
174
|
+
updatedAt: new Date().toISOString(),
|
|
175
|
+
updatedBy: typeof options.updatedBy === "string" ? options.updatedBy : "human",
|
|
176
|
+
};
|
|
177
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
178
|
+
const temporary = path + ".tmp-" + process.pid;
|
|
179
|
+
writeFileSync(temporary, JSON.stringify(stored, null, 2) + "\n", { encoding: "utf8", mode: 0o644 });
|
|
180
|
+
renameSync(temporary, path);
|
|
181
|
+
return { ok: true, revision, hash: sha256(canonicalJson(stored)), path };
|
|
182
|
+
}
|
|
183
|
+
//#endregion
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Types for the gbh session-store maintenance module (see session-store.js). */
|
|
2
|
+
|
|
3
|
+
/** One stored session artifact found under `<home>/sessions`. */
|
|
4
|
+
export interface StoredSessionRow {
|
|
5
|
+
id: string;
|
|
6
|
+
directory: string;
|
|
7
|
+
cwdSlug: string;
|
|
8
|
+
bytes: number;
|
|
9
|
+
updatedAt: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Outcome of one delete. */
|
|
13
|
+
export interface SessionDeleteResult {
|
|
14
|
+
id: string;
|
|
15
|
+
bytes: number;
|
|
16
|
+
directories: string[];
|
|
17
|
+
projectionCache: boolean;
|
|
18
|
+
trashedTo?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One deleted-session tombstone. */
|
|
22
|
+
export interface SessionTombstone {
|
|
23
|
+
id: string;
|
|
24
|
+
deletedAt: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Outcome of a tombstone sweep. */
|
|
28
|
+
export interface TombstoneSweepReport {
|
|
29
|
+
resurrected: string[];
|
|
30
|
+
pruned: string[];
|
|
31
|
+
kept: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export declare const DELETED_INDEX_NAME: string;
|
|
35
|
+
export declare function resolveHome(explicit?: string): string;
|
|
36
|
+
export declare function sessionsRoot(home: string): string;
|
|
37
|
+
export declare function projectionCachePath(home: string, sessionId: string): string;
|
|
38
|
+
export declare function deletedIndexPath(home: string): string;
|
|
39
|
+
export declare function trashRoot(home: string): string;
|
|
40
|
+
export declare function isSessionId(value: unknown): value is string;
|
|
41
|
+
export declare function findSessionDirectories(home: string, sessionId: string): string[];
|
|
42
|
+
export declare function listStoredSessions(home: string): StoredSessionRow[];
|
|
43
|
+
export declare function readTombstones(home: string): SessionTombstone[];
|
|
44
|
+
export declare function recordTombstone(home: string, sessionId: string, deletedAt?: string): number;
|
|
45
|
+
export declare function deleteSession(
|
|
46
|
+
home: string,
|
|
47
|
+
sessionId: string,
|
|
48
|
+
options?: { trash?: boolean; now?: Date },
|
|
49
|
+
): SessionDeleteResult;
|
|
50
|
+
export declare function sweepTombstones(
|
|
51
|
+
home: string,
|
|
52
|
+
options?: { maxAgeDays?: number; now?: Date },
|
|
53
|
+
): TombstoneSweepReport;
|
|
54
|
+
export declare function formatBytes(bytes: number): string;
|