session-tape 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,13 @@
1
+ """迁移录音机:把 A 的历史搬进 B。
2
+
3
+ 三个概念要分清(混起来就会写出"跨产品打分支"这种不存在的东西):
4
+
5
+ - **读**:从源产品读出历史 → 规范化成 `Msg`(只有角色、文本、时间);
6
+ - **渲染**:把 `Msg` 序列按目标产品的格式写出来(每个目标一个 renderer);
7
+ - **验收**:一律用**目标产品自己**的解析器/列表/续跑,不用我们自己的断言自证。
8
+
9
+ 源产品的读取复用 `session-fork-core` 的适配器(六个产品都是真机验过的),
10
+ 本包不重复实现读取,也不复制它的代码。
11
+ """
12
+
13
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
session_tape/_deps.py ADDED
@@ -0,0 +1,51 @@
1
+ """依赖兜底:`session-fork-core` 是读侧与部分写侧的依赖。
2
+
3
+ 两种到场方式都要支持:
4
+ · 已 `pip install`(正常安装路径);
5
+ · 开发期用环境变量 `FORK_CORE_PATH` 指向本地检出(不必先装)。
6
+
7
+ 统一在这里处理,避免每个模块各写一遍 `sys.path` 操作——那样一旦漏一处,
8
+ 表现是"某个目标突然说找不到模块",很难查。
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+
15
+
16
+ class MissingDependency(SystemExit):
17
+ """缺依赖时抛这个:带可执行的修复指令,而不是一段栈回溯。"""
18
+
19
+ def __init__(self) -> None:
20
+ super().__init__(
21
+ "✗ 需要 session-fork-core(读产品会话的适配器层):\n"
22
+ ' pip install "git+https://github.com/yamingmou/session-fork-core.git"\n'
23
+ " 或设置 FORK_CORE_PATH=<本地检出路径> 后再跑"
24
+ )
25
+
26
+
27
+ def ensure_fork_core():
28
+ """返回 `fork_core` 模块;拿不到就抛 MissingDependency。"""
29
+ try:
30
+ import fork_core
31
+ return fork_core
32
+ except ImportError:
33
+ pass
34
+ path = os.environ.get("FORK_CORE_PATH")
35
+ if path and os.path.isdir(path):
36
+ if path not in sys.path:
37
+ sys.path.insert(0, path)
38
+ try:
39
+ import fork_core
40
+ return fork_core
41
+ except ImportError:
42
+ pass
43
+ raise MissingDependency()
44
+
45
+
46
+ def has_fork_core() -> bool:
47
+ try:
48
+ ensure_fork_core()
49
+ return True
50
+ except SystemExit:
51
+ return False
session_tape/cli.py ADDED
@@ -0,0 +1,222 @@
1
+ """命令行:`session-tape --from <产品> --session <引用> --to <产品> --out <位置>`。
2
+
3
+ 刻意做成一个**独立入口**(不是给 session-fork 加个参数):
4
+ 它的语义是"搬到另一个产品",与"同一产品内打分支"的失败模式完全不同,
5
+ 混在一个命令里会让帮助文本和风险描述都变形。
6
+
7
+ 两个目标的"落地"不一样,所以接口分开:
8
+ · **pi**:只写一个会话文件 —— `--out` 给目录或 `.jsonl` 路径;
9
+ · **codex**:写 rollout **还要登记进产品库**,否则文件在但列表里看不见
10
+ ⇒ `--install-codex-home <CODEX_HOME>` 指到产品主目录(缺省只产文件、不登记)。
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import os
16
+ import sys
17
+ import uuid
18
+
19
+ from . import __version__, noise, render, source
20
+
21
+
22
+ def _pi_out(out: str) -> str:
23
+ """pi 的 `--out`:目录就按它的命名惯例落一个文件;`.jsonl` 就直接用。"""
24
+ if out.endswith(".jsonl"):
25
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
26
+ return out
27
+ os.makedirs(out, exist_ok=True)
28
+ import time
29
+ return os.path.join(out, f"{time.strftime('%Y-%m-%dT%H-%M-%S')}_{uuid.uuid4()}.jsonl")
30
+
31
+
32
+ def main(argv: list[str] | None = None) -> int:
33
+ argv = list(sys.argv[1:] if argv is None else argv)
34
+
35
+ # 子命令分派(易用性入口;复杂参数一个没删)
36
+ if argv and argv[0] == "list":
37
+ from .ui import cmd_list
38
+ return cmd_list(argv[1:])
39
+ if argv and argv[0] == "demo":
40
+ from .ui import cmd_demo
41
+ return cmd_demo()
42
+ if not argv:
43
+ from .ui import wizard
44
+ try:
45
+ return wizard()
46
+ except (KeyboardInterrupt, EOFError):
47
+ print("\n已取消。")
48
+ return 1
49
+
50
+ ap = argparse.ArgumentParser(
51
+ prog="session-tape",
52
+ description="把一个产品的会话历史搬到另一个产品里继续(只搬文本历史,单向)",
53
+ epilog="不知道从哪下手?直接敲 session-tape(向导),或 session-tape list / session-tape demo",
54
+ )
55
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
56
+ ap.add_argument("--from", dest="src", default="workbuddy",
57
+ help="源产品(workbuddy / claude-code / codex / hermes / pi / openclaw)")
58
+ ap.add_argument("--session", help='源会话引用(id,或 "current");与 --session-file 二选一')
59
+ ap.add_argument("--session-file", help="直接指定转录文件(用于 id 有歧义的产品,如 Codex 的线程级 id)")
60
+ ap.add_argument("--to", dest="dst", default="pi", help="目标产品(pi / codex / workbuddy / claude-code / hermes / openclaw)")
61
+ ap.add_argument("--out", help="输出位置:目录(按目标惯例命名)或 .jsonl 路径")
62
+ ap.add_argument("--install-codex-home", help="把会话登记进这个 CODEX_HOME(让 codex 列表里看得见)")
63
+ ap.add_argument("--install-wb-home", help="把会话登记进这个 WorkBuddy home(含 workbuddy.db 与 projects/)")
64
+ ap.add_argument("--project", default="", help="workbuddy 目标:写进哪个项目目录(缺省 migrated)")
65
+ ap.add_argument("--fill", help="官方建壳、我们灌内容:把历史写进这条已存在的 codex 会话(id 保持不变)")
66
+ ap.add_argument("--cwd", default="", help="写进目标会话的 cwd(缺省用源的 cwd)")
67
+ ap.add_argument("--name", default="", help="分支/会话标题(写进目标的标题字段)")
68
+ ap.add_argument("--limit", type=int, default=0, help="只搬最后 N 条(0=全部)")
69
+ ap.add_argument("--dry-run", action="store_true", help="只统计,不落盘")
70
+ args = ap.parse_args(argv)
71
+
72
+ if bool(args.session) == bool(args.session_file):
73
+ ap.error("--session 与 --session-file 必须且只能给一个")
74
+ if args.dst == "codex" and not (args.out or args.install_codex_home or args.fill):
75
+ ap.error("codex 目标需要 --out(产文件)或 --install-codex-home(登记进产品)")
76
+ if args.dst in ("claude-code", "claude") and not args.out:
77
+ ap.error("claude-code 目标需要 --out(指向 ~/.claude 或它的替身目录)")
78
+ if args.dst == "workbuddy" and not (args.out or args.install_wb_home):
79
+ ap.error("workbuddy 目标需要 --out(产文件)或 --install-wb-home(登记进产品)")
80
+ if args.dst == "pi" and not args.out:
81
+ ap.error("pi 目标需要 --out")
82
+
83
+ src = source.read_file(args.src, args.session_file) if args.session_file \
84
+ else source.read(args.src, args.session)
85
+
86
+ raw_n = len(src)
87
+ stats: dict[str, int] = {}
88
+ msgs = noise.clean(src.msgs, stats)
89
+ if args.limit and len(msgs) > args.limit:
90
+ # 截取必须落在"人说的话"上:往前扩到最近的 user 起点(不是往后丢)。
91
+ # 实测教训:往后丢会切出"纯 assistant"的会话——既不像一次对话,产品也可能显示得很怪。
92
+ start = len(msgs) - args.limit
93
+ while start > 0 and msgs[start].role != "user":
94
+ start -= 1
95
+ msgs = msgs[start:]
96
+
97
+ print(f"源 : {src.product} / {src.session_id or '(按文件)'}")
98
+ print(f"读到 : {raw_n} 条消息")
99
+ for k, v in stats.items():
100
+ print(f" 丢掉 : {k} × {v}")
101
+ if not any(m.role == "user" for m in msgs):
102
+ raise SystemExit("✗ 截取后没有任何'人说的话'——请把 --limit 调大,或不加")
103
+ print(f"待搬 : {len(msgs)} 条(user {sum(1 for m in msgs if m.role == 'user')} / "
104
+ f"assistant {sum(1 for m in msgs if m.role == 'assistant')})")
105
+
106
+ if args.dry_run:
107
+ print("(--dry-run:未落盘)")
108
+ return 0
109
+
110
+ cwd = args.cwd or src.cwd or os.getcwd()
111
+ # pi 实测会拒绝打开"cwd 不存在"的会话(Stored session working directory does not exist)
112
+ # ⇒ 源里记的 cwd 在本机不存在时,退回当前目录并明说,不要让用户面对一句产品报错。
113
+ if not os.path.isdir(cwd):
114
+ if args.cwd:
115
+ # 用户**明确指定**的目录:建出来(他说要放那儿,就放那儿)
116
+ os.makedirs(cwd, exist_ok=True)
117
+ print(f"注意 : --cwd 指定的目录不存在,已创建 {cwd}")
118
+ else:
119
+ # 从源里**推导**出来的目录:本机可能没有(源在另一台机器/另一个路径)
120
+ fallback = os.getcwd()
121
+ print(f"注意 : 源记录的 cwd 在本机不存在({cwd})⇒ 改用当前目录 {fallback}")
122
+ cwd = fallback
123
+
124
+ title = args.name or "(迁移)"
125
+ mod = render.module(args.dst)
126
+
127
+ if args.dst == "pi":
128
+ text = mod.render(msgs, cwd, title=title)
129
+ path = _pi_out(args.out)
130
+ with open(path, "w", encoding="utf-8") as f:
131
+ f.write(text)
132
+ print(f"写到 : {path}")
133
+ print(f"产物 : {text.count(chr(10))} 行,{len(text.encode('utf-8'))} 字节")
134
+ print("验收 : lab/verify.mjs <文件> / scripts/verify_gate_pi.py --pi <pi> --session <文件>")
135
+ return 0
136
+
137
+ # ---- hermes(库型:行写进 sessions + messages)----
138
+ if args.dst == "hermes":
139
+ if not args.out:
140
+ ap.error("hermes 目标需要 --out 指向 state.db(建议先复制一份再试)")
141
+ sid = "20261124_" + uuid.uuid4().hex[:12]
142
+ rows = mod.render(msgs, sid)
143
+ ref = mod.write(rows, args.out, sid)
144
+ print(f"会话 id : {sid}")
145
+ print(f"写入 : {ref}")
146
+ print(f"产物 : {len(rows)} 条消息(走适配器的事务链路)")
147
+ return 0
148
+
149
+ # ---- openclaw(与 pi 同形)----
150
+ if args.dst == "openclaw":
151
+ if not args.out:
152
+ ap.error("openclaw 目标需要 --out 指向 ~/.openclaw 或它的替身目录")
153
+ sid = str(uuid.uuid4())
154
+ lines = mod.render(msgs, cwd, title=title, session_id=sid)
155
+ path = mod.write(lines, args.out, sid)
156
+ print(f"会话 id : {sid}")
157
+ print(f"写到 : {path}")
158
+ print(f"产物 : {len(lines)} 行(1 header + {len(lines) - 1} 条消息)")
159
+ print("注意 : 本机无 OpenClaw,这一家只到 L1(我方读器往返),未做真机验收")
160
+ return 0
161
+
162
+ # ---- claude-code ----
163
+ if args.dst in ("claude-code", "claude"):
164
+ sid = str(uuid.uuid4())
165
+ lines = mod.render(msgs, cwd, title=title, session_id=sid)
166
+ path = mod.write(lines, args.out or os.path.expanduser("~/.claude"), sid, cwd=cwd)
167
+ print(f"会话 id : {sid}")
168
+ print(f"写到 : {path}")
169
+ print(f"产物 : {len(lines)} 条消息")
170
+ print("验收 : 用 Claude Code 的 /resume 看这条;或在装了 Claude 的机器上跑 selfcheck")
171
+ return 0
172
+
173
+ # ---- workbuddy ----
174
+ if args.dst == "workbuddy":
175
+ sid = str(uuid.uuid4())
176
+ home = os.path.expanduser(args.install_wb_home) if args.install_wb_home else ""
177
+ lines = mod.render(msgs, cwd, title=title, session_id=sid)
178
+ base = home or os.path.expanduser(args.out)
179
+ path = mod.write(lines, base, sid, project=args.project, cwd=cwd)
180
+ print(f"会话 id : {sid}")
181
+ print(f"写到 : {path}")
182
+ if home:
183
+ tpl = mod.register(path, sid, title, home=home, cwd=cwd)
184
+ print(f"已登记 : sessions 表新增一行(模板取自会话 {str(tpl)[:8]}…)")
185
+ else:
186
+ print("未登记 : 只产了文件。要让产品看见,加 --install-wb-home <目录>")
187
+ return 0
188
+
189
+ # ---- codex:官方建壳、我们灌内容 ----
190
+ if args.fill:
191
+ if args.dst != "codex":
192
+ ap.error("--fill 目前只对 codex 目标有效")
193
+ home = args.install_codex_home or ""
194
+ path, backup = mod.fill(msgs, args.fill, codex_home=home, title=title)
195
+ print(f"灌入 : {path}")
196
+ print(f"备份 : {backup}")
197
+ print(f"投影归零: 已设为 (0,0),产品会从第 0 字节重新解析")
198
+ print("会话 id 未变,容器元数据(cwd/provider/账号/系统提示)未动。")
199
+ return 0
200
+
201
+ # ---- codex:自建容器 ----
202
+ thread_id = str(uuid.uuid4())
203
+ lines = mod.render(msgs, cwd, title=title, thread_id=thread_id)
204
+ home = os.path.expanduser(args.install_codex_home) if args.install_codex_home else os.path.expanduser(args.out)
205
+ path = mod.write(lines, home, thread_id)
206
+ print(f"会话 id : {thread_id}")
207
+ print(f"写到 : {path}")
208
+
209
+ if args.install_codex_home:
210
+ first_user = next((m.text for m in msgs if m.role == "user"), "")
211
+ tpl = mod.register(path, thread_id, title,
212
+ codex_home=args.install_codex_home,
213
+ first_user_message=first_user)
214
+ print(f"已登记 : threads 表新增一行(模板取自会话 {tpl[:8]}…)")
215
+ print("现在它会出现在 codex 的会话列表里;点开/续跑由你验。")
216
+ else:
217
+ print("未登记 : 只产了文件。要让 codex 看见,加 --install-codex-home <CODEX_HOME>")
218
+ return 0
219
+
220
+
221
+ if __name__ == "__main__":
222
+ sys.exit(main())
session_tape/model.py ADDED
@@ -0,0 +1,33 @@
1
+ """规范化模型:迁移只认三样东西 —— 角色、文本、时间。
2
+
3
+ 为什么只有这三样:
4
+ 六种产品的存储格式各不相同(JSONL / SQLite / LevelDB),但**人说的话和模型的回答**
5
+ 在每一种里都存在,而且顺序一致。工具调用、思考过程、附件则各家互不相通——
6
+ 搬过去也没有对应物,所以**不进模型**。
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Msg:
15
+ """一条可搬的消息。`role` 只会是 "user" 或 "assistant"。"""
16
+
17
+ role: str
18
+ text: str
19
+ ts_ms: int = 0 # 毫秒时间戳;源里没有就留 0,渲染时按顺序补
20
+
21
+
22
+ @dataclass
23
+ class Source:
24
+ """一次读源的结果:消息序列 + 一点随行信息。"""
25
+
26
+ msgs: list[Msg]
27
+ product: str = "" # 源产品名(workbuddy / claude-code / ...)
28
+ session_id: str = ""
29
+ cwd: str = ""
30
+ dropped: dict[str, int] = field(default_factory=dict) # 各原因丢了多少条(给用户看)
31
+
32
+ def __len__(self) -> int:
33
+ return len(self.msgs)
session_tape/noise.py ADDED
@@ -0,0 +1,83 @@
1
+ """噪声过滤:搬之前先把"不是对话"的东西拿掉。
2
+
3
+ 三类噪声(都是真数据里撞出来的,不是假想):
4
+
5
+ 1. **占位文本**:用户中断时,产品会写一条 `Interrupted by user` / `[Request interrupted by user]`
6
+ 当作 assistant 的内容。直接搬过去,新产品的模型会以为"上一条回答就是这个"。
7
+ 2. **平台包裹**:源产品把用户输入包在 `<system-reminder>…</system-reminder>` 里,
8
+ 真正的指令在 `<user_query>…</user_query>` 内部。整段搬过去等于把 A 的内部机制带进 B。
9
+ 3. **重复投递**:同一句话在源里出现两次(用户重发/重试)——照搬就是两条一样的问句。
10
+
11
+ 原则:**宁可少搬一条,不要搬错一条**。丢了多少条、为什么,要能被打印出来核对。
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+
17
+ # 整条等于这些内容 ⇒ 不是对话内容
18
+ _PLACEHOLDER_EXACT = {
19
+ "Interrupted by user",
20
+ "[Request interrupted by user]",
21
+ "[Request interrupted by user for tool use]",
22
+ "No response requested.",
23
+ "Continue",
24
+ }
25
+
26
+ # 挂在开头且整条就是它的形态。
27
+ # ⚠️ 首版写成 `interrupted by user[^\]]*`,把「Interrupted by user 之后我怎么恢复?」
28
+ # 这种真问题也吞了(负向断言抓到的)。占位只有这几种确切形态,多一个字都不算。
29
+ _PLACEHOLDER_RE = re.compile(
30
+ r"^\s*\[?\s*(?:request\s+)?interrupted\s+by\s+user(?:\s+for\s+tool\s+use)?\s*\]?\s*$",
31
+ re.IGNORECASE,
32
+ )
33
+
34
+ # 平台包裹:整块 <tag ...>…</tag>
35
+ _WRAPPER_RE = re.compile(r"^\s*<([a-zA-Z][\w-]*)(?:\s[^>]*)?>.*?</\1>\s*$", re.DOTALL)
36
+ _USER_QUERY_RE = re.compile(r"<user_query>(.*?)</user_query>", re.DOTALL)
37
+
38
+
39
+ def strip_wrappers(text: str) -> str:
40
+ """剥掉平台包裹,只留人写的那句。有 `<user_query>` 就取它内部的。"""
41
+ m = _USER_QUERY_RE.search(text)
42
+ if m:
43
+ return m.group(1).strip()
44
+ out = text.strip()
45
+ # 可能套了多层(外层 system-reminder 里再包一层),反复剥
46
+ for _ in range(4):
47
+ m = _WRAPPER_RE.match(out)
48
+ if not m:
49
+ break
50
+ out = (m.group(0)[m.group(0).find(">") + 1: m.group(0).rfind("<")]).strip()
51
+ return out
52
+
53
+
54
+ def is_placeholder(text: str) -> bool:
55
+ t = text.strip()
56
+ if not t:
57
+ return True
58
+ if t in _PLACEHOLDER_EXACT:
59
+ return True
60
+ return bool(_PLACEHOLDER_RE.match(t))
61
+
62
+
63
+ def clean(msgs, stats: dict[str, int] | None = None):
64
+ """按顺序过滤 + 合并重复。
65
+
66
+ 返回新的 `Msg` 列表;`stats` 里累加各种丢弃原因的条数(便于打印核对)。
67
+ """
68
+ from .model import Msg
69
+
70
+ stats = stats if stats is not None else {}
71
+ out: list[Msg] = []
72
+ for m in msgs:
73
+ text = strip_wrappers(m.text) if m.role == "user" else m.text.strip()
74
+ if not text or is_placeholder(text):
75
+ key = "占位/中断文本"
76
+ stats[key] = stats.get(key, 0) + 1
77
+ continue
78
+ if out and out[-1].role == m.role and out[-1].text.strip() == text:
79
+ key = "重复投递(相邻同文)"
80
+ stats[key] = stats.get(key, 0) + 1
81
+ continue
82
+ out.append(Msg(role=m.role, text=text, ts_ms=m.ts_ms))
83
+ return out
@@ -0,0 +1,34 @@
1
+ """目标产品的渲染器。一个目标一个文件。
2
+
3
+ 每个目标的接口约定(缺一不可,因为不同产品的"落地"差别很大):
4
+ `render(msgs, cwd, **kw)` → 中间产物(文件文本 / 行序列)
5
+ `write(payload, out, **kw)` → 落盘,返回路径
6
+ `register(path, **kw)` → 可选:让产品**认识**这条会话(DB 型产品必须,文件型不需要)
7
+
8
+ 为什么不让渲染器直接写盘:验收要能分开做——
9
+ 先看"产物长什么样"(纯函数、可测),再看"产品认不认"(必须真机)。
10
+
11
+ 共同点(不满足产品就读不了):
12
+ ① 容器头部合法(会话 id / 版本 / cwd / 时间);
13
+ ② 每条消息用**目标产品自己的 id 形态**,连成它认识的结构(链或树);
14
+ ③ 时间戳单调。
15
+ 差异点(唯一不能靠"复制前缀"解决):**id 链必须重造**。
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from . import claude, codex, hermes, openclaw, pi, workbuddy
20
+
21
+ TARGETS = {
22
+ "pi": pi,
23
+ "codex": codex,
24
+ "workbuddy": workbuddy,
25
+ "claude-code": claude, "claude": claude,
26
+ "hermes": hermes,
27
+ "openclaw": openclaw,
28
+ }
29
+
30
+
31
+ def module(to: str):
32
+ if to not in TARGETS:
33
+ raise SystemExit(f"✗ 还不支持目标 {to};目前支持:{', '.join(sorted(set(TARGETS)))}")
34
+ return TARGETS[to]
@@ -0,0 +1,102 @@
1
+ """目标:Claude Code(`~/.claude/projects/<转义 cwd>/<sessionId>.jsonl`)。
2
+
3
+ 行形状取自**真机夹具**(session-fork-core 的 claude 适配器测试里那份,不是文档推演):
4
+
5
+ ```json
6
+ {"type":"user|assistant", "uuid":<uuid4>, "parentUuid":<上一条 uuid|null>,
7
+ "sessionId":<会话 id>, "cwd":<工作目录>, "timestamp":<ISO>,
8
+ "message":{"role":..., "content":[{"type":"text","text":...}]}}
9
+ ```
10
+
11
+ 与 pi / codex 的两处关键差别:
12
+ · 结构是**树**(`parentUuid`),不是自增序号;线性历史就是一条链;
13
+ · 会话文件放在**按 cwd 转义出来的目录**里(`/Users/a/b` → `-Users-a-b`)。
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import uuid
20
+ from datetime import datetime, timezone
21
+
22
+
23
+ def _iso(ms: int) -> str:
24
+ return datetime.fromtimestamp(ms / 1000, timezone.utc) \
25
+ .isoformat(timespec="milliseconds").replace("+00:00", "Z")
26
+
27
+
28
+ def project_dir_name(cwd: str) -> str:
29
+ """产品的目录转义:`/` 和 `.` 都变 `-`(`/Users/a/b` → `-Users-a-b`)。"""
30
+ return cwd.replace("/", "-").replace(".", "-") or "-"
31
+
32
+
33
+ def render(msgs, cwd: str, *, title: str = "", session_id: str | None = None) -> list[dict]:
34
+ if not msgs:
35
+ raise SystemExit("✗ 没有可搬的消息(源里全是占位/工具内容?)")
36
+
37
+ sid = session_id or str(uuid.uuid4())
38
+ stamps, prev = [], int(msgs[0].ts_ms or 0) or int(datetime.now().timestamp() * 1000)
39
+ for m in msgs:
40
+ ts = int(m.ts_ms or (prev + 1000 if prev else 0))
41
+ if ts <= prev:
42
+ ts = prev + 1000
43
+ stamps.append(ts)
44
+ prev = ts
45
+
46
+ lines, parent = [], None
47
+ for m, ts in zip(msgs, stamps):
48
+ mid = str(uuid.uuid4())
49
+ lines.append({
50
+ "type": m.role,
51
+ "uuid": mid,
52
+ "parentUuid": parent,
53
+ "sessionId": sid,
54
+ "cwd": cwd,
55
+ "timestamp": _iso(ts),
56
+ "message": {"role": m.role, "content": [{"type": "text", "text": m.text}]},
57
+ })
58
+ parent = mid
59
+ return lines
60
+
61
+
62
+ def write(lines: list[dict], out: str, session_id: str, *, cwd: str = "") -> str:
63
+ """落到 `projects/<转义 cwd>/<sessionId>.jsonl`;`out` 是 `~/.claude` 这一层。"""
64
+ base = os.path.join(os.path.expanduser(out), "projects",
65
+ project_dir_name(cwd or "/"))
66
+ os.makedirs(base, exist_ok=True)
67
+ path = os.path.join(base, f"{session_id}.jsonl")
68
+ with open(path, "w", encoding="utf-8") as f:
69
+ for o in lines:
70
+ f.write(json.dumps(o, ensure_ascii=False) + "\n")
71
+ return path
72
+
73
+
74
+ def register(path: str, session_id: str, title: str, *, claude_dir: str = "",
75
+ template_id: str | None = None) -> str:
76
+ """登记(`~/.claude` 里另有历史索引时由适配器补)。
77
+
78
+ ⚠️ 本机没有装 Claude Code,**登记这条路径没有真机验过**,只是复用适配器的实现;
79
+ 没有现成会话当模板时会明确失败,而不是伪造。
80
+ """
81
+ try:
82
+ from .._deps import ensure_fork_core
83
+ ensure_fork_core()
84
+ from fork_core.adapter_claude_code import ClaudeCodeAdapter # type: ignore
85
+ from fork_core.models import SessionMeta # type: ignore
86
+ except Exception as e: # pragma: no cover
87
+ raise SystemExit(f"✗ 登记需要 session-fork-core:{e}")
88
+
89
+ ad = ClaudeCodeAdapter()
90
+ tid = template_id
91
+ if not tid:
92
+ base = os.path.join(os.path.expanduser(claude_dir or "~/.claude"), "projects")
93
+ found = []
94
+ for root, _dirs, files in os.walk(base):
95
+ found += [f[:-6] for f in files if f.endswith(".jsonl")]
96
+ if len(found) > 5:
97
+ break
98
+ if not found:
99
+ raise SystemExit("✗ 目标 ~/.claude 里没有现成会话可当模板——先用 Claude Code 跑一轮")
100
+ tid = found[0]
101
+ ad.register_branch(SessionMeta(id=tid, title=""), session_id, path, title, parent_id=tid)
102
+ return tid