@galaxy-stack/blackhole-cli 2.0.1 → 2.0.3
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/dist/application.d.ts.map +1 -1
- package/dist/application.js +3 -0
- package/dist/application.js.map +1 -1
- package/dist/cli.js +24 -0
- package/dist/cli.js.map +1 -1
- package/dist/commands.d.ts.map +1 -1
- package/dist/commands.js +2 -0
- package/dist/commands.js.map +1 -1
- package/dist/config-command.d.ts +35 -0
- package/dist/config-command.d.ts.map +1 -0
- package/dist/config-command.js +273 -0
- package/dist/config-command.js.map +1 -0
- package/dist/flow.d.ts.map +1 -1
- package/dist/flow.js +14 -3
- package/dist/flow.js.map +1 -1
- package/dist/info.d.ts +21 -0
- package/dist/info.d.ts.map +1 -0
- package/dist/info.js +33 -0
- package/dist/info.js.map +1 -0
- package/dist/logs.d.ts.map +1 -1
- package/dist/logs.js +10 -2
- package/dist/logs.js.map +1 -1
- package/dist/manual-config.d.ts +17 -0
- package/dist/manual-config.d.ts.map +1 -1
- package/dist/manual-config.js +35 -0
- package/dist/manual-config.js.map +1 -1
- package/dist/options.d.ts +2 -2
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +5 -1
- package/dist/options.js.map +1 -1
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +39 -1
- package/dist/tui.js.map +1 -1
- package/dist/update.d.ts +45 -0
- package/dist/update.d.ts.map +1 -0
- package/dist/update.js +158 -0
- package/dist/update.js.map +1 -0
- package/dist/web/web.d.ts.map +1 -1
- package/dist/web/web.js +16 -5
- package/dist/web/web.js.map +1 -1
- package/package.json +4 -3
- package/skills/galaxy-ui/SKILL.md +18 -0
- package/skills/orbit-framework/SKILL.md +18 -0
- package/web/brand/app-icon-192.png +0 -0
- package/web/brand/app-icon-512.png +0 -0
- package/web/brand/client.template.js +581 -79
- package/web/brand/dsh-locale-keys.json +2020 -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 +2303 -88
- package/web/brand/lib/favicon.js +1 -1
- package/web/brand/lib/index.js +618 -18
- package/web/brand/lib/journey-host.js +282 -0
- package/web/brand/lib/journey-run.d.ts +66 -0
- package/web/brand/lib/journey-run.js +315 -0
- package/web/brand/lib/journey-store.d.ts +61 -0
- package/web/brand/lib/journey-store.js +177 -0
- package/web/brand/logo.png +0 -0
- package/web/brand/logo.svg +20 -0
- package/web/brand/panel/journey-panel.js +884 -0
- package/web/brand/vi.locales.json +838 -8
- package/web/brand/zalo.jpg +0 -0
- package/web/patches/gbh-web.patch.yml +51 -2
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
//#region gbh journey host: routes, agent tools, chat command
|
|
2
|
+
/**
|
|
3
|
+
* Host side of the Galaxy delivery journey: the browser route the panel drives,
|
|
4
|
+
* the agent tools that edit and run the same blueprint, and the human /journey
|
|
5
|
+
* command. All three share one engine, one validator, and one revision rule, so
|
|
6
|
+
* a human edit and an agent edit are the same kind of write.
|
|
7
|
+
*/
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { blueprintPathFor, readBlueprint, validateBlueprint, writeBlueprint } from "./journey-store.js";
|
|
10
|
+
import { advanceRun, cancelRun, createRun, decideRun, listRuns, readRun, summarizeRun, writeRun } from "./journey-run.js";
|
|
11
|
+
import { resolveHome } from "./session-store.js";
|
|
12
|
+
|
|
13
|
+
/** The tool result text block. */
|
|
14
|
+
function toolText(value) {
|
|
15
|
+
return [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** One run id that stays unique across restarts. */
|
|
19
|
+
function newRunId() {
|
|
20
|
+
return "run-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** In-process workspace root of an agent session; never taken from a request body. */
|
|
24
|
+
export function rootOfSession(session) {
|
|
25
|
+
const cwd = session?.header?.cwd;
|
|
26
|
+
return typeof cwd === "string" && cwd.length > 0 ? cwd : undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Load the blueprint a run works against, or an error body. */
|
|
30
|
+
function loadBlueprint(sessionWorkspaceRoot, ctx, sessionId) {
|
|
31
|
+
return sessionWorkspaceRoot(ctx, sessionId).then(root => {
|
|
32
|
+
if (root === undefined) {
|
|
33
|
+
return { error: { status: 409, body: { ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." } } };
|
|
34
|
+
}
|
|
35
|
+
const blueprint = readBlueprint(root);
|
|
36
|
+
if (blueprint.document === undefined) {
|
|
37
|
+
return { error: { status: 422, body: { ok: false, code: "journey/unparsable", message: "journey.json is not valid JSON." } } };
|
|
38
|
+
}
|
|
39
|
+
return { root: root, blueprint: blueprint };
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Start a run for the blueprint as it exists right now. */
|
|
44
|
+
export async function startJourneyRun(host, sessionId, feature) {
|
|
45
|
+
const home = resolveHome();
|
|
46
|
+
const context = await loadBlueprint(host.sessionWorkspaceRoot, host.ctx, sessionId);
|
|
47
|
+
if (context.error !== undefined) return context.error;
|
|
48
|
+
const document = context.blueprint.document;
|
|
49
|
+
const issues = validateBlueprint(document);
|
|
50
|
+
if (issues.length > 0) return { status: 422, body: { ok: false, code: "journey/invalid", issues: issues } };
|
|
51
|
+
const run = createRun({
|
|
52
|
+
runId: newRunId(),
|
|
53
|
+
sessionId: sessionId,
|
|
54
|
+
blueprintPath: context.blueprint.path,
|
|
55
|
+
workspaceRoot: context.root,
|
|
56
|
+
document: document,
|
|
57
|
+
feature: typeof feature === "string" && feature.length > 0 ? feature : undefined,
|
|
58
|
+
});
|
|
59
|
+
const advanced = await advanceRun(run, document, { cwd: context.root });
|
|
60
|
+
writeRun(home, advanced.run);
|
|
61
|
+
return { status: 200, body: { ok: true, run: summarizeRun(advanced.run), executed: advanced.executed } };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Advance, decide, cancel, list, or read a run. */
|
|
65
|
+
export async function continueJourneyRun(host, sessionId, payload) {
|
|
66
|
+
const home = resolveHome();
|
|
67
|
+
const op = typeof payload?.op === "string" ? payload.op : "advance";
|
|
68
|
+
if (op === "list") {
|
|
69
|
+
return { status: 200, body: { ok: true, runs: listRuns(home, sessionId).map(run => summarizeRun(run)) } };
|
|
70
|
+
}
|
|
71
|
+
const runId = typeof payload?.runId === "string" ? payload.runId : "";
|
|
72
|
+
if (runId.length === 0) {
|
|
73
|
+
return { status: 400, body: { ok: false, code: "invalid-request", message: "runId is required." } };
|
|
74
|
+
}
|
|
75
|
+
const run = readRun(home, runId);
|
|
76
|
+
if (run === undefined || run.sessionId !== sessionId) {
|
|
77
|
+
return { status: 404, body: { ok: false, code: "journey/unknown-run", message: "Run " + runId + " is not part of this session." } };
|
|
78
|
+
}
|
|
79
|
+
if (op === "status") return { status: 200, body: { ok: true, run: summarizeRun(run) } };
|
|
80
|
+
if (op === "cancel") {
|
|
81
|
+
cancelRun(run, { text: typeof payload?.note === "string" ? payload.note : undefined });
|
|
82
|
+
writeRun(home, run);
|
|
83
|
+
return { status: 200, body: { ok: true, run: summarizeRun(run) } };
|
|
84
|
+
}
|
|
85
|
+
if (op === "decide") {
|
|
86
|
+
const decision = typeof payload?.decision === "string" ? payload.decision : "";
|
|
87
|
+
const decided = decideRun(run, String(payload?.nodeId ?? ""), decision, {
|
|
88
|
+
text: typeof payload?.note === "string" ? payload.note : undefined,
|
|
89
|
+
by: payload?.updatedBy === "agent" ? "agent" : "human",
|
|
90
|
+
});
|
|
91
|
+
if (decided.ok !== true) return { status: 409, body: { ok: false, code: decided.code, message: decided.message } };
|
|
92
|
+
}
|
|
93
|
+
const context = await loadBlueprint(host.sessionWorkspaceRoot, host.ctx, sessionId);
|
|
94
|
+
if (context.error !== undefined) return context.error;
|
|
95
|
+
/* decideRun mutated the in-memory record; the file write below persists it. */
|
|
96
|
+
const advanced = await advanceRun(run, context.blueprint.document, { cwd: context.root });
|
|
97
|
+
writeRun(home, advanced.run);
|
|
98
|
+
return { status: 200, body: { ok: true, run: summarizeRun(advanced.run), executed: advanced.executed } };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Register the run route the panel drives. */
|
|
102
|
+
export function registerJourneyRunRoutes(host, connectionCtx) {
|
|
103
|
+
const ctx = host.ctx;
|
|
104
|
+
connectionCtx.connection.fetch.register({
|
|
105
|
+
path: "/api/galaxy/journey.run",
|
|
106
|
+
methods: ["GET", "HEAD", "POST"],
|
|
107
|
+
requestBody: "buffered",
|
|
108
|
+
fetch: async request => {
|
|
109
|
+
if (request.method !== "POST") {
|
|
110
|
+
const url = new URL(request.url);
|
|
111
|
+
const sessionId = url.searchParams.get("sessionId") ?? "";
|
|
112
|
+
const runId = url.searchParams.get("runId");
|
|
113
|
+
const home = resolveHome();
|
|
114
|
+
const body = runId === null
|
|
115
|
+
? { ok: true, runs: listRuns(home, sessionId).map(run => summarizeRun(run)) }
|
|
116
|
+
: (() => {
|
|
117
|
+
const run = readRun(home, runId);
|
|
118
|
+
if (run === undefined || run.sessionId !== sessionId) {
|
|
119
|
+
return { ok: false, code: "journey/unknown-run", message: "Run " + runId + " is not part of this session." };
|
|
120
|
+
}
|
|
121
|
+
return { ok: true, run: summarizeRun(run) };
|
|
122
|
+
})();
|
|
123
|
+
const response = host.jsonResponse(body, body.ok === true ? 200 : 404);
|
|
124
|
+
if (request.method === "GET") return response;
|
|
125
|
+
await response.body?.cancel();
|
|
126
|
+
return new Response(null, { status: response.status, headers: response.headers });
|
|
127
|
+
}
|
|
128
|
+
let payload;
|
|
129
|
+
try {
|
|
130
|
+
payload = await request.json();
|
|
131
|
+
} catch {
|
|
132
|
+
return host.jsonResponse({ ok: false, code: "invalid-request", message: "Expected a JSON body." }, 400);
|
|
133
|
+
}
|
|
134
|
+
const sessionId = typeof payload?.sessionId === "string" ? payload.sessionId : "";
|
|
135
|
+
const op = typeof payload?.op === "string" ? payload.op : "advance";
|
|
136
|
+
const result = op === "start" ? await startJourneyRun(host, sessionId, payload?.feature) : await continueJourneyRun(host, sessionId, payload);
|
|
137
|
+
if (result.status === 200 && result.body.run !== undefined) {
|
|
138
|
+
host.appendJourneyAudit({
|
|
139
|
+
at: new Date().toISOString(),
|
|
140
|
+
sessionId: sessionId,
|
|
141
|
+
runId: result.body.run.id,
|
|
142
|
+
event: "run/" + op,
|
|
143
|
+
by: payload?.updatedBy === "agent" ? "agent" : "human",
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return host.jsonResponse(result.body, result.status);
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Agent-facing journey tools: read, write under CAS, and drive the run. */
|
|
152
|
+
function journeyToolDefinitions(host) {
|
|
153
|
+
const objectSchema = (properties, required) => ({ type: "object", additionalProperties: false, properties: properties, required: required });
|
|
154
|
+
const textOutput = { schema: { type: "object", additionalProperties: true }, render: (args, value) => toolText(value) };
|
|
155
|
+
const workspaceRootOf = async sessionId => host.sessionWorkspaceRoot(host.ctx, sessionId);
|
|
156
|
+
return [
|
|
157
|
+
{
|
|
158
|
+
name: "journey_get",
|
|
159
|
+
description: "Read the workspace delivery-journey blueprint (journey.json): nodes, edges, revision, and validation issues. Read it before journey_set so the revision you send is current.",
|
|
160
|
+
parameters: objectSchema({ sessionId: { type: "string", description: "Session whose workspace holds the blueprint." } }, ["sessionId"]),
|
|
161
|
+
output: textOutput,
|
|
162
|
+
execute: async args => {
|
|
163
|
+
const root = await workspaceRootOf(String(args.sessionId ?? ""));
|
|
164
|
+
if (root === undefined) return { ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." };
|
|
165
|
+
const blueprint = readBlueprint(root);
|
|
166
|
+
return {
|
|
167
|
+
ok: blueprint.parseError === undefined,
|
|
168
|
+
path: blueprint.path,
|
|
169
|
+
exists: blueprint.exists,
|
|
170
|
+
revision: typeof blueprint.document?.revision === "number" ? blueprint.document.revision : 0,
|
|
171
|
+
document: blueprint.document,
|
|
172
|
+
issues: blueprint.document === undefined ? [] : validateBlueprint(blueprint.document),
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
{
|
|
177
|
+
name: "journey_set",
|
|
178
|
+
description: "Replace the workspace journey blueprint after validating it. Send the revision returned by journey_get as expectedRevision; on a race the call fails with journey/conflict plus the current document instead of overwriting it.",
|
|
179
|
+
parameters: objectSchema({
|
|
180
|
+
sessionId: { type: "string", description: "Session whose workspace holds the blueprint." },
|
|
181
|
+
document: { type: "object", description: "Full blueprint document with nodes[] and edges[]." },
|
|
182
|
+
expectedRevision: { type: "number", description: "Revision last read with journey_get." },
|
|
183
|
+
}, ["sessionId", "document", "expectedRevision"]),
|
|
184
|
+
output: textOutput,
|
|
185
|
+
execute: async args => {
|
|
186
|
+
const root = await workspaceRootOf(String(args.sessionId ?? ""));
|
|
187
|
+
if (root === undefined) return { ok: false, code: "journey/no-workspace", message: "This session has no workspace directory." };
|
|
188
|
+
const result = writeBlueprint(root, args.document, { expectedRevision: Number(args.expectedRevision ?? 0), updatedBy: "agent" });
|
|
189
|
+
if (result.ok === true) {
|
|
190
|
+
host.appendJourneyAudit({ at: new Date().toISOString(), sessionId: String(args.sessionId ?? ""), path: result.path, revision: result.revision, hash: result.hash, updatedBy: "agent" });
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
name: "journey_run",
|
|
197
|
+
description: "Drive the delivery run of this workspace: op=start begins a run for a feature, op=advance executes the next runnable nodes, op=status and op=list read progress, op=decide approves, rejects, or retries a waiting node, op=cancel stops the run. Command actions execute in the workspace root.",
|
|
198
|
+
parameters: objectSchema({
|
|
199
|
+
sessionId: { type: "string", description: "Session whose workspace holds the blueprint." },
|
|
200
|
+
op: { type: "string", description: "start | advance | status | list | decide | cancel" },
|
|
201
|
+
runId: { type: "string", description: "Run to act on; required for every op except start and list." },
|
|
202
|
+
feature: { type: "string", description: "Feature label for op=start." },
|
|
203
|
+
nodeId: { type: "string", description: "Node to decide, for op=decide." },
|
|
204
|
+
decision: { type: "string", description: "approve | reject | retry, for op=decide." },
|
|
205
|
+
note: { type: "string", description: "Free-text note recorded with the decision." },
|
|
206
|
+
}, ["sessionId", "op"]),
|
|
207
|
+
output: textOutput,
|
|
208
|
+
execute: async args => {
|
|
209
|
+
const sessionId = String(args.sessionId ?? "");
|
|
210
|
+
const op = String(args.op ?? "");
|
|
211
|
+
const payload = {
|
|
212
|
+
op: op,
|
|
213
|
+
runId: typeof args.runId === "string" ? args.runId : "",
|
|
214
|
+
nodeId: typeof args.nodeId === "string" ? args.nodeId : "",
|
|
215
|
+
decision: typeof args.decision === "string" ? args.decision : "",
|
|
216
|
+
note: typeof args.note === "string" ? args.note : "",
|
|
217
|
+
updatedBy: "agent",
|
|
218
|
+
};
|
|
219
|
+
const result = op === "start"
|
|
220
|
+
? await startJourneyRun(host, sessionId, typeof args.feature === "string" ? args.feature : undefined)
|
|
221
|
+
: await continueJourneyRun(host, sessionId, payload);
|
|
222
|
+
return result.body;
|
|
223
|
+
},
|
|
224
|
+
},
|
|
225
|
+
];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Register the agent tools once the tool registry is available. */
|
|
229
|
+
export function registerJourneyTools(host) {
|
|
230
|
+
host.ctx.inject(["tools"], scope => {
|
|
231
|
+
for (const definition of journeyToolDefinitions(host)) {
|
|
232
|
+
try {
|
|
233
|
+
scope.tools.register(definition);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
console.warn("gbh: journey tool " + definition.name + " was not registered: " + (error instanceof Error ? error.message : String(error)));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Register the human /journey command: print the blueprint and run state in chat. */
|
|
242
|
+
export function registerJourneyCommand(host) {
|
|
243
|
+
host.ctx.inject(["commands"], scope => {
|
|
244
|
+
scope.commands.register({
|
|
245
|
+
name: "journey",
|
|
246
|
+
description: "show the delivery journey blueprint and the current run",
|
|
247
|
+
input: { hint: "[status]" },
|
|
248
|
+
recordInput: false,
|
|
249
|
+
handler: async invocation => {
|
|
250
|
+
const session = invocation?.agent?.session;
|
|
251
|
+
const root = rootOfSession(session);
|
|
252
|
+
if (root === undefined) return { kind: "error", text: "Phiên này chưa có workspace." };
|
|
253
|
+
const blueprint = readBlueprint(root);
|
|
254
|
+
const issues = blueprint.document === undefined ? [] : validateBlueprint(blueprint.document);
|
|
255
|
+
const runs = listRuns(resolveHome(), session.id);
|
|
256
|
+
const active = runs.find(run => run.status !== "completed" && run.status !== "cancelled");
|
|
257
|
+
const lines = [
|
|
258
|
+
"Hành trình: " + blueprint.path + " (rev " + String(blueprint.document?.revision ?? 0) + (blueprint.exists ? "" : ", chưa ghi ra file") + ")",
|
|
259
|
+
"Node: " + String((blueprint.document?.nodes ?? []).length) + " · Edge: " + String((blueprint.document?.edges ?? []).length) + (issues.length > 0 ? " · " + String(issues.length) + " lỗi validate" : ""),
|
|
260
|
+
];
|
|
261
|
+
if (active !== undefined) {
|
|
262
|
+
const summary = summarizeRun(active);
|
|
263
|
+
lines.push("Run " + summary.id + " (" + summary.status + ") — " + Object.entries(summary.counts).map(entry => entry[0] + " " + String(entry[1])).join(", "));
|
|
264
|
+
for (const node of summary.nodes.filter(item => item.state === "awaiting_approval" || item.state === "blocked")) {
|
|
265
|
+
lines.push(" • " + node.nodeId + ": " + node.state + " — " + String(node.last?.note ?? ""));
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
lines.push("Chưa có run nào đang chạy. Mở tab Hành trình để chạy.");
|
|
269
|
+
}
|
|
270
|
+
return { kind: "success", text: lines.join("\n") };
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Wire every journey surface a host plugin needs. */
|
|
277
|
+
export function registerJourneyHost(host) {
|
|
278
|
+
host.ctx.inject(["connection"], connectionCtx => registerJourneyRunRoutes(host, connectionCtx));
|
|
279
|
+
registerJourneyTools(host);
|
|
280
|
+
registerJourneyCommand(host);
|
|
281
|
+
}
|
|
282
|
+
//#endregion
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Types for the gbh journey run engine (see journey-run.js). */
|
|
2
|
+
|
|
3
|
+
export interface JourneyRunNodeState {
|
|
4
|
+
state: string;
|
|
5
|
+
attempts: number;
|
|
6
|
+
evidence: Record<string, unknown>[];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface JourneyRun {
|
|
10
|
+
id: string;
|
|
11
|
+
sessionId: string;
|
|
12
|
+
blueprintPath: string;
|
|
13
|
+
blueprintRevision: number;
|
|
14
|
+
workspaceRoot: string;
|
|
15
|
+
feature: string;
|
|
16
|
+
status: string;
|
|
17
|
+
createdAt: string;
|
|
18
|
+
updatedAt: string;
|
|
19
|
+
nodes: Record<string, JourneyRunNodeState>;
|
|
20
|
+
log: Record<string, unknown>[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export declare const JOURNEY_RUN_STATES: readonly string[];
|
|
24
|
+
export declare const JOURNEY_RUN_STATUSES: readonly string[];
|
|
25
|
+
export declare function runsDirectory(home: string): string;
|
|
26
|
+
export declare function runPath(home: string, runId: string): string;
|
|
27
|
+
export declare function edgeIsActive(edge: { when?: string }, sourceState: string): boolean;
|
|
28
|
+
export declare function eligibleNodes(document: unknown, run: JourneyRun): Record<string, unknown>[];
|
|
29
|
+
export declare function runCommand(
|
|
30
|
+
command: string,
|
|
31
|
+
options?: { cwd?: string; timeoutMs?: number; signal?: AbortSignal; env?: Record<string, string> },
|
|
32
|
+
): Promise<{ exitCode: number | null; stdout: string; stderr: string; error?: string }>;
|
|
33
|
+
export declare function createRun(input: {
|
|
34
|
+
runId: string;
|
|
35
|
+
sessionId: string;
|
|
36
|
+
blueprintPath: string;
|
|
37
|
+
workspaceRoot: string;
|
|
38
|
+
document: { nodes?: Record<string, unknown>[]; revision?: number };
|
|
39
|
+
feature?: string;
|
|
40
|
+
now?: Date;
|
|
41
|
+
}): JourneyRun;
|
|
42
|
+
export declare function writeRun(home: string, run: JourneyRun): string;
|
|
43
|
+
export declare function readRun(home: string, runId: string): JourneyRun | undefined;
|
|
44
|
+
export declare function listRuns(home: string, sessionId?: string): JourneyRun[];
|
|
45
|
+
export declare function refreshRunStatus(run: JourneyRun): string;
|
|
46
|
+
export declare function advanceRun(
|
|
47
|
+
run: JourneyRun,
|
|
48
|
+
document: unknown,
|
|
49
|
+
options?: { cwd?: string; now?: Date; signal?: AbortSignal },
|
|
50
|
+
): Promise<{ run: JourneyRun; executed: { nodeId: string; status: string }[] }>;
|
|
51
|
+
export declare function decideRun(
|
|
52
|
+
run: JourneyRun,
|
|
53
|
+
nodeId: string,
|
|
54
|
+
decision: "approve" | "reject" | "retry",
|
|
55
|
+
note?: { text?: string; by?: string },
|
|
56
|
+
now?: Date,
|
|
57
|
+
): { ok: true; run: JourneyRun } | { ok: false; code: string; message: string };
|
|
58
|
+
export declare function cancelRun(run: JourneyRun, note?: { text?: string }, now?: Date): JourneyRun;
|
|
59
|
+
export declare function summarizeRun(run: JourneyRun): {
|
|
60
|
+
id: string;
|
|
61
|
+
feature: string;
|
|
62
|
+
status: string;
|
|
63
|
+
blueprintRevision: number;
|
|
64
|
+
counts: Record<string, number>;
|
|
65
|
+
nodes: { nodeId: string; state: string; attempts: number; last: Record<string, unknown> | null }[];
|
|
66
|
+
};
|
|
@@ -0,0 +1,315 @@
|
|
|
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
|
+
/** Run one shell command in the workspace, bounded and cancellable. */
|
|
75
|
+
export function runCommand(command, options = {}) {
|
|
76
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : DEFAULT_COMMAND_TIMEOUT_MS;
|
|
77
|
+
return new Promise(resolve => {
|
|
78
|
+
const child = spawn("/bin/sh", ["-c", command], {
|
|
79
|
+
cwd: options.cwd,
|
|
80
|
+
env: { ...process.env, ...(options.env || {}) },
|
|
81
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
82
|
+
});
|
|
83
|
+
let stdout = "";
|
|
84
|
+
let stderr = "";
|
|
85
|
+
let settled = false;
|
|
86
|
+
const timer = setTimeout(() => {
|
|
87
|
+
if (settled) return;
|
|
88
|
+
try { child.kill("SIGKILL"); } catch { /* already gone */ }
|
|
89
|
+
}, timeoutMs);
|
|
90
|
+
const finish = result => {
|
|
91
|
+
if (settled) return;
|
|
92
|
+
settled = true;
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
resolve(result);
|
|
95
|
+
};
|
|
96
|
+
child.stdout?.on("data", chunk => { stdout += chunk.toString("utf8"); });
|
|
97
|
+
child.stderr?.on("data", chunk => { stderr += chunk.toString("utf8"); });
|
|
98
|
+
child.on("error", error => finish({ exitCode: null, error: String(error), stdout, stderr }));
|
|
99
|
+
child.on("close", code => finish({ exitCode: code, stdout: boundOutput(stdout), stderr: boundOutput(stderr) }));
|
|
100
|
+
if (options.signal !== undefined) {
|
|
101
|
+
options.signal.addEventListener("abort", () => {
|
|
102
|
+
try { child.kill("SIGTERM"); } catch { /* already gone */ }
|
|
103
|
+
finish({ exitCode: null, error: "cancelled", stdout, stderr });
|
|
104
|
+
}, { once: true });
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Create one run for a blueprint; triggers start done so the first real node can run. */
|
|
110
|
+
export function createRun(input) {
|
|
111
|
+
const document = input.document;
|
|
112
|
+
const nodes = {};
|
|
113
|
+
for (const node of document.nodes || []) {
|
|
114
|
+
nodes[node.id] = { state: node.kind === "trigger" ? "done" : "pending", attempts: 0, evidence: [] };
|
|
115
|
+
if (node.kind === "trigger") {
|
|
116
|
+
nodes[node.id].evidence.push({ at: nowIso(input.now), status: "done", note: "trigger" });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const createdAt = nowIso(input.now);
|
|
120
|
+
return {
|
|
121
|
+
id: input.runId,
|
|
122
|
+
sessionId: input.sessionId,
|
|
123
|
+
blueprintPath: input.blueprintPath,
|
|
124
|
+
blueprintRevision: typeof document.revision === "number" ? document.revision : 0,
|
|
125
|
+
workspaceRoot: input.workspaceRoot,
|
|
126
|
+
feature: typeof input.feature === "string" && input.feature.length > 0 ? input.feature : "(không đặt tên)",
|
|
127
|
+
status: "running",
|
|
128
|
+
createdAt,
|
|
129
|
+
updatedAt: createdAt,
|
|
130
|
+
nodes,
|
|
131
|
+
log: [{ at: createdAt, event: "run/created", note: input.feature ?? "" }],
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Persist one run atomically. */
|
|
136
|
+
export function writeRun(home, run) {
|
|
137
|
+
mkdirSync(runsDirectory(home), { recursive: true });
|
|
138
|
+
const path = runPath(home, run.id);
|
|
139
|
+
const temporary = path + ".tmp-" + process.pid;
|
|
140
|
+
writeFileSync(temporary, JSON.stringify(run, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
|
|
141
|
+
renameSync(temporary, path);
|
|
142
|
+
return path;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Read one run record, or undefined. */
|
|
146
|
+
export function readRun(home, runId) {
|
|
147
|
+
const path = runPath(home, runId);
|
|
148
|
+
if (!existsSync(path)) return undefined;
|
|
149
|
+
try {
|
|
150
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
151
|
+
} catch {
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Every run of one session, newest first. */
|
|
157
|
+
export function listRuns(home, sessionId) {
|
|
158
|
+
const directory = runsDirectory(home);
|
|
159
|
+
if (!existsSync(directory)) return [];
|
|
160
|
+
const rows = [];
|
|
161
|
+
for (const file of readdirSync(directory)) {
|
|
162
|
+
if (!file.endsWith(".json")) continue;
|
|
163
|
+
const run = readRun(home, file.slice(0, -5));
|
|
164
|
+
if (run === undefined) continue;
|
|
165
|
+
if (sessionId !== undefined && run.sessionId !== sessionId) continue;
|
|
166
|
+
rows.push(run);
|
|
167
|
+
}
|
|
168
|
+
return rows.sort((left, right) => String(right.updatedAt).localeCompare(String(left.updatedAt)));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function record(run, nodeId, entry, now) {
|
|
172
|
+
const state = run.nodes[nodeId];
|
|
173
|
+
state.evidence.push({ at: nowIso(now), ...entry });
|
|
174
|
+
run.updatedAt = nowIso(now);
|
|
175
|
+
run.log.push({ at: nowIso(now), event: "node/" + entry.status, nodeId, note: entry.note ?? "" });
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Recompute the whole-run status from the node states. */
|
|
179
|
+
export function refreshRunStatus(run) {
|
|
180
|
+
const states = Object.values(run.nodes).map(node => node.state);
|
|
181
|
+
if (states.includes("running")) return "running";
|
|
182
|
+
if (states.includes("awaiting_approval")) return "awaiting_approval";
|
|
183
|
+
/* A node the engine cannot execute must surface as blocked, never as completed. */
|
|
184
|
+
if (states.includes("blocked")) return "blocked";
|
|
185
|
+
if (states.includes("pending")) return "blocked";
|
|
186
|
+
if (states.includes("failed")) return "failed";
|
|
187
|
+
return "completed";
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Execute the next eligible nodes, one at a time, persisting after each.
|
|
192
|
+
*
|
|
193
|
+
* @param run - the run record (mutated and returned).
|
|
194
|
+
* @param document - the blueprint the run was created from.
|
|
195
|
+
* @param options.cwd - workspace root every command runs in.
|
|
196
|
+
* @param options.now - injectable clock.
|
|
197
|
+
* @param options.adapters - optional override adapters, for tests.
|
|
198
|
+
*/
|
|
199
|
+
export async function advanceRun(run, document, options = {}) {
|
|
200
|
+
const now = () => (options.now instanceof Date ? options.now : new Date());
|
|
201
|
+
const executed = [];
|
|
202
|
+
if (run.status === "cancelled" || run.status === "completed" || run.status === "failed") return { run, executed };
|
|
203
|
+
for (let guard = 0; guard < 200; guard += 1) {
|
|
204
|
+
const eligible = eligibleNodes(document, run);
|
|
205
|
+
if (eligible.length === 0) break;
|
|
206
|
+
const node = eligible[0];
|
|
207
|
+
const state = run.nodes[node.id];
|
|
208
|
+
state.state = "running";
|
|
209
|
+
state.attempts += 1;
|
|
210
|
+
run.status = "running";
|
|
211
|
+
let outcome = { status: "done" };
|
|
212
|
+
if (node.kind === "approval") {
|
|
213
|
+
outcome = { status: "awaiting_approval", note: "Cần người/agent duyệt" };
|
|
214
|
+
} else if (node.kind === "gate") {
|
|
215
|
+
const gateKind = node.gate?.kind ?? "manual";
|
|
216
|
+
if (gateKind === "command" && typeof node.gate?.run === "string") {
|
|
217
|
+
const result = await runCommand(node.gate.run, { cwd: options.cwd, signal: options.signal });
|
|
218
|
+
outcome = result.exitCode === 0
|
|
219
|
+
? { status: "done", exitCode: 0, output: result.stdout }
|
|
220
|
+
: { status: "failed", exitCode: result.exitCode, output: result.stdout, error: result.stderr || result.error };
|
|
221
|
+
} else {
|
|
222
|
+
outcome = { status: "awaiting_approval", note: gateKind === "ci" ? "Xác nhận CI xanh (adapter CI ở P4)" : "Cần xác nhận" };
|
|
223
|
+
}
|
|
224
|
+
} else if (node.kind === "action") {
|
|
225
|
+
const actions = Array.isArray(node.actions) ? node.actions : [];
|
|
226
|
+
let blocked;
|
|
227
|
+
let failure;
|
|
228
|
+
const evidence = [];
|
|
229
|
+
for (const action of actions) {
|
|
230
|
+
if (!EXECUTABLE_ACTIONS.includes(action.kind)) { blocked = action.kind; break; }
|
|
231
|
+
if (action.kind === "manual") { blocked = "manual"; break; }
|
|
232
|
+
const result = await runCommand(String(action.run ?? ""), { cwd: options.cwd, signal: options.signal, timeoutMs: action.timeoutMs });
|
|
233
|
+
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 || "") });
|
|
234
|
+
if (result.exitCode !== 0) { failure = evidence[evidence.length - 1]; break; }
|
|
235
|
+
}
|
|
236
|
+
for (const entry of evidence) state.evidence.push(entry);
|
|
237
|
+
if (failure !== undefined) outcome = { status: "failed", exitCode: failure.exitCode, note: "Lệnh thất bại: " + String(failure.command) };
|
|
238
|
+
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 };
|
|
239
|
+
else outcome = { status: "done" };
|
|
240
|
+
} else if (node.kind === "join") {
|
|
241
|
+
const mode = node.join?.mode ?? "all";
|
|
242
|
+
const states = incomingEdges(document, node.id).map(edge => run.nodes[edge.from]?.state);
|
|
243
|
+
const ok = mode === "any" ? states.includes("done") : states.length > 0 && states.every(state => state === "done");
|
|
244
|
+
outcome = ok ? { status: "done" } : { status: "failed", note: "Nhánh gộp không đạt" };
|
|
245
|
+
} else if (node.kind === "notify") {
|
|
246
|
+
outcome = { status: "done", note: "Thông báo ghi vào log (adapter ngoài ở P4)" };
|
|
247
|
+
} else if (node.kind === "rollback") {
|
|
248
|
+
const actions = Array.isArray(node.actions) ? node.actions : [];
|
|
249
|
+
const command = actions.find(action => action.kind === "command");
|
|
250
|
+
if (command === undefined) outcome = { status: "awaiting_approval", note: "Cần xác nhận hoàn tác" };
|
|
251
|
+
else {
|
|
252
|
+
const result = await runCommand(String(command.run), { cwd: options.cwd, signal: options.signal });
|
|
253
|
+
outcome = result.exitCode === 0 ? { status: "done", exitCode: 0, output: result.stdout } : { status: "failed", exitCode: result.exitCode, error: result.stderr };
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
state.state = outcome.status;
|
|
257
|
+
record(run, node.id, outcome, now());
|
|
258
|
+
executed.push({ nodeId: node.id, status: outcome.status });
|
|
259
|
+
if (outcome.status === "awaiting_approval" || outcome.status === "blocked") continue;
|
|
260
|
+
}
|
|
261
|
+
run.status = refreshRunStatus(run);
|
|
262
|
+
return { run, executed };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Approve, reject, or manually complete one node; returns the updated run. */
|
|
266
|
+
export function decideRun(run, nodeId, decision, note, now = new Date()) {
|
|
267
|
+
const state = run.nodes[nodeId];
|
|
268
|
+
if (state === undefined) return { ok: false, code: "journey/unknown-node", message: "Node " + nodeId + " is not part of this run." };
|
|
269
|
+
if (!["awaiting_approval", "blocked"].includes(state.state) && decision !== "reset") {
|
|
270
|
+
return { ok: false, code: "journey/not-decidable", message: "Node " + nodeId + " is " + state.state + "." };
|
|
271
|
+
}
|
|
272
|
+
const by = typeof note?.by === "string" ? note.by : "human";
|
|
273
|
+
if (decision === "approve") {
|
|
274
|
+
state.state = "done";
|
|
275
|
+
record(run, nodeId, { status: "done", note: note?.text ?? "Đã duyệt", by }, now);
|
|
276
|
+
} else if (decision === "reject") {
|
|
277
|
+
state.state = "failed";
|
|
278
|
+
record(run, nodeId, { status: "failed", note: note?.text ?? "Bị từ chối", by }, now);
|
|
279
|
+
} else if (decision === "retry") {
|
|
280
|
+
state.state = "pending";
|
|
281
|
+
record(run, nodeId, { status: "pending", note: note?.text ?? "Chạy lại", by }, now);
|
|
282
|
+
} else {
|
|
283
|
+
return { ok: false, code: "journey/unknown-decision", message: "Unknown decision " + String(decision) };
|
|
284
|
+
}
|
|
285
|
+
run.status = refreshRunStatus(run);
|
|
286
|
+
run.updatedAt = nowIso(now);
|
|
287
|
+
return { ok: true, run };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Cancel a run: running and pending nodes stop; finished evidence stays. */
|
|
291
|
+
export function cancelRun(run, note, now = new Date()) {
|
|
292
|
+
for (const [nodeId, state] of Object.entries(run.nodes)) {
|
|
293
|
+
if (state.state === "done" || state.state === "failed") continue;
|
|
294
|
+
state.state = "skipped";
|
|
295
|
+
record(run, nodeId, { status: "skipped", note: note?.text ?? "Đã huỷ" }, now);
|
|
296
|
+
}
|
|
297
|
+
run.status = "cancelled";
|
|
298
|
+
run.updatedAt = nowIso(now);
|
|
299
|
+
return run;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Compact status a canvas, a tool, or a chat command can print. */
|
|
303
|
+
export function summarizeRun(run) {
|
|
304
|
+
const counts = {};
|
|
305
|
+
for (const state of Object.values(run.nodes)) counts[state.state] = (counts[state.state] ?? 0) + 1;
|
|
306
|
+
return {
|
|
307
|
+
id: run.id,
|
|
308
|
+
feature: run.feature,
|
|
309
|
+
status: run.status,
|
|
310
|
+
blueprintRevision: run.blueprintRevision,
|
|
311
|
+
counts,
|
|
312
|
+
nodes: Object.entries(run.nodes).map(([nodeId, state]) => ({ nodeId, state: state.state, attempts: state.attempts, last: state.evidence[state.evidence.length - 1] ?? null })),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
//#endregion
|