ralphflow-dsh 2.3.0 → 2.4.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.
Files changed (87) hide show
  1. package/README.md +47 -21
  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 +482 -334
  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.js +150 -47
  46. package/lib/owner.d.ts +34 -0
  47. package/lib/owner.js +49 -0
  48. package/lib/paths.d.ts +12 -0
  49. package/lib/paths.js +44 -0
  50. package/lib/pause.d.ts +12 -0
  51. package/lib/pause.js +19 -0
  52. package/lib/skills.d.ts +18 -31
  53. package/lib/skills.js +88 -44
  54. package/lib/status-contract.d.ts +114 -1
  55. package/lib/status-contract.js +106 -4
  56. package/lib/status-service.d.ts +5 -1
  57. package/lib/status-service.js +8 -1
  58. package/lib/tools.d.ts +14 -6
  59. package/lib/tools.js +90 -62
  60. package/lib/unfinished.d.ts +11 -0
  61. package/lib/unfinished.js +18 -0
  62. package/lib/verifier-preset.d.ts +40 -0
  63. package/lib/verifier-preset.js +126 -0
  64. package/lib/verify.d.ts +64 -10
  65. package/lib/verify.js +287 -77
  66. package/package.json +51 -38
  67. package/skills/ralphflow-create/SKILL.md +32 -0
  68. package/skills/ralphflow-create/graph-authoring.md +85 -0
  69. package/skills/ralphflow-create/matt/LICENSE +21 -0
  70. package/skills/ralphflow-create/matt/SHA256SUMS +6 -0
  71. package/skills/ralphflow-create/matt/SKILL-MECHANICS.md +22 -0
  72. package/skills/ralphflow-create/matt/SOURCE.md +12 -0
  73. package/skills/ralphflow-create/matt/grilling.md +30 -0
  74. package/skills/ralphflow-create/matt/to-spec.md +75 -0
  75. package/skills/ralphflow-create/matt/to-tickets.md +105 -0
  76. package/skills/ralphflow-create/matt/writing-for-agents.md +81 -0
  77. package/skills/ralphflow-create/ralphflow-authoring.md +31 -0
  78. package/skills/ralphflow-create/testing-workflow.md +60 -0
  79. package/skills/ralphflow-create/workflow-authoring.md +137 -0
  80. package/workflows/create-graph/steps/graph.md +17 -0
  81. package/workflows/create-graph/workflow.yaml +77 -0
  82. package/workflows/loop/workflow.yaml +23 -0
  83. package/workflows/spec/workflow.yaml +105 -0
  84. package/lib/create.d.ts +0 -10
  85. package/lib/create.js +0 -147
  86. package/workflows/loop.yaml +0 -45
  87. package/workflows/spec.yaml +0 -110
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Graph 工作流资产契约(目录形态 `graphs/<name>/graph.yaml`,兼容单文件 `graphs/<name>.yaml`)。
3
+ *
4
+ * 用户格式与 Flow 对齐:`steps` / `id` / `desc` / `do` / `output` / `check`;
5
+ * Graph 只额外用 `depends_on` 表达 DAG。运行时内部仍用 `GraphNode`
6
+ *(`artifact` / `dependsOn` / 派生的上游 `inputs`)。
7
+ *
8
+ * Graph 始终在 Git 隔离 worktree 中并行执行,没有 workspace 开关;
9
+ * 没有固定默认 CHECK;`check` 是显式判据字符串或 `null`。
10
+ */
11
+ import { createHash } from "node:crypto";
12
+ import { checkDefinition } from "./check.js";
13
+ export const GRAPH_KIND = "graph";
14
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
15
+ const stableIdPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
16
+ export function isStableId(value) {
17
+ return typeof value === "string"
18
+ && value.trim() === value
19
+ && stableIdPattern.test(value)
20
+ && !value.includes("..");
21
+ }
22
+ export function isArtifactPath(value) {
23
+ if (typeof value !== "string" || value.length === 0 || value.trim() !== value)
24
+ return false;
25
+ if (value.includes("\\") || value.includes("\0"))
26
+ return false;
27
+ if (value.startsWith("/") || /^[A-Za-z]:/.test(value))
28
+ return false;
29
+ const segments = value.split("/");
30
+ return segments.every((segment) => segment.length > 0 && segment !== "." && segment !== "..");
31
+ }
32
+ function deepFreeze(value) {
33
+ if (value === null || typeof value !== "object")
34
+ return value;
35
+ for (const child of Object.values(value))
36
+ deepFreeze(child);
37
+ return Object.freeze(value);
38
+ }
39
+ function clone(value) {
40
+ return structuredClone(value);
41
+ }
42
+ /** 校验并归一化一份 Graph 资产;返回的 asset 是深度冻结的快照。 */
43
+ export function validateGraphAsset(input) {
44
+ const errors = [];
45
+ const warnings = [];
46
+ const issue = (at, code, message) => {
47
+ errors.push({ path: at, code, message });
48
+ };
49
+ if (!isRecord(input)) {
50
+ return { asset: null, errors: [{ path: "", code: "INVALID_ASSET", message: "Graph 资产必须是一个 YAML 映射。" }], warnings };
51
+ }
52
+ if (input.kind !== GRAPH_KIND) {
53
+ issue("/kind", "MISSING_KIND", "Graph 资产必须显式声明 `kind: graph`。");
54
+ }
55
+ if (Object.prototype.hasOwnProperty.call(input, "nodes")) {
56
+ issue("/nodes", "OLD_NODES_FORMAT", "Graph 只使用 `steps`;`nodes` / `dependsOn` / `artifact` 不是本版本的字段,改用 `steps` + `depends_on` + `output`。");
57
+ }
58
+ const unsupportedTopLevel = [
59
+ "kind", "steps", "id", "name", "description", "manual_step",
60
+ "inputs", "resources", "parallel", "run_inputs", "shared_resources", "max_parallel_agents",
61
+ "workspace", "workspace_resources", "workspace_environment", "version",
62
+ ];
63
+ for (const key of Object.keys(input)) {
64
+ if (!unsupportedTopLevel.includes(key)) {
65
+ issue(`/${key}`, "UNSUPPORTED_FIELD", `Graph 资产不支持顶层字段 \`${key}\`。`);
66
+ }
67
+ }
68
+ for (const key of ["inputs", "resources", "parallel", "run_inputs", "shared_resources", "max_parallel_agents", "workspace", "workspace_resources", "workspace_environment", "version"]) {
69
+ if (Object.prototype.hasOwnProperty.call(input, key)) {
70
+ issue(`/${key}`, "REMOVED_FIELD", `Graph 资产不支持 \`${key}\`:Graph 始终用 Git 隔离;用 \`steps\` 的 \`depends_on\` 表达任务图,并发由宿主的 agent 额度管理。`);
71
+ }
72
+ }
73
+ if (!isStableId(input.id)) {
74
+ issue("/id", "INVALID_ID", "资产 id 必须是稳定的、可作文件名的标识(字母数字开头,只含 A-Z a-z 0-9 . _ -)。");
75
+ }
76
+ if (typeof input.name !== "string" || !input.name.trim()) {
77
+ issue("/name", "MISSING_NAME", "资产 name 不能为空。");
78
+ }
79
+ if (input.description !== undefined && typeof input.description !== "string") {
80
+ issue("/description", "INVALID_DESCRIPTION", "description 必须是字符串。");
81
+ }
82
+ const rawSteps = input.steps;
83
+ if (!Array.isArray(rawSteps) || rawSteps.length === 0) {
84
+ issue("/steps", "MISSING_STEPS", "Graph 资产至少需要一个步骤。");
85
+ return { asset: null, errors, warnings };
86
+ }
87
+ const stepIndexById = new Map();
88
+ const outputById = new Map();
89
+ rawSteps.forEach((raw, index) => {
90
+ if (!isRecord(raw))
91
+ return;
92
+ if (isStableId(raw.id)) {
93
+ stepIndexById.set(raw.id, index);
94
+ outputById.set(raw.id, typeof raw.output === "string" ? raw.output : `${raw.id}.md`);
95
+ }
96
+ });
97
+ const supportedStepKeys = new Set(["id", "desc", "do", "output", "depends_on", "execution", "check"]);
98
+ const normalized = [];
99
+ const artifactIndexByPath = new Map();
100
+ rawSteps.forEach((raw, index) => {
101
+ const at = `/steps/${index}`;
102
+ if (!isRecord(raw)) {
103
+ issue(at, "INVALID_STEP", "步骤必须是对象。");
104
+ normalized.push(null);
105
+ return;
106
+ }
107
+ for (const key of Object.keys(raw)) {
108
+ if (!supportedStepKeys.has(key))
109
+ issue(`${at}/${key}`, "UNSUPPORTED_STEP_FIELD", `Graph 步骤不支持 \`${key}\`;可用字段:id、desc、do、output、depends_on、execution、check。`);
110
+ }
111
+ if (!isStableId(raw.id))
112
+ issue(`${at}/id`, "INVALID_STEP_ID", "步骤 id 必须是稳定标识。");
113
+ else if ([...rawSteps.slice(0, index)].some((item) => isRecord(item) && item.id === raw.id)) {
114
+ issue(`${at}/id`, "DUPLICATE_STEP_ID", `步骤 id "${raw.id}" 重复。`);
115
+ }
116
+ if (typeof raw.desc !== "string" || !raw.desc.trim()) {
117
+ issue(`${at}/desc`, "MISSING_STEP_DESC", "每个步骤都要写 `desc`(一句话说明)。");
118
+ }
119
+ if (typeof raw.do !== "string" || !raw.do.trim())
120
+ issue(`${at}/do`, "MISSING_DO", "步骤 DO 不能为空。");
121
+ let check;
122
+ try {
123
+ const definition = checkDefinition(raw.check);
124
+ check = definition.mode === "disabled" ? null : { mode: "custom", criteria: definition.criteriaText };
125
+ }
126
+ catch (error) {
127
+ issue(`${at}/check`, "INVALID_CHECK", error instanceof Error ? error.message : String(error));
128
+ check = null;
129
+ }
130
+ const id = isStableId(raw.id) ? raw.id : "";
131
+ const artifact = typeof raw.output === "string" ? raw.output : (id ? `${id}.md` : `step-${index + 1}.md`);
132
+ if (!isArtifactPath(artifact)) {
133
+ issue(`${at}/output`, "INVALID_ARTIFACT_PATH", "output 必须是非空、安全的相对路径(不能含 . / .. 段)。");
134
+ }
135
+ else if (artifactIndexByPath.has(artifact)) {
136
+ issue(`${at}/output`, "DUPLICATE_ARTIFACT_PATH", `output "${artifact}" 与 /steps/${artifactIndexByPath.get(artifact)}/output 重复。`);
137
+ }
138
+ else {
139
+ artifactIndexByPath.set(artifact, index);
140
+ }
141
+ let dependsRaw = raw.depends_on === undefined ? [] : raw.depends_on;
142
+ if (!Array.isArray(dependsRaw)) {
143
+ issue(`${at}/depends_on`, "INVALID_DEPENDENCIES", "depends_on 必须是步骤 id 数组。");
144
+ dependsRaw = [];
145
+ }
146
+ const seenDependencies = new Set();
147
+ const dependsOn = dependsRaw.map((dependency, dependencyIndex) => {
148
+ if (!isStableId(dependency)) {
149
+ issue(`${at}/depends_on/${dependencyIndex}`, "INVALID_DEPENDENCY_ID", "依赖必须是合法步骤 id。");
150
+ return String(dependency);
151
+ }
152
+ if (seenDependencies.has(dependency)) {
153
+ issue(`${at}/depends_on/${dependencyIndex}`, "DUPLICATE_DEPENDENCY", `依赖 "${dependency}" 重复。`);
154
+ }
155
+ seenDependencies.add(dependency);
156
+ return dependency;
157
+ });
158
+ const execution = raw.execution === undefined ? "background" : raw.execution;
159
+ if (execution !== "background" && execution !== "main") {
160
+ issue(`${at}/execution`, "INVALID_EXECUTION", "execution 必须是 \"background\" 或 \"main\"。");
161
+ }
162
+ normalized.push({
163
+ id,
164
+ ...(typeof raw.desc === "string" ? { name: raw.desc.trim() } : {}),
165
+ do: typeof raw.do === "string" ? raw.do.trim() : String(raw.do ?? ""),
166
+ artifact,
167
+ dependsOn,
168
+ inputs: dependsOn.map((dependency) => ({ fromNode: dependency, artifact: outputById.get(dependency) ?? `${dependency}.md` })),
169
+ execution: execution,
170
+ check,
171
+ });
172
+ });
173
+ // 引用完整性 + 环检测
174
+ normalized.forEach((node, index) => {
175
+ if (!node)
176
+ return;
177
+ for (const [dependencyIndex, dependency] of node.dependsOn.entries()) {
178
+ const sourceIndex = stepIndexById.get(dependency);
179
+ if (sourceIndex === undefined) {
180
+ issue(`/steps/${index}/depends_on/${dependencyIndex}`, "UNKNOWN_DEPENDENCY", `依赖 "${dependency}" 不存在于本资产。`);
181
+ }
182
+ else if (dependency === node.id) {
183
+ issue(`/steps/${index}/depends_on/${dependencyIndex}`, "SELF_DEPENDENCY", "步骤不能依赖自身。");
184
+ }
185
+ }
186
+ for (const [inputIndex, reference] of node.inputs.entries()) {
187
+ const sourceIndex = stepIndexById.get(reference.fromNode);
188
+ if (sourceIndex === undefined) {
189
+ issue(`/steps/${index}/depends_on/${inputIndex}`, "UNKNOWN_INPUT_SOURCE", `输入来源 "${reference.fromNode}" 不存在。`);
190
+ continue;
191
+ }
192
+ const source = normalized[sourceIndex];
193
+ if (source && source.artifact !== reference.artifact) {
194
+ issue(`/steps/${index}/depends_on/${inputIndex}`, "INPUT_ARTIFACT_MISMATCH", `步骤 "${reference.fromNode}" 的 output 是 "${source.artifact}"。`);
195
+ }
196
+ }
197
+ });
198
+ const visiting = new Set();
199
+ const visited = new Set();
200
+ const cycleReported = new Set();
201
+ const visit = (id) => {
202
+ if (visited.has(id))
203
+ return;
204
+ if (visiting.has(id)) {
205
+ const index = stepIndexById.get(id);
206
+ if (index !== undefined && !cycleReported.has(id)) {
207
+ cycleReported.add(id);
208
+ issue(`/steps/${index}/depends_on`, "DEPENDENCY_CYCLE", `步骤 "${id}" 参与了依赖环。`);
209
+ }
210
+ return;
211
+ }
212
+ visiting.add(id);
213
+ const node = normalized[stepIndexById.get(id) ?? -1];
214
+ for (const dependency of node?.dependsOn ?? [])
215
+ if (stepIndexById.has(dependency))
216
+ visit(dependency);
217
+ visiting.delete(id);
218
+ visited.add(id);
219
+ };
220
+ for (const id of stepIndexById.keys())
221
+ visit(id);
222
+ let manualRaw = input.manual_step === undefined ? [] : input.manual_step;
223
+ if (typeof manualRaw === "string")
224
+ manualRaw = manualRaw.split(",").map((item) => item.trim()).filter(Boolean);
225
+ if (!Array.isArray(manualRaw)) {
226
+ issue("/manual_step", "INVALID_MANUAL_STEP", "manual_step 必须是步骤 id 列表(或逗号分隔字符串)。");
227
+ manualRaw = [];
228
+ }
229
+ const manualSeen = new Set();
230
+ const manualStep = manualRaw.map((id, index) => {
231
+ if (!isStableId(id))
232
+ issue(`/manual_step/${index}`, "INVALID_MANUAL_STEP_ID", "manual_step 条目必须是合法步骤 id。");
233
+ else if (!stepIndexById.has(id))
234
+ issue(`/manual_step/${index}`, "UNKNOWN_MANUAL_STEP", `manual_step 引用了不存在的步骤 "${id}"。`);
235
+ if (manualSeen.has(String(id)))
236
+ issue(`/manual_step/${index}`, "DUPLICATE_MANUAL_STEP", `步骤 "${String(id)}" 在 manual_step 中重复。`);
237
+ manualSeen.add(String(id));
238
+ return String(id);
239
+ });
240
+ if (errors.length > 0)
241
+ return { asset: null, errors, warnings };
242
+ const asset = {
243
+ kind: GRAPH_KIND,
244
+ id: input.id,
245
+ name: input.name.trim(),
246
+ ...(typeof input.description === "string" ? { description: input.description } : {}),
247
+ manual_step: manualStep,
248
+ nodes: normalized.filter((node) => node !== null),
249
+ };
250
+ return { asset: deepFreeze(asset), errors: [], warnings };
251
+ }
252
+ /** 资产内容哈希(报告与状态快照用;不依赖文件 mtime)。 */
253
+ export function graphAssetHash(asset) {
254
+ const canonical = {
255
+ kind: asset.kind,
256
+ id: asset.id,
257
+ name: asset.name,
258
+ description: asset.description,
259
+ manual_step: asset.manual_step,
260
+ nodes: asset.nodes.map((node) => ({
261
+ id: node.id,
262
+ name: node.name,
263
+ do: node.do,
264
+ artifact: node.artifact,
265
+ dependsOn: node.dependsOn,
266
+ inputs: node.inputs,
267
+ execution: node.execution,
268
+ check: node.check,
269
+ })),
270
+ };
271
+ return `sha256:${createHash("sha256").update(JSON.stringify(canonical)).digest("hex")}`;
272
+ }
273
+ /** 启动回执里显示的节点摘要。 */
274
+ export function describeGraphAsset(asset) {
275
+ return asset.nodes.map((node) => `${node.id}${node.dependsOn.length ? ` <- ${node.dependsOn.join(",")}` : ""}`).join(";");
276
+ }
@@ -0,0 +1,47 @@
1
+ import { type GraphAsset } from "./asset.js";
2
+ export declare const GRAPH_DIRNAME = "graphs";
3
+ export declare const BUILTIN_GRAPHS: readonly ["codewiki"];
4
+ export interface GraphWorkflowEntry {
5
+ name: string;
6
+ desc: string;
7
+ invalid: boolean;
8
+ problems: string[];
9
+ warnings: string[];
10
+ path?: string;
11
+ source: "workspace" | "global" | "builtin";
12
+ nodes: number;
13
+ id?: string;
14
+ }
15
+ export interface GraphLoadResult {
16
+ def: GraphAsset | null;
17
+ problems: string[];
18
+ warnings: string[];
19
+ path?: string;
20
+ }
21
+ export interface DiscoveredYaml {
22
+ kind: "flow" | "graph" | "conflict" | "unknown";
23
+ problems: string[];
24
+ nodes: number;
25
+ }
26
+ /** 项目级 Graph 资产目录:`<项目根>/.dsh/ralph-flow/graphs/` */
27
+ export declare function graphWorkspaceDir(workspace: string): string;
28
+ /** 用户级 Graph 资产目录:`<DSH_HOME|~/.dsh>/ralph-flow/graphs/` */
29
+ export declare function graphGlobalDir(): string;
30
+ /** 内置 Graph 资产路径(不落盘,随包发布;`lib/graph/assets.js` → `<pkg>/graphs/<name>/graph.yaml`)。 */
31
+ export declare function builtinGraphPath(name: string): string | undefined;
32
+ /**
33
+ * 只看顶层结构,判断一份 YAML 属于哪类资产。**不替代完整校验**:它只负责在把文件交给
34
+ * Flow 或 Graph 校验器之前,先发现“无 kind 的 nodes”“kind 与结构冲突”“两类结构同写”。
35
+ */
36
+ export declare function classifyYamlDocument(doc: unknown): DiscoveredYaml;
37
+ /** 某工作区里所有 Graph 资产的发现结果(工作区遮蔽全局/内置;不建目录)。 */
38
+ export declare function listGraphWorkflows(workspace: string): GraphWorkflowEntry[];
39
+ /** 加载一份 Graph 资产(工作区 → 全局 → 内置);目录/kind 不一致是硬错误。 */
40
+ export declare function loadGraphWorkflow(workspace: string, name: string): GraphLoadResult;
41
+ /** 跨类别同名:返回同时出现在 Flow 与 Graph 里的名字(doctor/list/start 都据此拒绝)。 */
42
+ export declare function crossKindNameConflicts(flowNames: readonly string[], graphEntries: readonly GraphWorkflowEntry[]): Array<{
43
+ name: string;
44
+ kind: "flow-graph";
45
+ }>;
46
+ /** 供测试与 doctor 用:列出候选文件(不读内容)。 */
47
+ export declare function graphAssetFiles(workspace: string): string[];
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Graph 资产的发现与加载(`graphs/` 目录 + 内置)。
3
+ *
4
+ * 与 Flow 的关系:**目录先分派、再看 kind**(design §2.3)。`workflows/` 只按 Flow 校验,
5
+ * `graphs/` 只按 Graph 校验;`kind` 与目录不一致、或同一名字跨类别出现,都是加载期硬错误,
6
+ * 不做“先找到哪个算哪个”的隐式解析。
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import yaml from "js-yaml";
12
+ import { RALPH_FLOW_DIR } from "../engine.js";
13
+ import { userRalphFlowDir } from "../paths.js";
14
+ import { GRAPH_ENTRY_FILE, assetCandidates, discoverAssetsIn } from "../asset-path.js";
15
+ import { validateGraphAsset } from "./asset.js";
16
+ export const GRAPH_DIRNAME = "graphs";
17
+ export const BUILTIN_GRAPHS = ["codewiki"];
18
+ /** 项目级 Graph 资产目录:`<项目根>/.dsh/ralph-flow/graphs/` */
19
+ export function graphWorkspaceDir(workspace) {
20
+ return path.join(workspace, RALPH_FLOW_DIR, GRAPH_DIRNAME);
21
+ }
22
+ /** 用户级 Graph 资产目录:`<DSH_HOME|~/.dsh>/ralph-flow/graphs/` */
23
+ export function graphGlobalDir() {
24
+ return userRalphFlowDir(GRAPH_DIRNAME);
25
+ }
26
+ /** 内置 Graph 资产路径(不落盘,随包发布;`lib/graph/assets.js` → `<pkg>/graphs/<name>/graph.yaml`)。 */
27
+ export function builtinGraphPath(name) {
28
+ const here = path.dirname(fileURLToPath(import.meta.url));
29
+ const candidates = [
30
+ ...assetCandidates(path.resolve(here, "..", "..", GRAPH_DIRNAME), name, GRAPH_ENTRY_FILE),
31
+ ...assetCandidates(path.resolve(here, "..", "..", "..", GRAPH_DIRNAME), name, GRAPH_ENTRY_FILE),
32
+ ];
33
+ return candidates.find((candidate) => {
34
+ try {
35
+ return fs.statSync(candidate).isFile();
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ });
41
+ }
42
+ /**
43
+ * 只看顶层结构,判断一份 YAML 属于哪类资产。**不替代完整校验**:它只负责在把文件交给
44
+ * Flow 或 Graph 校验器之前,先发现“无 kind 的 nodes”“kind 与结构冲突”“两类结构同写”。
45
+ */
46
+ export function classifyYamlDocument(doc) {
47
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
48
+ return { kind: "unknown", problems: ["内容不是一个 YAML 映射。"], nodes: 0 };
49
+ }
50
+ const record = doc;
51
+ const problems = [];
52
+ const hasSteps = Object.prototype.hasOwnProperty.call(record, "steps");
53
+ const hasNodes = Object.prototype.hasOwnProperty.call(record, "nodes");
54
+ const kind = record.kind;
55
+ if (kind !== undefined && kind !== "flow" && kind !== "graph")
56
+ problems.push("`kind` 只能是 `flow` 或 `graph`。");
57
+ if (hasSteps && hasNodes)
58
+ problems.push("资产同时写了 `steps` 和 `nodes`:Flow 与 Graph 字段不混用。");
59
+ // 新格式:Graph 也用 Flow 风格的 steps;只有「两类结构同写」才是冲突。
60
+ if (kind === "flow" && hasNodes)
61
+ problems.push("声明了 `kind: flow` 却写了 `nodes`:Flow 资产必须是 `steps`。");
62
+ if (kind === undefined && hasNodes)
63
+ problems.push("Graph 资产(`nodes`)必须显式声明 `kind: graph`;无 kind 的 nodes 资产不会被猜测成 Graph。");
64
+ if (problems.length > 0) {
65
+ return { kind: "conflict", problems, nodes: Array.isArray(record.nodes) ? record.nodes.length : 0 };
66
+ }
67
+ if (kind === "graph" || (kind === undefined && hasSteps)) {
68
+ return {
69
+ kind: kind === "graph" ? "graph" : "flow",
70
+ problems: [],
71
+ nodes: Array.isArray(record.nodes) ? record.nodes.length : Array.isArray(record.steps) ? record.steps.length : 0,
72
+ };
73
+ }
74
+ if (hasSteps)
75
+ return { kind: "flow", problems: [], nodes: 0 };
76
+ return { kind: "unknown", problems: ["没有 `steps` 或 `nodes`:无法判断工作流类别。"], nodes: 0 };
77
+ }
78
+ function readYamlFile(file) {
79
+ let raw;
80
+ try {
81
+ raw = fs.readFileSync(file, "utf-8");
82
+ }
83
+ catch (error) {
84
+ return { problem: `${file} 读取失败:${error instanceof Error ? error.message : String(error)}` };
85
+ }
86
+ try {
87
+ return { doc: yaml.load(raw.replace(/^\uFEFF/, "")) };
88
+ }
89
+ catch (error) {
90
+ return { problem: `${file} YAML 解析失败:${error instanceof Error ? error.message : String(error)}` };
91
+ }
92
+ }
93
+ function withGraphIdentity(doc, name) {
94
+ if (!doc || typeof doc !== "object" || Array.isArray(doc))
95
+ return doc;
96
+ const record = doc;
97
+ return { ...record, id: record.id ?? name, name: record.name ?? name };
98
+ }
99
+ function graphCandidatePaths(workspace, name) {
100
+ const out = [];
101
+ for (const [dir, source] of [
102
+ [graphWorkspaceDir(workspace), "workspace"],
103
+ [graphGlobalDir(), "global"],
104
+ ]) {
105
+ for (const file of assetCandidates(dir, name, GRAPH_ENTRY_FILE))
106
+ out.push({ file, source });
107
+ }
108
+ const builtin = builtinGraphPath(name);
109
+ if (builtin)
110
+ out.push({ file: builtin, source: "builtin" });
111
+ return out;
112
+ }
113
+ /** 某工作区里所有 Graph 资产的发现结果(工作区遮蔽全局/内置;不建目录)。 */
114
+ export function listGraphWorkflows(workspace) {
115
+ const found = new Map();
116
+ const addDir = (dir, source) => {
117
+ for (const [name, file] of discoverAssetsIn(dir, GRAPH_ENTRY_FILE)) {
118
+ if (!found.has(name))
119
+ found.set(name, { file, source });
120
+ }
121
+ };
122
+ addDir(graphWorkspaceDir(workspace), "workspace");
123
+ addDir(graphGlobalDir(), "global");
124
+ for (const name of BUILTIN_GRAPHS) {
125
+ if (found.has(name))
126
+ continue;
127
+ const file = builtinGraphPath(name);
128
+ if (file)
129
+ found.set(name, { file, source: "builtin" });
130
+ }
131
+ return [...found.entries()].map(([name, { file, source }]) => {
132
+ const { doc, problem } = readYamlFile(file);
133
+ if (problem)
134
+ return { name, desc: "", invalid: true, problems: [problem], warnings: [], path: file, source, nodes: 0 };
135
+ const classified = classifyYamlDocument(doc);
136
+ if (classified.kind === "flow") {
137
+ return {
138
+ name, desc: "", invalid: true,
139
+ problems: [`${file} 是 Flow 资产(steps),却放在 graphs/ 目录:Flow 资产只放 workflows/。`],
140
+ warnings: [], path: file, source, nodes: 0,
141
+ };
142
+ }
143
+ if (classified.kind !== "graph") {
144
+ return { name, desc: "", invalid: true, problems: classified.problems, warnings: [], path: file, source, nodes: classified.nodes };
145
+ }
146
+ const validation = validateGraphAsset(withGraphIdentity(doc, name));
147
+ return {
148
+ name,
149
+ desc: validation.asset?.description ?? "",
150
+ invalid: validation.asset === null,
151
+ problems: validation.errors.map((error) => `${error.path || "/"}:${error.message}`),
152
+ warnings: validation.warnings,
153
+ path: file,
154
+ source,
155
+ nodes: validation.asset?.nodes.length ?? classified.nodes,
156
+ ...(validation.asset ? { id: validation.asset.id } : {}),
157
+ };
158
+ }).sort((left, right) => left.name.localeCompare(right.name));
159
+ }
160
+ /** 加载一份 Graph 资产(工作区 → 全局 → 内置);目录/kind 不一致是硬错误。 */
161
+ export function loadGraphWorkflow(workspace, name) {
162
+ const problems = [];
163
+ const warnings = [];
164
+ const candidates = graphCandidatePaths(workspace, name);
165
+ // 工作区里的同名文件遮蔽全局/内置:只取第一个存在的候选,但**继续检查**是否还有别的
166
+ // 类别(Flow)用了同一个名字 —— 跨类别同名由 listAssetsIn/doctor 统一报。
167
+ let chosen;
168
+ for (const candidate of candidates) {
169
+ try {
170
+ if (fs.statSync(candidate.file).isFile()) {
171
+ chosen = candidate;
172
+ break;
173
+ }
174
+ }
175
+ catch { }
176
+ }
177
+ if (!chosen) {
178
+ problems.push(`未找到 Graph 工作流 "${name}"。把资产放到 ${graphWorkspaceDir(workspace)}/<name>/graph.yaml(目录形态;单文件 ${graphWorkspaceDir(workspace)}/<name>.yaml 也识别)即可被加载。`);
179
+ return { def: null, problems, warnings };
180
+ }
181
+ const { doc, problem } = readYamlFile(chosen.file);
182
+ if (problem)
183
+ return { def: null, problems: [problem], warnings, path: chosen.file };
184
+ const classified = classifyYamlDocument(doc);
185
+ if (classified.kind === "flow") {
186
+ problems.push(`${chosen.file} 是 Flow 资产(steps),却放在 graphs/ 目录:Flow 资产只放 workflows/。`);
187
+ return { def: null, problems, warnings, path: chosen.file };
188
+ }
189
+ if (classified.kind !== "graph") {
190
+ problems.push(...classified.problems);
191
+ return { def: null, problems, warnings, path: chosen.file };
192
+ }
193
+ const validation = validateGraphAsset(withGraphIdentity(doc, name));
194
+ warnings.push(...validation.warnings);
195
+ if (!validation.asset) {
196
+ problems.push(...validation.errors.map((error) => `${error.path || "/"}:${error.message}`));
197
+ return { def: null, problems, warnings, path: chosen.file };
198
+ }
199
+ const asset = validation.asset;
200
+ if (asset.id !== name) {
201
+ // 启动名与技能名来自目录名(单文件形态是文件名),id 是资产自身标识;不一致会让“报告里的 id”
202
+ // 与“启动的名字”分叉。
203
+ warnings.push(`资产 id "${asset.id}" 与启动名 "${name}" 不一致:启动名以资产名(目录名)为准,报告会同时记录两者。`);
204
+ }
205
+ return { def: asset, problems, warnings, path: chosen.file };
206
+ }
207
+ /** 跨类别同名:返回同时出现在 Flow 与 Graph 里的名字(doctor/list/start 都据此拒绝)。 */
208
+ export function crossKindNameConflicts(flowNames, graphEntries) {
209
+ const graphNames = new Set(graphEntries.map((entry) => entry.name));
210
+ return [...new Set(flowNames)].filter((name) => graphNames.has(name)).sort().map((name) => ({ name, kind: "flow-graph" }));
211
+ }
212
+ /** 供测试与 doctor 用:列出候选文件(不读内容)。 */
213
+ export function graphAssetFiles(workspace) {
214
+ const files = [];
215
+ for (const dir of [graphWorkspaceDir(workspace), graphGlobalDir()]) {
216
+ files.push(...discoverAssetsIn(dir, GRAPH_ENTRY_FILE).values());
217
+ }
218
+ for (const name of BUILTIN_GRAPHS) {
219
+ const file = builtinGraphPath(name);
220
+ if (file)
221
+ files.push(file);
222
+ }
223
+ return files;
224
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Graph 的分支命名。集成分支与节点分支共用一份定义:
3
+ * 状态读取时补 `branch` 与 Git 工作区都必须写出同一串名字。
4
+ */
5
+ export declare const INTEGRATION_BRANCH_PREFIX = "ralphflow";
6
+ /** 节点分支另起一个前缀:`refs/heads` 里一条分支不能同时是另一条分支的目录。 */
7
+ export declare const NODE_BRANCH_PREFIX = "ralphflow-node";
8
+ export declare function integrationBranchFor(instId: string): string;
9
+ export declare function nodeBranchFor(instId: string, nodeId: string): string;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Graph 的分支命名。集成分支与节点分支共用一份定义:
3
+ * 状态读取时补 `branch` 与 Git 工作区都必须写出同一串名字。
4
+ */
5
+ export const INTEGRATION_BRANCH_PREFIX = "ralphflow";
6
+ /** 节点分支另起一个前缀:`refs/heads` 里一条分支不能同时是另一条分支的目录。 */
7
+ export const NODE_BRANCH_PREFIX = "ralphflow-node";
8
+ export function integrationBranchFor(instId) {
9
+ return `${INTEGRATION_BRANCH_PREFIX}/${instId}`;
10
+ }
11
+ export function nodeBranchFor(instId, nodeId) {
12
+ return `${NODE_BRANCH_PREFIX}/${instId}/${nodeId}`;
13
+ }
@@ -0,0 +1,23 @@
1
+ export interface CheckDisabled {
2
+ mode: "disabled";
3
+ criteriaText: "";
4
+ criteria: [];
5
+ }
6
+ export interface CheckCustom {
7
+ mode: "custom";
8
+ criteriaText: string;
9
+ criteria: string[];
10
+ }
11
+ export type CheckDefinition = CheckDisabled | CheckCustom;
12
+ /** 多行判据:全部是列表项时逐项拆开,否则整段作为一条。 */
13
+ export declare function criteriaItems(criteria: string): string[];
14
+ /**
15
+ * 归一化 Graph CHECK:
16
+ * - 字符串:显式判据(与 Flow 的 `check` 同形)
17
+ * - `null` / 省略:关闭独立 CHECK
18
+ *
19
+ * 对象写法(`{mode: default}` / `{mode: custom, criteria}`)已移除。
20
+ */
21
+ export declare function checkDefinition(check: unknown): CheckDefinition;
22
+ /** 判据版本:自定义判据用原文 sha256;关闭时为 null。 */
23
+ export declare function checkVersion(definition: CheckDefinition): string | null;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Graph CHECK 判据归一化与快照。
3
+ *
4
+ * Graph 不提供固定的“默认 CHECK”文本:判据必须由资产作者(或设计 Graph 的模型)按
5
+ * writing-for-agents 写成显式验收条件。`check: null` 表示该节点跳过独立验证,
6
+ * 与 Flow 的“不写 check = 跳过”同一语义。
7
+ *
8
+ * 判定本身不在这里产生:Graph CHECK 必须走 `src/verify.ts` 的独立验证者运行时(T1)。
9
+ */
10
+ import { createHash } from "node:crypto";
11
+ /** 多行判据:全部是列表项时逐项拆开,否则整段作为一条。 */
12
+ export function criteriaItems(criteria) {
13
+ const lines = criteria.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
14
+ if (lines.length === 0)
15
+ return [criteria];
16
+ // 单行也允许带一个列表标记:作者常写 `criteria: |` + `1. …`,这里剥掉外层标记后
17
+ // 提示词再统一编号,证据才逐字对得上。
18
+ if (!lines.every((line) => /^(?:[-*+]\s+|\d+[.)、]\s*)/.test(line)))
19
+ return [criteria];
20
+ return lines.map((line) => line.replace(/^(?:[-*+]\s+|\d+[.)、]\s*)/, ""));
21
+ }
22
+ /**
23
+ * 归一化 Graph CHECK:
24
+ * - 字符串:显式判据(与 Flow 的 `check` 同形)
25
+ * - `null` / 省略:关闭独立 CHECK
26
+ *
27
+ * 对象写法(`{mode: default}` / `{mode: custom, criteria}`)已移除。
28
+ */
29
+ export function checkDefinition(check) {
30
+ if (check === undefined || check === null) {
31
+ return { mode: "disabled", criteriaText: "", criteria: [] };
32
+ }
33
+ if (check !== null && typeof check === "object") {
34
+ throw new Error("Graph CHECK 只接受字符串或 `check: null`;`{mode, criteria}` 对象写法已移除。");
35
+ }
36
+ if (typeof check !== "string" || !check.trim()) {
37
+ throw new Error("CHECK 需要非空判据字符串;要关闭 CHECK 请显式写 `check: null`。");
38
+ }
39
+ return { mode: "custom", criteriaText: check, criteria: criteriaItems(check) };
40
+ }
41
+ /** 判据版本:自定义判据用原文 sha256;关闭时为 null。 */
42
+ export function checkVersion(definition) {
43
+ if (definition.mode === "disabled")
44
+ return null;
45
+ return `sha256:${createHash("sha256").update(definition.criteriaText).digest("hex")}`;
46
+ }