ralphflow-dsh 2.3.1 → 2.4.1

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.
Files changed (87) hide show
  1. package/README.md +48 -22
  2. package/graphs/codewiki/format.md +362 -0
  3. package/graphs/codewiki/graph.yaml +39 -0
  4. package/graphs/codewiki/nodes/assemble.md +24 -0
  5. package/graphs/codewiki/nodes/core-pages.md +17 -0
  6. package/graphs/codewiki/nodes/module-pages.md +18 -0
  7. package/graphs/codewiki/nodes/operations-pages.md +18 -0
  8. package/graphs/codewiki/nodes/survey.md +22 -0
  9. package/lib/asset-path.d.ts +59 -0
  10. package/lib/asset-path.js +181 -0
  11. package/lib/assets.d.ts +42 -0
  12. package/lib/assets.js +86 -0
  13. package/lib/client/phase.d.ts +29 -0
  14. package/lib/client/phase.js +86 -0
  15. package/lib/client/selection.d.ts +28 -0
  16. package/lib/client/selection.js +9 -0
  17. package/lib/client/status-source.d.ts +3 -1
  18. package/lib/client/status-source.js +3 -2
  19. package/lib/client/status.js +49 -13
  20. package/lib/client/viewer.d.ts +18 -0
  21. package/lib/client/viewer.js +540 -0
  22. package/lib/client.js +1159 -64
  23. package/lib/engine.d.ts +111 -47
  24. package/lib/engine.js +473 -320
  25. package/lib/facade.d.ts +175 -0
  26. package/lib/facade.js +553 -0
  27. package/lib/graph/agent-registry.d.ts +4 -0
  28. package/lib/graph/agent-registry.js +20 -0
  29. package/lib/graph/asset.d.ts +47 -0
  30. package/lib/graph/asset.js +276 -0
  31. package/lib/graph/assets.d.ts +47 -0
  32. package/lib/graph/assets.js +224 -0
  33. package/lib/graph/branches.d.ts +9 -0
  34. package/lib/graph/branches.js +13 -0
  35. package/lib/graph/check.d.ts +23 -0
  36. package/lib/graph/check.js +46 -0
  37. package/lib/graph/engine.d.ts +55 -0
  38. package/lib/graph/engine.js +2002 -0
  39. package/lib/graph/report.d.ts +9 -0
  40. package/lib/graph/report.js +117 -0
  41. package/lib/graph/state.d.ts +244 -0
  42. package/lib/graph/state.js +358 -0
  43. package/lib/graph/workspace.d.ts +68 -0
  44. package/lib/graph/workspace.js +262 -0
  45. package/lib/index.d.ts +11 -1
  46. package/lib/index.js +156 -49
  47. package/lib/owner.d.ts +34 -0
  48. package/lib/owner.js +49 -0
  49. package/lib/paths.d.ts +12 -0
  50. package/lib/paths.js +44 -0
  51. package/lib/pause.d.ts +12 -0
  52. package/lib/pause.js +19 -0
  53. package/lib/skills.d.ts +17 -30
  54. package/lib/skills.js +85 -21
  55. package/lib/status-contract.d.ts +114 -1
  56. package/lib/status-contract.js +106 -4
  57. package/lib/status-service.d.ts +5 -1
  58. package/lib/status-service.js +8 -1
  59. package/lib/tools.d.ts +14 -6
  60. package/lib/tools.js +88 -60
  61. package/lib/unfinished.d.ts +11 -0
  62. package/lib/unfinished.js +18 -0
  63. package/lib/verifier-preset.d.ts +40 -0
  64. package/lib/verifier-preset.js +126 -0
  65. package/lib/verify.d.ts +82 -13
  66. package/lib/verify.js +382 -95
  67. package/package.json +50 -38
  68. package/skills/ralphflow-create/SKILL.md +32 -0
  69. package/skills/ralphflow-create/graph-authoring.md +85 -0
  70. package/skills/ralphflow-create/matt/LICENSE +21 -0
  71. package/skills/ralphflow-create/matt/SHA256SUMS +6 -0
  72. package/skills/ralphflow-create/matt/SKILL-MECHANICS.md +22 -0
  73. package/skills/ralphflow-create/matt/SOURCE.md +12 -0
  74. package/skills/ralphflow-create/matt/grilling.md +30 -0
  75. package/skills/ralphflow-create/matt/to-spec.md +75 -0
  76. package/skills/ralphflow-create/matt/to-tickets.md +105 -0
  77. package/skills/ralphflow-create/matt/writing-for-agents.md +81 -0
  78. package/skills/ralphflow-create/ralphflow-authoring.md +31 -0
  79. package/skills/ralphflow-create/testing-workflow.md +60 -0
  80. package/{references → skills/ralphflow-create}/workflow-authoring.md +25 -5
  81. package/workflows/create-graph/steps/graph.md +17 -0
  82. package/workflows/create-graph/workflow.yaml +77 -0
  83. package/workflows/loop/workflow.yaml +23 -0
  84. package/lib/create.d.ts +0 -2
  85. package/lib/create.js +0 -17
  86. package/workflows/loop.yaml +0 -45
  87. /package/workflows/{spec.yaml → spec/workflow.yaml} +0 -0
package/lib/facade.js ADDED
@@ -0,0 +1,553 @@
1
+ /**
2
+ * 门面:**按资产的 `kind` 路由**到 Flow 顺序引擎或 Graph DAG 引擎。
3
+ *
4
+ * 门面不是第三个引擎(design §4.1):它只做资产路由、生命周期编排、状态投影和工具转发;
5
+ * 每个实例只有一个写入者——Flow 实例由 `createEngine` 写,Graph 实例由 `createGraphEngine` 写。
6
+ * Flow 分支的每一步都委托给原引擎,保证既有行为逐字不变。
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import yaml from "js-yaml";
11
+ import { RALPH_FLOW_DIR, builtinWorkflowPath, createEngine, globalWorkflowsDirOf, } from "./engine.js";
12
+ import { createGraphEngine } from "./graph/engine.js";
13
+ import { builtinGraphPath, classifyYamlDocument, graphGlobalDir, graphWorkspaceDir, loadGraphWorkflow, } from "./graph/assets.js";
14
+ import { validateGraphAsset } from "./graph/asset.js";
15
+ import { checkDefinition, checkVersion } from "./graph/check.js";
16
+ import { isGraphTerminal, listGraphStates, readGraphState, } from "./graph/state.js";
17
+ import { mergeAssets } from "./assets.js";
18
+ import { FLOW_ENTRY_FILE, GRAPH_ENTRY_FILE, assetEntryAt, assetFileIn } from "./asset-path.js";
19
+ function flowFileExists(workspace, name) {
20
+ const dirs = [path.join(workspace, RALPH_FLOW_DIR, "workflows"), globalWorkflowsDirOf()];
21
+ return dirs.some((dir) => assetFileIn(dir, name, FLOW_ENTRY_FILE)) || Boolean(builtinWorkflowPath(name));
22
+ }
23
+ function graphFileExists(workspace, name) {
24
+ const dirs = [graphWorkspaceDir(workspace), graphGlobalDir()];
25
+ return dirs.some((dir) => assetFileIn(dir, name, GRAPH_ENTRY_FILE)) || Boolean(builtinGraphPath(name));
26
+ }
27
+ export function createFacade(workspace, options) {
28
+ // 回合收尾检查的观察值:本会话最近一次工具调用的时间。两个引擎共用同一份,
29
+ // 因为同一个主会话同一时刻只可能跑一种实例;值只在进程内,不落盘。
30
+ const actionTimes = new Map();
31
+ const ports = {
32
+ ...options.ports,
33
+ lastActionAt: (sessionId) => actionTimes.get(sessionId),
34
+ // 引擎侧的补记(带未完成项的进度记录 = 一次实质交卷):与宿主的 `tool/call` 观察值
35
+ // 共用同一个格子,判定口径只有一份。
36
+ noteAction,
37
+ };
38
+ const flow = createEngine(workspace, ports);
39
+ const graph = createGraphEngine({ ctx: options.ctx, ports, workspace });
40
+ /** 宿主每发生一次 `tool/call` 就报一次(引擎自己也补记进度记录);只记时间戳,不判断是谁的工具。 */
41
+ function noteAction(sessionId, time) {
42
+ actionTimes.set(sessionId, time);
43
+ }
44
+ function ensureLayout() {
45
+ flow.ensureLayout();
46
+ graph.ensureLayout();
47
+ }
48
+ function assetKindOf(name) {
49
+ const flowExists = flowFileExists(workspace, name);
50
+ const graphExists = graphFileExists(workspace, name);
51
+ if (flowExists && graphExists) {
52
+ return {
53
+ error: `名字 \`${name}\` 同时出现在 workflows/ 与 graphs/:跨类别同名是冲突。请重命名其中一个资产,再用唯一名字启动。`,
54
+ };
55
+ }
56
+ if (graphExists)
57
+ return { kind: "graph" };
58
+ if (flowExists)
59
+ return { kind: "flow" };
60
+ const assets = listAssets().filter((asset) => asset.name === name);
61
+ if (assets.length === 1)
62
+ return { kind: assets[0].kind };
63
+ return {
64
+ error: `未找到工作流 \`${name}\`。Flow 资产放 \`${path.join(workspace, RALPH_FLOW_DIR, "workflows")}/<name>/workflow.yaml\`,Graph 资产放 \`${path.join(workspace, RALPH_FLOW_DIR, "graphs")}/<name>/graph.yaml\`。`,
65
+ };
66
+ }
67
+ function listAssets() {
68
+ return mergeAssets(flow.listWorkflows(), graph.listWorkflows());
69
+ }
70
+ function kindOfInstance(instanceRef) {
71
+ const graphState = findGraphState(instanceRef);
72
+ if (graphState)
73
+ return "graph";
74
+ const flowState = findFlowInstance(instanceRef);
75
+ if (flowState)
76
+ return "flow";
77
+ return undefined;
78
+ }
79
+ function findGraphState(instanceRef) {
80
+ const all = listGraphStates(workspace);
81
+ const exact = all.find((entry) => entry.id === instanceRef);
82
+ if (exact)
83
+ return exact;
84
+ const prefixed = all.filter((entry) => entry.id.startsWith(instanceRef));
85
+ return prefixed.length === 1 ? prefixed[0] : undefined;
86
+ }
87
+ function findFlowInstance(instanceRef) {
88
+ const active = flow.listInstances();
89
+ const exact = active.find((entry) => entry.id === instanceRef);
90
+ if (exact)
91
+ return exact;
92
+ const prefixed = active.filter((entry) => entry.id.startsWith(instanceRef));
93
+ if (prefixed.length === 1)
94
+ return prefixed[0];
95
+ const history = flow.listHistory().filter((entry) => entry.id === instanceRef || entry.id.startsWith(instanceRef));
96
+ if (history.length === 1)
97
+ return { id: history[0].id, state: { active: false } };
98
+ return undefined;
99
+ }
100
+ function activeKindsOfSession(sessionId) {
101
+ return {
102
+ flow: flow.listInstances().find((entry) => entry.state.owner_session === sessionId && entry.state.active)?.id,
103
+ graph: graph.activeInstanceOfSession(sessionId)?.id,
104
+ };
105
+ }
106
+ async function start(workflowName, task, sessionId) {
107
+ const active = activeKindsOfSession(sessionId);
108
+ if (active.flow || active.graph) {
109
+ const id = active.graph ?? active.flow;
110
+ return { ok: false, text: `当前会话已有活跃实例 \`${id}\`(${active.graph ? "Graph" : "Flow"})。用 \`/ralphflow-continue\` 继续,或 \`/ralphflow-cancel\` 取消。` };
111
+ }
112
+ const kind = assetKindOf(workflowName.trim());
113
+ if ("error" in kind)
114
+ return { ok: false, text: kind.error };
115
+ if (kind.kind === "graph") {
116
+ ensureLayout();
117
+ return graph.start(workflowName, task, sessionId);
118
+ }
119
+ return flow.start(workflowName, task, sessionId);
120
+ }
121
+ async function onSubmit(agent, summary, unfinished) {
122
+ const sessionId = agent?.session?.id;
123
+ if (!sessionId)
124
+ return { ok: false, text: "找不到当前会话,无法交卷。" };
125
+ const graphSubmission = await graph.submitFromAgent(agent, summary, unfinished);
126
+ if (graphSubmission)
127
+ return graphSubmission;
128
+ return flow.onSubmit(sessionId, summary, unfinished);
129
+ }
130
+ async function continueInstance(sessionId, instanceRef) {
131
+ graph.syncSession(sessionId);
132
+ if (instanceRef) {
133
+ const graphState = findGraphState(instanceRef);
134
+ if (graphState)
135
+ return graph.continueInstance(sessionId, graphState.id);
136
+ return flow.continueInstance(sessionId, instanceRef);
137
+ }
138
+ const active = activeKindsOfSession(sessionId);
139
+ if (active.flow && active.graph) {
140
+ return { ok: false, text: `当前会话同时有 Flow 与 Graph 实例(\`${active.flow}\` / \`${active.graph}\`)。请显式给实例 ID。` };
141
+ }
142
+ if (active.graph)
143
+ return graph.continueInstance(sessionId, active.graph);
144
+ return flow.continueInstance(sessionId);
145
+ }
146
+ async function cancelInstance(sessionId, instanceRef, reason) {
147
+ if (instanceRef) {
148
+ const graphState = findGraphState(instanceRef);
149
+ if (graphState)
150
+ return graph.cancelInstance(sessionId, graphState.id, reason);
151
+ return flow.cancelInstance(sessionId, instanceRef, reason);
152
+ }
153
+ const active = activeKindsOfSession(sessionId);
154
+ if (active.flow && active.graph) {
155
+ return { ok: false, text: `当前会话同时有 Flow 与 Graph 实例(\`${active.flow}\` / \`${active.graph}\`)。请显式给实例 ID。` };
156
+ }
157
+ if (active.graph)
158
+ return graph.cancelInstance(sessionId, active.graph, reason);
159
+ return flow.cancelInstance(sessionId, instanceRef, reason);
160
+ }
161
+ /**
162
+ * 停止按钮 = 暂停:宿主把当前回合 cancel 成 `aborted/user` 后调用。
163
+ * Flow 与 Graph 走同一个入口;不在 DO 阶段的实例原样不动(停止回合不打断验证/审查门)。
164
+ */
165
+ function pauseForUserStop(sessionId) {
166
+ const active = activeKindsOfSession(sessionId);
167
+ const results = [];
168
+ if (active.graph)
169
+ results.push(graph.pauseForUserStop(sessionId));
170
+ if (active.flow)
171
+ results.push(flow.pauseForUserStop(sessionId));
172
+ return results.find((result) => result.ok) ?? results[0] ?? { ok: false, text: "当前会话没有可暂停的活跃实例。" };
173
+ }
174
+ async function cleanupInstance(instanceRef) {
175
+ return graph.cleanupInstance(instanceRef);
176
+ }
177
+ function respond(agent, text, todoId) {
178
+ return graph.respond(agent, text, todoId);
179
+ }
180
+ function statusOf(sessionId, instanceRef) {
181
+ graph.syncSession(sessionId);
182
+ if (instanceRef) {
183
+ const graphState = findGraphState(instanceRef);
184
+ if (graphState)
185
+ return graph.statusOf(sessionId, graphState.id);
186
+ return flow.statusOf(sessionId, instanceRef);
187
+ }
188
+ const active = activeKindsOfSession(sessionId);
189
+ if (active.graph)
190
+ return graph.statusOf(sessionId, active.graph);
191
+ if (active.flow)
192
+ return flow.statusOf(sessionId, active.flow);
193
+ const graphResult = graph.statusOf(sessionId);
194
+ if (graphResult.ok)
195
+ return graphResult;
196
+ return flow.statusOf(sessionId);
197
+ }
198
+ function listAll() {
199
+ const assets = listAssets();
200
+ const table = [
201
+ "## 可用工作流",
202
+ "",
203
+ "| 名字 | 类别 | 步骤/节点 | 说明 |",
204
+ "|---|---|---|---|",
205
+ ...assets.map((asset) => `| ${asset.invalid ? "❌ " : ""}\`${asset.name}\` | ${asset.kind === "graph" ? "Graph" : "Flow"} | ${asset.count} | ${(asset.desc || "(无描述)").replaceAll("|", "\\|")} |`),
206
+ ...(assets.some((asset) => asset.conflict) ? ["", "⚠️ 跨类别同名冲突:同名资产不能启动,请先改名。"] : []),
207
+ "",
208
+ ].join("\n");
209
+ const flowText = flow.listAll().text;
210
+ const activeIndex = flowText.indexOf("## 活跃实例");
211
+ const flowTail = activeIndex >= 0 ? flowText.slice(activeIndex) : "";
212
+ const graphText = graph.listAll().text;
213
+ const graphInstancesIndex = graphText.indexOf("## Graph 实例");
214
+ const graphTail = graphInstancesIndex >= 0 ? graphText.slice(graphInstancesIndex) : "";
215
+ return { ok: true, text: [flowTail, "", table, "", graphTail].join("\n") };
216
+ }
217
+ function diagnose(target) {
218
+ if (target && target.trim())
219
+ return diagnoseTarget(target.trim());
220
+ const assets = listAssets();
221
+ const conflicts = assets.filter((asset) => asset.conflict);
222
+ const conflictLines = conflicts.length > 0
223
+ ? ["## 跨类别同名冲突", "", ...conflicts.map((asset) => `- ❌ \`${asset.name}\`:同时出现在 workflows/ 与 graphs/;必须改名。`), ""]
224
+ : [];
225
+ const flowText = flow.diagnose().text;
226
+ const graphText = graph.diagnose().text;
227
+ return { ok: true, text: [...conflictLines, flowText, "", graphText].join("\n") };
228
+ }
229
+ function checksOfAsset(asset) {
230
+ const lines = [];
231
+ for (const node of asset.nodes) {
232
+ const criteria = node.check && typeof node.check === "object" && "criteria" in node.check
233
+ ? String(node.check.criteria ?? "")
234
+ : null;
235
+ const definition = checkDefinition(criteria);
236
+ lines.push(` - \`${node.id}\`:CHECK ${definition.mode}${definition.mode === "disabled" ? "" : `(${checkVersion(definition)})`}`);
237
+ if (definition.mode !== "disabled") {
238
+ for (const criterion of definition.criteria)
239
+ lines.push(` - ${criterion}`);
240
+ }
241
+ }
242
+ return lines;
243
+ }
244
+ function diagnoseTarget(target) {
245
+ // 1) 路径:工作区相对/绝对均可;入口文件或资产目录。
246
+ const absolute = path.isAbsolute(target) ? target : path.resolve(workspace, target);
247
+ const entry = assetEntryAt(absolute);
248
+ if (!entry) {
249
+ let isDirectory = false;
250
+ try {
251
+ isDirectory = fs.statSync(absolute).isDirectory();
252
+ }
253
+ catch { }
254
+ if (isDirectory) {
255
+ return { ok: false, text: `❌ \`${target}\` 里没有 \`workflow.yaml\` 或 \`graph.yaml\`:资产是目录加固定入口(\`workflows/<名字>/workflow.yaml\`、\`graphs/<名字>/graph.yaml\`)。` };
256
+ }
257
+ }
258
+ if (entry) {
259
+ const { file, name } = entry;
260
+ let doc;
261
+ try {
262
+ doc = yaml.load(fs.readFileSync(file, "utf-8").replace(/^\uFEFF/, ""));
263
+ }
264
+ catch (error) {
265
+ return { ok: false, text: `❌ \`${target}\` 读取失败:${error instanceof Error ? error.message : String(error)}` };
266
+ }
267
+ const classified = classifyYamlDocument(doc);
268
+ if (classified.kind === "graph") {
269
+ const identity = doc && typeof doc === "object" && !Array.isArray(doc)
270
+ ? { ...doc, id: doc.id ?? name, name: doc.name ?? name }
271
+ : doc;
272
+ const validation = validateGraphAsset(identity);
273
+ const inGraphs = path.resolve(file).startsWith(path.resolve(graphWorkspaceDir(workspace)) + path.sep)
274
+ || path.resolve(file) === path.resolve(builtinGraphPath(name) ?? "")
275
+ || path.resolve(file).startsWith(path.resolve(graphGlobalDir()) + path.sep);
276
+ const valid = validation.asset !== null && inGraphs;
277
+ const lines = [
278
+ `## Graph 资产诊断:\`${target}\``,
279
+ "",
280
+ `- 类别:Graph`,
281
+ `- 路径:\`${file}\``,
282
+ `- 名字:\`${name}\``,
283
+ ...(inGraphs ? [] : ["- ❌ 文件不在 graphs/ 目录:Graph 资产只放 `.dsh/ralph-flow/graphs/`。"]),
284
+ "",
285
+ ...(validation.asset
286
+ ? [inGraphs ? "- ✅ 定义有效" : "- ❌ 定义有效但位置错误"]
287
+ : ["- ❌ 定义无效", ...validation.errors.map((error) => ` - ${error.path || "/"}:${error.message}`)]),
288
+ ...(validation.warnings.length ? ["", "### 告警", ...validation.warnings.map((warning) => `- ⚠️ ${warning}`)] : []),
289
+ ...(validation.asset ? ["", "### 有效 CHECK", ...checksOfAsset(validation.asset)] : []),
290
+ "",
291
+ "结论:所有 ❌ 项即阻塞项,修复后重跑本命令直至全部 ✅。",
292
+ ];
293
+ return { ok: valid, text: lines.join("\n") };
294
+ }
295
+ if (classified.kind === "flow") {
296
+ const loaded = flow.loadWorkflow(name);
297
+ const valid = !!loaded.def && !loaded.problems.length;
298
+ const lines = [
299
+ `## Flow 资产诊断:\`${target}\``,
300
+ "",
301
+ `- 类别:Flow`,
302
+ `- 路径:\`${file}\``,
303
+ `- 名字:\`${name}\``,
304
+ "",
305
+ ...(valid ? ["- ✅ 定义有效"] : ["- ❌ 定义无效", ...loaded.problems.map((problem) => ` - ${problem}`)]),
306
+ ...(loaded.warnings.length ? ["", "### 告警", ...loaded.warnings.map((warning) => `- ⚠️ ${warning}`)] : []),
307
+ "",
308
+ "结论:所有 ❌ 项即阻塞项,修复后重跑本命令直至全部 ✅。",
309
+ ];
310
+ return { ok: valid, text: lines.join("\n") };
311
+ }
312
+ return { ok: false, text: `❌ \`${target}\` 无法判断资产类别:\n${classified.problems.map((problem) => `- ${problem}`).join("\n")}` };
313
+ }
314
+ // 2) 工作流名:先查 Graph 目录,再查 Flow。
315
+ const graphLoaded = loadGraphWorkflow(workspace, target);
316
+ if (graphLoaded.def || graphLoaded.path) {
317
+ const valid = !!graphLoaded.def && graphLoaded.problems.length === 0;
318
+ const lines = [
319
+ `## Graph 资产诊断:\`${target}\``,
320
+ "",
321
+ `- 类别:Graph`,
322
+ ...(graphLoaded.path ? [`- 路径:\`${graphLoaded.path}\``] : []),
323
+ "",
324
+ ...(valid ? ["- ✅ 定义有效"] : ["- ❌ 定义无效", ...graphLoaded.problems.map((problem) => ` - ${problem}`)]),
325
+ ...(graphLoaded.warnings.length ? ["", "### 告警", ...graphLoaded.warnings.map((warning) => `- ⚠️ ${warning}`)] : []),
326
+ ...(graphLoaded.def ? ["", "### 有效 CHECK", ...checksOfAsset(graphLoaded.def)] : []),
327
+ "",
328
+ "结论:所有 ❌ 项即阻塞项,修复后重跑本命令直至全部 ✅。",
329
+ ];
330
+ return { ok: valid, text: lines.join("\n") };
331
+ }
332
+ const loaded = flow.loadWorkflow(target);
333
+ const valid = !!loaded.def && loaded.problems.length === 0;
334
+ const lines = [
335
+ `## Flow 资产诊断:\`${target}\``,
336
+ "",
337
+ `- 类别:Flow`,
338
+ "",
339
+ ...(valid ? ["- ✅ 定义有效"] : ["- ❌ 定义无效", ...loaded.problems.map((problem) => ` - ${problem}`)]),
340
+ ...(loaded.warnings.length ? ["", "### 告警", ...loaded.warnings.map((warning) => `- ⚠️ ${warning}`)] : []),
341
+ "",
342
+ "结论:所有 ❌ 项即阻塞项,修复后重跑本命令直至全部 ✅。",
343
+ ];
344
+ return { ok: valid, text: lines.join("\n") };
345
+ }
346
+ function restore() {
347
+ flow.restore();
348
+ graph.restore();
349
+ }
350
+ function remindToSubmit(sessionId) {
351
+ const flowVerdict = flow.remindToSubmit(sessionId);
352
+ if (flowVerdict.remind || flowVerdict.message)
353
+ return flowVerdict;
354
+ return graph.remindToSubmit(sessionId);
355
+ }
356
+ function activeInstanceOfSession(sessionId) {
357
+ const active = activeKindsOfSession(sessionId);
358
+ if (active.graph)
359
+ return { id: active.graph, kind: "graph" };
360
+ if (active.flow)
361
+ return { id: active.flow, kind: "flow" };
362
+ return undefined;
363
+ }
364
+ let catalogCache = null;
365
+ /** 只读查看器目录:Flow 步骤链 + Graph DAG(含 DO/CHECK/依赖)。 */
366
+ function viewerCatalog() {
367
+ if (catalogCache && Date.now() - catalogCache.at < 5000)
368
+ return catalogCache.value;
369
+ try {
370
+ const assets = buildViewerCatalog();
371
+ catalogCache = { at: Date.now(), value: assets };
372
+ return assets;
373
+ }
374
+ catch {
375
+ // 只读面绝不能因为某个坏资产/权限错误把宿主状态流打断:空目录比崩溃好。
376
+ return [];
377
+ }
378
+ }
379
+ function buildViewerCatalog() {
380
+ const assets = [];
381
+ for (const entry of flow.listWorkflows()) {
382
+ const loaded = flow.loadWorkflow(entry.name);
383
+ const manual = new Set(loaded.def?.manual_step ?? []);
384
+ assets.push({
385
+ name: entry.name,
386
+ kind: "flow",
387
+ description: entry.desc,
388
+ invalid: entry.invalid,
389
+ problems: entry.problems,
390
+ steps: (loaded.def?.steps ?? []).map((step) => ({
391
+ id: step.id,
392
+ description: step.desc ?? "",
393
+ do: step.do ?? "",
394
+ checks: step.check ? [step.check] : (step.check_voting ?? []).map((voter) => voter.check),
395
+ input: step.input ?? "",
396
+ output: step.output ?? "",
397
+ onPass: step.on_pass ?? "",
398
+ onFail: step.on_fail ?? "",
399
+ manual: manual.has(step.id),
400
+ })),
401
+ nodes: [],
402
+ });
403
+ }
404
+ for (const entry of graph.listWorkflows()) {
405
+ const loaded = loadGraphWorkflow(workspace, entry.name);
406
+ const manual = new Set(loaded.def?.manual_step ?? []);
407
+ assets.push({
408
+ name: entry.name,
409
+ kind: "graph",
410
+ description: entry.desc,
411
+ invalid: entry.invalid,
412
+ problems: entry.problems,
413
+ steps: [],
414
+ nodes: (loaded.def?.nodes ?? []).map((node) => ({
415
+ id: node.id,
416
+ name: node.name ?? node.id,
417
+ do: node.do,
418
+ artifact: node.artifact,
419
+ dependsOn: [...node.dependsOn],
420
+ inputs: node.inputs.map((input) => ({ fromNode: input.fromNode, artifact: input.artifact })),
421
+ execution: node.execution,
422
+ check: node.check ? node.check.criteria : "(已关闭 CHECK)",
423
+ checkMode: node.check ? "custom" : "disabled",
424
+ manual: manual.has(node.id),
425
+ })),
426
+ });
427
+ }
428
+ return assets;
429
+ }
430
+ function graphProjectionToStatus(projection, history) {
431
+ const stage = projection.status === "completed" ? "done"
432
+ : projection.status === "cancelled" ? "cancelled"
433
+ : projection.status === "failed" ? "failed"
434
+ : projection.status === "paused" || projection.status === "interrupted" ? "paused"
435
+ : projection.nextAction?.kind === "manual_review" ? "gate"
436
+ : projection.counts.running > 0 ? "executing" : "switching";
437
+ return {
438
+ id: projection.id,
439
+ kind: "graph",
440
+ workflow: projection.workflow,
441
+ task: projection.task.slice(0, 2000),
442
+ step: "",
443
+ stage,
444
+ hint: projection.nextAction?.message ?? projection.phase,
445
+ failures: 0,
446
+ maxFailures: 0,
447
+ updatedAt: projection.updatedAt,
448
+ report: projection.report,
449
+ steps: [],
450
+ votes: [],
451
+ recent: history.slice(-5).map((entry) => ({ step: entry.step ?? "", event: entry.event, detail: entry.detail ?? "" })),
452
+ graph: {
453
+ phase: projection.phase,
454
+ status: projection.status,
455
+ counts: projection.counts,
456
+ current: projection.current,
457
+ nextAction: projection.nextAction,
458
+ nodes: projection.nodes.map((node) => ({
459
+ id: node.id,
460
+ name: node.name,
461
+ status: node.status,
462
+ label: node.label,
463
+ dependsOn: node.dependsOn,
464
+ attempts: node.attempts,
465
+ current: node.current,
466
+ execution: node.execution,
467
+ artifact: node.artifact ? { path: node.artifact.path, sha256: node.artifact.sha256 } : null,
468
+ check: node.check,
469
+ manual: node.manual,
470
+ integration: node.integration,
471
+ integrationCommit: node.integrationCommit,
472
+ todoId: node.todoId,
473
+ })),
474
+ integration: projection.integration,
475
+ delivery: projection.delivery,
476
+ },
477
+ };
478
+ }
479
+ function uiStatus(sessionId) {
480
+ const flowStatus = flow.uiStatus(sessionId);
481
+ const graphStatus = graph.uiStatus(sessionId);
482
+ const graphChosen = graphStatus.projection;
483
+ if (!graphChosen)
484
+ return flowStatus;
485
+ const graphState = readGraphState(workspace, graphChosen.id);
486
+ const graphView = graphProjectionToStatus(graphChosen, graphState?.history ?? []);
487
+ if (!flowStatus.status)
488
+ return { status: graphView, error: graphStatus.error ?? flowStatus.error };
489
+ const flowIsActive = flowStatus.status.stage !== "done" && flowStatus.status.stage !== "cancelled" && flowStatus.status.stage !== "failed";
490
+ const graphIsActive = !isGraphTerminal(graphChosen.status);
491
+ if (flowIsActive !== graphIsActive)
492
+ return flowIsActive ? flowStatus : { status: graphView, error: graphStatus.error };
493
+ const flowTime = Date.parse(flowStatus.status.updatedAt) || 0;
494
+ const graphTime = Date.parse(graphChosen.updatedAt) || 0;
495
+ return graphTime > flowTime ? { status: graphView, error: graphStatus.error } : flowStatus;
496
+ }
497
+ function uiReport(ref) {
498
+ return flow.uiReport(ref);
499
+ }
500
+ async function submitFromAny(agent, summary, unfinished) {
501
+ return onSubmit(agent, summary, unfinished);
502
+ }
503
+ return {
504
+ kind: "facade",
505
+ projectDir: workspace,
506
+ root: flow.root,
507
+ instancesDir: flow.instancesDir,
508
+ workflowsDir: flow.workflowsDir,
509
+ reportsDir: flow.reportsDir,
510
+ graphsDir: graph.graphsDir,
511
+ // Flow-compatible surface
512
+ ensureLayout,
513
+ listWorkflows: () => flow.listWorkflows(),
514
+ loadWorkflow: flow.loadWorkflow,
515
+ readState: flow.readState,
516
+ listInstances: () => flow.listInstances(),
517
+ listHistory: () => flow.listHistory(),
518
+ instanceDir: flow.instanceDir,
519
+ artifactsDirOf: flow.artifactsDirOf,
520
+ artifactsRelDirOf: flow.artifactsRelDirOf,
521
+ reportRelPathOf: flow.reportRelPathOf,
522
+ destroyInstance: flow.destroyInstance,
523
+ // facade lifecycle
524
+ start,
525
+ onSubmit,
526
+ submitFromAny,
527
+ noteAssistantText: flow.noteAssistantText,
528
+ noteAction,
529
+ remindToSubmit,
530
+ continueInstance,
531
+ resetCurrent: flow.resetCurrent,
532
+ rewindTo: flow.rewindTo,
533
+ cancelInstance,
534
+ pauseForUserStop,
535
+ cleanupInstance,
536
+ respond,
537
+ statusOf,
538
+ listAll,
539
+ restore,
540
+ diagnose,
541
+ activeInstanceOfSession,
542
+ activeKindsOfSession,
543
+ kindOfInstance,
544
+ listAssets,
545
+ viewerCatalog,
546
+ uiStatus,
547
+ uiReport,
548
+ // Graph-only surfaces used by the status service / tests
549
+ graph,
550
+ flow,
551
+ findGraphState,
552
+ };
553
+ }
@@ -0,0 +1,4 @@
1
+ export declare function registerGraphAgent(agentId: string, workspace: string): void;
2
+ export declare function unregisterGraphAgent(agentId: string): void;
3
+ export declare function graphAgentWorkspace(agentId: string | undefined): string | undefined;
4
+ export declare function graphAgentWorkspaces(): string[];
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Graph 节点 agent → 所属工作区。
3
+ *
4
+ * 节点 agent 的 cwd 是它的 worktree(Git 模式)或项目工作区;工具调用必须回到**发起实例
5
+ * 所在的工作区**解析引擎,绝不能按子会话 cwd 新建第二个引擎(否则绑定、状态、报告全部分叉)。
6
+ * 这是一个进程内路由表,不是状态、不落盘:agent 创建时登记,dispose 时摘除。
7
+ */
8
+ const owners = new Map();
9
+ export function registerGraphAgent(agentId, workspace) {
10
+ owners.set(agentId, workspace);
11
+ }
12
+ export function unregisterGraphAgent(agentId) {
13
+ owners.delete(agentId);
14
+ }
15
+ export function graphAgentWorkspace(agentId) {
16
+ return agentId ? owners.get(agentId) : undefined;
17
+ }
18
+ export function graphAgentWorkspaces() {
19
+ return [...new Set(owners.values())];
20
+ }
@@ -0,0 +1,47 @@
1
+ export declare const GRAPH_KIND: "graph";
2
+ export type GraphExecution = "background" | "main";
3
+ export interface GraphInputReference {
4
+ fromNode: string;
5
+ artifact: string;
6
+ }
7
+ export interface GraphCheckCustom {
8
+ mode: "custom";
9
+ criteria: string;
10
+ }
11
+ export type GraphCheck = GraphCheckCustom;
12
+ export interface GraphNode {
13
+ id: string;
14
+ name?: string;
15
+ do: string;
16
+ artifact: string;
17
+ dependsOn: string[];
18
+ inputs: GraphInputReference[];
19
+ execution: GraphExecution;
20
+ check: GraphCheck | null;
21
+ }
22
+ export interface GraphAsset {
23
+ kind: typeof GRAPH_KIND;
24
+ id: string;
25
+ name: string;
26
+ description?: string;
27
+ manual_step: string[];
28
+ nodes: GraphNode[];
29
+ }
30
+ export interface GraphAssetIssue {
31
+ path: string;
32
+ code: string;
33
+ message: string;
34
+ }
35
+ export interface GraphAssetValidation {
36
+ asset: GraphAsset | null;
37
+ errors: GraphAssetIssue[];
38
+ warnings: string[];
39
+ }
40
+ export declare function isStableId(value: unknown): value is string;
41
+ export declare function isArtifactPath(value: unknown): value is string;
42
+ /** 校验并归一化一份 Graph 资产;返回的 asset 是深度冻结的快照。 */
43
+ export declare function validateGraphAsset(input: unknown): GraphAssetValidation;
44
+ /** 资产内容哈希(报告与状态快照用;不依赖文件 mtime)。 */
45
+ export declare function graphAssetHash(asset: GraphAsset): string;
46
+ /** 启动回执里显示的节点摘要。 */
47
+ export declare function describeGraphAsset(asset: GraphAsset): string;