@aiyiran/myclaw 1.1.169 → 1.1.171

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -132,8 +132,8 @@ voice-output.js → voice-input.js → myclaw-tts.js
132
132
  ▼ ▼
133
133
  服务端(sync_workspace.py,本机 18800 / 远程经 nginx /sync)
134
134
  ├─ 按 workspace 自行算目录,写两个文件:
135
- debug-data.js ← 每次覆盖,window.__DEBUG_DATA__ = {规范化记录}(数据,喂渲染也给 AI 读)
136
- debug-record.html ← 恒定壳,含 CSS + 前端渲染器,运行时加载 debug-data.js 渲染
135
+ __debug-data__.js ← 每次覆盖,window.__DEBUG_DATA__ = {规范化记录}(数据,喂渲染也给 AI 读)
136
+ 调试日志.html ← 恒定壳,含 CSS + 前端渲染器,运行时加载 __debug-data__.js 渲染
137
137
 
138
138
  同步循环 → 上传 CDN → 可展示给学生
139
139
  ```
@@ -144,7 +144,7 @@ voice-output.js → voice-input.js → myclaw-tts.js
144
144
  |------|------|------|--------|
145
145
  | **probe**(采集侧) | `assets/debug-probe.js` | 在 iframe 内采集现场,`postMessage` 上报 | traceId、workspace、上传、判因 |
146
146
  | **collector**(接收侧) | `assets/debug-collector.js` | 父页面收事件、攒记录、关闭时提交 | probe 注入、AI 修复、HTML 模板 |
147
- | **server**(落库侧) | `server/debug_record.py` | 算目录、校验、normalize、写 debug-data.js + 恒定 HTML 壳 | 采集、CDN 上传(交给同步循环) |
147
+ | **server**(落库侧) | `server/debug_record.py` | 算目录、校验、normalize、写 __debug-data__.js + 恒定 HTML 壳 | 采集、CDN 上传(交给同步循环) |
148
148
  | **renderer**(渲染侧) | HTML 壳内联 JS(`render_shell_html()` 里) | 读 `window.__DEBUG_DATA__`,渲染小结/线索/回放 | 数据清洗(服务端做) |
149
149
 
150
150
  ### 关键设计约束(改之前先读)
@@ -161,9 +161,9 @@ voice-output.js → voice-input.js → myclaw-tts.js
161
161
  5. **前端不传文件路径**。前端只传逻辑字段(claw / workspace / entryFile),**服务端自己算目录**。`claw` 不是路径层级,只用于跟本机 `CLAW_NAME` 校验防串写;真实路径是 `{openclaw_root}/{workspace}/debug/`。
162
162
 
163
163
  6. **数据/渲染分离,落盘两个文件**(固定文件名,每次覆盖):
164
- - `debug-data.js`:`window.__DEBUG_DATA__ = {...}`,唯一数据源(喂前端渲染 + 给 AI 直接读)。
165
- - `debug-record.html`:**恒定壳**,内容不随数据变(哈希不变 → 同步不会反复当成更新)。壳内联 CSS + 渲染器 JS,运行时用 `debug-data.js?t=<时间戳>` 动态加载绕 CDN 缓存。
166
- - ⚠️ 渲染逻辑(事件转写 / 错误解释 / 线索提取)现在在**前端 JS**(`render_shell_html()` 里),不在 Python。改文案/样式改这里,且因为壳恒定,AI 修 bug 应读 `debug-data.js` 而非 HTML。
164
+ - `__debug-data__.js`:`window.__DEBUG_DATA__ = {...}`,唯一数据源(喂前端渲染 + 给 AI 直接读)。
165
+ - `调试日志.html`:**恒定壳**,内容不随数据变(哈希不变 → 同步不会反复当成更新)。壳内联 CSS + 渲染器 JS,运行时用 `__debug-data__.js?t=<时间戳>` 动态加载绕 CDN 缓存。
166
+ - ⚠️ 渲染逻辑(事件转写 / 错误解释 / 线索提取)现在在**前端 JS**(`render_shell_html()` 里),不在 Python。改文案/样式改这里,且因为壳恒定,AI 修 bug 应读 `__debug-data__.js` 而非 HTML。
167
167
 
168
168
  ### 接口
169
169
 
@@ -192,4 +192,4 @@ voice-output.js → voice-input.js → myclaw-tts.js
192
192
  ### 已知待办
193
193
 
194
194
  - 整链路端到端实测(单测已过,未在真实 gateway + 同步进程跑通)。
195
- - `{workspace}/debug/debug-record.html` 会进 `__MY_ARTIFACTS__.json` 作品列表,是否需要从列表过滤、改走专门入口,待定。
195
+ - `{workspace}/debug/调试日志.html` 会进 `__MY_ARTIFACTS__.json` 作品列表,是否需要从列表过滤、改走专门入口,待定。
@@ -424,6 +424,7 @@
424
424
  '__teacher__.json',
425
425
  '__teacher-view__.html',
426
426
  '__任务__.html',
427
+ '__debug-data__.js',
427
428
  'USER.md',
428
429
  'TOOLS.md',
429
430
  'SOUL.md',
@@ -325,34 +325,20 @@
325
325
 
326
326
  // ═══ 3. Debug 按钮 ═══
327
327
 
328
- function buildTestDonePrompt() {
329
- var rec = window.myclawLastDebugRecord;
328
+ function buildTestDonePrompt(keepLogs) {
330
329
  var lines = ["我刚才已经完成了测试。"];
331
330
 
332
- // 调试数据落在 debug-data.jswindow.__DEBUG_DATA__ = {...}),AI 直接读这个
333
- // 数据文件即可,不要读同目录的 debug-record.html(那只是给人看的渲染壳)。
334
- var dataFile = null;
335
- if (rec) {
336
- if (rec.debugRecordPath) {
337
- dataFile = rec.debugRecordPath.replace(/debug-record\.html$/, "debug-data.js");
338
- } else if (rec.workspace) {
339
- dataFile = rec.workspace + "/debug/debug-data.js";
340
- }
341
- }
342
- if (dataFile) {
343
- lines.push("请你读取调试数据文件:" + dataFile);
344
- } else {
345
- lines.push("请你读取本次测试的调试数据文件 debug/debug-data.js。");
346
- }
347
- lines.push("它是一行 `window.__DEBUG_DATA__ = {...}` 的赋值,里面的 events 数组就是完整运行现场;不要去读同目录的 debug-record.html。");
348
- if (rec && rec.entryFile) {
349
- lines.push("我刚才测试的文件是:" + rec.entryFile);
350
- }
331
+ lines.push("请你读取调试数据文件 debug/__debug-data__.js,它是一行 `window.__DEBUG_DATA__ = {...}` 的赋值,里面的 events 数组就是完整运行现场。");
351
332
 
352
333
  lines.push("");
353
334
  lines.push("请帮我判断:我们之前的问题是否已经修复。");
354
335
  lines.push("如果已经修复,请简单说明你从 events 里看到了什么证据。");
355
336
  lines.push("如果还没有修复,请指出 events 里最关键的问题,并建议下一步最小修改。");
337
+ if (keepLogs) {
338
+ lines.push("请保留现有调试日志,不要删除或精简这些 console.log,后面还要继续观察。");
339
+ } else {
340
+ lines.push("如果你确认问题已经修复,请把为了调试临时添加的 console.log / 运行提示清理掉;如果还没修复,请先保留必要日志。");
341
+ }
356
342
 
357
343
  return lines.join("\n");
358
344
  }
@@ -387,9 +373,7 @@
387
373
 
388
374
  menu.appendChild(makeItem("查报错", showDebugModal));
389
375
  menu.appendChild(makeItem("加日志", showLogModal));
390
- menu.appendChild(makeItem("看结果", function () {
391
- sendGeneratedPrompt(buildTestDonePrompt());
392
- }));
376
+ menu.appendChild(makeItem("看结果", showTestDoneModal));
393
377
 
394
378
  wrap.appendChild(btn);
395
379
  wrap.appendChild(menu);
@@ -417,6 +401,11 @@
417
401
  if (modal) modal.remove();
418
402
  }
419
403
 
404
+ function closeTestDoneModal() {
405
+ var modal = document.getElementById("myclaw-test-done-modal");
406
+ if (modal) modal.remove();
407
+ }
408
+
420
409
  function makeDebugLabel(text) {
421
410
  var label = document.createElement("div");
422
411
  label.textContent = text;
@@ -571,30 +560,16 @@
571
560
  var state = { description: "" };
572
561
 
573
562
  function buildDebugPrompt() {
574
- var rec = window.myclawLastDebugRecord;
575
563
  var lines = [];
576
564
 
577
- // 调试数据现在落在 debug-data.js(window.__DEBUG_DATA__ = {...}),
578
- // 与 debug-record.html 同目录。AI 直接读这个数据文件即可,不用读 HTML。
579
- var dataFile = null;
580
- if (rec) {
581
- if (rec.debugRecordPath) {
582
- dataFile = rec.debugRecordPath.replace(/debug-record\.html$/, "debug-data.js");
583
- } else if (rec.workspace) {
584
- dataFile = rec.workspace + "/debug/debug-data.js";
585
- }
586
- }
587
- if (dataFile) {
588
- lines.push("调试数据文件:" + dataFile);
589
- lines.push("");
590
- }
591
-
565
+ lines.push("调试数据文件:debug/__debug-data__.js");
566
+ lines.push("");
592
567
  lines.push("学生描述:" + (state.description || "(未填写)"));
593
568
  lines.push("");
594
569
  lines.push("请从学生描述里提取:我做了什么、发生了什么、我的预期是什么。");
595
570
  lines.push("");
596
571
  lines.push("如何阅读调试数据(按下面抓重点,别东翻西找):");
597
- lines.push("1. 读上面的调试数据文件 debug-data.js,它是一行 `window.__DEBUG_DATA__ = {...}` 的赋值,里面的 events 数组就是完整运行现场。(不要去读同目录的 debug-record.html,那只是给人看的渲染壳。)");
572
+ lines.push("1. 读调试数据文件 debug/__debug-data__.js,它是一行 `window.__DEBUG_DATA__ = {...}` 的赋值,里面的 events 数组就是完整运行现场。");
598
573
  lines.push("2. 先在 events 里找 runtime-error / unhandledrejection / 以及 payload.level 为 error 的 console 事件,它们是问题的起点。");
599
574
  lines.push("3. 抓住报错事件的 message、stack、filename、lineno——直接定位到源码里出错的那个函数/那几行,只看相关代码段,不要通读整个作品文件。");
600
575
  lines.push("4. 再倒着看报错之前的 page-enter / click / keydown / console,还原“做了什么 → 触发了什么”的因果链,确认重现路径。");
@@ -691,15 +666,13 @@
691
666
 
692
667
  function buildLogPrompt() {
693
668
  var lines = [];
694
- lines.push("我需要你帮我添加一些调试信息,我希望调试信息非常清晰、全面。");
695
- lines.push("我正在解决的问题是关于:" + state.problem);
669
+ lines.push("目前的信息如下:debug/__debug-data__.js");
670
+ lines.push("我要解决一个问题:" + state.problem);
696
671
  lines.push("");
697
- lines.push("这些调试信息后续会给到你,用来帮我继续解决问题。");
698
- lines.push("");
699
- lines.push("请只添加调试信息,不要顺手修改功能逻辑。");
700
672
  lines.push("请优先添加 console.log,文字要清楚,适合小学生看懂。");
701
673
  lines.push("请在关键步骤都加上信息,比如:有没有点到、进入了哪一步、重要变量现在是多少、为什么没有继续。");
702
- lines.push("改完后告诉我:你在哪些地方加了提示、每条提示能帮我看出什么。");
674
+ lines.push("");
675
+ lines.push("另外,你帮我看一下,如果你能直接找到原因就先尝试修复一下。如果不容易找到,就仅仅加日志。但是,日志一定要加。");
703
676
  return lines.join("\n");
704
677
  }
705
678
 
@@ -787,6 +760,61 @@
787
760
  problemField.focus();
788
761
  }
789
762
 
763
+ function showTestDoneModal() {
764
+ if (document.getElementById("myclaw-test-done-modal")) return;
765
+
766
+ var overlay = document.createElement("div");
767
+ overlay.id = "myclaw-test-done-modal";
768
+
769
+ var box = document.createElement("div");
770
+ box.className = "myclaw-debug-box myclaw-test-done-box";
771
+
772
+ var header = document.createElement("div");
773
+ header.className = "myclaw-debug-header myclaw-test-done-header";
774
+ header.innerHTML = "<span>✅ 看测试结果</span>";
775
+ var closeX = document.createElement("span");
776
+ closeX.textContent = "✕";
777
+ closeX.className = "myclaw-debug-close";
778
+ closeX.onclick = function () { closeTestDoneModal(); };
779
+ header.appendChild(closeX);
780
+
781
+ var body = document.createElement("div");
782
+ body.className = "myclaw-test-done-body";
783
+ body.textContent = "让 AI 看刚才的测试日志,并判断问题有没有修好。";
784
+
785
+ var footer = document.createElement("div");
786
+ footer.className = "myclaw-test-done-actions";
787
+
788
+ function makeAction(text, className, keepLogs) {
789
+ var btn = document.createElement("button");
790
+ btn.type = "button";
791
+ btn.className = className;
792
+ btn.textContent = text;
793
+ btn.addEventListener("click", function () {
794
+ closeTestDoneModal();
795
+ sendGeneratedPrompt(buildTestDonePrompt(keepLogs));
796
+ });
797
+ return btn;
798
+ }
799
+
800
+ var keepBtn = makeAction("检查并保留日志", "myclaw-test-done-keep", true);
801
+ var cleanBtn = makeAction("检查并去掉日志", "myclaw-test-done-clean", false);
802
+ var cancelBtn = document.createElement("button");
803
+ cancelBtn.type = "button";
804
+ cancelBtn.className = "myclaw-test-done-cancel";
805
+ cancelBtn.textContent = "取消";
806
+ cancelBtn.addEventListener("click", function () { closeTestDoneModal(); });
807
+
808
+ footer.appendChild(keepBtn);
809
+ footer.appendChild(cleanBtn);
810
+ footer.appendChild(cancelBtn);
811
+ box.appendChild(header);
812
+ box.appendChild(body);
813
+ box.appendChild(footer);
814
+ overlay.appendChild(box);
815
+ document.body.appendChild(overlay);
816
+ }
817
+
790
818
  // ═══ 3.1 Prompt 小助手按钮(实现见 myclaw-iteration.js) ═══
791
819
 
792
820
  function createPromptButton() {
@@ -1109,7 +1137,7 @@ btn.addEventListener("click", function () {
1109
1137
  " to { opacity: 1; }",
1110
1138
  "}",
1111
1139
  /* Debug 提交弹框 */
1112
- "#myclaw-debug-modal, #myclaw-log-modal {",
1140
+ "#myclaw-debug-modal, #myclaw-log-modal, #myclaw-test-done-modal {",
1113
1141
  " position: fixed; inset: 0; z-index: 99999;",
1114
1142
  " background: rgba(0,0,0,0.45);",
1115
1143
  " display: flex; align-items: center; justify-content: center;",
@@ -1131,6 +1159,9 @@ btn.addEventListener("click", function () {
1131
1159
  ".myclaw-log-header {",
1132
1160
  " background: linear-gradient(135deg,#0ea5e9,#6366f1);",
1133
1161
  "}",
1162
+ ".myclaw-test-done-header {",
1163
+ " background: linear-gradient(135deg,#10b981,#14b8a6);",
1164
+ "}",
1134
1165
  ".myclaw-debug-close {",
1135
1166
  " cursor: pointer; padding: 2px 8px; border-radius: 4px; font-size: 15px;",
1136
1167
  "}",
@@ -1173,6 +1204,26 @@ btn.addEventListener("click", function () {
1173
1204
  ".myclaw-debug-submit:disabled {",
1174
1205
  " cursor: not-allowed;",
1175
1206
  "}",
1207
+ ".myclaw-test-done-box { width: 460px; }",
1208
+ ".myclaw-test-done-body {",
1209
+ " padding: 20px; color: #cdd6f4; font-size: 14px;",
1210
+ " line-height: 1.7; font-family: -apple-system,sans-serif;",
1211
+ "}",
1212
+ ".myclaw-test-done-actions {",
1213
+ " display: flex; flex-direction: column; gap: 10px;",
1214
+ " padding: 0 20px 20px;",
1215
+ "}",
1216
+ ".myclaw-test-done-actions button {",
1217
+ " padding: 11px 12px; border: none; border-radius: 8px;",
1218
+ " color: #fff; font-size: 14px; font-weight: bold;",
1219
+ " font-family: -apple-system,sans-serif; cursor: pointer;",
1220
+ "}",
1221
+ ".myclaw-test-done-keep { background: #10b981; }",
1222
+ ".myclaw-test-done-clean { background: #6366f1; }",
1223
+ ".myclaw-test-done-cancel { background: #3d3d5c; color: #cdd6f4 !important; }",
1224
+ ".myclaw-test-done-keep:hover { background: #059669; }",
1225
+ ".myclaw-test-done-clean:hover { background: #4f46e5; }",
1226
+ ".myclaw-test-done-cancel:hover { background: #4b4b6a; }",
1176
1227
  ].join("\n");
1177
1228
  document.head.appendChild(style);
1178
1229
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiyiran/myclaw",
3
- "version": "1.1.169",
3
+ "version": "1.1.171",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -29,6 +29,11 @@
29
29
  "name": "chat-history-extractor",
30
30
  "strategy": "on",
31
31
  "description": "从 OpenClaw session URL 提取并渲染聊天记录"
32
+ },
33
+ {
34
+ "name": "yiran-skill-session-rollback",
35
+ "strategy": "on",
36
+ "description": "把会话还原到上一版 transcript(从 *.jsonl.reset 归档回滚)"
32
37
  }
33
38
  ],
34
39
  "_doc_agents": "Step 3: 将 agent-list/ 下的智能体分发到 ~/.openclaw/ 并注册到 openclaw.json",
@@ -5,20 +5,20 @@ debug_record.py
5
5
  把前端收集到的 currentDebugRecord 落盘成两个文件,供学生/老师/AI 查看。
6
6
 
7
7
  【架构:数据与渲染分离】
8
- - debug-data.js —— 每次覆盖写。内容是 `window.__DEBUG_DATA__ = {规范化后的记录}`。
8
+ - __debug-data__.js —— 每次覆盖写。内容是 `window.__DEBUG_DATA__ = {规范化后的记录}`。
9
9
  这是**唯一数据源**:既喂前端渲染,也给 AI 直接读。
10
- - debug-record.html —— 恒定的“壳”。包含 CSS + 前端渲染器 JS,运行时动态加载
11
- debug-data.js 并渲染。内容不随数据变化,因此同步循环不会
10
+ - 调试日志.html —— 恒定的“壳”。包含 CSS + 前端渲染器 JS,运行时动态加载
11
+ __debug-data__.js 并渲染。内容不随数据变化,因此同步循环不会
12
12
  反复把它当成“更新”重传。
13
13
 
14
14
  为什么这么拆:
15
15
  1. HTML 壳恒定 → 哈希不变 → 不再被同步误判为更新(根除循环上传问题)。
16
- 2. AI 读的是纯数据 debug-data.js,信噪比高,不掺样式。
16
+ 2. AI 读的是纯数据 __debug-data__.js,信噪比高,不掺样式。
17
17
  3. 渲染逻辑在前端,改样式不用动 Python、不用重启同步进程。
18
18
 
19
19
  服务端职责(本文件):
20
20
  - 接收 / 校验 / normalize 记录
21
- - 写出 debug-data.js 和 debug-record.html
21
+ - 写出 __debug-data__.js 和 调试日志.html
22
22
  渲染职责(前端,在 HTML 壳的内联 JS 里):
23
23
  - 读 window.__DEBUG_DATA__,渲染小结 / 线索 / 运行回放 / 原始数据
24
24
 
@@ -65,7 +65,7 @@ ERROR_EVENT_TYPES = {
65
65
 
66
66
 
67
67
  # =============================================================================
68
- # 2. 保存层:写 debug-data.js + 恒定的 debug-record.html 壳
68
+ # 2. 保存层:写 __debug-data__.js + 恒定的 调试日志.html 壳
69
69
  # =============================================================================
70
70
 
71
71
 
@@ -74,8 +74,8 @@ def save_debug_record(record: Dict[str, Any], debug_dir: Path) -> Dict[str, str]
74
74
  落盘调试记录。
75
75
 
76
76
  写两个文件:
77
- - debug-data.js 每次覆盖,内容 = window.__DEBUG_DATA__ = {normalized record}
78
- - debug-record.html 恒定壳(内容不变),负责加载并渲染上面的数据
77
+ - __debug-data__.js 每次覆盖,内容 = window.__DEBUG_DATA__ = {normalized record}
78
+ - 调试日志.html 恒定壳(内容不变),负责加载并渲染上面的数据
79
79
  """
80
80
  debug_dir.mkdir(parents=True, exist_ok=True)
81
81
 
@@ -83,12 +83,12 @@ def save_debug_record(record: Dict[str, Any], debug_dir: Path) -> Dict[str, str]
83
83
 
84
84
  # 数据文件:每次覆盖
85
85
  data_js = "window.__DEBUG_DATA__ = " + safe_json_for_js(normalized_record) + ";\n"
86
- data_path = debug_dir / "debug-data.js"
86
+ data_path = debug_dir / "__debug-data__.js"
87
87
  write_text_atomic(data_path, data_js)
88
88
 
89
89
  # HTML 壳:内容恒定(不含数据)。每次都写没关系——内容一致,
90
90
  # 基于内容哈希的同步不会把它当成变更重传。
91
- html_path = debug_dir / "debug-record.html"
91
+ html_path = debug_dir / "调试日志.html"
92
92
  write_text_atomic(html_path, render_shell_html())
93
93
 
94
94
  return {"html_path": str(html_path), "data_path": str(data_path)}
@@ -181,7 +181,7 @@ def handle_save_request(body: Dict[str, Any], openclaw_root: str, server_claw: s
181
181
  paths = save_debug_record(body, debug_dir)
182
182
 
183
183
  cdn_base = f"https://cdn.yiranlaoshi.com/{claw}"
184
- debug_record_url = f"{cdn_base}/{workspace}/debug/debug-record.html"
184
+ debug_record_url = f"{cdn_base}/{workspace}/debug/调试日志.html"
185
185
 
186
186
  record = normalize_record(body)
187
187
 
@@ -206,7 +206,7 @@ def assert_safe_id(value: str, field_name: str) -> None:
206
206
 
207
207
 
208
208
  # =============================================================================
209
- # 4. record / event 规范化(数据清洗留在服务端,输出进 debug-data.js)
209
+ # 4. record / event 规范化(数据清洗留在服务端,输出进 __debug-data__.js)
210
210
  # =============================================================================
211
211
 
212
212
 
@@ -391,7 +391,7 @@ def safe_json_for_js(value: Any) -> str:
391
391
  # 这个函数返回的内容**不随数据变化**,是纯静态的“壳”:
392
392
  # - <style> 页面样式
393
393
  # - 前端渲染器 JS(事件转写 / 错误解释 / 线索提取 / DOM 渲染)
394
- # - 运行时动态加载 debug-data.js?t=<时间戳> 绕开 CDN 缓存
394
+ # - 运行时动态加载 __debug-data__.js?t=<时间戳> 绕开 CDN 缓存
395
395
  # 渲染逻辑是从原 Python 函数(format_replay_event / simplify_error_message /
396
396
  # extract_clues / render_*)逐一移植过来的 JS 版本。
397
397
  #
@@ -719,13 +719,13 @@ def render_shell_html() -> str:
719
719
 
720
720
  // 动态加载数据,带时间戳绕开 CDN 缓存(壳恒定,数据每次新)
721
721
  var s = document.createElement("script");
722
- s.src = "debug-data.js?t=" + Date.now();
722
+ s.src = "__debug-data__.js?t=" + Date.now();
723
723
  s.onload = function () {
724
724
  try { render(window.__DEBUG_DATA__); }
725
725
  catch (e) { document.getElementById("dynamic").textContent = "渲染失败:" + (e && e.message); }
726
726
  };
727
727
  s.onerror = function () {
728
- document.getElementById("dynamic").textContent = "调试数据加载失败(debug-data.js)";
728
+ document.getElementById("dynamic").textContent = "调试数据加载失败(__debug-data__.js)";
729
729
  };
730
730
  document.head.appendChild(s);
731
731
  })();
@@ -477,8 +477,8 @@ def _put_file_to_qiniu(token, key, abs_path):
477
477
  """统一上传入口。HTML 文件注入 probe 后以字节上传;其余走原始文件上传。"""
478
478
  ext = os.path.splitext(abs_path)[1].lower()
479
479
  if ext in (".html", ".htm"):
480
- # debug-record.html 是展示壳,不是学生作品,跳过 probe 注入
481
- if os.path.basename(abs_path) != "debug-record.html":
480
+ # 调试日志.html 是展示壳,不是学生作品,跳过 probe 注入
481
+ if os.path.basename(abs_path) != "调试日志.html":
482
482
  with open(abs_path, "rb") as f:
483
483
  data = inject_probe_into_html(f.read())
484
484
  return put_data(token, key, data, mime_type="text/html")
@@ -0,0 +1,120 @@
1
+ ---
2
+ name: yiran-skill-session-rollback
3
+ description: Restore an OpenClaw conversation/session to its previous transcript version by locating the right session key, current sessionId, and archived `*.jsonl.reset.<timestamp>` transcript, then repointing the key back to the chosen prior version. Use when the user asks to recover a chat, roll back a conversation, restore the previous version of a session, or revert a session after reset. Trigger even if the user provides only a session id fragment, a TUI id, an agent name, or conversation text and you need to search for the matching session first.
4
+ ---
5
+
6
+ Restore the target conversation to an earlier transcript version.
7
+
8
+ Read `references/usage-and-design.md` when you need the full design rationale, safety model, or the division of labor between skill, script, and agent judgment.
9
+
10
+ ## Previous version definition
11
+
12
+ **Previous version / 上一版** means:
13
+
14
+ > For a given session key, the most recent valid transcript version that directly preceded the current live version.
15
+
16
+ Use these rules:
17
+
18
+ 1. Treat the `sessionId` currently referenced by `sessions.json` as the **current version**.
19
+ 2. Look for the most recent prior transcript that can be tied to the same session key with high confidence.
20
+ 3. If there is exactly one clear prior candidate, that candidate is the **previous version**.
21
+ 4. If multiple reasonable prior candidates exist, treat "previous version" as **ambiguous** and ask the user before switching.
22
+
23
+ Important clarifications:
24
+
25
+ - "Previous version" is **not** the oldest version.
26
+ - "Previous version" is **not** just the newest `*.jsonl.reset.*` file anywhere in the agent directory.
27
+ - "Previous version" means the **direct predecessor** of the current live version for that specific session key.
28
+ - In simple one-main-session agents, a single reset archive is often sufficient to define the previous version.
29
+ - In complex agents with multiple historical branches, never guess.
30
+
31
+ ## Workflow
32
+
33
+ 1. Identify the target session.
34
+ - Accept any of these as clues:
35
+ - full session key, like `agent:daidai:main`
36
+ - agent name, like `daidai`
37
+ - TUI id, like `tui-...`
38
+ - partial session id
39
+ - distinctive text from the conversation
40
+ - Prefer the bundled discovery script first:
41
+ - `scripts/find_session_candidates.py <query> [--agent <agentId>] [--limit N]`
42
+ - Search `~/.openclaw/agents/*/sessions/sessions.json` and the sibling transcript files until one session is clearly identified.
43
+ - If multiple candidates remain, stop and ask the user to disambiguate.
44
+ - Treat short aliases like `ming` as likely human shorthand for the agent (`mingzi`) if the match is unique; otherwise ask.
45
+
46
+ 2. Inspect the session store before editing.
47
+ - Read the target agent's `sessions.json`.
48
+ - Record:
49
+ - current `sessionId`
50
+ - current `sessionFile`
51
+ - matching reset archives in the same `sessions/` directory
52
+ - Prefer the **most recent previous version** unless the user explicitly asks for an older one.
53
+
54
+ 3. Verify that the rollback target is real.
55
+ - Prefer a reset archive that can be tied to the target session key by explicit text evidence inside the transcript.
56
+ - If explicit evidence is unavailable, use stronger heuristics only when the mapping is unambiguous.
57
+ - A single reset archive in that agent's session directory is usually acceptable as the "previous version" candidate for a simple `agent:<id>:main` test restore.
58
+ - If the mapping is ambiguous, do not guess.
59
+
60
+ 4. Restore both index and transcript file.
61
+ - Prefer the bundled script for the final switch step:
62
+ - `scripts/rollback_session.py --agent <agentId> --key <sessionKey> --target-session-id <oldSessionId> [--archive <path>]`
63
+ - The script updates `sessions.json`, restores `<sessionId>.jsonl` from an archive when needed, and leaves safety backups behind.
64
+ - Keep archive files in place unless the user explicitly asks to delete them.
65
+
66
+ 5. Prevent immediate re-breakage.
67
+ - If the environment still uses aggressive reset rules and the user is likely to test immediately, warn that the next message may mint a fresh session again.
68
+ - If the user asked to make rollback stick, suggest changing `session.reset` to a longer `idle` policy before testing.
69
+
70
+ 6. Reload runtime state when needed.
71
+ - Restart the gateway if the session store is cached in memory or if the user asks for a full refresh.
72
+
73
+ 7. Report exactly what changed.
74
+ - Include:
75
+ - resolved session key
76
+ - old sessionId
77
+ - restored sessionId
78
+ - whether transcript file had to be recreated from `.reset`
79
+ - where the previous live version was backed up
80
+ - whether a gateway restart was performed
81
+
82
+ ## Safety rules
83
+
84
+ - Back up `sessions.json` before editing it.
85
+ - Preserve the current live transcript before switching.
86
+ - The bundled script copies the current `.jsonl` to a timestamped `.manual-switch-backup.*` file so a mistaken switch can be undone without loss.
87
+ - Do not batch-edit unrelated sessions unless the user explicitly asked for that.
88
+ - Do not claim success based only on `sessions.json`; confirm the target `.jsonl` file exists.
89
+ - Do not guess across multiple ambiguous candidates.
90
+
91
+ ## Fast search hints
92
+
93
+ Use these patterns when searching:
94
+
95
+ - key search:
96
+ - `agent:<agentId>:main`
97
+ - `agent:<agentId>:tui-...`
98
+ - transcript archives:
99
+ - `*.jsonl.reset.*`
100
+ - clue text:
101
+ - grep distinctive conversation text across `~/.openclaw/agents/*/sessions/*`
102
+
103
+ ## Typical recovery logic
104
+
105
+ 1. Find session key.
106
+ 2. Find current `sessionId` in `sessions.json`.
107
+ 3. Find the previous archived transcript for that same session.
108
+ 4. Run `scripts/rollback_session.py` to:
109
+ - back up `sessions.json`
110
+ - back up the current live transcript
111
+ - restore the target transcript file if needed
112
+ - rewrite `sessions.json` to point back to the target session
113
+ 5. Restart gateway if required.
114
+
115
+ ## When to stop and ask
116
+
117
+ Stop and ask if:
118
+ - more than one session matches the user's clue
119
+ - the reset archive cannot be tied to the target session confidently
120
+ - the user asks for "the earliest version" and there are multiple historical candidates with no clear chain
@@ -0,0 +1,291 @@
1
+ # Session Rollback Skill - Usage and Design
2
+
3
+ 这份说明面向两类读者:
4
+
5
+ - **人类维护者**:想知道这个 skill 到底怎么工作、边界在哪里
6
+ - **AI/agent**:想知道什么时候该用 skill,什么时候该停下来问用户
7
+
8
+ ---
9
+
10
+ ## 1. 能力边界
11
+
12
+ 这个 skill 解决的是:
13
+
14
+ > 把某个 OpenClaw 会话 key 重新指回某个更早的 transcript 版本。
15
+
16
+ 它不是“修复所有历史问题”的万能工具,而是一个**安全切换器**。
17
+
18
+ 它做的事情包括:
19
+
20
+ 1. 定位目标会话
21
+ 2. 找到要恢复的旧 transcript 版本
22
+ 3. 保留当前 live 版本备份
23
+ 4. 把 session key 改指到旧版本
24
+ 5. 必要时恢复 `<sessionId>.jsonl`
25
+ 6. 必要时提醒重启 gateway
26
+
27
+ ---
28
+
29
+ ## 2. 实际工作分层
30
+
31
+ 这套能力分三层:
32
+
33
+ ### A. Skill(流程层)
34
+ `SKILL.md` 负责:
35
+
36
+ - 定义什么时候触发这个能力
37
+ - 规定恢复流程
38
+ - 规定什么时候可以自动做
39
+ - 规定什么时候必须停下来问用户
40
+
41
+ ### B. Script(执行层)
42
+ `scripts/rollback_session.py` 负责:
43
+
44
+ - 备份 `sessions.json`
45
+ - 备份当前 live transcript
46
+ - 恢复目标 transcript 文件
47
+ - 改写 `sessions.json`
48
+
49
+ ### C. Agent 判断(决策层)
50
+ 模型负责:
51
+
52
+ - 从用户线索里定位目标 session
53
+ - 判断“上一版”是不是唯一明确
54
+ - 判断是否有歧义
55
+ - 决定是否需要重启 gateway
56
+
57
+ 一句话:
58
+
59
+ > **skill 定流程,脚本做切换,agent 负责判断。**
60
+
61
+ ---
62
+
63
+ ## 3. 为什么不能只靠脚本
64
+
65
+ 脚本适合做“已知目标”的安全切换。
66
+
67
+ 但用户经常不会直接给:
68
+
69
+ - 完整 session key
70
+ - 完整旧 session id
71
+ - 完整 archive 路径
72
+
73
+ 用户更可能只给:
74
+
75
+ - agent 名字
76
+ - 一段对话文本
77
+ - 一个 TUI id
78
+ - “切回上一版”
79
+
80
+ 这些都需要 agent 先做定位和判断。
81
+
82
+ 所以:
83
+
84
+ - **纯脚本不够用**
85
+ - **纯 prompt 也不稳定**
86
+ - 最合理的是:**skill + script + agent 判断**
87
+
88
+ ---
89
+
90
+ ## 4. 为什么切换时必须保留当前版本
91
+
92
+ 恢复动作本身也可能出错,比如:
93
+
94
+ - 目标选错了
95
+ - “上一版”理解错了
96
+ - 用户其实想回到更早版本
97
+ - 同一个 agent 下有多个历史候选
98
+
99
+ 所以切换时必须默认保留当前 live 版本。
100
+
101
+ 当前脚本已经这样做:
102
+
103
+ - 备份 `sessions.json`
104
+ - 备份当前 `.jsonl`
105
+
106
+ 这样即使切错,也能无损切回来。
107
+
108
+ 这是这个 skill 的核心安全原则之一。
109
+
110
+ ---
111
+
112
+ ## 5. “上一版” 的正式定义
113
+
114
+ **上一版 / previous version** 指的是:
115
+
116
+ > 对某个 session key 来说,当前 live 版本之前最近一次有效绑定的 transcript 版本。
117
+
118
+ 判断规则:
119
+
120
+ 1. 先把 `sessions.json` 当前指向的 `sessionId` 视为**当前版**。
121
+ 2. 再寻找与该 session key 高置信关联的最近前身 transcript。
122
+ 3. 如果只有一个明确候选,它就是**上一版**。
123
+ 4. 如果存在多个合理候选,则“上一版”视为**有歧义**,必须先向用户确认。
124
+
125
+ 特别说明:
126
+
127
+ - 上一版**不是**最老版本
128
+ - 上一版**不是**目录里最新的任意 `*.jsonl.reset.*`
129
+ - 上一版是**当前版本的直接前身**
130
+ - 对简单单主会话 agent,唯一 reset 档案通常足以定义上一版
131
+ - 对复杂多分支 agent,不能靠猜
132
+
133
+ ## 6. 什么情况下可以自动切
134
+
135
+ 可以自动切的典型情况:
136
+
137
+ ### 情况 A:用户给了明确目标
138
+ 例如:
139
+
140
+ - `session key = agent:main:main`
141
+ - `session id = 50b65539-...`
142
+
143
+ 这种情况可以直接执行。
144
+
145
+ ### 情况 B:只有一个明确的上一版候选
146
+ 例如:
147
+
148
+ - 某个 agent 的 `main` 当前只有一份 `*.jsonl.reset.*`
149
+ - 没有多份歧义历史
150
+
151
+ 这种情况下,“切到上一版”可以直接做。
152
+
153
+ ---
154
+
155
+ ## 6. 什么情况下必须停下来问
156
+
157
+ 必须停下来问的典型情况:
158
+
159
+ ### 情况 A:存在多个历史候选
160
+ 例如:
161
+
162
+ - `agent:main:main` 这种会有多份 reset 档案
163
+ - “上一版”可能有多种理解
164
+
165
+ ### 情况 B:找不到能明确绑定到这个 key 的 archive
166
+ 例如:
167
+
168
+ - reset 文件存在
169
+ - 但无法判断它是否真属于当前目标 session
170
+
171
+ ### 情况 C:用户给的线索太模糊
172
+ 例如:
173
+
174
+ - 只说“帮我恢复 main”
175
+ - 但有多个 main-like 对话
176
+
177
+ 这时不要猜。
178
+
179
+ ---
180
+
181
+ ## 7. 当前脚本的职责
182
+
183
+ `scripts/rollback_session.py` 当前已经支持:
184
+
185
+ - 指定 agent
186
+ - 指定 session key
187
+ - 指定目标 session id
188
+ - 可选指定 archive 路径
189
+ - 自动备份当前 live transcript
190
+ - 自动备份 `sessions.json`
191
+ - 自动恢复目标 `.jsonl`
192
+
193
+ 它当前**不负责**:
194
+
195
+ - 从模糊文本自动搜索候选 session
196
+ - 自动决定哪个才是“上一版”
197
+ - 自动批量处理多个歧义 session
198
+
199
+ 这些仍然属于 agent 决策层。
200
+
201
+ ---
202
+
203
+ ## 8. 推荐使用方式
204
+
205
+ ### 场景 1:明确恢复到指定版本
206
+ 直接调用脚本:
207
+
208
+ ```bash
209
+ python3 skills/yiran-skill-session-rollback/scripts/rollback_session.py \
210
+ --agent main \
211
+ --key agent:main:main \
212
+ --target-session-id 50b65539-0224-4f97-ae29-10e3fda589fc \
213
+ --archive /Users/.../50b65539-0224-4f97-ae29-10e3fda589fc.jsonl.reset....
214
+ ```
215
+
216
+ ### 场景 2:恢复到“上一版”
217
+ 先由 agent:
218
+
219
+ 1. 定位目标 session
220
+ 2. 判断唯一上一版候选
221
+ 3. 再调用脚本
222
+
223
+ ---
224
+
225
+ ## 9. 当前成熟度
226
+
227
+ 目前这个 skill 的成熟度可以定义为:
228
+
229
+ > **半自动、可安全执行的 session rollback 工具**
230
+
231
+ 这意味着:
232
+
233
+ - 单次恢复已经比较稳
234
+ - 有回滚保护
235
+ - 适合人工确认后执行
236
+ - 还不适合无监督批量自动恢复复杂多分支历史
237
+
238
+ ---
239
+
240
+ ## 10. 当前脚本清单
241
+
242
+ ### `scripts/find_session_candidates.py`
243
+ 作用:
244
+ - 输入 agent 名 / 文本 / TUI id / session id 片段
245
+ - 输出候选 session 列表
246
+ - 只做查找,不做修改
247
+
248
+ 示例:
249
+
250
+ ```bash
251
+ python3 skills/yiran-skill-session-rollback/scripts/find_session_candidates.py ming --limit 5
252
+ python3 skills/yiran-skill-session-rollback/scripts/find_session_candidates.py tui-65d670f7 --limit 5
253
+ python3 skills/yiran-skill-session-rollback/scripts/find_session_candidates.py "假设现场出现 5 种常见对话" --agent sun --limit 5
254
+ ```
255
+
256
+ 注意:
257
+ - 它会给出排序和命中原因
258
+ - 如果有多个接近候选,仍然应该先问用户,不要直接切
259
+
260
+ ### `scripts/rollback_session.py`
261
+ 作用:
262
+ - 在目标已明确时,安全切换到旧版本
263
+ - 自动保留当前 live 版本备份
264
+
265
+ ---
266
+
267
+ ## 11. 后续可扩展方向
268
+
269
+ 如果以后还要增强,可以优先做:
270
+
271
+ 1. `find_previous_version.py`
272
+ - 自动给出“上一版”的候选与置信度
273
+
274
+ 2. 批量模式
275
+ - 只处理“唯一明确上一版”的 session
276
+ - 歧义项自动跳过并报告
277
+
278
+ 3. 更强的内容匹配
279
+ - 减少因为 transcript 文本偶然命中带来的噪音候选
280
+
281
+ ---
282
+
283
+ ## 11. 一句话总结
284
+
285
+ 这个 skill 的正确心智模型不是:
286
+
287
+ > “一个神奇脚本,自动把一切恢复好”
288
+
289
+ 而是:
290
+
291
+ > **一个安全恢复工作流:先判断,再切换,并且默认保留当前版本作为回滚点。**
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env python3
2
+ """Find likely OpenClaw session candidates from vague user clues.
3
+
4
+ This script is the discovery companion to `rollback_session.py`.
5
+ It does not modify anything.
6
+
7
+ Use it when the user provides incomplete input such as:
8
+ - an agent name or shorthand
9
+ - a TUI id fragment
10
+ - a partial session id
11
+ - a distinctive piece of conversation text
12
+ - a partial session key
13
+
14
+ The script searches `~/.openclaw/agents/*/sessions/` and returns ranked candidates.
15
+ """
16
+
17
+ import argparse
18
+ import json
19
+ from pathlib import Path
20
+ from typing import Dict, List, Tuple
21
+
22
+
23
+ def load_json(path: Path):
24
+ with path.open('r', encoding='utf-8') as f:
25
+ return json.load(f)
26
+
27
+
28
+ def safe_read_prefix(path: Path, max_chars: int = 12000) -> str:
29
+ try:
30
+ with path.open('r', encoding='utf-8', errors='ignore') as f:
31
+ return f.read(max_chars)
32
+ except Exception:
33
+ return ''
34
+
35
+
36
+ def score_candidate(query: str, agent_id: str, key: str, item: dict, transcript_prefix: str) -> Tuple[int, List[str]]:
37
+ q = query.strip().lower()
38
+ score = 0
39
+ reasons: List[str] = []
40
+
41
+ hay_agent = agent_id.lower()
42
+ hay_key = key.lower()
43
+ hay_sid = str(item.get('sessionId', '')).lower()
44
+ hay_file = str(item.get('sessionFile', '')).lower()
45
+ hay_text = transcript_prefix.lower()
46
+
47
+ if q == hay_agent or q == agent_id:
48
+ score += 100
49
+ reasons.append('exact agent match')
50
+ elif q in hay_agent:
51
+ score += 40
52
+ reasons.append('agent substring match')
53
+
54
+ if q == hay_key:
55
+ score += 120
56
+ reasons.append('exact session key match')
57
+ elif q in hay_key:
58
+ score += 60
59
+ reasons.append('session key substring match')
60
+
61
+ if q and q in hay_sid:
62
+ score += 70
63
+ reasons.append('session id substring match')
64
+
65
+ if q and q in hay_file:
66
+ score += 20
67
+ reasons.append('session file path match')
68
+
69
+ if q and q in hay_text:
70
+ score += 50
71
+ reasons.append('transcript text match')
72
+
73
+ # helpful shorthand heuristics
74
+ if q == 'ming' and agent_id == 'mingzi':
75
+ score += 30
76
+ reasons.append('known shorthand: ming -> mingzi')
77
+
78
+ return score, reasons
79
+
80
+
81
+ def main():
82
+ p = argparse.ArgumentParser(description='Find likely OpenClaw session candidates from vague clues.')
83
+ p.add_argument('query', help='Agent name, session key fragment, session id fragment, tui id, or distinctive text')
84
+ p.add_argument('--limit', type=int, default=10, help='Maximum candidates to print')
85
+ p.add_argument('--agent', help='Restrict search to one agent id')
86
+ p.add_argument('--include-transcript-prefix', action='store_true', help='Include a short transcript preview in output')
87
+ args = p.parse_args()
88
+
89
+ root = Path.home() / '.openclaw' / 'agents'
90
+ if not root.exists():
91
+ raise SystemExit('Agents directory not found')
92
+
93
+ candidates = []
94
+ for agent_dir in sorted(root.iterdir()):
95
+ if not agent_dir.is_dir():
96
+ continue
97
+ agent_id = agent_dir.name
98
+ if args.agent and agent_id != args.agent:
99
+ continue
100
+ sessions_dir = agent_dir / 'sessions'
101
+ sessions_json = sessions_dir / 'sessions.json'
102
+ if not sessions_json.exists():
103
+ continue
104
+ try:
105
+ data = load_json(sessions_json)
106
+ except Exception:
107
+ continue
108
+ for key, item in data.items():
109
+ if not isinstance(item, dict):
110
+ continue
111
+ session_file = Path(item.get('sessionFile', '')) if item.get('sessionFile') else None
112
+ prefix = safe_read_prefix(session_file) if session_file and session_file.exists() else ''
113
+ score, reasons = score_candidate(args.query, agent_id, key, item, prefix)
114
+ if score <= 0:
115
+ continue
116
+ candidates.append({
117
+ 'score': score,
118
+ 'reasons': reasons,
119
+ 'agent': agent_id,
120
+ 'key': key,
121
+ 'sessionId': item.get('sessionId'),
122
+ 'sessionFile': item.get('sessionFile'),
123
+ 'updatedAt': item.get('updatedAt'),
124
+ 'hasSessionFile': bool(session_file and session_file.exists()),
125
+ 'transcriptPreview': prefix[:300] if args.include_transcript_prefix and prefix else None,
126
+ })
127
+
128
+ candidates.sort(key=lambda x: (-x['score'], str(x.get('updatedAt') or 0), x['key']))
129
+ result = {
130
+ 'query': args.query,
131
+ 'count': len(candidates),
132
+ 'candidates': candidates[: args.limit],
133
+ 'note': 'Use the top candidate only when the match is unambiguous. If several close candidates remain, ask the user to confirm.'
134
+ }
135
+ print(json.dumps(result, ensure_ascii=False, indent=2))
136
+
137
+
138
+ if __name__ == '__main__':
139
+ main()
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env python3
2
+ """Safely repoint an OpenClaw session key to an earlier transcript version.
3
+
4
+ Design goals:
5
+ - Make the final switch deterministic once a target sessionId is known.
6
+ - Preserve the current live version before switching so mistakes are reversible.
7
+ - Restore the target plain `.jsonl` file from an archive when needed.
8
+
9
+ What this script does not do:
10
+ - It does not discover the correct target from vague user language.
11
+ - It does not decide which historical candidate is "the right one" when multiple
12
+ archives are plausible.
13
+
14
+ Expected operating model:
15
+ - An agent or human identifies the target session key and target session id first.
16
+ - This script performs the safe on-disk switch.
17
+ """
18
+
19
+ import argparse
20
+ import json
21
+ import shutil
22
+ import sys
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Optional, Tuple
26
+
27
+
28
+ def now_tag() -> str:
29
+ return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H-%M-%S.%fZ')
30
+
31
+
32
+ def fail(msg: str, code: int = 1):
33
+ print(msg, file=sys.stderr)
34
+ raise SystemExit(code)
35
+
36
+
37
+ def load_json(path: Path):
38
+ with path.open('r', encoding='utf-8') as f:
39
+ return json.load(f)
40
+
41
+
42
+ def save_json(path: Path, data):
43
+ with path.open('w', encoding='utf-8') as f:
44
+ json.dump(data, f, ensure_ascii=False, indent=2)
45
+ f.write('\n')
46
+
47
+
48
+ def backup_file(path: Path, suffix: str) -> Path:
49
+ """Create a timestamped backup next to the original file.
50
+
51
+ This is the core safety feature that makes mistaken switches reversible.
52
+ """
53
+ tag = now_tag()
54
+ backup = path.with_name(f"{path.name}.{suffix}.{tag}")
55
+ shutil.copy2(path, backup)
56
+ return backup
57
+
58
+
59
+ def ensure_target_plain_file(sessions_dir: Path, target_session_id: str, archive_path: Optional[Path]) -> Tuple[Path, Optional[Path]]:
60
+ """Ensure the target `<sessionId>.jsonl` exists.
61
+
62
+ OpenClaw often leaves historical transcripts as `*.jsonl.reset.<timestamp>`.
63
+ A rollback is not complete until the plain `.jsonl` file exists again.
64
+ """
65
+ plain = sessions_dir / f'{target_session_id}.jsonl'
66
+ restored_from = None
67
+ if plain.exists():
68
+ return plain, restored_from
69
+
70
+ if archive_path and archive_path.exists():
71
+ shutil.copy2(archive_path, plain)
72
+ restored_from = archive_path
73
+ return plain, restored_from
74
+
75
+ # Fallback: auto-find matching archive for target sid
76
+ matches = sorted(sessions_dir.glob(f'{target_session_id}.jsonl.reset.*'))
77
+ if len(matches) == 1:
78
+ shutil.copy2(matches[0], plain)
79
+ restored_from = matches[0]
80
+ return plain, restored_from
81
+ if len(matches) > 1:
82
+ fail(f'Ambiguous target archive for {target_session_id}; pass --archive explicitly.')
83
+
84
+ fail(f'Target transcript missing: neither {plain.name} nor a usable archive was found.')
85
+
86
+
87
+ def main():
88
+ p = argparse.ArgumentParser(description='Repoint an OpenClaw session key to a previous transcript version safely.')
89
+ p.add_argument('--agent', required=True, help='Agent id, e.g. daidai')
90
+ p.add_argument('--key', required=True, help='Full session key, e.g. agent:daidai:main')
91
+ p.add_argument('--target-session-id', required=True, help='Session id to restore to')
92
+ p.add_argument('--archive', help='Optional explicit archive path to restore from')
93
+ p.add_argument('--allow-missing-current-file', action='store_true', help='Do not fail if current sessionFile is missing')
94
+ args = p.parse_args()
95
+
96
+ sessions_dir = Path.home() / '.openclaw' / 'agents' / args.agent / 'sessions'
97
+ sessions_json = sessions_dir / 'sessions.json'
98
+ if not sessions_json.exists():
99
+ fail(f'sessions.json not found: {sessions_json}')
100
+
101
+ data = load_json(sessions_json)
102
+ if args.key not in data or not isinstance(data[args.key], dict):
103
+ fail(f'Session key not found: {args.key}')
104
+
105
+ item = data[args.key]
106
+ current_session_id = item.get('sessionId')
107
+ current_session_file = Path(item.get('sessionFile', '')) if item.get('sessionFile') else None
108
+ if not current_session_id:
109
+ fail(f'Current sessionId missing for {args.key}')
110
+ if not current_session_file:
111
+ fail(f'Current sessionFile missing for {args.key}')
112
+ if not current_session_file.exists() and not args.allow_missing_current_file:
113
+ fail(f'Current sessionFile does not exist: {current_session_file}')
114
+
115
+ archive_path = Path(args.archive).expanduser() if args.archive else None
116
+ if archive_path and not archive_path.exists():
117
+ fail(f'Archive path does not exist: {archive_path}')
118
+
119
+ # Safety backups: always preserve the current state before switching.
120
+ sessions_json_backup = backup_file(sessions_json, 'bak.manual-switch')
121
+ current_file_backup = None
122
+ if current_session_file.exists():
123
+ current_file_backup = backup_file(current_session_file, 'manual-switch-backup')
124
+
125
+ target_plain, restored_from = ensure_target_plain_file(sessions_dir, args.target_session_id, archive_path)
126
+
127
+ item['sessionId'] = args.target_session_id
128
+ item['sessionFile'] = str(target_plain)
129
+ item['updatedAt'] = int(target_plain.stat().st_mtime * 1000)
130
+ save_json(sessions_json, data)
131
+
132
+ result = {
133
+ 'ok': True,
134
+ 'agent': args.agent,
135
+ 'key': args.key,
136
+ 'fromSessionId': current_session_id,
137
+ 'fromSessionFile': str(current_session_file),
138
+ 'fromSessionFileBackup': str(current_file_backup) if current_file_backup else None,
139
+ 'sessionsJsonBackup': str(sessions_json_backup),
140
+ 'toSessionId': args.target_session_id,
141
+ 'toSessionFile': str(target_plain),
142
+ 'restoredTargetFromArchive': str(restored_from) if restored_from else None,
143
+ 'note': 'Gateway restart may still be needed if runtime has cached session state.'
144
+ }
145
+ print(json.dumps(result, ensure_ascii=False, indent=2))
146
+
147
+
148
+ if __name__ == '__main__':
149
+ main()