ralphflow-dsh 0.1.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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +196 -0
  3. package/lib/actions.d.ts +37 -0
  4. package/lib/actions.js +55 -0
  5. package/lib/check-voting.d.ts +54 -0
  6. package/lib/check-voting.js +289 -0
  7. package/lib/check.d.ts +64 -0
  8. package/lib/check.js +329 -0
  9. package/lib/client/CommandCard.d.ts +24 -0
  10. package/lib/client/CommandCard.js +69 -0
  11. package/lib/client/HeaderAction.d.ts +39 -0
  12. package/lib/client/HeaderAction.js +509 -0
  13. package/lib/client/RunCard.d.ts +27 -0
  14. package/lib/client/RunCard.js +375 -0
  15. package/lib/client/client.d.ts +3 -0
  16. package/lib/client/client.js +275 -0
  17. package/lib/client/definition.d.ts +126 -0
  18. package/lib/client/definition.js +259 -0
  19. package/lib/client/hidden-runs.d.ts +6 -0
  20. package/lib/client/hidden-runs.js +52 -0
  21. package/lib/client/http-state.d.ts +67 -0
  22. package/lib/client/http-state.js +81 -0
  23. package/lib/client/markdown.d.ts +26 -0
  24. package/lib/client/markdown.js +174 -0
  25. package/lib/client/notify-watch.d.ts +38 -0
  26. package/lib/client/notify-watch.js +98 -0
  27. package/lib/client/notify.d.ts +21 -0
  28. package/lib/client/notify.js +168 -0
  29. package/lib/client/snapshots.d.ts +8 -0
  30. package/lib/client/snapshots.js +101 -0
  31. package/lib/client.js +2361 -0
  32. package/lib/commands.d.ts +41 -0
  33. package/lib/commands.js +223 -0
  34. package/lib/create.d.ts +14 -0
  35. package/lib/create.js +98 -0
  36. package/lib/deps.d.ts +17 -0
  37. package/lib/deps.js +19 -0
  38. package/lib/done-detect.d.ts +2 -0
  39. package/lib/done-detect.js +28 -0
  40. package/lib/driver.d.ts +32 -0
  41. package/lib/driver.js +248 -0
  42. package/lib/engine.d.ts +306 -0
  43. package/lib/engine.js +2851 -0
  44. package/lib/events.d.ts +35 -0
  45. package/lib/events.js +52 -0
  46. package/lib/index.d.ts +11 -0
  47. package/lib/index.js +201 -0
  48. package/lib/jobs.d.ts +56 -0
  49. package/lib/jobs.js +355 -0
  50. package/lib/mutex.d.ts +9 -0
  51. package/lib/mutex.js +21 -0
  52. package/lib/session-hygiene.d.ts +25 -0
  53. package/lib/session-hygiene.js +205 -0
  54. package/lib/tools.d.ts +24 -0
  55. package/lib/tools.js +716 -0
  56. package/lib/voting-progress.d.ts +37 -0
  57. package/lib/voting-progress.js +89 -0
  58. package/package.json +73 -0
  59. package/workflows/loop.yaml +27 -0
  60. package/workflows/spec.yaml +105 -0
package/lib/driver.js ADDED
@@ -0,0 +1,248 @@
1
+ import { isSubWorkflowStep, MANUAL_GATE_MARKER, DEFAULT_ADVERSARIAL_TIMEOUT_MS } from "./engine.js";
2
+ import { readFileSync } from "fs";
3
+ import { adversarialCheck, liveVerifierCount } from "./check.js";
4
+ import { runVotingCheck } from "./check-voting.js";
5
+ import { readVotingProgress, deleteVotingProgress } from "./voting-progress.js";
6
+ import { voterStatusLabel } from "./check-voting.js";
7
+ function fmtVotingOverview(step) {
8
+ if (!Array.isArray(step.check_voting) || step.check_voting.length === 0)
9
+ return "";
10
+ const n = step.check_voting.length;
11
+ const rows = step.check_voting
12
+ .map((e, i) => ` ${i + 1}/${n} ${String(e.check).split("\n")[0].trim().substring(0, 50)} · 模型:${typeof e.model === "string" ? e.model : e.model ? `${e.model.providerID}/${e.model.modelID}` : "默认"}`)
13
+ .join("\n");
14
+ return `[各验证者检查依据]\n${rows}`;
15
+ }
16
+ /**
17
+ * 对 DO 刚完成的步骤运行独立验证并推进状态机(do→check→on_pass/on_fail/暂停)。
18
+ * 调用前置条件:实例状态为 do 阶段(done 已达成,或人工门已批准)。
19
+ * 返回过渡文本(供工具/命令返回给模型),并发射全部 UI 事件帧。
20
+ */
21
+ export async function runCheckAndAdvance(ctx, instId, workflow, step, state) {
22
+ try {
23
+ return await driveInner(ctx, instId, workflow, step, state);
24
+ }
25
+ finally {
26
+ // 释放实例级 abort 注册(cancel 之后到达的本段信号不再保留)
27
+ try {
28
+ ctx.deps.dispose?.();
29
+ }
30
+ catch { }
31
+ }
32
+ }
33
+ async function driveInner(ctx, instId, workflow, step, state) {
34
+ const { engine, emit } = ctx;
35
+ const sessionId = state.session_id ?? null;
36
+ // do→check 转换(与 opencode 版一致:仅在真实边界记录 DO 完成)
37
+ if (state.current_phase === "do") {
38
+ engine.logEvent(instId, "info", "done_detected", { step: state.current_step });
39
+ engine.addStepRecord(instId, state.current_step, "do", "passed", state.fail_count || 0, undefined, state.workflow_name);
40
+ }
41
+ engine.clearManualStepMarker(instId);
42
+ engine.clearManualGate(instId);
43
+ engine.clearReinjectCounter(instId);
44
+ engine.clearDoPromptCache(instId);
45
+ engine.clearDoneTagDetected(instId);
46
+ engine.writeState({ ...state, current_phase: "check" }, instId);
47
+ engine.recordStepStart(instId, state.current_step, "check");
48
+ // ── no-check 步骤:未配置独立验证 → DO 完成即直通 on_pass ───────────────────
49
+ if (step.no_check) {
50
+ const noCheckReason = "本步骤未配置独立验证(no-check),完成即通过。";
51
+ engine.addStepRecord(instId, step.id, "check", "passed", state.fail_count || 0, noCheckReason, state.workflow_name);
52
+ emit.emit(instId, "tool-ralphflow/check-result", { runId: instId, step: step.id, passed: true, reason: noCheckReason });
53
+ const result = engine.handleCheckPassed(instId, engine.readState(instId) ?? { ...state, current_phase: "check" }, workflow, step, { reason: noCheckReason }, true);
54
+ return finishTransition(ctx, instId, workflow, state, result);
55
+ }
56
+ const isVoting = Array.isArray(step.check_voting) && step.check_voting.length > 0;
57
+ const adversarialConfig = engine.getEffectiveAdversarialCheck(instId, workflow);
58
+ engine.logEvent(instId, "info", "step_start", { step: state.current_step, phase: "check" });
59
+ // 超时上限透传:UI 据此画「剩余时间」进度条,等待有了终点感
60
+ const effectiveTimeoutMs = (isVoting && Array.isArray(step.check_voting)
61
+ ? Math.max(...step.check_voting.map((v) => v.timeout_ms ?? adversarialConfig?.timeout_ms ?? 0), adversarialConfig?.timeout_ms ?? 0)
62
+ : adversarialConfig?.timeout_ms) || DEFAULT_ADVERSARIAL_TIMEOUT_MS;
63
+ emit.emit(instId, "tool-ralphflow/step-start", {
64
+ runId: instId, step: state.current_step, phase: "check", failCount: state.fail_count || 0,
65
+ ts: Date.now(),
66
+ // 验证者总数:投票期首票落地前 UI 就能显示「已收 M/N 票」,不再静默
67
+ voters: isVoting ? step.check_voting.length : 1,
68
+ timeoutMs: effectiveTimeoutMs,
69
+ });
70
+ const checkPrompt = isVoting ? "" : engine.buildCheckPrompt(instId, step, state.user_task);
71
+ let checkResult;
72
+ try {
73
+ if (isVoting && step.check_voting) {
74
+ if (state.current_phase === "do") {
75
+ deleteVotingProgress(engine, instId);
76
+ }
77
+ const progress = readVotingProgress(engine, instId);
78
+ const outcome = await runVotingCheck(ctx.deps, engine, instId, sessionId, ctx.parent, step, state.user_task, step.check_voting, adversarialConfig, {
79
+ phase: state.current_phase,
80
+ workflowName: state.workflow_name,
81
+ progress,
82
+ // 投票进度通过 runSingleVoter 发射的 check-verdict 事件逐票推送,无需额外回调
83
+ });
84
+ if (outcome.kind === "cancelled") {
85
+ engine.logEvent(instId, "warn", "voting_cancelled", { step: step.id });
86
+ return { text: "工作流实例已被取消。", completed: false, paused: false };
87
+ }
88
+ if (outcome.kind === "infra_pause") {
89
+ checkResult = { passed: false, infra: true, reason: outcome.reason };
90
+ }
91
+ else {
92
+ checkResult = { passed: outcome.kind === "passed", reason: outcome.reason };
93
+ }
94
+ }
95
+ else {
96
+ const singleCheckConfig = step.check_model
97
+ ? { ...(adversarialConfig || {}), model: step.check_model }
98
+ : adversarialConfig;
99
+ checkResult = await adversarialCheck(ctx.deps, sessionId, ctx.parent, instId, step, checkPrompt, state.user_task, singleCheckConfig);
100
+ }
101
+ }
102
+ catch (err) {
103
+ engine.logEvent(instId, "error", "adversarial_check_uncaught", { stepId: step.id, error: err.message });
104
+ const st = engine.readState(instId);
105
+ if (st && st.active && st.current_phase === "check" && st.current_step === state.current_step && st.workflow_name === state.workflow_name) {
106
+ engine.writeState({ ...st, paused: true, pause_reason: "check_error", last_failure_reason: `对抗性检查崩溃:${err.message}` }, instId);
107
+ }
108
+ emit.emit(instId, "tool-ralphflow/check-result", { runId: instId, step: step.id, passed: false, reason: `对抗性检查崩溃:${err.message}`, infra: true });
109
+ // 同 infra 暂停分支:绕过 finishTransition 的直接 return,补发暂停帧
110
+ emit.emit(instId, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
111
+ return {
112
+ text: `⚠️ 验证未能运行 · 🙋 轮到你了\n\n对抗性检查崩溃:${err.message}\n\n这是验证程序自身的问题,不是你工作成果的问题——本次不计入失败次数,已完成的工作保持原样。\n\n👉 处理后运行 /ralphflow-continue 即可重新验证(无需重做任务),或 /ralphflow-cancel 放弃。`,
113
+ completed: false, paused: true,
114
+ };
115
+ }
116
+ // 状态竞争防御:验证期间实例被取消/接管/暂停则丢弃判定
117
+ const cur = engine.readState(instId);
118
+ if (!cur || !cur.active || cur.paused || cur.current_phase !== "check"
119
+ || cur.workflow_name !== state.workflow_name || cur.current_step !== state.current_step) {
120
+ engine.logEvent(instId, "warn", "check_result_discarded", { reason: cur?.paused ? "instance paused during check" : "state changed during check" });
121
+ return { text: "", completed: false, paused: false };
122
+ }
123
+ if (checkResult.infra) {
124
+ engine.writeState({ ...cur, paused: true, pause_reason: "check_error", last_failure_reason: checkResult.reason }, instId);
125
+ engine.logEvent(instId, "warn", "workflow_paused", { workflow: cur.workflow_name, step: cur.current_step, reason: "check_infra_error" });
126
+ emit.emit(instId, "tool-ralphflow/check-result", { runId: instId, step: step.id, passed: false, infra: true, reason: checkResult.reason });
127
+ // 此分支直接 return 不经过 finishTransition——run-end failed 帧必须在这里
128
+ // 补发,否则 client 卡片永远停在「验证中」、活体面板一直转(暂停语义在
129
+ // UI 上不可见)。
130
+ emit.emit(instId, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
131
+ return {
132
+ text: `⚠️ 验证未能运行 · 🙋 轮到你了\n\n${checkResult.reason}\n\n这是验证进程自身的问题(额度/API/超时),不是你工作成果的问题:本次不计入失败次数,已完成的工作无需重做。\n\n👉 问题解决后运行 /ralphflow-continue 直接重新验证,或 /ralphflow-cancel 放弃。`,
133
+ completed: false, paused: true,
134
+ };
135
+ }
136
+ emit.emit(instId, "tool-ralphflow/check-result", {
137
+ runId: instId, step: step.id, passed: checkResult.passed, reason: checkResult.reason,
138
+ aggregatedFails: checkResult.passed ? [] : [checkResult.reason],
139
+ });
140
+ engine.addStepRecord(instId, cur.current_step, "check", checkResult.passed ? "passed" : "failed", cur.fail_count || 0, checkResult.reason, cur.workflow_name);
141
+ const result = checkResult.passed
142
+ ? engine.handleCheckPassed(instId, cur, workflow, step, checkResult)
143
+ : engine.handleCheckFailed(instId, cur, workflow, step, checkResult);
144
+ return finishTransition(ctx, instId, workflow, state, result);
145
+ }
146
+ /**
147
+ * 验证判定后的公共收尾:完成→报告+run-end;暂停→run-end failed;
148
+ * 推进→step-start 事件 +(人工审查步骤只预告,真正停门发生在其 DO 完成时)。
149
+ */
150
+ function finishTransition(ctx, instId, workflow, state, result) {
151
+ const { engine, emit } = ctx;
152
+ if (result.completed) {
153
+ // 工作流结束:报告已由 handleCheckPassed 归档,读取并发射报告/结束事件。
154
+ // 实例此刻已被 destroyInstance 删除——用进入本段前锁定的属主会话发送,
155
+ // 否则终态帧读不到 state.json 会被静默丢弃。
156
+ const owner = state.session_id ?? null;
157
+ const reportPath = engine.getReportPath(instId);
158
+ let reportText = "";
159
+ try {
160
+ reportText = readFileSync(reportPath, "utf-8");
161
+ }
162
+ catch { }
163
+ if (reportText) {
164
+ emit.emitFinal(instId, owner, "tool-ralphflow/report", { runId: instId, text: reportText, reportPath });
165
+ }
166
+ emit.emitFinal(instId, owner, "tool-ralphflow/run-end", { runId: instId, stopReason: "done", reportId: instId });
167
+ return { text: result.text, completed: true, paused: false };
168
+ }
169
+ if (result.paused) {
170
+ emit.emit(instId, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
171
+ return { text: result.text, completed: false, paused: true };
172
+ }
173
+ // 推进到下一步(do 阶段)——发射事件;人工审查步骤不发"已完成待审查"卡,
174
+ // 审查门在其 DO 完成时由 job 触发(gate 帧此刻才真实)。
175
+ const next = engine.readState(instId);
176
+ if (next && next.active && next.current_phase === "do") {
177
+ engine.clearDoneTagDetected(instId);
178
+ engine.clearManualGate(instId);
179
+ const nextWf = next.workflow_name === workflow.name ? workflow : engine.loadWorkflow(next.workflow_name);
180
+ if (nextWf?.manual_step?.includes(next.current_step))
181
+ engine.writeManualStepMarker(instId);
182
+ engine.markPromptDelivered(next.current_step, instId);
183
+ emit.emit(instId, "tool-ralphflow/step-start", {
184
+ runId: instId, step: next.current_step, phase: "do", failCount: next.fail_count ?? 0,
185
+ ts: Date.now(),
186
+ });
187
+ if (nextWf?.manual_step?.includes(next.current_step)) {
188
+ return {
189
+ text: `${result.text}\n\n---\n\n> 📋 下一步 **${next.current_step}** 是人工审查步骤:模型完成后会停下等你审查批准,届时对话里会出现审查卡片。`,
190
+ completed: false,
191
+ paused: false,
192
+ };
193
+ }
194
+ }
195
+ return { text: result.text, completed: false, paused: false };
196
+ }
197
+ /** 供 tools/commands 复用的辅助:读单实例的状态快照文本(对齐 opencode 版信息量) */
198
+ export function statusText(engine, instId, sessionId) {
199
+ const st = engine.readState(instId);
200
+ if (!st)
201
+ return `实例 ${instId} 不存在。`;
202
+ const info = engine.listInstances().find((i) => i.id === instId);
203
+ const line = [`实例 \`${instId}\`(工作流: ${st.workflow_name})`];
204
+ line.push(`- 状态: ${info ? engine.instanceStatusLabel(info) : st.active ? (st.paused ? "⏸ 已暂停" : "🔨 执行中") : "已结束"}`);
205
+ if (sessionId != null) {
206
+ line.push(`- 属主会话: ${st.session_id === sessionId ? "🟢 本会话" : st.session_id ? `\`${st.session_id.slice(0, 8)}\`` : "无"}`);
207
+ }
208
+ else if (st.session_id) {
209
+ line.push(`- 属主会话: \`${st.session_id.slice(0, 8)}\``);
210
+ }
211
+ line.push(`- 步骤: ${st.current_step} · 阶段: ${st.current_phase === "do" ? "DO 执行" : "CHECK 验证"} · 失败次数: ${st.fail_count ?? 0}`);
212
+ if (info?.lastActivity)
213
+ line.push(`- 最后活动: ${engine.formatLastActivity(info.lastActivity)}`);
214
+ // 当前步骤详情
215
+ const wf = engine.loadWorkflow(st.workflow_name);
216
+ const step = wf ? engine.getStep(wf, st.current_step) : null;
217
+ if (wf && step && !isSubWorkflowStep(step)) {
218
+ const s = step;
219
+ const detail = [];
220
+ detail.push(`- 任务: ${(s.do || "").split("\n")[0].trim().slice(0, 80)}`);
221
+ if ((st.fail_count ?? 0) >= s.max_fail_count)
222
+ detail.push(` ⚠️ 已达最大失败次数 ${s.max_fail_count}`);
223
+ line.push(...detail);
224
+ }
225
+ if (st.last_failure_reason) {
226
+ const reason = st.last_failure_reason.length > 2000 ? st.last_failure_reason.slice(0, 2000) + "…" : st.last_failure_reason;
227
+ line.push(`- 上次失败原因:\n\n ${reason.split("\n").join("\n ")}`);
228
+ }
229
+ // 人工门待审提示
230
+ if (engine.markerExists(MANUAL_GATE_MARKER, instId)) {
231
+ line.push(`\n> 📋 该实例停在人工审查门(步骤 \`${st.current_step}\`):确认无误后运行 \`/ralphflow-continue\` 批准进入验证;需返工则 \`/ralphflow-reset <意见>\` 打回重做。`);
232
+ }
233
+ // 验证中断检测:phase=check 且无任何登记中的验证者会话 → 进程曾在验证期间重启
234
+ // (先清孤儿登记:kill -9 残留的 live 文件不能让这里永远报「验证进行中」)
235
+ if (!st.paused && st.current_phase === "check" && liveVerifierCount(engine, instId) === 0) {
236
+ line.push(`\n> ⏸ 验证似乎已中断(例如进程重启)。运行 \`/ralphflow-continue\` 恢复验证(已投出的票会保留)。`);
237
+ }
238
+ // 多验证者投票进度
239
+ const progress = readVotingProgress(engine, instId);
240
+ if (progress && progress.stepId === st.current_step && progress.entries.length > 0) {
241
+ line.push(`\n**投票进度**(${progress.stepId}):`);
242
+ for (const e of progress.entries) {
243
+ const summary = (e.check || "").split("\n")[0].trim().slice(0, 40);
244
+ line.push(` ${voterStatusLabel(e.status)} 验证者 ${e.index + 1}/${progress.entries.length}${e.model ? ` · ${e.model}` : ""} — ${summary}${e.reason ? `\n ${e.reason.split("\n")[0].slice(0, 120)}` : ""}`);
245
+ }
246
+ }
247
+ return line.join("\n");
248
+ }
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Ralph Flow Engine for opencode.
3
+ *
4
+ * The WORKFLOW LOGIC (prompt building, the check-result state machine, workflow
5
+ * loading, lint/doctor) mirrors the Claude Code plugin's mcp-server/server.mjs
6
+ * so the two stay behavior-compatible; see SYNC.md.
7
+ *
8
+ * The RUNTIME PLUMBING is opencode-native, NOT a mirror. opencode runs one
9
+ * plugin instance per project directory (shared memory, events carry the
10
+ * sessionID), so the Claude version's multi-PROCESS coordination is unnecessary
11
+ * and was actively harmful here:
12
+ * - No shared mutable "bound instance": every instance-scoped function takes an
13
+ * explicit `instId` (like the original opencode plugin passed `directory`),
14
+ * so there is nothing to serialize and no in-memory state lock.
15
+ * - No cross-process file lock: a single process needs none; operations on one
16
+ * instance are naturally serialized by opencode's per-session turn model.
17
+ * - Ownership is just `session_id` stored in the instance's state.json — no
18
+ * owner-session file, no pid/ppid liveness inference.
19
+ *
20
+ * Multi-instance is kept for parity: state lives under
21
+ * .opencode/ralph-flow/instances/<instance-id>/, so different sessions can run
22
+ * their own workflow in the same project.
23
+ */
24
+ export interface CheckVotingEntry {
25
+ check: string;
26
+ model?: string | {
27
+ providerID?: string;
28
+ modelID?: string;
29
+ };
30
+ timeout_ms?: number;
31
+ system_prompt?: string;
32
+ }
33
+ export interface NormalStepDef {
34
+ id: string;
35
+ desc: string;
36
+ do: string;
37
+ input: string;
38
+ output: string;
39
+ check?: string;
40
+ /** 合法缺省 check 的步骤(无独立验证,DO 完成即直通 on_pass);由解析器标注 */
41
+ no_check?: boolean;
42
+ check_voting?: CheckVotingEntry[];
43
+ check_model?: string | {
44
+ providerID?: string;
45
+ modelID?: string;
46
+ };
47
+ on_pass: string;
48
+ on_fail: string;
49
+ max_fail_count: number;
50
+ reset?: boolean;
51
+ }
52
+ export interface SubWorkflowStepDef {
53
+ id: string;
54
+ desc: string;
55
+ workflow: string;
56
+ inputs?: Record<string, string>;
57
+ input: string;
58
+ output: string;
59
+ on_pass: string;
60
+ on_fail: string;
61
+ max_fail_count: number;
62
+ reset?: boolean;
63
+ }
64
+ export type StepDef = NormalStepDef | SubWorkflowStepDef;
65
+ export interface AdversarialCheckConfig {
66
+ model?: string | {
67
+ providerID?: string;
68
+ modelID?: string;
69
+ };
70
+ agent?: string;
71
+ system_prompt?: string;
72
+ timeout_ms?: number;
73
+ }
74
+ export interface WorkflowDef {
75
+ name: string;
76
+ description: string;
77
+ manual_step: string[];
78
+ steps: StepDef[];
79
+ adversarial_check?: AdversarialCheckConfig;
80
+ auto_reset?: boolean;
81
+ }
82
+ export interface RalphFlowState {
83
+ active: boolean;
84
+ workflow_name: string;
85
+ current_step: string;
86
+ current_phase: string;
87
+ fail_count: number;
88
+ user_task: string;
89
+ paused: boolean;
90
+ pause_reason?: string;
91
+ last_failure_reason?: string;
92
+ instance_id?: string;
93
+ /** The session that owns/drives this instance. Set by the tool that touches it. */
94
+ session_id?: string;
95
+ }
96
+ export interface StepExecutionRecord {
97
+ stepId: string;
98
+ phase: string;
99
+ status: "passed" | "failed";
100
+ failCount: number;
101
+ startTime: string;
102
+ endTime?: string;
103
+ reason?: string;
104
+ /**
105
+ * 该记录产生时所在的工作流(嵌套子工作流时是内层工作流名)。2.7.1 起写入;
106
+ * 旧实例的记录没有此字段——passedStepIds 对无字段记录回退到仅按 stepId 过滤。
107
+ */
108
+ workflowName?: string;
109
+ }
110
+ export interface CheckResult {
111
+ passed: boolean;
112
+ infra?: boolean;
113
+ reason: string;
114
+ }
115
+ export interface InstanceInfo {
116
+ id: string;
117
+ state: RalphFlowState;
118
+ owner: string | null;
119
+ manualGate: boolean;
120
+ doneTag: boolean;
121
+ lastActivity: Date | null;
122
+ }
123
+ export interface TransitionResult {
124
+ text: string;
125
+ paused?: boolean;
126
+ completed?: boolean;
127
+ /**
128
+ * opencode 原生增量(Claude 版可忽略):本次转换进入了哪个 composite 步骤的
129
+ * 子工作流。注入层的 reset 门需要它——进入子工作流后 state 已推进到子工作流
130
+ * 内部第一步,(sourceStep → currentStep) 再也回指不到 composite 步骤上标记的
131
+ * reset/auto_reset(同 id 重入时首尾状态甚至完全相同)。状态机行为不变,
132
+ * 仅多返回这一元数据。
133
+ */
134
+ enteredCompositeStepId?: string;
135
+ }
136
+ /**
137
+ * Platform seam — the little the engine needs from the host.
138
+ */
139
+ export interface Platform {
140
+ /** Abort a still-running adversarial check (in-process handle). */
141
+ abortActiveCheck?(instId: string): void;
142
+ }
143
+ /**
144
+ * Strip UTF-8 BOM (Byte Order Mark) from file content.
145
+ * Windows Notepad and some editors add BOM to UTF-8 files.
146
+ * js-yaml and JSON.parse don't handle BOM, causing parse failures.
147
+ */
148
+ export declare function stripBom(text: string): string;
149
+ export declare const RALPH_FLOW_DIR = "ralph-flow";
150
+ /**
151
+ * popState 的「栈文件损坏」哨兵:与 null(栈为空=真正顶层)严格区分。
152
+ * 收到哨兵绝不能走「顶层完成→销毁实例」分支——父帧可能仍在,误判会连本带
153
+ * 息丢掉父工作流的剩余步骤。
154
+ */
155
+ declare const STACK_CORRUPTED: unique symbol;
156
+ export declare const MANUAL_STEP_MARKER = ".manual-step-active";
157
+ export declare const MANUAL_GATE_MARKER = ".manual-gate";
158
+ export declare const DONE_TAG_MARKER = ".done-tag-detected";
159
+ export declare const REINJECT_WARNED_MARKER = ".reinject-warned";
160
+ export declare const MAX_DO_REINJECT = 5;
161
+ export declare const MAX_NESTING_DEPTH = 5;
162
+ export declare const MAX_VOTERS = 5;
163
+ export declare const VOTING_PROGRESS_FILENAME = ".check-voting-progress.json";
164
+ export interface Engine extends ReturnType<typeof createEngine> {
165
+ }
166
+ export declare function createEngine(projectDir: string, platform: Platform): {
167
+ projectDir: string;
168
+ getRalphFlowDir: () => string;
169
+ getInstancesRoot: () => string;
170
+ getReportsDir: () => string;
171
+ getInstanceDir: (instId: string) => string;
172
+ instPath: (name: string, instId: string) => string;
173
+ getArtifactsDir: (instId: string) => string;
174
+ getArtifactsRelDir: (instId: string) => string;
175
+ getPluginWorkflowsDir: () => string;
176
+ getProjectWorkflowsDir: () => string;
177
+ getGlobalWorkflowsDir: () => string | null;
178
+ getGlobalConfigHome: () => string | null;
179
+ generateInstanceId: (workflowName: string) => string;
180
+ isValidInstanceId: (id: unknown) => id is string;
181
+ instanceExists: (instId: string) => boolean;
182
+ writeArtifactsDirName: (instId: string, task: string) => void;
183
+ writeExtraDirs: (instId: string, dirs: string[]) => void;
184
+ readExtraDirs: (instId: string) => string[];
185
+ readOwnerSession: (instId: string) => string | null;
186
+ claimOwnership: (instId: string, sessionId: string | null) => void;
187
+ listInstances: () => InstanceInfo[];
188
+ resolveInstance: (explicitId: string | null | undefined, sessionId: string | null) => {
189
+ ok: true;
190
+ id: string;
191
+ attached: boolean;
192
+ } | {
193
+ ok: false;
194
+ text: string;
195
+ };
196
+ bindInstance: (instId: string, sessionId: string | null) => void;
197
+ destroyInstance: (instId: string, status: string) => string | null;
198
+ instanceStatusLabel: (info: InstanceInfo) => string;
199
+ formatInstanceList: (instances: InstanceInfo[], actionHint?: string) => string;
200
+ formatLastActivity: (date: Date | null) => string;
201
+ readState: (instId: string) => RalphFlowState | null;
202
+ writeState: (state: RalphFlowState, instId: string) => void;
203
+ isValidState: (s: any) => s is RalphFlowState;
204
+ writeMarker: (name: string, content: string, instId: string) => void;
205
+ clearMarker: (name: string, instId: string) => void;
206
+ markerExists: (name: string, instId: string) => boolean;
207
+ writeManualStepMarker: (instId: string) => void;
208
+ clearManualStepMarker: (instId: string) => void;
209
+ clearManualGate: (instId: string) => void;
210
+ clearReinjectCounter: (instId: string) => void;
211
+ readReinjectCount: (instId: string, stepId?: string, phase?: string) => number;
212
+ clearDoPromptCache: (instId: string) => void;
213
+ clearDoneTagDetected: (instId: string) => void;
214
+ writeDoPromptCache: (prompt: string, instId: string) => void;
215
+ readDoPromptCache: (instId: string) => string;
216
+ buildDoNudge: (instId: string, stepId: string) => string;
217
+ markPromptDelivered: (stepId: string, instId: string) => void;
218
+ writeAdversarialSession: (checkSessionId: string, instId: string) => void;
219
+ clearAdversarialSession: (instId: string) => void;
220
+ readAdversarialSession: (instId: string) => string | null;
221
+ readAdversarialSessions: (instId: string) => string[];
222
+ removeAdversarialSession: (checkSessionId: string, instId: string) => void;
223
+ pruneStaleAdversarialSessions: (instId: string, graceMs?: number) => number;
224
+ parseWorkflowFile: (filePath: string, workflowName: string, problems?: string[]) => WorkflowDef | null;
225
+ loadWorkflow: (workflowName: string, problems?: string[]) => WorkflowDef | null;
226
+ listWorkflows: () => Array<{
227
+ name: string;
228
+ desc: string;
229
+ invalid?: boolean;
230
+ }>;
231
+ lintWorkflow: (wf: WorkflowDef, rawParsed: any, fromBuiltin?: boolean) => string[];
232
+ buildDoctorReport: () => string;
233
+ getStep: (workflow: WorkflowDef, stepId: string) => StepDef | null;
234
+ buildDoPrompt: (instId: string, step: NormalStepDef, userTask?: string, retryContext?: string, retryCount?: number) => string;
235
+ buildCheckPrompt: (instId: string, step: NormalStepDef, userTask?: string) => string;
236
+ buildVotingCheckPrompt: (instId: string, step: NormalStepDef, userTask: string | undefined, entry: CheckVotingEntry, index: number, count: number) => string;
237
+ buildSubWorkflowUserTask: (instId: string, step: SubWorkflowStepDef, parentUserTask: string) => string;
238
+ resolveSubWorkflowEntry: (instId: string, subWorkflowName: string, parentUserTask: string, parentStep: SubWorkflowStepDef, maxDepth?: number, retryContext?: string, retryCount?: number) => {
239
+ text: string;
240
+ error?: boolean;
241
+ };
242
+ renderStepText: (instId: string, text: string) => string;
243
+ pushState: (state: RalphFlowState, instId: string) => void;
244
+ popState: (instId: string) => RalphFlowState | typeof STACK_CORRUPTED | null;
245
+ getStackDepth: (instId: string) => number;
246
+ readStateStack: (instId: string) => RalphFlowState[];
247
+ getEffectiveAdversarialCheck: (instId: string, workflow: WorkflowDef) => AdversarialCheckConfig | undefined;
248
+ logEvent: (instId: string, level: string, event: string, extra?: Record<string, unknown>) => void;
249
+ recordStepStart: (instId: string, stepId: string, phase: string) => void;
250
+ stepStartTime: (instId: string, stepId: string, phase: string) => string | undefined;
251
+ addStepRecord: (instId: string, stepId: string, phase: string, status: "passed" | "failed", failCount: number, reason?: string, workflowName?: string) => void;
252
+ loadStepRecords: (instId: string) => StepExecutionRecord[];
253
+ passedStepIds: (instId: string, workflowName: string) => string[];
254
+ readUiEventFrames: (instId: string, max?: number) => {
255
+ type: string;
256
+ data: Record<string, unknown>;
257
+ }[];
258
+ snapshotAllInstances: () => Record<string, unknown>[];
259
+ readHistory: (limit?: number) => Record<string, unknown>[];
260
+ appendArchivedUiEvent: (instId: string, type: string, data: Record<string, unknown>) => void;
261
+ buildReportText: (workflowName: string, status: string, stepRecords: StepExecutionRecord[]) => string;
262
+ archiveReport: (instId: string, workflowName: string, status: string, records: StepExecutionRecord[]) => string | null;
263
+ getReportPath: (instId: string) => string;
264
+ reportExists: (instId: string) => boolean;
265
+ matchCheckTag: (responseText: string) => RegExpMatchArray | null;
266
+ parseCheckResult: (responseText: string) => boolean;
267
+ getAdversarialCheckReason: (responseText: string) => string;
268
+ handleCheckPassed: (instId: string, state: RalphFlowState, workflow: WorkflowDef, step: StepDef, checkResult: {
269
+ reason?: string;
270
+ }, skipped?: boolean) => TransitionResult;
271
+ handleCheckFailed: (instId: string, state: RalphFlowState, workflow: WorkflowDef, step: StepDef, checkResult: {
272
+ reason?: string;
273
+ }) => TransitionResult;
274
+ shouldResetOnTransition: typeof shouldResetOnTransition;
275
+ migrateLegacyInstance: () => void;
276
+ ensureProjectWorkflows: () => void;
277
+ };
278
+ export declare function isSubWorkflowStep(step: StepDef): step is SubWorkflowStepDef;
279
+ /**
280
+ * 判断从 sourceStepId 转换到 targetStepId 时是否应触发上下文重置。
281
+ * 标了 reset 的步骤任何方式进入都触发(含同步骤重试——失败原因经
282
+ * retryContext 文本通道注入,不丢现场);auto_reset = 全部步骤标 reset。
283
+ */
284
+ export declare function shouldResetOnTransition(workflow: WorkflowDef, sourceStepId: string, targetStepId: string): boolean;
285
+ /**
286
+ * Resolve the yaml adversarial_check.model field into the SDK's
287
+ * {providerID, modelID} shape. Shared by the engine's inheritance walk
288
+ * (usability test) and check.ts (actual SDK call) so the two can never
289
+ * drift: a model this cannot resolve is treated as absent.
290
+ */
291
+ export declare function resolveCheckModel(model: AdversarialCheckConfig["model"]): {
292
+ providerID: string;
293
+ modelID: string;
294
+ } | undefined;
295
+ /**
296
+ * 验证者模型优先级链(设计 §7):
297
+ * 条目 model(最强) > 步骤 check_model(仅单 check 场景) > effective(workflow+祖先链)
298
+ * 之后的 agent 配置 / owner session / 全局默认由 check.ts 的既有 fallback 链处理。
299
+ */
300
+ export declare function resolveVerifierModel(entryModel: AdversarialCheckConfig["model"] | undefined, stepModel: AdversarialCheckConfig["model"] | undefined, effective: AdversarialCheckConfig | undefined): {
301
+ providerID: string;
302
+ modelID: string;
303
+ } | undefined;
304
+ export declare const DEFAULT_ADVERSARIAL_SYSTEM_PROMPT = "\u4F60\u662F\u4E00\u4E2A\u4E25\u683C\u3001\u72EC\u7ACB\u7684\u68C0\u67E5\u8005\u3002\u6839\u636E\"\u68C0\u67E5\u4F9D\u636E\"\u5224\u65AD DO \u9636\u6BB5\u58F0\u79F0\u5B8C\u6210\u7684\u5DE5\u4F5C\u662F\u5426\u771F\u7684\u5B8C\u6210\u3002\n\n## \u94C1\u5F8B\n\n**\u4F60\u4E0D\u80FD\u4FEE\u6539\u4EFB\u4F55\u6587\u4EF6\u3002\u65E0\u4F8B\u5916\u3002** \u4F60\u7684 `edit` \u6743\u9650\u5DF2\u88AB\u786C\u6027\u62D2\u7EDD\u3002bash \u53EF\u4EE5\u8DD1\u4EFB\u610F\u9A8C\u8BC1\u547D\u4EE4\u2014\u2014\u547D\u4EE4\u4EA7\u751F\u7684\u526F\u4F5C\u7528\uFF08\u4E34\u65F6\u6587\u4EF6\u3001\u7F13\u5B58\u3001\u6784\u5EFA\u4EA7\u7269\uFF09\u4E0D\u7B97\"\u4F60\u4FEE\u6539\u4E86\u6587\u4EF6\"\uFF1B\u4F46\u4E3B\u52A8\u6539\u6E90\u7801/\u6D4B\u8BD5/\u914D\u7F6E\u90FD\u8BA9\u672C\u6B21\u9A8C\u8BC1\u4F5C\u5E9F\u3002\u8FDD\u89C4\u5373\u5931\u8D25\uFF0C\u6CA1\u6709\"\u4EC5\u6B64\u4E00\u6B21\"\u3002\n\n## \u4E0D\u8981\u76F8\u4FE1 DO \u9636\u6BB5\u7684\u62A5\u544A\n\nDO \u7684\u5B9E\u73B0\u603B\u7ED3\u53EF\u80FD\u4E0D\u5B8C\u6574\u3001\u4E0D\u51C6\u786E\u3001\u8FC7\u4E8E\u4E50\u89C2\u3002**\u4F60\u5FC5\u987B\u72EC\u7ACB\u9A8C\u8BC1\u4E00\u5207**\uFF1A\u8BFB\u771F\u5B9E\u4EE3\u7801\u3001\u8DD1\u771F\u5B9E\u547D\u4EE4\u3001\u770B\u771F\u5B9E\u8F93\u51FA\u3002\u65E0\u6CD5\u72EC\u7ACB\u9A8C\u8BC1\u7684\u4F9D\u636E\u9879 \u2192 \u4E0D\u901A\u8FC7\u3002\n\n## \u7406\u6027\u5316\u2014\u2014\u8FD9\u4E9B\u5FF5\u5934\u5192\u51FA\u6765\u65F6\n\n| \u8111\u91CC\u5192\u51FA\u7684\u60F3\u6CD5 | \u73B0\u5B9E |\n|---|---|\n| \"\u6D4B\u8BD5\u6302\u4E86\uFF0C\u987A\u624B\u4FEE\u4E00\u4E0B\u518D\u8DD1\" | \u6C61\u67D3\u8BC1\u636E\uFF0C\u672C\u6B21\u9A8C\u8BC1\u4F5C\u5E9F |\n| \"DO \u62A5\u544A\u8BF4\u505A\u5B8C\u4E86\" | \u4E0D\u4FE1\u62A5\u544A\u3002\u770B\u4EE3\u7801\u3001\u8DD1\u6D4B\u8BD5\uFF0C\u81EA\u5DF1\u5224\u65AD |\n| \"\u6539\u7684\u662F\u65E0\u5173\u6587\u4EF6\" | \u4EFB\u4F55\u4E3B\u52A8\u6539\u52A8\u90FD\u8BA9\u9A8C\u8BC1\u4E0D\u53EF\u4FE1 |\n| \"\u770B\u7740\u5BF9\uFF0C\u5E94\u8BE5\u901A\u8FC7\" | \u901A\u8FC7\u5FC5\u987B\u6709\u6267\u884C\u8BC1\u636E\uFF0C\u7981\u6B62\"\u770B\u7740\u5BF9\" |\n| \"\u5BF9\u7ED3\u8BBA\u4E0D\u786E\u5B9A\" | \u4EFB\u4F55\u7591\u95EE \u2192 \u4E0D\u901A\u8FC7\uFF0C\u6CA1\u6709\u4F8B\u5916 |\n\n## \u8F93\u51FA\u683C\u5F0F(\u7CBE\u70BC,\u7ED3\u6784\u5316)\n\n**\u5224\u5B9A**:\u6700\u540E\u4E00\u884C\u8F93\u51FA\u6807\u7B7E:\n- \u901A\u8FC7 \u2192 `<promise-check>true</promise-check>`\n- \u4E0D\u901A\u8FC7 \u2192 `<promise-check>false</promise-check>`\n\n**\u8BC1\u636E\u4E0E\u539F\u56E0,\u6BCF\u6761\u4E00\u884C,\u6700\u591A 10 \u884C**,\u4F4D\u7F6E\u524D\u7F00\u6309\u60C5\u51B5\u9009\u7528:\n- \u5177\u4F53\u4EE3\u7801\u95EE\u9898:`[\u6587\u4EF6:\u884C\u53F7] \u95EE\u9898\u4E00\u53E5\u8BDD`\n- \u6A21\u5757\u7EA7\u95EE\u9898:`[\u6A21\u5757\u540D] \u95EE\u9898\u4E00\u53E5\u8BDD`\n- \u67B6\u6784\u7EA7/\u8DE8\u6587\u4EF6\u95EE\u9898:\u76F4\u63A5\u5199\u95EE\u9898\u4E00\u53E5\u8BDD,\u4E0D\u52A0\u524D\u7F00\n\n\u793A\u4F8B:\n- `[auth.service.ts:47] JWT \u5BC6\u94A5\u786C\u7F16\u7801`\n- `[payment] \u4E0E auth \u5171\u4EAB\u5168\u5C40\u53EF\u53D8\u72B6\u6001,\u8026\u5408\u8FC7\u9AD8`\n- `\u7F3A\u5C11\u7EDF\u4E00\u9519\u8BEF\u5904\u7406\u5C42,\u5404\u6A21\u5757\u5F02\u5E38\u5904\u7406\u6563\u843D`\n\n\u4E0D\u8981\u590D\u8FF0\u68C0\u67E5\u4F9D\u636E\u539F\u6587,\u4E0D\u8981\u5199\u7ED3\u8BBA\u6027\u7A7A\u8BDD\u3002\u8BC1\u636E\u4E3A\u51C6\u3002\u6807\u7B7E\u72EC\u5360\u6700\u540E\u4E00\u884C\u3002";
305
+ export declare const DEFAULT_ADVERSARIAL_TIMEOUT_MS = 900000;
306
+ export {};