ralphflow-dsh 2.4.1 → 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.
@@ -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;
@@ -1,4 +1,4 @@
1
- import { type HistoryEntry } from "../engine.js";
1
+ import type { HistoryEntry } from "../engine.js";
2
2
  import type { GraphAsset, GraphNode } from "./asset.js";
3
3
  export type GraphRunStatus = "running" | "paused" | "waiting" | "interrupted" | "completed" | "failed" | "cancelled";
4
4
  export type GraphNodeStatus = "pending" | "blocked" | "running" | "verifying" | "reworking" | "waiting_review" | "waiting" | "integrating" | "accepting" | "completed" | "failed" | "cancelled" | "interrupted";
@@ -137,18 +137,17 @@ export interface GraphInstanceState {
137
137
  };
138
138
  history: HistoryEntry[];
139
139
  }
140
- export declare function graphRootOf(workspace: string): string;
141
- export declare function graphInstancesDirOf(workspace: string): string;
142
- export declare function graphReportsDirOf(workspace: string): string;
143
- export declare function graphInstanceDirOf(workspace: string, instId: string): string;
144
- export declare function graphStatePathOf(workspace: string, instId: string): string;
145
- export declare function graphArtifactsRootOf(workspace: string): string;
146
- export declare function graphArtifactsDirOf(workspace: string, state: Pick<GraphInstanceState, "artifacts_dir_name">): string;
147
- export declare function graphNodeArtifactDirOf(workspace: string, state: Pick<GraphInstanceState, "artifacts_dir_name">, nodeId: string, attemptId: string): string;
148
- export declare function readGraphState(workspace: string, instId: string): GraphInstanceState | null;
149
- export declare function writeGraphState(workspace: string, state: GraphInstanceState, instId: string): void;
150
- /** 扫描本工作区所有 Graph 实例状态(包含已结束但保留的实例)。 */
151
- export declare function listGraphStates(workspace: string): Array<{
140
+ export declare function graphInstancesDirAt(root: string): string;
141
+ export declare function graphReportsDirAt(root: string): string;
142
+ export declare function graphInstanceDirAt(root: string, instId: string): string;
143
+ export declare function graphStatePathAt(root: string, instId: string): string;
144
+ export declare function graphArtifactsRootAt(root: string): string;
145
+ export declare function graphArtifactsDirAt(root: string, state: Pick<GraphInstanceState, "artifacts_dir_name">): string;
146
+ export declare function graphNodeArtifactDirAt(root: string, state: Pick<GraphInstanceState, "artifacts_dir_name">, nodeId: string, attemptId: string): string;
147
+ export declare function readGraphStateAt(root: string, instId: string): GraphInstanceState | null;
148
+ export declare function writeGraphStateAt(root: string, state: GraphInstanceState, instId: string): void;
149
+ /** 扫描运行态根下的所有 Graph 实例状态(包含已结束但保留的实例)。 */
150
+ export declare function listGraphStatesAt(root: string): Array<{
152
151
  id: string;
153
152
  state: GraphInstanceState;
154
153
  }>;
@@ -239,6 +238,7 @@ export interface GraphRunProjection {
239
238
  report: string | null;
240
239
  }
241
240
  export declare function nodeNameOf(state: GraphInstanceState, node: GraphNode): string;
242
- export declare function projectionOf(state: GraphInstanceState, id: string): GraphRunProjection;
241
+ /** `reportPath` = 报告在人话里的写法(默认布局相对路径 / 外部化绝对路径),由调用方按运行态布局给。 */
242
+ export declare function projectionOf(state: GraphInstanceState, id: string, reportPath: string): GraphRunProjection;
243
243
  /** 运行输入与提示词共用的安全路径:只接受相对路径,拒绝逃出工作区。 */
244
244
  export declare function resolveInside(root: string, relative: string): string | null;
@@ -8,40 +8,39 @@
8
8
  */
9
9
  import fs from "node:fs";
10
10
  import path from "node:path";
11
- import { RALPH_FLOW_DIR } from "../engine.js";
12
11
  import { pauseLabel } from "../pause.js";
13
12
  import { nodeBranchFor } from "./branches.js";
14
13
  export const GRAPH_ACTIVE_STATUSES = ["running", "paused", "waiting", "interrupted"];
15
14
  export function isGraphTerminal(status) {
16
15
  return status === "completed" || status === "failed" || status === "cancelled";
17
16
  }
18
- export function graphRootOf(workspace) {
19
- return path.join(workspace, RALPH_FLOW_DIR);
17
+ // ── 运行态路径:`root` 是运行态根(默认 `<项目根>/.dsh/ralph-flow`,外部化时 = 外部目录)──
18
+ // 这里只接受**根**,不接受工作区:外部状态目录与项目根是两个不同的概念,混用一个参数会让
19
+ // 「实例放哪」在两处调用里悄悄分叉。
20
+ export function graphInstancesDirAt(root) {
21
+ return path.join(root, "instances");
20
22
  }
21
- export function graphInstancesDirOf(workspace) {
22
- return path.join(graphRootOf(workspace), "instances");
23
+ export function graphReportsDirAt(root) {
24
+ return path.join(root, "reports");
23
25
  }
24
- export function graphReportsDirOf(workspace) {
25
- return path.join(graphRootOf(workspace), "reports");
26
+ export function graphInstanceDirAt(root, instId) {
27
+ return path.join(graphInstancesDirAt(root), instId);
26
28
  }
27
- export function graphInstanceDirOf(workspace, instId) {
28
- return path.join(graphInstancesDirOf(workspace), instId);
29
+ export function graphStatePathAt(root, instId) {
30
+ return path.join(graphInstanceDirAt(root, instId), "state.json");
29
31
  }
30
- export function graphStatePathOf(workspace, instId) {
31
- return path.join(graphInstanceDirOf(workspace, instId), "state.json");
32
+ export function graphArtifactsRootAt(root) {
33
+ return path.join(root, "artifacts");
32
34
  }
33
- export function graphArtifactsRootOf(workspace) {
34
- return path.join(graphRootOf(workspace), "artifacts");
35
+ export function graphArtifactsDirAt(root, state) {
36
+ return path.join(graphArtifactsRootAt(root), state.artifacts_dir_name);
35
37
  }
36
- export function graphArtifactsDirOf(workspace, state) {
37
- return path.join(graphArtifactsRootOf(workspace), state.artifacts_dir_name);
38
+ export function graphNodeArtifactDirAt(root, state, nodeId, attemptId) {
39
+ return path.join(graphArtifactsDirAt(root, state), "nodes", nodeId, attemptId);
38
40
  }
39
- export function graphNodeArtifactDirOf(workspace, state, nodeId, attemptId) {
40
- return path.join(graphArtifactsDirOf(workspace, state), "nodes", nodeId, attemptId);
41
- }
42
- export function readGraphState(workspace, instId) {
41
+ export function readGraphStateAt(root, instId) {
43
42
  try {
44
- const raw = fs.readFileSync(graphStatePathOf(workspace, instId), "utf-8");
43
+ const raw = fs.readFileSync(graphStatePathAt(root, instId), "utf-8");
45
44
  const parsed = JSON.parse(raw);
46
45
  if (!parsed || parsed.kind !== "graph" || !parsed.graph || !parsed.graph.asset)
47
46
  return null;
@@ -83,18 +82,18 @@ export function readGraphState(workspace, instId) {
83
82
  return null;
84
83
  }
85
84
  }
86
- export function writeGraphState(workspace, state, instId) {
85
+ export function writeGraphStateAt(root, state, instId) {
87
86
  state.updated_at = new Date().toISOString();
88
- const dir = graphInstanceDirOf(workspace, instId);
87
+ const dir = graphInstanceDirAt(root, instId);
89
88
  fs.mkdirSync(dir, { recursive: true });
90
89
  const target = path.join(dir, "state.json");
91
90
  const tmp = path.join(dir, `.state.${process.pid}.tmp`);
92
91
  fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, "utf-8");
93
92
  fs.renameSync(tmp, target);
94
93
  }
95
- /** 扫描本工作区所有 Graph 实例状态(包含已结束但保留的实例)。 */
96
- export function listGraphStates(workspace) {
97
- const dir = graphInstancesDirOf(workspace);
94
+ /** 扫描运行态根下的所有 Graph 实例状态(包含已结束但保留的实例)。 */
95
+ export function listGraphStatesAt(root) {
96
+ const dir = graphInstancesDirAt(root);
98
97
  let entries = [];
99
98
  try {
100
99
  entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -106,7 +105,7 @@ export function listGraphStates(workspace) {
106
105
  for (const entry of entries) {
107
106
  if (!entry.isDirectory())
108
107
  continue;
109
- const state = readGraphState(workspace, entry.name);
108
+ const state = readGraphStateAt(root, entry.name);
110
109
  if (state)
111
110
  out.push({ id: entry.name, state });
112
111
  }
@@ -230,7 +229,8 @@ function checkProjection(state, node) {
230
229
  return { mode, status: "pending", reason: "", reworks: state.graph.rework_counts[node.id] ?? 0 };
231
230
  return { mode, status: verdict.status, reason: verdict.reason, reworks: state.graph.rework_counts[node.id] ?? 0 };
232
231
  }
233
- export function projectionOf(state, id) {
232
+ /** `reportPath` = 报告在人话里的写法(默认布局相对路径 / 外部化绝对路径),由调用方按运行态布局给。 */
233
+ export function projectionOf(state, id, reportPath) {
234
234
  const nodes = state.graph.asset.nodes.map((node) => {
235
235
  const status = nodeStatusOf(state, node);
236
236
  const attempt = latestAttemptOfNode(state, node.id);
@@ -345,7 +345,7 @@ export function projectionOf(state, id) {
345
345
  },
346
346
  startedAt: state.started_at,
347
347
  updatedAt: state.updated_at,
348
- report: isGraphTerminal(state.graph.status) ? `${RALPH_FLOW_DIR}/reports/${id}.md` : null,
348
+ report: isGraphTerminal(state.graph.status) ? reportPath : null,
349
349
  };
350
350
  }
351
351
  /** 运行输入与提示词共用的安全路径:只接受相对路径,拒绝逃出工作区。 */
@@ -16,8 +16,9 @@ export declare function branchTip(root: string, branch: string): Promise<string
16
16
  /** 快进集成分支。调用方先证明节点分支包含 previous,这里只做引用前进。 */
17
17
  export declare function advanceIntegration(root: string, branch: string, previous: string, commit: string): Promise<void>;
18
18
  export declare function containsCommit(cwd: string, ancestor: string, descendant: string): Promise<boolean>;
19
- export declare function worktreeRootOf(workspace: string, instId: string): string;
20
- export declare function nodeWorktreePathOf(workspace: string, instId: string, nodeId: string): string;
19
+ /** 节点 worktree 的根:跟随运行态根(外部化时也在项目根之外,不污染目标仓库)。 */
20
+ export declare function worktreeRootOf(root: string, instId: string): string;
21
+ export declare function nodeWorktreePathOf(root: string, instId: string, nodeId: string): string;
21
22
  /** 节点 worktree 建在节点自己的分支上:`git worktree add -b <branch> <path> <起点>`。 */
22
23
  export declare function ensureNodeWorktree(root: string, workspacePath: string, branch: string, startPoint: string): Promise<{
23
24
  path: string;
@@ -11,7 +11,7 @@ import { createHash } from "node:crypto";
11
11
  import fs from "node:fs";
12
12
  import path from "node:path";
13
13
  import { promisify } from "node:util";
14
- import { graphInstanceDirOf } from "./state.js";
14
+ import { graphInstanceDirAt } from "./state.js";
15
15
  import { INTEGRATION_BRANCH_PREFIX, NODE_BRANCH_PREFIX, integrationBranchFor, nodeBranchFor } from "./branches.js";
16
16
  const execFile = promisify(execFileCallback);
17
17
  export { INTEGRATION_BRANCH_PREFIX, NODE_BRANCH_PREFIX, integrationBranchFor, nodeBranchFor };
@@ -86,11 +86,12 @@ export async function containsCommit(cwd, ancestor, descendant) {
86
86
  return false;
87
87
  }
88
88
  }
89
- export function worktreeRootOf(workspace, instId) {
90
- return path.join(graphInstanceDirOf(workspace, instId), WORKTREES_DIRNAME);
89
+ /** 节点 worktree 的根:跟随运行态根(外部化时也在项目根之外,不污染目标仓库)。 */
90
+ export function worktreeRootOf(root, instId) {
91
+ return path.join(graphInstanceDirAt(root, instId), WORKTREES_DIRNAME);
91
92
  }
92
- export function nodeWorktreePathOf(workspace, instId, nodeId) {
93
- return path.join(worktreeRootOf(workspace, instId), nodeId);
93
+ export function nodeWorktreePathOf(root, instId, nodeId) {
94
+ return path.join(worktreeRootOf(root, instId), nodeId);
94
95
  }
95
96
  async function listedWorktrees(root) {
96
97
  const listing = await git(root, "worktree", "list", "--porcelain");
package/lib/index.d.ts CHANGED
@@ -10,5 +10,15 @@ export declare const inject: string[];
10
10
  */
11
11
  export interface Config {
12
12
  verifierProvider?: string;
13
+ /**
14
+ * 外部状态目录(等价于 `$RALPH_FLOW_STATE_DIR`):`instances/`、`reports/`、`artifacts/`
15
+ * 全部落这里,项目根下**不建** `.dsh/ralph-flow/`。非空即启用;空值按未配置处理。
16
+ */
17
+ stateDir?: string;
18
+ /**
19
+ * 无头模式(等价于 `$RALPH_FLOW_HEADLESS=1`):工作流发现与加载跳过项目级资产目录,
20
+ * 只认用户级与内置;带顶层 `manual_step` 的 Flow / Graph 在加载期拒绝(没有人能放行审查门)。
21
+ */
22
+ ignoreWorkspaceWorkflows?: boolean;
13
23
  }
14
24
  export declare function apply(ctx: Context, config?: Config): void;
package/lib/index.js CHANGED
@@ -59,6 +59,11 @@ export function apply(ctx, config = {}) {
59
59
  // 未声明 Config schema(宿主不需要额外依赖),非法类型按未配置处理,不让 apply 抛错。
60
60
  const configuredProvider = typeof config?.verifierProvider === "string" ? config.verifierProvider.trim() : "";
61
61
  const verifierProvider = configuredProvider || DEFAULT_VERIFIER_PROVIDER;
62
+ /** 运行态选项:插件配置优先,缺省由 `paths.ts` 读环境变量。 */
63
+ const runtime = {
64
+ ...(typeof config?.stateDir === "string" && config.stateDir.trim() ? { stateDir: config.stateDir.trim() } : {}),
65
+ ...(config?.ignoreWorkspaceWorkflows === true ? { ignoreWorkspaceWorkflows: true } : {}),
66
+ };
62
67
  /** 插件加载目录的项目根(没有会话可问时的唯一回落;不再有环境变量旁路)。 */
63
68
  const workspace = projectRootOf(process.cwd());
64
69
  const log = (level, event, data) => {
@@ -76,6 +81,36 @@ export function apply(ctx, config = {}) {
76
81
  return undefined;
77
82
  }
78
83
  };
84
+ /**
85
+ * 回退自己发起的回合中止(`EnginePorts.interrupt`)不是用户按停止:`cancel({kind:"user"})`
86
+ * 会以 `turn/end { reason: { kind: "aborted", reason: { kind: "user" } } }` 收尾,而下面
87
+ * 「停止按钮 = 暂停」的监听会把它当成用户停止,把回退刚清掉的 `paused` 立刻写回 ——
88
+ * 目标步 DO 随即被 `stillLive()` 丢弃。标记只由随后的 user-abort `turn/end` 消费;
89
+ * `turn/start` 与超时兜底负责清掉没有对应事件的残留,绝不吞掉下一次真正的用户停止。
90
+ */
91
+ const rewindInterrupts = new Map();
92
+ const REWIND_INTERRUPT_TTL_MS = 10_000;
93
+ const noteRewindInterrupt = (sessionId) => {
94
+ rewindInterrupts.set(sessionId, (rewindInterrupts.get(sessionId) ?? 0) + 1);
95
+ const timer = setTimeout(() => {
96
+ const left = (rewindInterrupts.get(sessionId) ?? 0) - 1;
97
+ if (left > 0)
98
+ rewindInterrupts.set(sessionId, left);
99
+ else
100
+ rewindInterrupts.delete(sessionId);
101
+ }, REWIND_INTERRUPT_TTL_MS);
102
+ timer.unref?.();
103
+ };
104
+ const consumeRewindInterrupt = (sessionId) => {
105
+ const count = rewindInterrupts.get(sessionId) ?? 0;
106
+ if (count <= 0)
107
+ return false;
108
+ if (count === 1)
109
+ rewindInterrupts.delete(sessionId);
110
+ else
111
+ rewindInterrupts.set(sessionId, count - 1);
112
+ return true;
113
+ };
79
114
  /** 同一段文本的重复投递护栏:命令被连按/重试时只处理一次(窗口内去重) */
80
115
  const recentDeliveries = new Map();
81
116
  const DEDUPE_WINDOW_MS = 5000;
@@ -351,7 +386,30 @@ export function apply(ctx, config = {}) {
351
386
  // 每个调用点都必须显式选一个 —— 端口名就是分类,代码里一眼看得出(见 docs/v2/delivery-classification.md
352
387
  // 与 scripts/delivery-classification-test.mjs 的静态审计)。
353
388
  deliverDirective,
389
+ // 新一轮(round)载体:引擎自驱的「下一轮 DO」(回合收尾的提醒)走 followup —— 本回合正常
390
+ // 收尾,提醒成为下一回合的第一条。与 steer 的差别见 deliverRound 的注释。
391
+ deliverRound,
354
392
  deliverNotice,
393
+ /**
394
+ * 中止属主会话当前回合:`/ralphflow-rewind` 的第一件事。与宿主停止按钮同款调用
395
+ * (`dsh-api-session-controller` 的 cancel:`agent.cancel({ kind: "user" }, { keepInbox: true })`)。
396
+ * 只登记「有回合可停」的中止标记,避免空闲 no-op 污染下一次真正的用户停止。
397
+ */
398
+ interrupt: (sessionId) => {
399
+ const agent = agentOf(sessionId);
400
+ if (!agent || typeof agent.cancel !== "function")
401
+ return;
402
+ if (agent.status !== "running")
403
+ return;
404
+ noteRewindInterrupt(sessionId);
405
+ try {
406
+ agent.cancel({ kind: "user" }, { keepInbox: true });
407
+ }
408
+ catch (e) {
409
+ consumeRewindInterrupt(sessionId);
410
+ throw e;
411
+ }
412
+ },
355
413
  statusChanged,
356
414
  /** 把挂起的播报在**安全边界**补齐(reset 门在整段替换前先调一次:让替换把它们一并遮蔽) */
357
415
  flushNotices,
@@ -408,7 +466,7 @@ export function apply(ctx, config = {}) {
408
466
  const key = ws && ws.trim() ? ws.trim() : workspace;
409
467
  let e = engines.get(key);
410
468
  if (!e) {
411
- e = createFacade(key, { ctx, ports });
469
+ e = createFacade(key, { ctx, ports, ...runtime });
412
470
  engines.set(key, e);
413
471
  // **不在这里建目录**:engineFor 是所有工具(含只读的 list/doctor/status)的入口,
414
472
  // 在这里 ensureLayout 会让只读命令在用户从没用过 ralphflow 的项目里创建整棵
@@ -424,7 +482,7 @@ export function apply(ctx, config = {}) {
424
482
  // 工作流 → 快捷技能。带上会话 id:名字不合语法的工作流要**当场把原因说给用户听**
425
483
  // (引擎也可能由无会话的路径创建,那就只写日志 —— 见 src/skills.ts)。
426
484
  try {
427
- registerWorkflowSkills?.(discoverAssetsIn(key), sessionId ? { sessionId } : undefined);
485
+ registerWorkflowSkills?.(discoverAssetsIn(key, runtime), sessionId ? { sessionId } : undefined);
428
486
  }
429
487
  catch { }
430
488
  }
@@ -445,14 +503,14 @@ export function apply(ctx, config = {}) {
445
503
  pause(session) {
446
504
  const cwd = cwdOf(session);
447
505
  const key = cwd ? projectRootOf(cwd) : workspace;
448
- const engine = engines.get(key) ?? createFacade(key, { ctx, ports });
506
+ const engine = engines.get(key) ?? createFacade(key, { ctx, ports, ...runtime });
449
507
  return engine.pauseForUserStop(session.id);
450
508
  },
451
509
  async read(session) {
452
510
  // Viewing status never runs restore or registers skills / sends a notice.
453
511
  const cwd = cwdOf(session);
454
512
  const key = cwd ? projectRootOf(cwd) : workspace;
455
- const engine = engines.get(key) ?? createFacade(key, { ctx, ports });
513
+ const engine = engines.get(key) ?? createFacade(key, { ctx, ports, ...runtime });
456
514
  const active = engine.uiStatus(session.id);
457
515
  const catalog = engine.viewerCatalog();
458
516
  if (active.status && engine.readState(active.status.id)?.active)
@@ -518,11 +576,20 @@ export function apply(ctx, config = {}) {
518
576
  }
519
577
  catch { } });
520
578
  const ev = e;
579
+ // 新回合开始:回退发起的那次中止已经收尾,清掉可能没等到 turn/end 的残留标记。
580
+ if (ev.type === "turn/start") {
581
+ rewindInterrupts.delete(sid);
582
+ return;
583
+ }
521
584
  // 停止按钮 = 暂停:宿主把当前回合 cancel 成 `turn/end { kind:"aborted", reason:{kind:"user"} }`。
522
585
  // Flow 与 Graph 同一条路径;**不在观察者里 append/写会话**,交给微任务(同 flushNotices 的纪律)。
523
586
  if (ev.type === "turn/end") {
524
587
  const reason = ev.data?.reason;
525
588
  if (reason?.kind === "aborted" && reason.reason?.kind === "user") {
589
+ // 这次 abort 是 `/ralphflow-rewind` 自己发起的:它不是用户停止,不能暂停实例
590
+ // (否则回退刚清掉的 paused 会被写回,目标步 DO 被丢弃)。
591
+ if (consumeRewindInterrupt(sid))
592
+ return;
526
593
  queueMicrotask(() => {
527
594
  try {
528
595
  existingEngineFor(sid)?.pauseForUserStop(sid);
@@ -587,6 +654,10 @@ export function apply(ctx, config = {}) {
587
654
  log("warn", "turn_stopping_failed", { sessionId: sid, error: e instanceof Error ? e.message : String(e) });
588
655
  return;
589
656
  }
657
+ // 引擎已自行投递(按轮门 / `reset: true` 的步骤必须先换上下文再投任务书 —— 顺序
658
+ // 只能由引擎在替换完成后掌握):这里**绝不能再投一次**,否则模型会收到两份任务书。
659
+ if (verdict.delivered)
660
+ return;
590
661
  // 本包客户端以 notice + summary 匹配播报,再由私有节点绕过普通 context 的过滤
591
662
  if (!verdict.message)
592
663
  return;
@@ -633,7 +704,7 @@ export function apply(ctx, config = {}) {
633
704
  if (!cwd)
634
705
  return;
635
706
  try {
636
- registerWorkflowSkills?.(discoverAssetsIn(projectRootOf(cwd)), s?.id ? { sessionId: s.id } : undefined);
707
+ registerWorkflowSkills?.(discoverAssetsIn(projectRootOf(cwd), runtime), s?.id ? { sessionId: s.id } : undefined);
637
708
  }
638
709
  catch { }
639
710
  });
package/lib/paths.d.ts CHANGED
@@ -1,5 +1,38 @@
1
1
  /** 插件命名空间:项目内 `.dsh/ralph-flow/`,用户级 `<DSH_HOME>/ralph-flow/`。 */
2
2
  export declare const RALPH_FLOW_NAME = "ralph-flow";
3
+ /**
4
+ * 项目内的运行时根目录。**项目根 dot-dir**(§1.8):项目根 = 最近的含 `.git` 的祖先目录,
5
+ * 与原生 Skill 的 `<projectRoot>/.dsh/skills` 用同一条规则;用户级命名空间
6
+ * `<DSH_HOME>/ralph-flow/` 由本文件解析。
7
+ *
8
+ * 注意:这里是**项目根相对路径**(含 `/`),`path.join(projectRoot, RALPH_FLOW_DIR)` 仍成立。
9
+ */
10
+ export declare const RALPH_FLOW_DIR = ".dsh/ralph-flow";
11
+ /** 运行态外部化:设置后 instances/reports/artifacts 全部落这个目录(支持 `~`)。 */
12
+ export declare const RALPH_FLOW_STATE_DIR_ENV = "RALPH_FLOW_STATE_DIR";
13
+ /** 无头模式开关:为真时忽略项目级工作流资产,并拒绝带人工审查门的 Flow / Graph。 */
14
+ export declare const RALPH_FLOW_HEADLESS_ENV = "RALPH_FLOW_HEADLESS";
15
+ /** 运行态选项:环境变量的显式版本(插件配置 > 环境变量 > 默认)。 */
16
+ export interface RuntimeOptions {
17
+ /** 外部状态目录(等价于 `$RALPH_FLOW_STATE_DIR`)。 */
18
+ stateDir?: string;
19
+ /** 无头模式(等价于 `$RALPH_FLOW_HEADLESS=1`)。 */
20
+ ignoreWorkspaceWorkflows?: boolean;
21
+ }
22
+ /** 一份解析好的运行态布局:Flow 与 Graph 的所有运行目录都从这里取。 */
23
+ export interface RalphFlowLayout {
24
+ /** 运行态根:默认 `<项目根>/.dsh/ralph-flow`;外部化时 = 外部目录。 */
25
+ root: string;
26
+ /** 项目级资产目录:始终 `<项目根>/.dsh/ralph-flow/workflows`(只读发现用)。 */
27
+ workflowsDir: string;
28
+ instancesDir: string;
29
+ reportsDir: string;
30
+ artifactsDir: string;
31
+ /** 外部化:运行态不在项目根下,报告/提示词里的路径要给绝对路径。 */
32
+ external: boolean;
33
+ /** 无头:发现与加载跳过项目级资产目录,Flow / Graph 的人工审查门在加载期拒绝。 */
34
+ headless: boolean;
35
+ }
3
36
  /**
4
37
  * 项目根:最近的含 `.git` 的祖先目录;没有就用 `dir` 本身。
5
38
  *
@@ -10,3 +43,22 @@ export declare function projectRootOf(dir: string): string;
10
43
  export declare function dshUserRoot(): string;
11
44
  /** 用户级插件目录:`<DSH_HOME|~/.dsh>/ralph-flow[/...]`。 */
12
45
  export declare function userRalphFlowDir(...segments: string[]): string;
46
+ /**
47
+ * 一类资产的搜索目录,顺序 = 优先级:项目级优先,用户级兜底;无头运行只剩用户级。
48
+ * 资产类型的目录名(`workflows/` / `graphs/`)只在这里拼一次。
49
+ */
50
+ export declare function assetSearchDirs(workspace: string, kind: "workflows" | "graphs", headless: boolean): string[];
51
+ /**
52
+ * 报告与提示词里的路径写法:外部化时给绝对路径(工作区里读不到它),否则给项目根相对路径。
53
+ * Flow 的报告/产出与 Graph 的报告共用这一条规则。
54
+ */
55
+ export declare function displayPath(projectRoot: string, absolute: string, external: boolean): string;
56
+ /** 展开 `~` / `~/...`(与 `$DSH_HOME` 的解析口径一致);其余原样返回。 */
57
+ export declare function expandHomePath(value: string): string;
58
+ /** 无头模式是否开启:插件配置显式开启,或 `$RALPH_FLOW_HEADLESS` 非空且不为假值。 */
59
+ export declare function headlessModeEnabled(explicit?: boolean): boolean;
60
+ /**
61
+ * 解析运行态布局。`stateDir` 非空即外部化(显式配置优先于环境变量);
62
+ * 相对路径按项目根解析 —— 插件只有一个项目根,写相对路径的人指的就是项目旁边。
63
+ */
64
+ export declare function resolveRalphFlowLayout(projectRoot: string, options?: RuntimeOptions): RalphFlowLayout;
package/lib/paths.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * DSH 原生路径规则:**项目根 / 用户根**。
2
+ * 运行态布局:**项目根 / 用户根 / 外部状态根**。
3
3
  *
4
4
  * 规则与 `@deepseek-ai/dsh-skill-filesystem` 的 Skill 根一致(源码在
5
5
  * `findProjectRoot` 与 `@deepseek-ai/dsh-home-paths` 的 `resolveDshHome`):
@@ -9,14 +9,31 @@
9
9
  * - 用户根:`resolveDshHome()` —— 显式配置 > `$DSH_HOME`(支持 `~`,空值视为未设置)
10
10
  * > `~/.dsh`。
11
11
  *
12
- * 插件的项目级数据(资产 + 实例/报告/产出)全部挂在项目根;用户级资产挂在用户根。
12
+ * 插件的项目级数据(资产 + 实例/报告/产出)默认全部挂在项目根;用户级资产挂在用户根。
13
+ * 无人值守运行时可以把**运行态**(实例、报告、产出)搬出项目根(`RALPH_FLOW_STATE_DIR`),
14
+ * 并让工作流来源只认用户级与内置(`RALPH_FLOW_HEADLESS`)。两件事都在这里解析成一份布局,
15
+ * Flow 与 Graph 共用,绝不各自拼路径。
16
+ *
13
17
  * 这里只解析路径,不建目录、不校验内容。
14
18
  */
15
19
  import fs from "node:fs";
20
+ import os from "node:os";
16
21
  import path from "node:path";
17
22
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
18
23
  /** 插件命名空间:项目内 `.dsh/ralph-flow/`,用户级 `<DSH_HOME>/ralph-flow/`。 */
19
24
  export const RALPH_FLOW_NAME = "ralph-flow";
25
+ /**
26
+ * 项目内的运行时根目录。**项目根 dot-dir**(§1.8):项目根 = 最近的含 `.git` 的祖先目录,
27
+ * 与原生 Skill 的 `<projectRoot>/.dsh/skills` 用同一条规则;用户级命名空间
28
+ * `<DSH_HOME>/ralph-flow/` 由本文件解析。
29
+ *
30
+ * 注意:这里是**项目根相对路径**(含 `/`),`path.join(projectRoot, RALPH_FLOW_DIR)` 仍成立。
31
+ */
32
+ export const RALPH_FLOW_DIR = ".dsh/ralph-flow";
33
+ /** 运行态外部化:设置后 instances/reports/artifacts 全部落这个目录(支持 `~`)。 */
34
+ export const RALPH_FLOW_STATE_DIR_ENV = "RALPH_FLOW_STATE_DIR";
35
+ /** 无头模式开关:为真时忽略项目级工作流资产,并拒绝带人工审查门的 Flow / Graph。 */
36
+ export const RALPH_FLOW_HEADLESS_ENV = "RALPH_FLOW_HEADLESS";
20
37
  /**
21
38
  * 项目根:最近的含 `.git` 的祖先目录;没有就用 `dir` 本身。
22
39
  *
@@ -42,3 +59,59 @@ export function dshUserRoot() {
42
59
  export function userRalphFlowDir(...segments) {
43
60
  return path.join(dshUserRoot(), RALPH_FLOW_NAME, ...segments);
44
61
  }
62
+ /**
63
+ * 一类资产的搜索目录,顺序 = 优先级:项目级优先,用户级兜底;无头运行只剩用户级。
64
+ * 资产类型的目录名(`workflows/` / `graphs/`)只在这里拼一次。
65
+ */
66
+ export function assetSearchDirs(workspace, kind, headless) {
67
+ const userDir = userRalphFlowDir(kind);
68
+ return headless ? [userDir] : [path.join(path.resolve(workspace), RALPH_FLOW_DIR, kind), userDir];
69
+ }
70
+ /**
71
+ * 报告与提示词里的路径写法:外部化时给绝对路径(工作区里读不到它),否则给项目根相对路径。
72
+ * Flow 的报告/产出与 Graph 的报告共用这一条规则。
73
+ */
74
+ export function displayPath(projectRoot, absolute, external) {
75
+ return external ? absolute : path.relative(path.resolve(projectRoot), absolute).split(path.sep).join("/");
76
+ }
77
+ /** 展开 `~` / `~/...`(与 `$DSH_HOME` 的解析口径一致);其余原样返回。 */
78
+ export function expandHomePath(value) {
79
+ if (value === "~")
80
+ return os.homedir();
81
+ if (value.startsWith("~/") || value.startsWith("~\\"))
82
+ return path.join(os.homedir(), value.slice(2));
83
+ return value;
84
+ }
85
+ function nonEmpty(value) {
86
+ const trimmed = typeof value === "string" ? value.trim() : "";
87
+ return trimmed ? trimmed : undefined;
88
+ }
89
+ /** 环境变量里的布尔开关:空值与 `0/false/no/off` 算关闭,其余非空值算开启。 */
90
+ function truthyEnv(name) {
91
+ const raw = process.env[name];
92
+ const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
93
+ return value !== "" && value !== "0" && value !== "false" && value !== "no" && value !== "off";
94
+ }
95
+ /** 无头模式是否开启:插件配置显式开启,或 `$RALPH_FLOW_HEADLESS` 非空且不为假值。 */
96
+ export function headlessModeEnabled(explicit) {
97
+ return explicit === true || truthyEnv(RALPH_FLOW_HEADLESS_ENV);
98
+ }
99
+ /**
100
+ * 解析运行态布局。`stateDir` 非空即外部化(显式配置优先于环境变量);
101
+ * 相对路径按项目根解析 —— 插件只有一个项目根,写相对路径的人指的就是项目旁边。
102
+ */
103
+ export function resolveRalphFlowLayout(projectRoot, options = {}) {
104
+ const project = path.resolve(projectRoot);
105
+ const configured = nonEmpty(options.stateDir) ?? nonEmpty(process.env[RALPH_FLOW_STATE_DIR_ENV]);
106
+ const externalRoot = configured ? path.resolve(project, expandHomePath(configured)) : undefined;
107
+ const root = externalRoot ?? path.join(project, RALPH_FLOW_DIR);
108
+ return {
109
+ root,
110
+ workflowsDir: path.join(project, RALPH_FLOW_DIR, "workflows"),
111
+ instancesDir: path.join(root, "instances"),
112
+ reportsDir: path.join(root, "reports"),
113
+ artifactsDir: path.join(root, "artifacts"),
114
+ external: externalRoot !== undefined,
115
+ headless: headlessModeEnabled(options.ignoreWorkspaceWorkflows),
116
+ };
117
+ }
@@ -0,0 +1,29 @@
1
+ import type { PauseReason } from "./pause.js";
2
+ /** 契约版本:宿主按这个字段判断解析规则;形状不兼容时才升。 */
3
+ export declare const TERMINAL_RECORD_SCHEMA_VERSION = 1;
4
+ /** 记录的三种状态:终态(done / cancelled)与暂停态(paused)。 */
5
+ export type TerminalRecordStatus = "done" | "cancelled" | "paused";
6
+ /** 两个**终态**(会归档报告并销毁实例);暂停态不在其中。 */
7
+ export type ArchiveStatus = Exclude<TerminalRecordStatus, "paused">;
8
+ /** 一份结构化终态记录(磁盘上的 `reports/<instanceId>.json`)。 */
9
+ export interface TerminalRecord {
10
+ schemaVersion: typeof TERMINAL_RECORD_SCHEMA_VERSION;
11
+ instanceId: string;
12
+ workflow: string;
13
+ status: TerminalRecordStatus;
14
+ /** 暂停原因:仅 `status === "paused"` 时有值;引擎所有暂停路径都会写入原因。 */
15
+ pauseReason: PauseReason | null;
16
+ /** 已归档 Markdown 报告的绝对路径;未归档暂停态为 `null`。 */
17
+ reportPath: string | null;
18
+ updatedAt: string;
19
+ }
20
+ /**
21
+ * 原子写一份终态记录;失败**抛出**(临时文件已清理)。
22
+ * 调用方负责把失败变成一条告警,而不是让实例卡在销毁前。
23
+ */
24
+ export declare function writeTerminalRecord(reportsDir: string, instanceId: string, record: TerminalRecord): void;
25
+ /**
26
+ * 移除某个实例的终态记录(不存在是正常情况:运行中的实例本就不该有记录)。
27
+ * 删除失败**抛出**:留着一份过期的 `paused` 会冒充真实状态,调用方必须把它变成告警。
28
+ */
29
+ export declare function removeTerminalRecord(reportsDir: string, instanceId: string): void;