ralphflow-dsh 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/facade.js CHANGED
@@ -8,23 +8,33 @@
8
8
  import fs from "node:fs";
9
9
  import path from "node:path";
10
10
  import yaml from "js-yaml";
11
- import { RALPH_FLOW_DIR, builtinWorkflowPath, createEngine, globalWorkflowsDirOf, } from "./engine.js";
11
+ import { builtinWorkflowPath, createEngine, globalWorkflowsDirOf, } from "./engine.js";
12
12
  import { createGraphEngine } from "./graph/engine.js";
13
13
  import { builtinGraphPath, classifyYamlDocument, graphGlobalDir, graphWorkspaceDir, loadGraphWorkflow, } from "./graph/assets.js";
14
14
  import { validateGraphAsset } from "./graph/asset.js";
15
15
  import { checkDefinition, checkVersion } from "./graph/check.js";
16
- import { isGraphTerminal, listGraphStates, readGraphState, } from "./graph/state.js";
16
+ import { isGraphTerminal, } from "./graph/state.js";
17
17
  import { mergeAssets } from "./assets.js";
18
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));
19
+ import { assetSearchDirs, resolveRalphFlowLayout } from "./paths.js";
20
+ function flowFileExists(workspace, name, headless) {
21
+ return assetSearchDirs(workspace, "workflows", headless).some((dir) => assetFileIn(dir, name, FLOW_ENTRY_FILE))
22
+ || Boolean(builtinWorkflowPath(name));
22
23
  }
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));
24
+ function graphFileExists(workspace, name, headless) {
25
+ return assetSearchDirs(workspace, "graphs", headless).some((dir) => assetFileIn(dir, name, GRAPH_ENTRY_FILE))
26
+ || Boolean(builtinGraphPath(name));
27
+ }
28
+ /** `file` 是否位于 `dir` 之下(用于识别被无头模式忽略的项目级资产路径)。 */
29
+ function insideDir(file, dir) {
30
+ const relative = path.relative(path.resolve(dir), path.resolve(file));
31
+ return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
26
32
  }
27
33
  export function createFacade(workspace, options) {
34
+ // 运行态选项与来源规则:门面、Flow、Graph 拿的是同一份(各自按同一条规则解析路径)。
35
+ const runtime = options;
36
+ const layout = resolveRalphFlowLayout(workspace, runtime);
37
+ const headless = layout.headless;
28
38
  // 回合收尾检查的观察值:本会话最近一次工具调用的时间。两个引擎共用同一份,
29
39
  // 因为同一个主会话同一时刻只可能跑一种实例;值只在进程内,不落盘。
30
40
  const actionTimes = new Map();
@@ -35,8 +45,8 @@ export function createFacade(workspace, options) {
35
45
  // 共用同一个格子,判定口径只有一份。
36
46
  noteAction,
37
47
  };
38
- const flow = createEngine(workspace, ports);
39
- const graph = createGraphEngine({ ctx: options.ctx, ports, workspace });
48
+ const flow = createEngine(workspace, ports, runtime);
49
+ const graph = createGraphEngine({ ...options, ports, workspace });
40
50
  /** 宿主每发生一次 `tool/call` 就报一次(引擎自己也补记进度记录);只记时间戳,不判断是谁的工具。 */
41
51
  function noteAction(sessionId, time) {
42
52
  actionTimes.set(sessionId, time);
@@ -46,8 +56,8 @@ export function createFacade(workspace, options) {
46
56
  graph.ensureLayout();
47
57
  }
48
58
  function assetKindOf(name) {
49
- const flowExists = flowFileExists(workspace, name);
50
- const graphExists = graphFileExists(workspace, name);
59
+ const flowExists = flowFileExists(workspace, name, headless);
60
+ const graphExists = graphFileExists(workspace, name, headless);
51
61
  if (flowExists && graphExists) {
52
62
  return {
53
63
  error: `名字 \`${name}\` 同时出现在 workflows/ 与 graphs/:跨类别同名是冲突。请重命名其中一个资产,再用唯一名字启动。`,
@@ -60,8 +70,17 @@ export function createFacade(workspace, options) {
60
70
  const assets = listAssets().filter((asset) => asset.name === name);
61
71
  if (assets.length === 1)
62
72
  return { kind: assets[0].kind };
73
+ if (headless) {
74
+ const [flowDir] = assetSearchDirs(workspace, "workflows", true);
75
+ const [graphDir] = assetSearchDirs(workspace, "graphs", true);
76
+ return {
77
+ error: `未找到工作流 \`${name}\`。无头运行只从用户级资产目录与内置工作流解析:Flow 放 \`${path.join(flowDir, "<name>", "workflow.yaml")}\`,Graph 放 \`${path.join(graphDir, "<name>", "graph.yaml")}\`。`,
78
+ };
79
+ }
80
+ const [flowDir] = assetSearchDirs(workspace, "workflows", false);
81
+ const [graphDir] = assetSearchDirs(workspace, "graphs", false);
63
82
  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\`。`,
83
+ error: `未找到工作流 \`${name}\`。Flow 资产放 \`${flowDir}/<name>/workflow.yaml\`,Graph 资产放 \`${graphDir}/<name>/graph.yaml\`。`,
65
84
  };
66
85
  }
67
86
  function listAssets() {
@@ -77,7 +96,7 @@ export function createFacade(workspace, options) {
77
96
  return undefined;
78
97
  }
79
98
  function findGraphState(instanceRef) {
80
- const all = listGraphStates(workspace);
99
+ const all = graph.listStates();
81
100
  const exact = all.find((entry) => entry.id === instanceRef);
82
101
  if (exact)
83
102
  return exact;
@@ -244,6 +263,18 @@ export function createFacade(workspace, options) {
244
263
  function diagnoseTarget(target) {
245
264
  // 1) 路径:工作区相对/绝对均可;入口文件或资产目录。
246
265
  const absolute = path.isAbsolute(target) ? target : path.resolve(workspace, target);
266
+ // 无头模式下项目级资产不参与发现与加载:按路径诊断它也只会验证一份「不会被用」的定义,
267
+ // 所以直接说清它被忽略,并指向用户级目录(校验面与加载面必须是同一套来源规则)。
268
+ if (headless) {
269
+ const ignoredDir = [assetSearchDirs(workspace, "workflows", false)[0], assetSearchDirs(workspace, "graphs", false)[0]]
270
+ .find((dir) => insideDir(absolute, dir));
271
+ if (ignoredDir) {
272
+ return {
273
+ ok: false,
274
+ text: `无头运行忽略项目级工作流资产:\`${target}\` 在 \`${ignoredDir}\` 下,不会被发现、校验或启动。把资产放到用户级目录(\`${globalWorkflowsDirOf()}\` 或 \`${graphGlobalDir()}\`)再诊断。`,
275
+ };
276
+ }
277
+ }
247
278
  const entry = assetEntryAt(absolute);
248
279
  if (!entry) {
249
280
  let isDirectory = false;
@@ -312,7 +343,7 @@ export function createFacade(workspace, options) {
312
343
  return { ok: false, text: `❌ \`${target}\` 无法判断资产类别:\n${classified.problems.map((problem) => `- ${problem}`).join("\n")}` };
313
344
  }
314
345
  // 2) 工作流名:先查 Graph 目录,再查 Flow。
315
- const graphLoaded = loadGraphWorkflow(workspace, target);
346
+ const graphLoaded = loadGraphWorkflow(workspace, target, runtime);
316
347
  if (graphLoaded.def || graphLoaded.path) {
317
348
  const valid = !!graphLoaded.def && graphLoaded.problems.length === 0;
318
349
  const lines = [
@@ -402,7 +433,7 @@ export function createFacade(workspace, options) {
402
433
  });
403
434
  }
404
435
  for (const entry of graph.listWorkflows()) {
405
- const loaded = loadGraphWorkflow(workspace, entry.name);
436
+ const loaded = loadGraphWorkflow(workspace, entry.name, runtime);
406
437
  const manual = new Set(loaded.def?.manual_step ?? []);
407
438
  assets.push({
408
439
  name: entry.name,
@@ -482,7 +513,7 @@ export function createFacade(workspace, options) {
482
513
  const graphChosen = graphStatus.projection;
483
514
  if (!graphChosen)
484
515
  return flowStatus;
485
- const graphState = readGraphState(workspace, graphChosen.id);
516
+ const graphState = graph.readState(graphChosen.id);
486
517
  const graphView = graphProjectionToStatus(graphChosen, graphState?.history ?? []);
487
518
  if (!flowStatus.status)
488
519
  return { status: graphView, error: graphStatus.error ?? flowStatus.error };
@@ -517,8 +548,8 @@ export function createFacade(workspace, options) {
517
548
  listHistory: () => flow.listHistory(),
518
549
  instanceDir: flow.instanceDir,
519
550
  artifactsDirOf: flow.artifactsDirOf,
520
- artifactsRelDirOf: flow.artifactsRelDirOf,
521
- reportRelPathOf: flow.reportRelPathOf,
551
+ artifactsDisplayDirOf: flow.artifactsDisplayDirOf,
552
+ reportPathOf: flow.reportPathOf,
522
553
  destroyInstance: flow.destroyInstance,
523
554
  // facade lifecycle
524
555
  start,
@@ -1,3 +1,4 @@
1
+ import { type RuntimeOptions } from "../paths.js";
1
2
  import { type GraphAsset } from "./asset.js";
2
3
  export declare const GRAPH_DIRNAME = "graphs";
3
4
  export declare const BUILTIN_GRAPHS: readonly ["codewiki"];
@@ -34,14 +35,18 @@ export declare function builtinGraphPath(name: string): string | undefined;
34
35
  * Flow 或 Graph 校验器之前,先发现“无 kind 的 nodes”“kind 与结构冲突”“两类结构同写”。
35
36
  */
36
37
  export declare function classifyYamlDocument(doc: unknown): DiscoveredYaml;
37
- /** 某工作区里所有 Graph 资产的发现结果(工作区遮蔽全局/内置;不建目录)。 */
38
- export declare function listGraphWorkflows(workspace: string): GraphWorkflowEntry[];
38
+ /**
39
+ * 某工作区里所有 Graph 资产的发现结果(工作区遮蔽全局/内置;不建目录)。
40
+ *
41
+ * 无头运行跳过项目级 `graphs/`:受管仓库里的同名定义不能覆盖工厂内置的 Graph。
42
+ */
43
+ export declare function listGraphWorkflows(workspace: string, runtime?: RuntimeOptions): GraphWorkflowEntry[];
39
44
  /** 加载一份 Graph 资产(工作区 → 全局 → 内置);目录/kind 不一致是硬错误。 */
40
- export declare function loadGraphWorkflow(workspace: string, name: string): GraphLoadResult;
45
+ export declare function loadGraphWorkflow(workspace: string, name: string, runtime?: RuntimeOptions): GraphLoadResult;
41
46
  /** 跨类别同名:返回同时出现在 Flow 与 Graph 里的名字(doctor/list/start 都据此拒绝)。 */
42
47
  export declare function crossKindNameConflicts(flowNames: readonly string[], graphEntries: readonly GraphWorkflowEntry[]): Array<{
43
48
  name: string;
44
49
  kind: "flow-graph";
45
50
  }>;
46
51
  /** 供测试与 doctor 用:列出候选文件(不读内容)。 */
47
- export declare function graphAssetFiles(workspace: string): string[];
52
+ export declare function graphAssetFiles(workspace: string, runtime?: RuntimeOptions): string[];
@@ -10,11 +10,21 @@ import path from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import yaml from "js-yaml";
12
12
  import { RALPH_FLOW_DIR } from "../engine.js";
13
- import { userRalphFlowDir } from "../paths.js";
13
+ import { assetSearchDirs, headlessModeEnabled, userRalphFlowDir } from "../paths.js";
14
14
  import { GRAPH_ENTRY_FILE, assetCandidates, discoverAssetsIn } from "../asset-path.js";
15
15
  import { validateGraphAsset } from "./asset.js";
16
16
  export const GRAPH_DIRNAME = "graphs";
17
17
  export const BUILTIN_GRAPHS = ["codewiki"];
18
+ /**
19
+ * 无头运行拒绝人工审查门的统一解释。
20
+ *
21
+ * 与 Flow 同一条纪律:没有会话能执行 `/ralphflow-continue`,Graph 会停在 `waiting_review`
22
+ * 等一个永远不会出现的确认。加载期拒绝,让启动失败得响亮。
23
+ */
24
+ function headlessGateProblem(name, gates) {
25
+ return `Graph 工作流 \`${name}\` 声明了人工审查门(\`manual_step\`:${gates.map((gate) => `\`${gate}\``).join("、")}),但本次是无头运行:没有会话能执行 \`/ralphflow-continue\` 放行它。`
26
+ + `无头运行只接受没有审查门的 Graph:请删掉顶层 \`manual_step\`,让节点由独立 CHECK 的判定自动推进;需要人工审查的工作流放到交互式会话里运行。`;
27
+ }
18
28
  /** 项目级 Graph 资产目录:`<项目根>/.dsh/ralph-flow/graphs/` */
19
29
  export function graphWorkspaceDir(workspace) {
20
30
  return path.join(workspace, RALPH_FLOW_DIR, GRAPH_DIRNAME);
@@ -96,12 +106,15 @@ function withGraphIdentity(doc, name) {
96
106
  const record = doc;
97
107
  return { ...record, id: record.id ?? name, name: record.name ?? name };
98
108
  }
99
- function graphCandidatePaths(workspace, name) {
109
+ /** Graph 资产的搜索目录(项目级优先;无头运行只剩用户级),带来源标签。 */
110
+ function graphSearchDirs(workspace, headless) {
111
+ const globalDir = graphGlobalDir();
112
+ return assetSearchDirs(workspace, GRAPH_DIRNAME, headless)
113
+ .map((dir) => ({ dir, source: dir === globalDir ? "global" : "workspace" }));
114
+ }
115
+ function graphCandidatePaths(workspace, name, headless) {
100
116
  const out = [];
101
- for (const [dir, source] of [
102
- [graphWorkspaceDir(workspace), "workspace"],
103
- [graphGlobalDir(), "global"],
104
- ]) {
117
+ for (const { dir, source } of graphSearchDirs(workspace, headless)) {
105
118
  for (const file of assetCandidates(dir, name, GRAPH_ENTRY_FILE))
106
119
  out.push({ file, source });
107
120
  }
@@ -110,8 +123,13 @@ function graphCandidatePaths(workspace, name) {
110
123
  out.push({ file: builtin, source: "builtin" });
111
124
  return out;
112
125
  }
113
- /** 某工作区里所有 Graph 资产的发现结果(工作区遮蔽全局/内置;不建目录)。 */
114
- export function listGraphWorkflows(workspace) {
126
+ /**
127
+ * 某工作区里所有 Graph 资产的发现结果(工作区遮蔽全局/内置;不建目录)。
128
+ *
129
+ * 无头运行跳过项目级 `graphs/`:受管仓库里的同名定义不能覆盖工厂内置的 Graph。
130
+ */
131
+ export function listGraphWorkflows(workspace, runtime = {}) {
132
+ const headless = headlessModeEnabled(runtime.ignoreWorkspaceWorkflows);
115
133
  const found = new Map();
116
134
  const addDir = (dir, source) => {
117
135
  for (const [name, file] of discoverAssetsIn(dir, GRAPH_ENTRY_FILE)) {
@@ -119,8 +137,8 @@ export function listGraphWorkflows(workspace) {
119
137
  found.set(name, { file, source });
120
138
  }
121
139
  };
122
- addDir(graphWorkspaceDir(workspace), "workspace");
123
- addDir(graphGlobalDir(), "global");
140
+ for (const { dir, source } of graphSearchDirs(workspace, headless))
141
+ addDir(dir, source);
124
142
  for (const name of BUILTIN_GRAPHS) {
125
143
  if (found.has(name))
126
144
  continue;
@@ -144,6 +162,19 @@ export function listGraphWorkflows(workspace) {
144
162
  return { name, desc: "", invalid: true, problems: classified.problems, warnings: [], path: file, source, nodes: classified.nodes };
145
163
  }
146
164
  const validation = validateGraphAsset(withGraphIdentity(doc, name));
165
+ if (validation.asset && headless && validation.asset.manual_step.length > 0) {
166
+ return {
167
+ name,
168
+ desc: validation.asset.description ?? "",
169
+ invalid: true,
170
+ problems: [headlessGateProblem(name, validation.asset.manual_step)],
171
+ warnings: validation.warnings,
172
+ path: file,
173
+ source,
174
+ nodes: validation.asset.nodes.length,
175
+ id: validation.asset.id,
176
+ };
177
+ }
147
178
  return {
148
179
  name,
149
180
  desc: validation.asset?.description ?? "",
@@ -158,10 +189,11 @@ export function listGraphWorkflows(workspace) {
158
189
  }).sort((left, right) => left.name.localeCompare(right.name));
159
190
  }
160
191
  /** 加载一份 Graph 资产(工作区 → 全局 → 内置);目录/kind 不一致是硬错误。 */
161
- export function loadGraphWorkflow(workspace, name) {
192
+ export function loadGraphWorkflow(workspace, name, runtime = {}) {
162
193
  const problems = [];
163
194
  const warnings = [];
164
- const candidates = graphCandidatePaths(workspace, name);
195
+ const headless = headlessModeEnabled(runtime.ignoreWorkspaceWorkflows);
196
+ const candidates = graphCandidatePaths(workspace, name, headless);
165
197
  // 工作区里的同名文件遮蔽全局/内置:只取第一个存在的候选,但**继续检查**是否还有别的
166
198
  // 类别(Flow)用了同一个名字 —— 跨类别同名由 listAssetsIn/doctor 统一报。
167
199
  let chosen;
@@ -175,7 +207,8 @@ export function loadGraphWorkflow(workspace, name) {
175
207
  catch { }
176
208
  }
177
209
  if (!chosen) {
178
- problems.push(`未找到 Graph 工作流 "${name}"。把资产放到 ${graphWorkspaceDir(workspace)}/<name>/graph.yaml(目录形态;单文件 ${graphWorkspaceDir(workspace)}/<name>.yaml 也识别)即可被加载。`);
210
+ const dir = headless ? graphGlobalDir() : graphWorkspaceDir(workspace);
211
+ problems.push(`未找到 Graph 工作流 "${name}"。把资产放到 ${dir}/<name>/graph.yaml(目录形态;单文件 ${dir}/<name>.yaml 也识别)即可被加载。`);
179
212
  return { def: null, problems, warnings };
180
213
  }
181
214
  const { doc, problem } = readYamlFile(chosen.file);
@@ -197,6 +230,9 @@ export function loadGraphWorkflow(workspace, name) {
197
230
  return { def: null, problems, warnings, path: chosen.file };
198
231
  }
199
232
  const asset = validation.asset;
233
+ if (headless && asset.manual_step.length > 0) {
234
+ return { def: null, problems: [headlessGateProblem(name, asset.manual_step)], warnings, path: chosen.file };
235
+ }
200
236
  if (asset.id !== name) {
201
237
  // 启动名与技能名来自目录名(单文件形态是文件名),id 是资产自身标识;不一致会让“报告里的 id”
202
238
  // 与“启动的名字”分叉。
@@ -210,9 +246,9 @@ export function crossKindNameConflicts(flowNames, graphEntries) {
210
246
  return [...new Set(flowNames)].filter((name) => graphNames.has(name)).sort().map((name) => ({ name, kind: "flow-graph" }));
211
247
  }
212
248
  /** 供测试与 doctor 用:列出候选文件(不读内容)。 */
213
- export function graphAssetFiles(workspace) {
249
+ export function graphAssetFiles(workspace, runtime = {}) {
214
250
  const files = [];
215
- for (const dir of [graphWorkspaceDir(workspace), graphGlobalDir()]) {
251
+ for (const { dir } of graphSearchDirs(workspace, headlessModeEnabled(runtime.ignoreWorkspaceWorkflows))) {
216
252
  files.push(...discoverAssetsIn(dir, GRAPH_ENTRY_FILE).values());
217
253
  }
218
254
  for (const name of BUILTIN_GRAPHS) {
@@ -1,9 +1,10 @@
1
1
  import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { Agent } from "@deepseek-ai/dsh-agent";
3
3
  import { type EnginePorts, type ToolResult } from "../engine.js";
4
+ import { type RuntimeOptions } from "../paths.js";
4
5
  import { type GraphWorkflowEntry } from "./assets.js";
5
6
  import { type GraphInstanceState, type GraphRunProjection } from "./state.js";
6
- export interface GraphEngineOptions {
7
+ export interface GraphEngineOptions extends RuntimeOptions {
7
8
  ctx: Context;
8
9
  ports: EnginePorts;
9
10
  workspace: string;
@@ -18,12 +18,13 @@ import { createHash, randomUUID } from "node:crypto";
18
18
  import { defineTool } from "@deepseek-ai/dsh-tools";
19
19
  import { pauseLabel } from "../pause.js";
20
20
  import { OWNER_HEARTBEAT_REFRESH_MS, ownerAlive, ownerRecheckMs, runtimeId, stampOwner } from "../owner.js";
21
- import { RALPH_FLOW_DIR, SUBMIT_REMINDER_STALL_LIMIT, makeArtifactsDirName, } from "../engine.js";
21
+ import { SUBMIT_REMINDER_STALL_LIMIT, makeArtifactsDirName, } from "../engine.js";
22
22
  import { graphAssetHash, } from "./asset.js";
23
+ import { displayPath, resolveRalphFlowLayout } from "../paths.js";
23
24
  import { checkDefinition, checkVersion } from "./check.js";
24
25
  import { assetReferenceSection, assetRootOf } from "../asset-path.js";
25
26
  import { graphWorkspaceDir, listGraphWorkflows, loadGraphWorkflow, } from "./assets.js";
26
- import { acceptanceOfNode, attemptsOfNode, graphArtifactsDirOf, graphArtifactsRootOf, graphInstanceDirOf, graphInstancesDirOf, graphNodeArtifactDirOf, graphReportsDirOf, graphRootOf, graphStatePathOf, isGraphTerminal, latestAttemptOfNode, listGraphStates, nodeNameOf, nodeReleased, nodeStatusOf, projectionOf, pushGraphHistory, readGraphState, verdictOfAttempt, waitingTodoOfNode, writeGraphState, } from "./state.js";
27
+ import { acceptanceOfNode, attemptsOfNode, graphArtifactsDirAt, graphArtifactsRootAt, graphInstanceDirAt, graphInstancesDirAt, graphNodeArtifactDirAt, graphReportsDirAt, isGraphTerminal, latestAttemptOfNode, listGraphStatesAt, nodeNameOf, nodeReleased, nodeStatusOf, projectionOf, pushGraphHistory, readGraphStateAt, verdictOfAttempt, waitingTodoOfNode, writeGraphStateAt, } from "./state.js";
27
28
  import { buildGraphReport } from "./report.js";
28
29
  import { registerGraphAgent, unregisterGraphAgent } from "./agent-registry.js";
29
30
  import { advanceIntegration, branchTip, captureWorkspaceChanges, ensureIntegrationBranch, ensureNodeWorktree, integrationBranchFor, nodeBranchFor, nodeReadyForIntegration, nodeWorktreePathOf, removeCleanWorktree, resolveProject, workspaceRelative, worktreeRootOf, } from "./workspace.js";
@@ -47,9 +48,6 @@ function uniqueId(asset) {
47
48
  const slug = asset.id.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 16) || "graph";
48
49
  return `${slug}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
49
50
  }
50
- function relOrAbsolute(workspace, absolute) {
51
- return workspaceRelative(workspace, absolute) ?? absolute;
52
- }
53
51
  function syntheticStep(node, criteria) {
54
52
  return { id: node.id, do: node.do, check: criteria, desc: node.name ?? node.id };
55
53
  }
@@ -74,11 +72,19 @@ function classifyManualResponse(text) {
74
72
  }
75
73
  export function createGraphEngine(options) {
76
74
  const { ctx, ports, workspace } = options;
77
- const root = graphRootOf(workspace);
75
+ // Flow 与 Graph 按同一条规则解析运行态布局(外部状态目录 / 无头模式)。
76
+ const layout = resolveRalphFlowLayout(workspace, options);
77
+ const root = layout.root;
78
+ const externalState = layout.external;
79
+ const headless = layout.headless;
78
80
  const graphsDir = graphWorkspaceDir(workspace);
79
- const instancesDir = graphInstancesDirOf(workspace);
80
- const reportsDir = graphReportsDirOf(workspace);
81
- const artifactsRoot = graphArtifactsRootOf(workspace);
81
+ const instancesDir = graphInstancesDirAt(root);
82
+ const reportsDir = graphReportsDirAt(root);
83
+ const artifactsRoot = graphArtifactsRootAt(root);
84
+ /** 产出目录在报告/提示词里的写法(外部化时绝对路径,否则工作区相对路径)。 */
85
+ const artifactsDisplayRoot = displayPath(workspace, artifactsRoot, externalState);
86
+ /** 报告路径在人话里的写法(状态面、报告头共用同一份事实)。 */
87
+ const reportPathOf = (instId) => displayPath(workspace, path.join(reportsDir, `${instId}.md`), externalState);
82
88
  const runs = new Map();
83
89
  const agentBindings = new Map();
84
90
  const log = (level, event, data) => {
@@ -88,7 +94,11 @@ export function createGraphEngine(options) {
88
94
  catch { }
89
95
  };
90
96
  function ensureLayout() {
91
- for (const dir of [root, graphsDir, instancesDir, reportsDir, artifactsRoot]) {
97
+ const dirs = [root, instancesDir, reportsDir, artifactsRoot];
98
+ // 项目资产目录只在默认布局下创建:外部化/无头运行时不在目标仓库里留下 `.dsh/ralph-flow/`。
99
+ if (!externalState && !headless)
100
+ dirs.push(graphsDir);
101
+ for (const dir of dirs) {
92
102
  try {
93
103
  fs.mkdirSync(dir, { recursive: true });
94
104
  }
@@ -96,7 +106,7 @@ export function createGraphEngine(options) {
96
106
  }
97
107
  }
98
108
  function instanceDir(instId) {
99
- return graphInstanceDirOf(workspace, instId);
109
+ return graphInstanceDirAt(root, instId);
100
110
  }
101
111
  function logFileOf(instId) {
102
112
  return path.join(instanceDir(instId), "execution.log");
@@ -162,13 +172,14 @@ export function createGraphEngine(options) {
162
172
  const reportPath = path.join(reportsDir, `${run.instId}.md`);
163
173
  try {
164
174
  fs.mkdirSync(reportsDir, { recursive: true });
165
- const artifactsRelDir = `${RALPH_FLOW_DIR}/artifacts/${run.state.artifacts_dir_name}/nodes`;
175
+ const artifactsDirLabel = `${artifactsDisplayRoot}/${run.state.artifacts_dir_name}/nodes`;
166
176
  const content = buildGraphReport(run.state, {
167
177
  instanceId: run.instId,
168
178
  workspace,
169
- statePath: graphStatePathOf(workspace, run.instId),
170
179
  reportPath,
171
- artifactsRelDir,
180
+ logPath: archivedLogOf(run.instId),
181
+ artifactsDirLabel,
182
+ external: externalState,
172
183
  });
173
184
  const tmp = path.join(reportsDir, `.${run.instId}.${process.pid}.tmp`);
174
185
  fs.writeFileSync(tmp, content, "utf-8");
@@ -182,7 +193,7 @@ export function createGraphEngine(options) {
182
193
  }
183
194
  function persist(run) {
184
195
  try {
185
- writeGraphState(workspace, run.state, run.instId);
196
+ writeGraphStateAt(root, run.state, run.instId);
186
197
  ports.statusChanged?.();
187
198
  }
188
199
  catch (error) {
@@ -234,16 +245,16 @@ export function createGraphEngine(options) {
234
245
  }
235
246
  // ── 资产发现 ────────────────────────────────────────────────────────────────
236
247
  function listWorkflows() {
237
- return listGraphWorkflows(workspace);
248
+ return listGraphWorkflows(workspace, options);
238
249
  }
239
250
  function loadWorkflow(name) {
240
- return loadGraphWorkflow(workspace, name);
251
+ return loadGraphWorkflow(workspace, name, options);
241
252
  }
242
253
  function readState(instId) {
243
- return readGraphState(workspace, instId);
254
+ return readGraphStateAt(root, instId);
244
255
  }
245
256
  function listStates() {
246
- return listGraphStates(workspace);
257
+ return listGraphStatesAt(root);
247
258
  }
248
259
  function activeInstanceOfSession(sessionId) {
249
260
  return listStates().filter((entry) => entry.state.active && entry.state.owner_session === sessionId).at(-1);
@@ -499,7 +510,9 @@ export function createGraphEngine(options) {
499
510
  persist(run);
500
511
  const status = run.state.graph.status;
501
512
  const label = status === "completed" ? "完成" : status === "cancelled" ? "取消" : status === "failed" ? "失败" : status;
502
- const reportLine = report ? `报告:\`${relOrAbsolute(workspace, report)}\`` : "报告写入失败,状态记录仍在 `instances/` 里。";
513
+ const reportLine = report
514
+ ? `报告:\`${displayPath(workspace, report, externalState)}\``
515
+ : `报告写入失败,状态记录仍在 \`${displayPath(workspace, instancesDir, externalState)}\` 里。`;
503
516
  notify(run, `Graph 实例 \`${run.instId}\` ${label}。${reportLine}`, `${status === "completed" ? "✅" : status === "cancelled" ? "⏹" : "❌"} Graph ${label}:${run.state.graph.asset.name}`);
504
517
  log(status === "failed" ? "warn" : "info", status === "completed" ? "graph_complete" : status === "cancelled" ? "graph_cancelled" : "graph_failed", { instId: run.instId });
505
518
  run.agents.clear();
@@ -656,7 +669,7 @@ export function createGraphEngine(options) {
656
669
  // 节点要在交卷前把新头合进来(它的分支会包含两者)。
657
670
  const baseline = recorded?.baseline ?? integration.current_commit;
658
671
  const branch = recorded?.branch ?? nodeBranchFor(run.instId, node.id);
659
- const worktreePath = nodeWorktreePathOf(workspace, run.instId, node.id);
672
+ const worktreePath = nodeWorktreePathOf(root, run.instId, node.id);
660
673
  const existing = await ensureNodeWorktree(projectRoot, worktreePath, branch, baseline);
661
674
  attempt.workspace = { path: existing.path, baseline };
662
675
  if (!recorded) {
@@ -706,7 +719,7 @@ export function createGraphEngine(options) {
706
719
  return refs;
707
720
  }
708
721
  function doPrompt(run, node, attempt, rework, manual = "") {
709
- const artifactPath = path.join(graphNodeArtifactDirOf(workspace, run.state, node.id, attempt.id), node.artifact);
722
+ const artifactPath = path.join(graphNodeArtifactDirAt(root, run.state, node.id, attempt.id), node.artifact);
710
723
  const lines = [
711
724
  `# Graph 节点执行 · ${node.id}`,
712
725
  "",
@@ -754,7 +767,7 @@ export function createGraphEngine(options) {
754
767
  * 不重复「完成条件」那类长文 —— 催促是低频的(≤2 次空回合 / 20 次总上限)。
755
768
  */
756
769
  function nodeRecap(run, node, attempt) {
757
- const artifactPath = path.join(graphNodeArtifactDirOf(workspace, run.state, node.id, attempt.id), node.artifact);
770
+ const artifactPath = path.join(graphNodeArtifactDirAt(root, run.state, node.id, attempt.id), node.artifact);
758
771
  const refs = inputRefs(run, node);
759
772
  const assetRoot = assetRootOf(run.state.graph.asset_path);
760
773
  const lines = [
@@ -1001,7 +1014,7 @@ export function createGraphEngine(options) {
1001
1014
  const content = args?.content;
1002
1015
  if (typeof content !== "string" || content.length === 0)
1003
1016
  return "content 必须是非空字符串,产物未写入。";
1004
- const dir = graphNodeArtifactDirOf(workspace, run.state, node.id, attempt.id);
1017
+ const dir = graphNodeArtifactDirAt(root, run.state, node.id, attempt.id);
1005
1018
  const file = path.join(dir, node.artifact);
1006
1019
  fs.mkdirSync(path.dirname(file), { recursive: true });
1007
1020
  fs.writeFileSync(file, content, "utf-8");
@@ -1067,7 +1080,7 @@ export function createGraphEngine(options) {
1067
1080
  // Git 模式:捕获工作区变更,供独立验证者取证。
1068
1081
  if (run.state.graph.project.mode === "git" && attempt.workspace?.path) {
1069
1082
  try {
1070
- const changes = await captureWorkspaceChanges(attempt.workspace.path, attempt.workspace.baseline ?? run.state.graph.integration?.baseline ?? "", graphNodeArtifactDirOf(workspace, run.state, nodeId, attemptId));
1083
+ const changes = await captureWorkspaceChanges(attempt.workspace.path, attempt.workspace.baseline ?? run.state.graph.integration?.baseline ?? "", graphNodeArtifactDirAt(root, run.state, nodeId, attemptId));
1071
1084
  attemptsOfNode(run.state, nodeId).find((item) => item.id === attemptId).workspace_changes = {
1072
1085
  path: changes.path, sha256: changes.sha256, files: changes.files,
1073
1086
  };
@@ -1111,7 +1124,7 @@ export function createGraphEngine(options) {
1111
1124
  assetPath: run.state.graph.asset_path,
1112
1125
  ...(run.state.owner_session ? { ownerSession: run.state.owner_session } : {}),
1113
1126
  checkIndex: 0,
1114
- artifactsRelDir: `${RALPH_FLOW_DIR}/artifacts/${run.state.artifacts_dir_name}/nodes/${node.id}/${attempt.id}`,
1127
+ artifactsRelDir: `${artifactsDisplayRoot}/${run.state.artifacts_dir_name}/nodes/${node.id}/${attempt.id}`,
1115
1128
  signal: run.abort.signal,
1116
1129
  logEvent: (level, event, extra) => logEvent(run.instId, level, event, { ...(extra ?? {}), node: node.id, attempt: attempt.id }),
1117
1130
  graph: graphScope,
@@ -1426,7 +1439,7 @@ export function createGraphEngine(options) {
1426
1439
  function restoreRun(instId) {
1427
1440
  if (runs.has(instId))
1428
1441
  return runs.get(instId);
1429
- const state = readGraphState(workspace, instId);
1442
+ const state = readGraphStateAt(root, instId);
1430
1443
  if (!state)
1431
1444
  return null;
1432
1445
  const run = {
@@ -1502,7 +1515,7 @@ export function createGraphEngine(options) {
1502
1515
  return;
1503
1516
  const timer = setTimeout(() => {
1504
1517
  try {
1505
- const state = readGraphState(workspace, instId);
1518
+ const state = readGraphStateAt(root, instId);
1506
1519
  if (!state || !state.active || state.graph.status !== "running")
1507
1520
  return;
1508
1521
  if ((state.owner_heartbeat_at ?? 0) > beatAt)
@@ -1764,7 +1777,7 @@ export function createGraphEngine(options) {
1764
1777
  }
1765
1778
  // 保留的 worktree 连同它的 git 注册与目录原样留下;只在目录确实为空时收掉 worktrees 根。
1766
1779
  // 不递归删除:否则会把刚判定“保留”的目录一起抹掉,注册表还会留下 prunable。
1767
- const worktreesRoot = worktreeRootOf(workspace, id);
1780
+ const worktreesRoot = worktreeRootOf(root, id);
1768
1781
  try {
1769
1782
  if (fs.existsSync(worktreesRoot) && fs.readdirSync(worktreesRoot).length === 0)
1770
1783
  fs.rmdirSync(worktreesRoot);
@@ -1821,14 +1834,14 @@ export function createGraphEngine(options) {
1821
1834
  const target = findInstance(sessionId, instanceRef);
1822
1835
  if (!target)
1823
1836
  return { ok: false, text: `没有找到 Graph 实例 \`${instanceRef}\`。` };
1824
- return { ok: true, text: formatProjection(projectionOf(target.state, target.id)) };
1837
+ return { ok: true, text: formatProjection(projectionOf(target.state, target.id, reportPathOf(target.id))) };
1825
1838
  }
1826
1839
  const active = activeInstanceOfSession(sessionId);
1827
1840
  const retained = listStates().filter((entry) => entry.state.owner_session === sessionId).at(-1);
1828
1841
  const chosen = active ?? retained;
1829
1842
  if (!chosen)
1830
1843
  return { ok: false, text: "当前会话没有 Graph 实例。" };
1831
- return { ok: true, text: formatProjection(projectionOf(chosen.state, chosen.id)) };
1844
+ return { ok: true, text: formatProjection(projectionOf(chosen.state, chosen.id, reportPathOf(chosen.id))) };
1832
1845
  }
1833
1846
  function listAll() {
1834
1847
  const workflows = listWorkflows();
@@ -1847,7 +1860,7 @@ export function createGraphEngine(options) {
1847
1860
  if (states.length === 0)
1848
1861
  lines.push("(暂无 Graph 实例)");
1849
1862
  for (const { id, state } of states) {
1850
- const projection = projectionOf(state, id);
1863
+ const projection = projectionOf(state, id, reportPathOf(id));
1851
1864
  lines.push(`- \`${id}\` — ${state.workflow_name} · ${projection.phase} · ${projection.counts.completed}/${projection.counts.total}`);
1852
1865
  }
1853
1866
  return { ok: true, text: lines.join("\n") };
@@ -1875,7 +1888,7 @@ export function createGraphEngine(options) {
1875
1888
  if (states.length === 0)
1876
1889
  lines.push("(暂无 Graph 实例)");
1877
1890
  for (const { id, state } of states) {
1878
- const projection = projectionOf(state, id);
1891
+ const projection = projectionOf(state, id, reportPathOf(id));
1879
1892
  if (state.active) {
1880
1893
  lines.push(`- \`${id}\` — ${state.workflow_name} · ${projection.phase}${state.graph.pause_reason ? `(${pauseLabel(state.graph.pause_reason)})` : ""}`);
1881
1894
  }
@@ -1965,7 +1978,7 @@ export function createGraphEngine(options) {
1965
1978
  const chosen = active ?? retained;
1966
1979
  if (!chosen)
1967
1980
  return { projection: null, error: null };
1968
- return { projection: projectionOf(chosen.state, chosen.id), error: null };
1981
+ return { projection: projectionOf(chosen.state, chosen.id, reportPathOf(chosen.id)), error: null };
1969
1982
  }
1970
1983
  const graphEngineFace = {
1971
1984
  kind: "graph",
@@ -1980,7 +1993,7 @@ export function createGraphEngine(options) {
1980
1993
  readState,
1981
1994
  listStates,
1982
1995
  instanceDir,
1983
- artifactsDirOf: (state) => graphArtifactsDirOf(workspace, state),
1996
+ artifactsDirOf: (state) => graphArtifactsDirAt(root, state),
1984
1997
  start,
1985
1998
  submitFromAgent,
1986
1999
  continueInstance,
@@ -1996,7 +2009,7 @@ export function createGraphEngine(options) {
1996
2009
  uiStatus,
1997
2010
  activeInstanceOfSession,
1998
2011
  syncSession,
1999
- projectionOf: (state, id) => projectionOf(state, id),
2012
+ projectionOf: (state, id) => projectionOf(state, id, reportPathOf(id)),
2000
2013
  };
2001
2014
  return graphEngineFace;
2002
2015
  }
@@ -2,8 +2,12 @@ import { type GraphInstanceState } from "./state.js";
2
2
  export interface GraphReportInput {
3
3
  instanceId: string;
4
4
  workspace: string;
5
- statePath: string;
6
5
  reportPath: string;
7
- artifactsRelDir: string;
6
+ /** 归档后的执行日志路径(与报告同目录;外部化时也在项目根之外)。 */
7
+ logPath: string;
8
+ /** 产出目录的展示路径(外部化时绝对路径)。 */
9
+ artifactsDirLabel: string;
10
+ /** 运行态是否外部化:决定报告与日志给绝对路径还是工作区相对路径。 */
11
+ external: boolean;
8
12
  }
9
13
  export declare function buildGraphReport(state: GraphInstanceState, input: GraphReportInput): string;
@@ -5,8 +5,8 @@
5
5
  * 报告只指路,不复制执行日志原文(design §3.4):验证者提示词/判定原文在 execution.log,
6
6
  * 这里只写判定结论、逐条证据摘要与产物引用。
7
7
  */
8
- import path from "node:path";
9
8
  import { formatDuration } from "../engine.js";
9
+ import { displayPath } from "../paths.js";
10
10
  import { pauseLabel } from "../pause.js";
11
11
  import { nodeNameOf, nodeStatusOf, NODE_STATUS_LABELS, projectionOf } from "./state.js";
12
12
  const STATUS_LABELS = {
@@ -40,9 +40,9 @@ export function buildGraphReport(state, input) {
40
40
  `- 开始:${startedAt}`,
41
41
  `- 结束:${endedAt}`,
42
42
  `- 总耗时:${formatDuration(duration)}`,
43
- `- 产出目录:${code(`${input.artifactsRelDir}/`)}`,
44
- `- 本报告:${code(`${path.relative(input.workspace, input.reportPath).split(path.sep).join("/")}`)}`,
45
- `- 执行日志:${code(`.dsh/ralph-flow/reports/${input.instanceId}-execution.log`)}`,
43
+ `- 产出目录:${code(`${input.artifactsDirLabel}/`)}`,
44
+ `- 本报告:${code(displayPath(input.workspace, input.reportPath, input.external))}`,
45
+ `- 执行日志:${code(displayPath(input.workspace, input.logPath, input.external))}`,
46
46
  "- 资产:",
47
47
  ` - id:${code(asset.id)}`,
48
48
  ` - 版本:${code(state.graph.asset_hash)}`,
@@ -51,7 +51,7 @@ export function buildGraphReport(state, input) {
51
51
  "## 判定",
52
52
  "",
53
53
  ];
54
- const projection = projectionOf(state, input.instanceId);
54
+ const projection = projectionOf(state, input.instanceId, input.reportPath);
55
55
  const completed = asset.nodes.filter((node) => nodeStatusOf(state, node) === "completed").length;
56
56
  const unfinished = asset.nodes.length - completed;
57
57
  const success = projectionStatus === "completed" && unfinished === 0;