ralphflow-dsh 0.1.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +220 -167
  2. package/cordis.patch.yml +11 -0
  3. package/lib/create.d.ts +7 -11
  4. package/lib/create.js +132 -83
  5. package/lib/engine.d.ts +667 -262
  6. package/lib/engine.js +3583 -2579
  7. package/lib/index.d.ts +3 -4
  8. package/lib/index.js +222 -163
  9. package/lib/message-source.d.ts +25 -0
  10. package/lib/message-source.js +2 -0
  11. package/lib/reset.d.ts +40 -0
  12. package/lib/reset.js +147 -0
  13. package/lib/tools.d.ts +31 -14
  14. package/lib/tools.js +407 -684
  15. package/lib/verify.d.ts +57 -0
  16. package/lib/verify.js +326 -0
  17. package/lib/voting.d.ts +63 -0
  18. package/lib/voting.js +131 -0
  19. package/package.json +25 -44
  20. package/workflows/loop.yaml +21 -6
  21. package/workflows/spec.yaml +51 -46
  22. package/lib/actions.d.ts +0 -37
  23. package/lib/actions.js +0 -55
  24. package/lib/check-voting.d.ts +0 -54
  25. package/lib/check-voting.js +0 -289
  26. package/lib/check.d.ts +0 -64
  27. package/lib/check.js +0 -329
  28. package/lib/client/CommandCard.d.ts +0 -24
  29. package/lib/client/CommandCard.js +0 -69
  30. package/lib/client/HeaderAction.d.ts +0 -39
  31. package/lib/client/HeaderAction.js +0 -509
  32. package/lib/client/RunCard.d.ts +0 -27
  33. package/lib/client/RunCard.js +0 -375
  34. package/lib/client/client.d.ts +0 -3
  35. package/lib/client/client.js +0 -275
  36. package/lib/client/definition.d.ts +0 -126
  37. package/lib/client/definition.js +0 -259
  38. package/lib/client/hidden-runs.d.ts +0 -6
  39. package/lib/client/hidden-runs.js +0 -52
  40. package/lib/client/http-state.d.ts +0 -67
  41. package/lib/client/http-state.js +0 -81
  42. package/lib/client/markdown.d.ts +0 -26
  43. package/lib/client/markdown.js +0 -174
  44. package/lib/client/notify-watch.d.ts +0 -38
  45. package/lib/client/notify-watch.js +0 -98
  46. package/lib/client/notify.d.ts +0 -21
  47. package/lib/client/notify.js +0 -168
  48. package/lib/client/snapshots.d.ts +0 -8
  49. package/lib/client/snapshots.js +0 -101
  50. package/lib/client.js +0 -2361
  51. package/lib/commands.d.ts +0 -41
  52. package/lib/commands.js +0 -223
  53. package/lib/deps.d.ts +0 -17
  54. package/lib/deps.js +0 -19
  55. package/lib/done-detect.d.ts +0 -2
  56. package/lib/done-detect.js +0 -28
  57. package/lib/driver.d.ts +0 -32
  58. package/lib/driver.js +0 -248
  59. package/lib/events.d.ts +0 -35
  60. package/lib/events.js +0 -52
  61. package/lib/jobs.d.ts +0 -56
  62. package/lib/jobs.js +0 -355
  63. package/lib/mutex.d.ts +0 -9
  64. package/lib/mutex.js +0 -21
  65. package/lib/session-hygiene.d.ts +0 -25
  66. package/lib/session-hygiene.js +0 -205
  67. package/lib/voting-progress.d.ts +0 -37
  68. package/lib/voting-progress.js +0 -89
@@ -1,205 +0,0 @@
1
- /**
2
- * Ralph Flow for dsh — 会话卫生:检测与修复「插件自定义事件帧砖化会话」
3
- *
4
- * 背景:dsh 会话日志落盘后若含未知事件类型(不在 KNOWN_SESSION_EVENT_TYPES
5
- * 且未标 ignorable),加载时被 SessionFormatUnsupportedError 拒绝——整个会话
6
- * 打不开(会话变砖)。历史版本曾用 session.append 写 tool-ralphflow/* 自定义
7
- * 帧,已砖化过真实会话(见 scripts/unbrick-sessions.mjs 与 ~/.dsh/unbrick-*)。
8
- *
9
- * 本模块(v2 架构):
10
- * - scanSessionLogs:扫描 $DSH_HOME/sessions 下全部 .zstd 会话日志,检出含
11
- * tool-ralphflow 事件帧的会话(doctor 报告 / unbrick 工具共用);
12
- * - unbrickSessions:备份后移除这些帧,按 dsh 多帧 zstd 格式重写(header
13
- * 单帧 + 事件分批帧,与 dsh-session-persistence 的 frame-boundary 语义对齐)。
14
- * 压缩走系统 zstd CLI(与 dsh 全链路同款工具,插件无 JS 压缩依赖;缺失时
15
- * 给出明确指引而非静默失败)。
16
- */
17
- import { execSync } from "node:child_process";
18
- import fs from "node:fs";
19
- import os from "node:os";
20
- import path from "node:path";
21
- /** 本插件写过的全部自定义帧类型(检测/移除名单) */
22
- const PLUGIN_EVENT_TYPES = new Set([
23
- "tool-ralphflow/run-start",
24
- "tool-ralphflow/run-detach",
25
- "tool-ralphflow/step-start",
26
- "tool-ralphflow/check-voter-start",
27
- "tool-ralphflow/check-verdict",
28
- "tool-ralphflow/check-result",
29
- "tool-ralphflow/gate",
30
- "tool-ralphflow/rewind",
31
- "tool-ralphflow/reset",
32
- "tool-ralphflow/report",
33
- "tool-ralphflow/run-end",
34
- "tool-ralphflow/command-result",
35
- ]);
36
- /** 会话存储根:$DSH_HOME/sessions(尊重 DSH_HOME,缺省 ~/.dsh) */
37
- export function sessionRoot() {
38
- const home = process.env.DSH_HOME && path.isAbsolute(process.env.DSH_HOME)
39
- ? process.env.DSH_HOME
40
- : path.join(os.homedir(), ".dsh");
41
- return path.join(home, "sessions");
42
- }
43
- function zstdAvailable() {
44
- try {
45
- execSync("zstd --version", { stdio: "ignore" });
46
- return true;
47
- }
48
- catch {
49
- return false;
50
- }
51
- }
52
- function listSessionLogs(root) {
53
- const out = [];
54
- const walk = (dir) => {
55
- let entries;
56
- try {
57
- entries = fs.readdirSync(dir, { withFileTypes: true });
58
- }
59
- catch {
60
- return;
61
- }
62
- for (const e of entries) {
63
- // 跳过解砖备份目录(历史 v2 脚本与内置模块的备份都可能含待移除帧)
64
- if (e.isDirectory() && /(^|-)(ralphflow-)?unbrick-backup-/.test(e.name))
65
- continue;
66
- const p = path.join(dir, e.name);
67
- if (e.isDirectory())
68
- walk(p);
69
- else if (e.name.endsWith(".zstd"))
70
- out.push(p);
71
- }
72
- };
73
- walk(root);
74
- return out;
75
- }
76
- function decodeLog(file) {
77
- try {
78
- const text = execSync("zstd -d -c", {
79
- input: fs.readFileSync(file),
80
- maxBuffer: 512 * 1024 * 1024,
81
- }).toString("utf-8");
82
- return text.split("\n").filter(Boolean);
83
- }
84
- catch {
85
- return null;
86
- }
87
- }
88
- function pluginFrameCount(lines) {
89
- const types = new Map();
90
- for (const line of lines) {
91
- try {
92
- const type = JSON.parse(line)?.type;
93
- if (typeof type === "string" && PLUGIN_EVENT_TYPES.has(type)) {
94
- types.set(type, (types.get(type) ?? 0) + 1);
95
- }
96
- }
97
- catch { }
98
- }
99
- const sorted = [...types.entries()].sort((a, b) => b[1] - a[1]);
100
- return { count: sorted.reduce((n, [, c]) => n + c, 0), types: sorted.map(([t, c]) => `${t}×${c}`) };
101
- }
102
- /** 扫描全部会话存储,返回含插件自定义帧的会话(只读,不修改) */
103
- export function scanSessionLogs() {
104
- const out = [];
105
- if (!zstdAvailable())
106
- return out;
107
- const root = sessionRoot();
108
- if (!fs.existsSync(root))
109
- return out;
110
- for (const file of listSessionLogs(root)) {
111
- try {
112
- const lines = decodeLog(file);
113
- if (!lines)
114
- continue;
115
- const { count, types } = pluginFrameCount(lines);
116
- if (count > 0)
117
- out.push({ file, count, types });
118
- }
119
- catch { }
120
- }
121
- return out;
122
- }
123
- /** 多帧 zstd:第一帧 header 单独成帧,其余事件按批次独立成帧(v2 正确格式) */
124
- function encodeMultiFrame(lines) {
125
- if (lines.length === 0)
126
- throw new Error("empty log");
127
- const frames = [];
128
- const headerLine = lines[0];
129
- frames.push(execSync("zstd -q -f -c", {
130
- input: Buffer.from(headerLine + "\n", "utf-8"),
131
- maxBuffer: 64 * 1024 * 1024,
132
- }));
133
- const BATCH = 64;
134
- const rest = lines.slice(1);
135
- for (let i = 0; i < rest.length; i += BATCH) {
136
- const chunk = rest.slice(i, i + BATCH);
137
- frames.push(execSync("zstd -q -f -c", {
138
- input: Buffer.from(chunk.join("\n") + "\n", "utf-8"),
139
- maxBuffer: 64 * 1024 * 1024,
140
- }));
141
- }
142
- return Buffer.concat(frames);
143
- }
144
- /**
145
- * 解砖:备份并移除全部插件自定义帧。
146
- * skipFreshMs 内的文件跳过(可能是正在运行的进程仍在写——例如当前宿主进程
147
- * 自己;解砖对象应是已停写的历史会话)。
148
- */
149
- export function unbrickSessions(skipFreshMs = 60_000) {
150
- const result = { scanned: 0, fixed: 0, backupRoot: null, fixedFiles: [], errors: [] };
151
- if (!zstdAvailable()) {
152
- result.errors.push("系统未安装 zstd CLI(`zstd --version` 失败)。安装 zstd 后重试,或手动运行 scripts/unbrick-sessions.mjs。");
153
- return result;
154
- }
155
- const root = sessionRoot();
156
- if (!fs.existsSync(root)) {
157
- result.errors.push(`未找到会话目录:${root}`);
158
- return result;
159
- }
160
- const files = listSessionLogs(root);
161
- result.scanned = files.length;
162
- const now = Date.now();
163
- const backupRoot = path.join(root, "ralphflow-unbrick-backup-" + Date.now());
164
- let backupCreated = false;
165
- for (const file of files) {
166
- try {
167
- const st = fs.statSync(file);
168
- if (now - st.mtimeMs < skipFreshMs)
169
- continue; // 活跃写盘中的会话不动
170
- const lines = decodeLog(file);
171
- if (!lines) {
172
- result.errors.push(`解码失败(可能正在写入或已损坏):${file}`);
173
- continue;
174
- }
175
- const { count } = pluginFrameCount(lines);
176
- if (count === 0)
177
- continue;
178
- const kept = lines.filter((line) => {
179
- try {
180
- const type = JSON.parse(line)?.type;
181
- return !(typeof type === "string" && PLUGIN_EVENT_TYPES.has(type));
182
- }
183
- catch {
184
- return true;
185
- }
186
- });
187
- if (!backupCreated) {
188
- fs.mkdirSync(backupRoot, { recursive: true });
189
- backupCreated = true;
190
- }
191
- const rel = path.relative(root, file);
192
- const bak = path.join(backupRoot, rel);
193
- fs.mkdirSync(path.dirname(bak), { recursive: true });
194
- fs.copyFileSync(file, bak);
195
- fs.writeFileSync(file, encodeMultiFrame(kept));
196
- result.fixed++;
197
- result.fixedFiles.push(`${rel}(移除 ${count} 帧)`);
198
- }
199
- catch (e) {
200
- result.errors.push(`${file}: ${e instanceof Error ? e.message : String(e)}`);
201
- }
202
- }
203
- result.backupRoot = backupCreated ? backupRoot : null;
204
- return result;
205
- }
@@ -1,37 +0,0 @@
1
- /**
2
- * Voting progress persistence (.check-voting-progress.json).
3
- *
4
- * Multi-voter CHECK progress must survive across: concurrent voters, infra
5
- * auto-retry, check_error pause, user continue. These events may happen in
6
- * different processes/sessions, so progress is persisted per-instance.
7
- *
8
- * Lifecycle (design §5.3):
9
- * - entry with phase="do" → delete (new round, all re-vote)
10
- * - entry with phase="check" + file → keep; infra_failed reset to pending
11
- * - entry with phase="check" no file → all re-vote (restart, plugin hook)
12
- * - aggregate done (pass/fail) → delete
13
- * - check_error pause → keep
14
- * - crash recovery / reset/rewind/cancel → delete
15
- */
16
- import type { Engine, CheckVotingEntry } from "./engine.js";
17
- export type VoterStatus = "pending" | "running" | "passed" | "failed" | "infra_pending" | "infra_failed" | "cancelled";
18
- export interface VoterProgressEntry {
19
- index: number;
20
- check: string;
21
- model: string | null;
22
- status: VoterStatus;
23
- reason: string;
24
- /** 本次运行开始时刻(ms)——UI 用它显示「该票已跑 Xs」;retry 轮会刷新 */
25
- startedAt?: number;
26
- }
27
- export interface VotingProgress {
28
- stepId: string;
29
- workflowName: string;
30
- entries: VoterProgressEntry[];
31
- updatedAt: string;
32
- }
33
- export declare function progressFilePath(engine: Engine, instId: string): string;
34
- export declare function initVotingProgress(stepId: string, workflowName: string, entries: CheckVotingEntry[]): VotingProgress;
35
- export declare function readVotingProgress(engine: Engine, instId: string): VotingProgress | null;
36
- export declare function writeVotingProgress(engine: Engine, instId: string, progress: VotingProgress): void;
37
- export declare function deleteVotingProgress(engine: Engine, instId: string): void;
@@ -1,89 +0,0 @@
1
- /**
2
- * Voting progress persistence (.check-voting-progress.json).
3
- *
4
- * Multi-voter CHECK progress must survive across: concurrent voters, infra
5
- * auto-retry, check_error pause, user continue. These events may happen in
6
- * different processes/sessions, so progress is persisted per-instance.
7
- *
8
- * Lifecycle (design §5.3):
9
- * - entry with phase="do" → delete (new round, all re-vote)
10
- * - entry with phase="check" + file → keep; infra_failed reset to pending
11
- * - entry with phase="check" no file → all re-vote (restart, plugin hook)
12
- * - aggregate done (pass/fail) → delete
13
- * - check_error pause → keep
14
- * - crash recovery / reset/rewind/cancel → delete
15
- */
16
- import fs from "fs";
17
- import path from "path";
18
- import { VOTING_PROGRESS_FILENAME } from "./engine.js";
19
- export function progressFilePath(engine, instId) {
20
- return path.join(engine.getInstanceDir(instId), VOTING_PROGRESS_FILENAME);
21
- }
22
- export function initVotingProgress(stepId, workflowName, entries) {
23
- return {
24
- stepId,
25
- workflowName,
26
- entries: entries.map((e, i) => ({
27
- index: i,
28
- check: e.check,
29
- model: typeof e.model === "string" ? e.model : e.model ? `${e.model.providerID ?? ""}/${e.model.modelID ?? ""}` : null,
30
- status: "pending",
31
- reason: "",
32
- })),
33
- updatedAt: new Date().toISOString(),
34
- };
35
- }
36
- export function readVotingProgress(engine, instId) {
37
- try {
38
- const file = progressFilePath(engine, instId);
39
- if (!fs.existsSync(file))
40
- return null;
41
- const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
42
- if (!raw || typeof raw !== "object" || !Array.isArray(raw.entries))
43
- return null;
44
- const entries = raw.entries
45
- .filter((e) => e && typeof e === "object" && typeof e.index === "number")
46
- .map((e) => ({
47
- index: e.index,
48
- check: typeof e.check === "string" ? e.check : "",
49
- model: typeof e.model === "string" ? e.model : null,
50
- status: ["pending", "running", "passed", "failed", "infra_pending", "infra_failed", "cancelled"].includes(e.status)
51
- ? e.status
52
- : "pending",
53
- reason: typeof e.reason === "string" ? e.reason : "",
54
- // startedAt 透传:check-voting 在 running 时写入,回读时必须保留,
55
- // 否则「读取→改状态→写回」会把运行时长丢掉
56
- ...(typeof e.startedAt === "number" && e.startedAt > 0 ? { startedAt: e.startedAt } : {}),
57
- }));
58
- return {
59
- stepId: typeof raw.stepId === "string" ? raw.stepId : "",
60
- workflowName: typeof raw.workflowName === "string" ? raw.workflowName : "",
61
- entries,
62
- updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : "",
63
- };
64
- }
65
- catch {
66
- return null;
67
- }
68
- }
69
- export function writeVotingProgress(engine, instId, progress) {
70
- try {
71
- // 防复活:cancel 可插在任一在飞 vote 回调之前——实例目录已删时绝不重建,
72
- // 否则 destroyInstance 后会留下幽灵目录(doctor 持续报缺 state.json)。
73
- if (!engine.instanceExists(instId))
74
- return;
75
- const file = progressFilePath(engine, instId);
76
- if (!fs.existsSync(path.dirname(file)))
77
- return;
78
- const tmp = file + ".tmp." + process.pid;
79
- fs.writeFileSync(tmp, JSON.stringify({ ...progress, updatedAt: new Date().toISOString() }, null, 2));
80
- fs.renameSync(tmp, file);
81
- }
82
- catch { }
83
- }
84
- export function deleteVotingProgress(engine, instId) {
85
- try {
86
- fs.unlinkSync(progressFilePath(engine, instId));
87
- }
88
- catch { }
89
- }