Repository navigation
Expand file tree
/
Copy pathsync.py
More file actions
2647 lines (2430 loc) · 152 KB
/
Copy pathsync.py
File metadata and controls
2647 lines (2430 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""跨 Agent 会话同步 CLI:codex / hermes / dsh / zcode / workbuddy / claude / opencode → dsh + Markdown 归档。
zcode 只作为读取源(只出不进:向 zcode 写入会话已移除——双端同对话易混乱,
且活库写入验证成本高;历史实现保留在 agentsync/zcodewrite.py 供参考)。
用法:
python sync.py status # 五源概览(含各源上次同步时间)
python sync.py to-dsh [--source ...] [--scope inc|7d|30d|Nd|all] [--apply] ...
# 人在回路两道确认:交互终端未指定时弹菜单(来源区 → 数据量);
# 非交互(agent/脚本)必须显式给 --source/--scope(参数即确认),缺失拒绝执行
python sync.py pull [--source ...] [--scope ...] # 各源 → 规范库 ~/.session-sync(安全,免退出)
python sync.py push --target codex [--source] [--scope] [--apply] # 规范库 → 目标(断点续推)
python sync.py attach-dsh [--apply] # 挂工作区分组(需退出 dsh)
python sync.py archive [--source all] [--apply]
python sync.py verify [--root PATH]
所有写操作默认 dry-run,加 --apply 才落盘。
"""
from __future__ import annotations
import argparse
import json
import os
import sqlite3
import sys
import time
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from agentsync import archive as archive_mod
from agentsync import confirm, dshwrite, paths, readers, syncstate
ALL_SOURCES = ["zcode", "hermes", "dsh", "codex", "workbuddy", "workbuddy-ai", "kilo", "claude", "opencode", "qoder", "openclaw",
"cursor", "trae", "mimo", "kimi", "minimax", "grok", "copilot", "gemini", "cline", "pi"]
def _fmt_ts(ms: int) -> str:
if not ms:
return "-"
return datetime.fromtimestamp(ms / 1000).strftime("%m-%d %H:%M")
def load_sources(which: list[str], p: paths.StorePaths, include_playground: bool = False):
return readers.load_sources(which, p, include_playground=include_playground)
def _filter(sessions: list, args) -> list:
out = sessions
if args.session:
wanted = {w.strip() for w in args.session.split(",") if w.strip()}
out = [s for s in out if s.source_id in wanted or any(w in s.source_id for w in wanted)]
if args.cwd:
out = [s for s in out if s.cwd and args.cwd.lower() in s.cwd.lower()]
if args.since:
cutoff = (datetime.now().timestamp() - args.since * 86400) * 1000
out = [s for s in out if s.created_at >= cutoff]
if args.limit:
out = out[: args.limit]
return out
def _parse_sources(raw: str, defaults: list[str]) -> list[str]:
raw = (raw or "").strip()
if raw in ("all", "*", "全部"):
return list(defaults)
which = [s.strip() for s in raw.split(",") if s.strip()]
for s in which:
if s not in ALL_SOURCES:
sys.exit(f"未知来源:{s}(可选 {ALL_SOURCES})")
return which or defaults
def _resolve_sources(args, include_dsh: bool = False) -> list[str]:
"""确认 1/2 · 来源区:显式 --source 即确认;交互终端弹菜单;非交互缺参拒绝。
非 dsh 目标默认全集含 dsh 自身(dsh 会话反向流出);dsh 目标不含 dsh。
"""
defaults = list(confirm.SYNC_SOURCES) + (["dsh"] if include_dsh else [])
raw = (getattr(args, "source", "") or "").strip()
if raw:
which = _parse_sources(raw, defaults)
print(f"✔ 确认 1/2 来源区:{' + '.join(which)}(--source)")
return which
if confirm.interactive():
which = confirm.prompt_sources()
print(f"✔ 确认 1/2 来源区:{' + '.join(which)}")
return which
sys.exit(confirm.NONINTERACTIVE_HELP)
def _resolve_scope(args) -> dict:
"""确认 2/2 · 数据量:显式 --scope 即确认;交互终端弹菜单;非交互缺参拒绝。"""
raw = (getattr(args, "scope", "") or "").strip()
if raw:
scope = confirm.parse_scope(raw)
print(f"✔ 确认 2/2 数据量:{confirm.scope_label(scope)}(--scope {confirm.scope_spec(scope)})")
return scope
if confirm.interactive():
scope = confirm.prompt_scope()
print(f"✔ 确认 2/2 数据量:{confirm.scope_label(scope)}")
return scope
sys.exit(confirm.NONINTERACTIVE_HELP)
def cmd_web(args):
from agentsync import webui
webui.serve(port=args.port, open_browser=not args.no_open)
def cmd_status(args):
p = paths.detect()
print("== 存储探测 ==")
print(f" zcode db : {p.zcode_db or '未找到'}")
print(f" hermes db : {p.hermes_db or '未找到'}")
print(f" dsh sessions : {p.dsh_sessions or '未找到'}")
print(f" codex sessions : {p.codex_sessions or '未找到'}")
print(f" workbuddy home : {p.workbuddy_home or '未找到'}(国内版)")
print(f" workbuddy-ai : {p.workbuddy_ai_home or '未找到'}(国际版)")
print(f" claude projects: {p.claude_projects or '未找到'}")
print(f" opencode db : {p.opencode_db or '未找到'}")
print(f" qoder home : {p.qoder_home or '未找到'}")
print(f" openclaw home : {p.openclaw_home or '未找到'}")
print(f" cursor db : {p.cursor_global_db or '未找到'}")
print(f" trae db : {p.trae_global_db or '未找到'}")
print(f" mimo home : {p.mimo_home or '未找到'}")
print(f" kilo db : {p.kilo_db or '未找到'}")
print(f" kimi home : {p.kimi_home or '未找到'}")
print(f" minimax home : {p.minimax_home or '未找到'}")
print(f" grok home : {p.grok_home or '未找到'}")
print(f" copilot user : {p.copilot_home or '未找到'}")
print(f" gemini home : {p.gemini_home or '未找到'}")
print(f" cline home : {p.cline_home or '未找到'}")
print(f" pi home : {p.pi_home or '未找到'}")
if args.verbose:
return
loaded = load_sources(ALL_SOURCES, p)
print()
print("== 会话统计 ==")
for src in ALL_SOURCES:
ss = loaded.get(src, [])
if not ss:
print(f" {src:7}: 0")
continue
newest = max(ss, key=lambda s: s.created_at or 0)
label = (newest.title or (newest.turns[0].prompt[:30] if newest.turns else ""))[:30]
extra = "(已排除🤖子代理)" if src == "dsh" else ""
print(f" {src:7}: {len(ss):3} 个会话{extra},最近:{_fmt_ts(newest.created_at)} 「{label}」")
# 已导入到 dsh 的会话
if p.dsh_sessions:
imported = [s for s in loaded.get("dsh", []) if s.source_id.startswith("import-")]
print(f"\n dsh 中 import-* 会话:{len(imported)} 个(由同步工具/插件导入)")
st = syncstate.load(p.dsh_sessions)
if st:
parts = [f"{k} {_fmt_ts(v)}" for k, v in sorted(st.items())]
print(" 上次同步(增量基准):" + " · ".join(parts))
# 规范库 C 总览(存在才显示)
from agentsync import store
if store.store_exists():
ov = store.overview()
counts = " · ".join(f"{k} {v}" for k, v in sorted(ov["counts"].items())) or "(空)"
print(f"\n== 规范库 C:{ov['dir']} ==")
print(f" 会话:{counts}")
if ov["state"]:
parts = [f"{k} {_fmt_ts(v)}" for k, v in sorted(ov["state"].items())]
print(" pull 基准:" + " · ".join(parts))
for tgt, stt in sorted(ov["push"].items()):
parts = [f"{k} {_fmt_ts(v)}" for k, v in sorted(stt.items())]
print(f" push 水位[{tgt}]:" + " · ".join(parts))
def _compute_cutoffs(scope: dict, which: list[str], state: dict) -> tuple[dict[str, int | None], list[str]]:
"""数据量确认 → 每源增量下界;返回 (cutoffs, 首次无基准源列表)。"""
cutoffs: dict[str, int | None] = {}
if scope["kind"] == "days":
c = int(time.time() * 1000) - scope["days"] * 86400000
cutoffs = {src: c for src in which}
print(f"数据量过滤:{confirm.scope_label(scope)}(活跃时间 ≥ {datetime.fromtimestamp(c / 1000).strftime('%m-%d %H:%M')})")
elif scope["kind"] == "inc":
for src in which:
cutoffs[src] = syncstate.cutoff_for(state, src)
first = [src for src in which if cutoffs.get(src) is None] if scope["kind"] == "inc" else []
return cutoffs, first
def _run_sink(args, name: str, get_store, writer, loader=None, state_dir=None, state_file=None, include_dsh=None):
"""通用写入目标执行器:两道确认 → 历史拦截 → 增量过滤 → plan/apply → 推进基准。
dsh/codex/claude 的 root 是目录;hermes 的 root 是 state.db 文件
(增量基准与墓碑落其所在目录)。push 模式:loader 读规范库 C,
state_dir/state_file 指向 C 内每目标水位文件(断点续推的根基)。
"""
p = paths.detect()
store = get_store(p)
if not store:
sys.exit(f"未找到 {name} 会话存储")
if include_dsh is None:
include_dsh = name != "dsh"
which = _resolve_sources(args, include_dsh=include_dsh)
# 防自我回环:来源=目标(如 push--target opencode 推 opencode 自家会话)会造成
# 同一会话双份(uuid5 id ≠ 原生 id),一律跳过。
target = name.split(":")[-1]
if target in which:
print(f" [跳过] 来源 {target} 与目标相同(防重复导入)")
which = [s for s in which if s != target]
if not which:
sys.exit("所选来源全部与目标相同,无可同步内容")
scope = _resolve_scope(args)
root = args.root or str(store)
s_root = state_dir or (root if os.path.isdir(root) else os.path.dirname(root))
fname = state_file or ".agentsync-state.json"
titles = {}
tfile = getattr(args, "titles", None)
if tfile:
titles = json.load(open(tfile, encoding="utf-8"))
print(f"标题覆盖:{len(titles)} 条(来自 {tfile})")
loaded = (loader or load_sources)(which, p, include_playground=getattr(args, "include_playground", False))
# 数据量确认 → 每源增量下界(None = 不过滤:全部历史 / 首次增量)
state = syncstate.load(s_root, fname)
# 人工拦截:历史全量(scope=all,或 inc 首跑无基准)在 --apply 时必须显式确认——
# 交互弹 y/N(默认 N=取消);非交互必须由人显式给 --confirm-history,否则拒绝。
full_sources = confirm.history_full_sources(scope, which, state, available=set(loaded))
if full_sources and args.apply and not getattr(args, "confirm_history", False):
if confirm.interactive():
if not confirm.prompt_history_confirm("'/'".join(full_sources)):
sys.exit("已取消:未做任何修改。")
else:
sys.exit(confirm.NONINTERACTIVE_HISTORY_HELP)
elif full_sources and getattr(args, "confirm_history", False):
print(f"⚠ 历史全量:{'+'.join(full_sources)} 已由 --confirm-history 显式确认")
cutoffs, first = _compute_cutoffs(scope, which, state)
if first:
print(f"仅增量:{'/'.join(first)} 首次运行无基准,按全部历史处理")
# 候选先收集后执行(大批量时可逐条勾选);dry-run 只读预览免闸
candidates: list[tuple[str, object]] = []
for src in which:
sessions = _filter(loaded.get(src, []), args)
c = cutoffs.get(src)
if c is not None:
sessions = syncstate.apply_cutoff(sessions, c)
candidates.extend((src, s) for s in sessions)
def _label(item):
src, sess = item
d = datetime.fromtimestamp((sess.updated_at or sess.created_at or 0) / 1000).strftime("%m-%d")
t = (sess.title or sess.turns[0].prompt[:24] if sess.turns else "")[:30]
return f"[{src:9}] {d} {t}"
keep = confirm.batch_gate(candidates, gated=bool(args.apply),
confirm_batch=bool(getattr(args, "confirm_batch", False)), label_of=_label)
if keep is not None:
candidates = keep
total = planned = applied = 0
for src, sess in candidates:
total += 1
plan = writer.plan_write(root, sess, budget=args.budget, force=args.force, titles=titles)
tag = plan["action"]
n_units = len(plan.get("events") or plan.get("lines") or plan.get("rows") or [])
extra = ""
if tag == "append":
extra = f"(源 {plan['sourceTurns']} 轮 > 已有 {plan['existingTurns']} 轮,追加 {n_units} 单元)"
elif tag == "create":
extra = f"({plan['stats']['messages']} 消息 / {plan['stats']['toolCalls']} 工具调用)"
elif tag == "skip-deleted":
extra = f"({plan['reason']})"
print(f" [{tag:13}] {src}:{sess.source_id} 「{(sess.title or sess.turns[0].prompt[:24] if sess.turns else '')[:32]}」 {extra}")
if tag in ("create", "append"):
planned += 1
if args.apply:
msg = writer.apply_write(plan)
print(f" └─ applied: {msg}")
applied += 1
mode = "APPLY" if args.apply else "DRY-RUN(--apply 落盘)"
print(f"\n{mode}:共 {total} 个候选,{planned} 个待写入,{applied} 个已写入(target={name} root={root})")
if args.apply:
done = [src for src in which if src in loaded]
syncstate.mark(s_root, done, fname)
print(f"增量基准已推进:{'/'.join(done)}(下次『仅增量』从这里起算)")
def cmd_pull(args):
"""pull:各源 → 规范库 C(~/.session-sync)。只读各 agent、只写 C——
无需退出任何应用,历史全量也不拦截(C 是内部规范库,不触碰 agent 存储)。
"""
from agentsync import store
p = paths.detect()
which = _resolve_sources(args, include_dsh=True)
scope = _resolve_scope(args)
c_dir = store.store_dir()
loaded = load_sources(which, p)
if "dsh" in loaded:
loaded["dsh"] = store.native_only(loaded["dsh"]) # import-* 不回流(防环形复制)
state = syncstate.load(c_dir)
cutoffs, first = _compute_cutoffs(scope, which, state)
if first:
print(f"仅增量:{'/'.join(first)} 首次运行无基准,按全部历史处理")
tomb = dshwrite.load_tombstones(c_dir)
# 候选先收集后执行;pull 本身写 C(安全),但大批量仍给逐条勾选的控制权
candidates: list[tuple[str, object]] = []
for src in which:
sessions = _filter(loaded.get(src, []), args)
c = cutoffs.get(src)
if c is not None:
sessions = syncstate.apply_cutoff(sessions, c)
candidates.extend((src, s) for s in sessions)
def _label(item):
src, sess = item
d = datetime.fromtimestamp((sess.updated_at or sess.created_at or 0) / 1000).strftime("%m-%d")
t = (sess.title or sess.turns[0].prompt[:24] if sess.turns else "")[:30]
return f"[{src:9}] {d} {t}"
keep = confirm.batch_gate(candidates, gated=True,
confirm_batch=bool(getattr(args, "confirm_batch", False)), label_of=_label)
if keep is not None:
candidates = keep
total = created = updated = ok = skipped = 0
for src, sess in candidates:
total += 1
label = (sess.title or sess.turns[0].prompt[:24] if sess.turns else "")[:32]
if sess.source_id in tomb:
skipped += 1
continue
r = store.write_session(sess)
if r == "create":
created += 1
elif r == "update":
updated += 1
else:
ok += 1
if r != "up-to-date":
print(f" [{r:13}] {src}:{sess.source_id} 「{label}」")
print(f"\nPULL:共 {total} 个候选,新增 {created},更新 {updated},无变化 {ok},墓碑拦 {skipped}(C={c_dir})")
syncstate.mark(c_dir, [s for s in which if s in loaded])
print("pull 基准已推进(下次『仅增量』从这里起算)")
def cmd_push(args):
"""push:规范库 C → 目标 agent。幂等断点续推(C 内每目标水位文件);
写 agent 存储照旧两道确认 + 历史全量拦截;换任何 agent 重跑自动从断点继续。
"""
from agentsync import claudewrite, clinewrite, codexwrite, geminiwrite, hermeswrite, minimaxwrite, opencodewrite, piwrite, store, workbuddywrite
if not store.store_exists():
sys.exit("规范库 C 为空:先跑 python sync.py pull")
writers = {"dsh": dshwrite, "codex": codexwrite, "claude": claudewrite, "hermes": hermeswrite,
"opencode": opencodewrite, "kilo": opencodewrite, "workbuddy": workbuddywrite, "minimax": minimaxwrite,
"workbuddy-ai": workbuddywrite,
"pi": piwrite, "gemini": geminiwrite, "cline": clinewrite}
getters = {
"dsh": lambda p: p.dsh_sessions,
"codex": lambda p: p.codex_sessions,
"claude": lambda p: p.claude_projects,
"hermes": lambda p: p.hermes_db,
"opencode": lambda p: p.opencode_db,
"kilo": lambda p: p.kilo_db,
"workbuddy": lambda p: p.workbuddy_home,
"workbuddy-ai": lambda p: p.workbuddy_ai_home,
"minimax": lambda p: p.minimax_home,
"pi": lambda p: p.pi_home,
"gemini": lambda p: p.gemini_home,
"cline": lambda p: p.cline_home,
}
target = args.target
_run_sink(
args, f"push:{target}", getters[target], writers[target],
loader=lambda which, p: store.read_store(which),
state_dir=store.store_dir(),
state_file=f"push-{target}-state.json",
include_dsh=(target != "dsh"),
)
def cmd_to_dsh(args):
from agentsync import dshwrite as _w
_run_sink(args, "dsh", lambda p: p.dsh_sessions, _w)
def cmd_to_codex(args):
from agentsync import codexwrite as _w
_run_sink(args, "codex", lambda p: p.codex_sessions, _w)
def cmd_to_claude(args):
from agentsync import claudewrite as _w
_run_sink(args, "claude", lambda p: p.claude_projects, _w)
def cmd_to_hermes(args):
from agentsync import hermeswrite as _w
_run_sink(args, "hermes", lambda p: p.hermes_db, _w)
def cmd_to_opencode(args):
from agentsync import opencodewrite as _w
_run_sink(args, "opencode", lambda p: p.opencode_db, _w)
def cmd_to_kilo(args):
# kilo 是 opencode 服务器分支,三表同构——写入直接复用 opencodewrite(db 同目录墓碑/旁路清单同款)
from agentsync import opencodewrite as _w
_run_sink(args, "kilo", lambda p: p.kilo_db, _w)
def cmd_to_workbuddy(args):
from agentsync import workbuddywrite as _w
_run_sink(args, "workbuddy", lambda p: p.workbuddy_home, _w)
def cmd_to_workbuddy_ai(args):
from agentsync import workbuddywrite as _w
_run_sink(args, "workbuddy-ai", lambda p: p.workbuddy_ai_home, _w)
def cmd_to_minimax(args):
from agentsync import minimaxwrite as _w
_run_sink(args, "minimax", lambda p: p.minimax_home, _w)
def cmd_to_pi(args):
from agentsync import piwrite as _w
_run_sink(args, "pi", lambda p: p.pi_home, _w)
def cmd_to_gemini(args):
from agentsync import geminiwrite as _w
_run_sink(args, "gemini", lambda p: p.gemini_home, _w)
def cmd_to_cline(args):
from agentsync import clinewrite as _w
_run_sink(args, "cline", lambda p: p.cline_home, _w)
def cmd_archive(args):
p = paths.detect()
which = _parse_sources(args.source, ALL_SOURCES)
loaded = load_sources(which, p)
out_dir = args.out or os.path.join(os.path.dirname(os.path.abspath(__file__)), "archive")
n = 0
for src in which:
sessions = _filter(loaded.get(src, []), args)
n += len(sessions)
if args.apply:
written = archive_mod.write_archive(sessions, out_dir)
print(f" {src:7}: {len(written)} 篇已写入 {out_dir}{os.sep}{src}")
else:
print(f" {src:7}: {len(sessions)} 个会话待归档(--apply 落盘 → {out_dir})")
if not args.apply:
print(f"\nDRY-RUN:共 {n} 个会话,加 --apply 写出 Markdown")
def cmd_verify(args):
p = paths.detect()
root = args.root or str(p.dsh_sessions)
from agentsync.readers import _zstd_decode_all, _parse_jsonl
import glob
n = ok_n = 0
for path in sorted(glob.glob(os.path.join(root, "*", "import-*", "session.jsonl*"))):
n += 1
raw = open(path, "rb").read()
text = _zstd_decode_all(raw).decode("utf-8", errors="replace") if path.endswith(".zstd") else raw.decode("utf-8", errors="replace")
lines = _parse_jsonl(text)
events = [o for o in lines if o.get("type") != "session"]
ok, problems = dshwrite.validate_session_events(events)
ok_n += ok
status = "OK " if ok else "BAD"
print(f" [{status}] {os.path.basename(os.path.dirname(path))}: {len(events)} events")
for pr in problems[:3]:
print(f" - {pr}")
print(f"\n校验 {n} 个导入会话:{ok_n} 通过")
def cmd_selftest(args):
"""沙箱端到端自检:不动任何真实数据,全部在 .selftest/ 里完成。
覆盖:dsh 写入→读回→增量追加→校验;归档渲染。
(zcode 写入方向已移除——只出不进;zcode 读取在 status/归档路径中隐式覆盖。)
任何一步失败即退出码 1。换机器/升级 dsh 后先跑这个。
"""
import shutil
import tempfile
from agentsync.model import Session, Step, ToolResult, Turn
from agentsync.readers import read_dsh, read_zcode
here = os.path.dirname(os.path.abspath(__file__))
box = os.path.join(here, ".selftest")
shutil.rmtree(box, ignore_errors=True)
os.makedirs(box)
failures = []
def check(name: bool | tuple[bool, str], label: str):
ok, detail = (name, "") if isinstance(name, bool) else name
print(f" [{'PASS' if ok else 'FAIL'}] {label}{(' — ' + detail) if detail and not ok else ''}")
if not ok:
failures.append(label)
def fake(v2=False) -> Session:
turns = [
Turn("第一问:你好", [Step([{"type": "reasoning", "text": "想想"}, {"type": "text", "text": "第一答"}])]),
]
if v2:
turns.append(
Turn(
"第二问:跑个命令",
[
Step(
[{"type": "text", "text": "我来执行"}, {"type": "tool-call", "id": "call_t1", "name": "Bash", "arguments": '{"command": "echo hi"}'}],
[{"id": "call_t1", "name": "Bash", "arguments": '{"command": "echo hi"}'}],
[ToolResult("call_t1", [{"type": "text", "text": "hi"}], is_error=False)],
),
Step([{"type": "text", "text": "命令输出 hi"}]),
],
)
)
return Session(
source="codex",
source_id="selftest-0001",
title="自检会话",
cwd="D:\\SelfTest",
created_at=1787000000000,
model="test-model",
turns=turns,
)
print("== 1/8 dsh 写入与读回(沙箱根)==")
dsh_root = os.path.join(box, "dsh-root")
plan = dshwrite.plan_write(dsh_root, fake(), None)
check(plan["action"] == "create", "plan 首次为 create")
dshwrite.apply_write(plan)
header, events = dshwrite.read_log_events(plan["path"])
ok, problems = dshwrite.validate_session_events(events)
check(ok and len(events) > 0, f"事件校验通过({len(events)} 事件)")
back = read_dsh(dsh_root, include_imports=True)
check(len(back) == 1 and len(back[0].turns) == 1 and back[0].title == "[codex] 自检会话", "读回 1 会话 1 轮带标题(自动来源前缀)")
check(read_dsh(dsh_root) == [], "read_dsh 默认排除 import-*(防 dsh→反向目标二次成环)")
print("== 2/8 dsh 增量追加 ==")
plan2 = dshwrite.plan_write(dsh_root, fake(v2=True), None)
check(plan2["action"] == "append" and len(plan2["events"]) > 0, f"plan 二次为 append(+{len(plan2['events'])} 事件)")
dshwrite.apply_write(plan2)
_, events2 = dshwrite.read_log_events(plan2["path"])
seqs = [e["seq"] for e in events2]
ok2, _ = dshwrite.validate_session_events(events2)
check(ok2 and seqs == list(range(len(seqs))), "追加后 seq 连续且校验通过")
plan3 = dshwrite.plan_write(dsh_root, fake(v2=True), None)
check(plan3["action"] == "up-to-date", "三次执行为 up-to-date(幂等)")
# 标题投影回填(projcache title 行 + identity 校验)
pc_dir = os.path.join(box, "storages")
os.makedirs(pc_dir, exist_ok=True)
pc_path = os.path.join(pc_dir, "session_projcache.json")
with open(pc_path, "w", encoding="utf-8") as f:
json.dump({"ver": 1, "tables": {"sessions": {}}}, f)
tb = dshwrite.plan_title_backfill(dsh_root)
check(len(tb["backfill"]) == 1, "title 回填计划覆盖新导入")
dshwrite.apply_title_backfill(tb)
sid_key = next(iter(tb["backfill"]))
pc1 = json.load(open(pc_path, encoding="utf-8"))
check(pc1["tables"]["sessions"][sid_key]["rows"]["title"]["val"] == "[codex] 自检会话", "回填 title 值带来源前缀")
tb2 = dshwrite.plan_title_backfill(dsh_root)
check(not tb2["backfill"], "二次回填为空(幂等)")
# 回归:identity 失配但 title 一致 → 仍须重建条目(早期版本被 continue 跳过 → 侧栏无标题)
pc1["tables"]["sessions"][sid_key]["identity"] = {"createdAt": 1, "cwd": "X:\\old"}
with open(pc_path, "w", encoding="utf-8") as f:
json.dump(pc1, f)
tb3 = dshwrite.plan_title_backfill(dsh_root)
check(sid_key in tb3["backfill"], "identity 失配且 title 一致时仍重建条目(回归)")
# 轮级真实时间(回归:事件时间曾被压平到会话创建时间)
sess_t = fake(v2=True)
sess_t.created_at = 1787000000000
sess_t.turns[0].time = 1787003600000
sess_t.turns[1].time = 1787007200000
root_t = os.path.join(box, "dsh-time")
plan_t = dshwrite.plan_write(root_t, sess_t, None)
dshwrite.apply_write(plan_t)
_, evs_t = dshwrite.read_log_events(plan_t["path"])
ts_turns = [e["time"] for e in evs_t if e["type"] == "turn/start"]
check(ts_turns == [1787003600000, 1787007200000], "轮级时间落盘(turn/start 用 Turn.time,不压平)")
print("== 3/8 归档渲染 ==")
out = archive_mod.write_archive([fake(v2=True)], os.path.join(box, "archive"))
check(len(out) == 1 and os.path.getsize(out[0]) > 0, f"Markdown 已生成({os.path.basename(out[0]) if out else '-'})")
print("== 4/8 确认与增量(HITL 纯函数)==")
from agentsync import confirm as cf
from agentsync import syncstate
check(cf.parse_scope("inc")["kind"] == "inc", "scope: inc")
check(cf.parse_scope("all") == {"kind": "all", "days": None}, "scope: all")
check(cf.parse_scope("14d") == {"kind": "days", "days": 14}, "scope: 14d")
check(cf.parse_scope("14")["days"] == 14, "scope: 14(无 d 后缀)")
try:
cf.parse_scope("abc")
check(False, "scope: 非法值应退出")
except SystemExit:
check(True, "scope: 非法值退出")
check(cf.parse_sources_answer("2,5") == ["zcode", "workbuddy"], "来源组合 2,5 → zcode+workbuddy")
check(cf.parse_sources_answer("") == cf.SYNC_SOURCES, "来源空输入 → 全部(默认同步源全集)")
check(cf.parse_sources_answer("zcode,workbuddy") == ["zcode", "workbuddy"], "来源名称组合")
base_ms = 1787000000000
s_old = fake()
s_old.updated_at = base_ms - 10 * 86400000
s_new = fake()
s_new.updated_at = base_ms - 1000
kept = syncstate.apply_cutoff([s_old, s_new], base_ms - 7 * 86400000)
check(len(kept) == 1 and kept[0] is s_new, "cutoff 过滤:只留 7 天内活跃")
st_dir = os.path.join(box, "state-root")
os.makedirs(st_dir, exist_ok=True)
syncstate.mark(st_dir, ["zcode"])
st = syncstate.load(st_dir)
check("zcode" in st and st["zcode"] > 0, "状态文件 mark/load 往返")
check(
syncstate.cutoff_for(st, "zcode") is not None and syncstate.cutoff_for(st, "hermes") is None,
"cutoff_for:有基准取基准-重叠,无基准 None(首次=全部)",
)
st_full = {"zcode": 1, "hermes": 1}
check(cf.history_full_sources({"kind": "all", "days": None}, ["zcode", "claude"], {}) == ["zcode", "claude"],
"历史拦截:scope=all 全部所选源命中")
check(cf.history_full_sources({"kind": "inc", "days": None}, ["zcode", "claude"], st_full) == ["claude"],
"历史拦截:inc 首跑无基准的源命中")
check(cf.history_full_sources({"kind": "inc", "days": None}, ["zcode"], st_full) == [],
"历史拦截:inc 有基准不命中")
check(cf.history_full_sources({"kind": "days", "days": 7}, ["zcode"], {}) == [],
"历史拦截:天数窗口(有界)不命中")
check(cf.parse_pick_answer("all", 5) is None and cf.parse_pick_answer("", 5) is None, "pick:all/空=全选")
check(cf.parse_pick_answer("1,3-5", 8) == [0, 2, 3, 4], "pick:编号+范围")
check(cf.parse_pick_answer("2", 3) == [1], "pick:单选")
try:
cf.parse_pick_answer("9", 3)
check(False, "pick:越界应退出")
except SystemExit:
check(True, "pick:越界退出")
check(cf.batch_gate(list(range(20)), gated=False, confirm_batch=False, label_of=str) is None,
"gate:未启用(dry-run)放行")
check(cf.batch_gate(list(range(5)), gated=True, confirm_batch=False, label_of=str) is None,
"gate:阈内放行")
check(cf.batch_gate(list(range(20)), gated=True, confirm_batch=True, label_of=str) is None,
"gate:--confirm-batch 放行")
try:
cf.batch_gate(list(range(20)), gated=True, confirm_batch=False, label_of=str)
check(False, "gate:非交互超阈应拒绝")
except SystemExit:
check(True, "gate:非交互超阈拒绝(一股脑防线)")
from agentsync.dshwrite import _is_junk
check(_is_junk("Reply PONG", "Reply PONG", 1) and _is_junk("Say hello in one word.", "Say hello in one word.", 1),
"junk:claude 冒烟句(reply*/say hello* 前缀)")
check(_is_junk("你好鸭", "你好鸭", 1), "junk:你好鸭")
check(not _is_junk("微前端基座与子应用UI库冲突迁移Ant Design Vue方案", "微前端…", 56)
and not _is_junk("你好,你用了什么模型", "你好,你用了什么模型", 2),
"junk:真实会话不误伤(包含≠等于)")
print("== 5/8 claude / opencode 读取器(沙箱样本)==")
import tempfile
from agentsync.readers import read_claude, read_opencode
claude_root = os.path.join(box, "claude", "projects")
proj_dir = os.path.join(claude_root, "D--Proj")
os.makedirs(proj_dir)
c_sid = "11111111-2222-3333-4444-555555555555"
c_recs = [
{"type": "ai-title", "aiTitle": "配置 Codex 命令启动", "sessionId": c_sid},
{"type": "user", "isSidechain": False, "cwd": "D:\\Proj", "timestamp": "2026-08-01T00:00:00.000Z",
"message": {"role": "user", "content": "跑一下<system-reminder>别理我</system-reminder>测试"}},
{"type": "assistant", "timestamp": "2026-08-01T00:00:01.000Z",
"message": {"role": "assistant", "model": "claude-test", "content": [
{"type": "thinking", "thinking": "想一想"},
{"type": "tool_use", "id": "call_x1", "name": "Bash", "input": {"command": "echo hi"}},
]}},
{"type": "user", "timestamp": "2026-08-01T00:00:02.000Z",
"message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "call_x1", "content": "hi", "is_error": False}]}},
{"type": "assistant", "timestamp": "2026-08-01T00:00:03.000Z",
"message": {"role": "assistant", "model": "claude-test", "content": [{"type": "text", "text": "结果 hi"}]}},
{"type": "assistant", "isSidechain": True, "timestamp": "2026-08-01T00:00:04.000Z",
"message": {"role": "assistant", "content": [{"type": "text", "text": "子代理输出"}]}},
{"type": "queue-operation", "operation": "dequeue", "timestamp": "2026-08-01T00:00:05.000Z"},
]
with open(os.path.join(proj_dir, c_sid + ".jsonl"), "w", encoding="utf-8") as f:
for r in c_recs:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
smoke_dir = os.path.join(claude_root, "T--tmp-smoke")
os.makedirs(smoke_dir)
with open(os.path.join(smoke_dir, "99999999-8888-7777-6666-555555555555.jsonl"), "w", encoding="utf-8") as f:
f.write(json.dumps({"type": "user", "cwd": os.path.join(tempfile.gettempdir(), "x"),
"timestamp": "2026-08-01T00:00:00.000Z",
"message": {"role": "user", "content": "PONG"}}, ensure_ascii=False) + "\n")
cl = read_claude(claude_root)
check(len(cl) == 1 and cl[0].source_id == c_sid, "claude:读回 1 会话(TEMP 冒烟整文件跳过)")
check(cl[0].title == "配置 Codex 命令启动" and cl[0].cwd == "D:\\Proj", "claude:ai-title + 行内 cwd")
check(cl[0].turns[0].prompt == "跑一下测试", "claude:system-reminder 注入已剥")
st_c = cl[0].turns[0].steps[0]
check(any(b["type"] == "reasoning" for b in st_c.content) and st_c.tool_calls[0]["name"] == "Bash",
"claude:thinking + tool_use")
check(st_c.tool_results and st_c.tool_results[0].content[0]["text"] == "hi", "claude:tool_result 挂回原 step")
check(len(cl[0].turns[0].steps) == 2 and cl[0].turns[0].steps[1].content[0]["text"] == "结果 hi",
"claude:文本步在位,子代理/事件行被跳过")
import uuid as _uuid
v5_sid = str(_uuid.uuid5(_uuid.UUID("a2c4e6d8-1b3f-4a5c-8e7d-9f0a1b2c3d4e"), "selftest:import"))
assert _uuid.UUID(v5_sid).version == 5
with open(os.path.join(proj_dir, v5_sid + ".jsonl"), "w", encoding="utf-8") as f:
f.write(json.dumps({"type": "user", "cwd": "D:\\Proj", "timestamp": "2026-08-01T00:00:00.000Z",
"message": {"role": "user", "content": "导入回流测试"}}, ensure_ascii=False) + "\n")
cl2 = read_claude(claude_root)
check(len(cl2) == 1 and cl2[0].source_id == c_sid, "claude:uuid5 导入会话不回流(防 A→claude→A 成环)")
oc_db = os.path.join(box, "opencode.db")
con = sqlite3.connect(oc_db)
con.executescript(
"CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT, title TEXT, model TEXT, time_created INTEGER, time_updated INTEGER);"
"CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);"
"CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, data TEXT);"
)
con.execute("INSERT INTO session VALUES ('ses_test0001', 'D:/oc', 'OC 测试', 'gpt-test', 1787000000000, 1787000009000)")
con.execute("INSERT INTO message VALUES ('msg_u1', 'ses_test0001', 1787000001000, '{\"role\":\"user\"}')")
con.execute("INSERT INTO part VALUES ('prt_u1', 'msg_u1', 'ses_test0001', 1787000001000, '{\"type\":\"text\",\"text\":\"你好 opencode\"}')")
con.execute("INSERT INTO message VALUES ('msg_a1', 'ses_test0001', 1787000002000, '{\"role\":\"assistant\"}')")
con.execute("INSERT INTO part VALUES ('prt_a1', 'msg_a1', 'ses_test0001', 1787000002000, '{\"type\":\"text\",\"text\":\"收到\"}')")
con.execute("INSERT INTO message VALUES ('msg_s1', 'ses_test0001', 1787000003000, '{\"role\":\"compaction\"}')")
con.commit()
con.close()
oc = read_opencode(oc_db)
check(len(oc) == 1 and oc[0].title == "OC 测试", "opencode:读回 1 会话")
check(oc[0].turns[0].prompt == "你好 opencode" and oc[0].turns[0].steps[0].content[0]["text"] == "收到",
"opencode:user→assistant 轮(compaction 消息跳过)")
check(oc[0].updated_at == 1787000009000 and oc[0].cwd == "D:/oc" and oc[0].model == "gpt-test",
"opencode:updated_at / cwd / model")
# mimo:同构 opencode + 首跑自动导入 claude 会话(external_import 表)+ TEMP/归档排除
from agentsync.readers import read_mimo
mm_home = os.path.join(box, "mimo-home")
os.makedirs(mm_home)
mm_db = os.path.join(mm_home, "mimocode.db")
con = sqlite3.connect(mm_db)
con.executescript(
"CREATE TABLE session (id TEXT PRIMARY KEY, directory TEXT, title TEXT, time_created INTEGER,"
" time_updated INTEGER, time_archived INTEGER);"
"CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT);"
"CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, data TEXT);"
"CREATE TABLE external_import (source TEXT, source_key TEXT, session_id TEXT,"
" source_path TEXT, source_mtime INTEGER, time_imported INTEGER, message_ids TEXT);"
)
con.execute("INSERT INTO session VALUES ('ses_mmnative', 'D:/mm', 'MM 测试', 1787000100000, 1787000109000, NULL)")
con.execute("INSERT INTO message VALUES ('msg_mu1', 'ses_mmnative', 1787000101000, '{\"role\":\"user\"}')")
con.execute("INSERT INTO part VALUES ('prt_mu1', 'msg_mu1', 'ses_mmnative', 1787000101000, '{\"type\":\"text\",\"text\":\"你好 mimo\"}')")
con.execute("INSERT INTO message VALUES ('msg_ma1', 'ses_mmnative', 1787000102000, '{\"role\":\"assistant\",\"model\":\"mimo-test\"}')")
con.execute("INSERT INTO part VALUES ('prt_mr1', 'msg_ma1', 'ses_mmnative', 1787000102000, '{\"type\":\"reasoning\",\"text\":\"想想\"}')")
con.execute("INSERT INTO part VALUES ('prt_mt1', 'msg_ma1', 'ses_mmnative', 1787000102100, '{\"type\":\"text\",\"text\":\"收到\"}')")
# 首跑自动导入的 claude 会话(external_import 登记)——必须排除
con.execute("INSERT INTO session VALUES ('ses_mmimport', 'D:/cc', '导入副本', 1787000000000, 1787000005000, NULL)")
con.execute("INSERT INTO message VALUES ('msg_mi1', 'ses_mmimport', 1787000001000, '{\"role\":\"user\"}')")
con.execute("INSERT INTO part VALUES ('prt_mi1', 'msg_mi1', 'ses_mmimport', 1787000001000, '{\"type\":\"text\",\"text\":\"claude 原话\"}')")
con.execute("INSERT INTO external_import VALUES ('cc', 'k1', 'ses_mmimport', 'x.jsonl', 0, 0, NULL)")
# TEMP 冒烟(mimo 自测 calculator 类)——排除
con.execute("INSERT INTO session VALUES ('ses_mmtemp', ?, '冒烟', 1787000200000, 1787000200000, NULL)",
(os.path.join(tempfile.gettempdir(), "mm-smoke").replace("\\", "/"),))
# 归档会话——默认排除
con.execute("INSERT INTO session VALUES ('ses_mmarch', 'D:/mm', '归档的', 1787000300000, 1787000300000, 1787000301000)")
con.execute("INSERT INTO message VALUES ('msg_mah', 'ses_mmarch', 1787000300000, '{\"role\":\"user\"}')")
con.execute("INSERT INTO part VALUES ('prt_mah', 'msg_mah', 'ses_mmarch', 1787000300000, '{\"type\":\"text\",\"text\":\"归档前的话\"}')")
con.commit()
con.close()
mm = read_mimo(mm_home)
check(len(mm) == 1 and mm[0].source_id == "ses_mmnative",
"mimo:仅原生 1 会话(claude 自动导入/TEMP/归档全排除)")
check(mm[0].turns[0].prompt == "你好 mimo" and mm[0].model == "mimo-test"
and any(b["type"] == "reasoning" for b in mm[0].turns[0].steps[0].content),
"mimo:轮次 + reasoning + 模型名(message.data.model,session 无 model 列)")
check(read_mimo(mm_home, include_archived=True)[0].source_id == "ses_mmnative"
and len(read_mimo(mm_home, include_archived=True)) == 2,
"mimo:include_archived 收归档会话(展示口径)")
# kimi:Kimi Work wire.jsonl 协议(turn.prompt / content.part think+text / llm.request)
from agentsync.readers import read_kimi
kw_home = os.path.join(box, "kimi-home")
kw_sess = os.path.join(kw_home, "sessions", "wd_test_ab12", "conv-kwtest0001")
os.makedirs(os.path.join(kw_sess, "agents", "main"))
with open(os.path.join(kw_home, "session_index.jsonl"), "w", encoding="utf-8") as f:
f.write(json.dumps({"sessionId": "conv-kwtest0001", "sessionDir": kw_sess.replace("\\", "/"),
"workDir": "D:/kw"}, ensure_ascii=False) + "\n")
f.write(json.dumps({"sessionId": "ctitle-9999", "sessionDir": "x", "workDir": "D:/kw"},
ensure_ascii=False) + "\n")
with open(os.path.join(kw_sess, "state.json"), "w", encoding="utf-8") as f:
json.dump({"title": '<meta awareness="low" timestamp="2026-09-09 14:19" /> 你是kimi吗?',
"createdAt": "2026-09-09T06:19:00.666Z", "updatedAt": "2026-09-09T06:19:11.326Z",
"custom": {"workspacePath": "D:\\kw"}}, f, ensure_ascii=False)
kw_lines = [
{"type": "metadata", "protocol_version": "1.4", "created_at": 1788934740884},
{"type": "config.update", "profileName": "agent", "systemPrompt": "You are Kimi Code CLI..."},
{"type": "turn.prompt", "input": [{"type": "text",
"text": '<meta awareness="low" timestamp="2026-09-09 14:19" />\n你是kimi吗?'}],
"origin": {"kind": "user"}, "time": 1788934741357},
{"type": "llm.request", "kind": "loop", "provider": "kimi", "model": "k2d6-agent",
"maxTokens": 262144, "time": 1788934741364},
{"type": "context.append_loop_event", "event": {"type": "step.begin", "uuid": "u-step1",
"turnId": "0", "step": 1}, "time": 1788934741362},
{"type": "context.append_loop_event", "event": {"type": "content.part", "uuid": "u-p1",
"turnId": "0", "step": 1, "stepUuid": "u-step1",
"part": {"type": "think", "think": "用户问身份,回答 Kimi"}},
"time": 1788934751359},
{"type": "context.append_loop_event", "event": {"type": "content.part", "uuid": "u-p2",
"turnId": "0", "step": 1, "stepUuid": "u-step1",
"part": {"type": "text", "text": "是的,我是 Kimi。"}},
"time": 1788934751360},
{"type": "context.append_loop_event", "event": {"type": "step.end", "uuid": "u-step1",
"turnId": "0", "step": 1, "usage": {"output": 189},
"finishReason": "end_turn"}, "time": 1788934751359},
{"type": "usage.record", "model": "k2d6-agent", "usage": {"output": 189},
"usageScope": "turn", "time": 1788934751359},
]
with open(os.path.join(kw_sess, "agents", "main", "wire.jsonl"), "w", encoding="utf-8") as f:
for r in kw_lines:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
kw = read_kimi(kw_home)
check(len(kw) == 1 and kw[0].source_id == "conv-kwtest0001", "kimi:读回 1 会话(ctitle-* 副作用会话排除)")
check(kw[0].title == "你是kimi吗?" and kw[0].turns[0].prompt == "你是kimi吗?",
"kimi:标题/prompt 的 <meta> 注入前缀已剥")
check(kw[0].model == "k2d6-agent" and kw[0].cwd == "D:\\kw" and kw[0].created_at == 1788934740666,
"kimi:模型(llm.request)/ cwd(workspacePath)/ ISO→ms 时间")
_st_k = kw[0].turns[0].steps[0]
check(any(b["type"] == "reasoning" and b["text"] == "用户问身份,回答 Kimi" for b in _st_k.content)
and any(b["type"] == "text" and b["text"] == "是的,我是 Kimi。" for b in _st_k.content),
"kimi:content.part think→reasoning + text 归并同 step,config/usage 行跳过")
# qoder:索引(vscdb questTaskListSnapshot)+ 正文(cache/projects conversation-history)两跳
from agentsync.readers import read_qoder
qh = os.path.join(box, "qoder-home")
# 文件名 = id 前 8 位(真实布局:task-63023fd1… → task-630/task-630.jsonl)
q_sess_dir = os.path.join(qh, "cache", "projects", "BI-7528aed1", "conversation-history", "task-sel")
os.makedirs(q_sess_dir)
q_lines = [
{"role": "user", "timestamp": "2026-08-26T02:45:00.000Z",
"message": {"role": "user", "content": [{"type": "text", "text": "<user_query>\n文档内容补充建议\n</user_query>"}]}},
{"role": "assistant", "timestamp": "2026-08-26T02:45:30.000Z",
"message": {"role": "assistant", "content": [{"type": "text", "text": "先看现有文档。"}]}},
]
with open(os.path.join(q_sess_dir, "task-sel.jsonl"), "w", encoding="utf-8") as f:
for r in q_lines:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
q_vscdb = os.path.join(box, "qoder-vscdb")
con = sqlite3.connect(q_vscdb)
con.execute("CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value BLOB)")
snap = {"folders": {"d:/BI": {"tasks": [
{"id": "task-selftest-0001", "name": "文档内容补充建议", "createTime": 1787000000000, "updatedAtTimestamp": 1787000060000},
{"id": "task-ghost-0002", "name": "正文已清的幽灵", "createTime": 1787000000000},
]}}}
con.execute("INSERT INTO ItemTable VALUES ('aicoding.questTaskListSnapshot', ?)", (json.dumps(snap),))
con.commit()
con.close()
qs = read_qoder(qh, q_vscdb)
check(len(qs) == 1 and qs[0].source_id == "task-selftest-0001" and qs[0].title == "文档内容补充建议",
"qoder:索引+正文两跳读回(无正文的幽灵任务跳过)")
check(qs[0].turns[0].prompt == "文档内容补充建议" and qs[0].turns[0].steps[0].content[0]["text"] == "先看现有文档。",
"qoder:user_query 包装已剥、assistant 文本在位")
check(qs[0].cwd == "d:/BI" and qs[0].created_at == 1787000000000 and qs[0].updated_at == 1787000060000,
"qoder:cwd/时间取自索引快照")
# openclaw:活跃 + reset 孤儿快照 + toolCall/toolResult 配对
from agentsync.readers import read_openclaw
oc_dir = os.path.join(box, "openclaw-home", "agents", "main", "sessions")
os.makedirs(oc_dir)
def _oc_lines(sid):
return [
{"type": "session", "version": 3, "id": sid, "timestamp": "2026-04-02T01:57:16.932Z",
"cwd": "C:\\w"},
{"type": "model_change", "model": "gpt-test"},
{"type": "message", "timestamp": "2026-04-02T01:57:16.945Z",
"message": {"role": "user", "content": [{"type": "text", "text": "建个目录"}]}},
{"type": "message", "timestamp": "2026-04-02T01:57:18.000Z",
"message": {"role": "assistant", "content": [
{"type": "thinking", "thinking": "查一下"},
{"type": "toolCall", "id": "call_t1", "name": "exec",
"arguments": {"command": "mkdir d"}}]}},
{"type": "message", "timestamp": "2026-04-02T01:57:20.000Z",
"message": {"role": "toolResult", "toolCallId": "call_t1", "toolName": "exec",
"content": [{"type": "text", "text": "done"}],
"details": {"status": "completed", "exitCode": 0}}},
{"type": "message", "timestamp": "2026-04-02T01:57:22.000Z",
"message": {"role": "assistant", "content": [{"type": "text", "text": "好了"}]}},
]
with open(os.path.join(oc_dir, "aaaa1111-0000.jsonl"), "w", encoding="utf-8") as f:
for r in _oc_lines("aaaa1111-0000"):
f.write(json.dumps(r, ensure_ascii=False) + "\n")
# 孤儿快照(内容只在 .reset 里)+ 同 uuid 双快照(取最新)
with open(os.path.join(oc_dir, "bbbb2222-0000.jsonl.reset.2026-04-01T00-00-00.000Z"), "w", encoding="utf-8") as f:
for r in _oc_lines("bbbb2222-0000"):
f.write(json.dumps(r, ensure_ascii=False) + "\n")
with open(os.path.join(oc_dir, "bbbb2222-0000.jsonl.reset.2026-05-01T00-00-00.000Z"), "w", encoding="utf-8") as f:
for r in _oc_lines("bbbb2222-0000"):
f.write(json.dumps(r, ensure_ascii=False) + "\n")
# 标题剥离 + 子代理排除:Control UI 的 Sender 元数据块/日期戳包裹、/new 控制条、[Subagent Context]
def _oc_user_lines(sid, prompt, ts0="2026-04-02T01:57:16.945Z"):
return [
{"type": "session", "version": 3, "id": sid, "timestamp": "2026-04-02T01:57:16.932Z", "cwd": "C:\\w"},
{"type": "message", "timestamp": ts0,
"message": {"role": "user", "content": [{"type": "text", "text": prompt}]}},
{"type": "message", "timestamp": "2026-04-02T01:57:18.000Z",
"message": {"role": "assistant", "content": [{"type": "text", "text": "收到"}]}},
]
_oc_wrap = ('Sender (untrusted metadata):\n```json\n{\n "label": "openclaw-control-ui",\n'
' "id": "openclaw-control-ui"\n}\n```\n\n[Thu 2026-04-02 09:57 GMT+8] ')
eeee_lines = _oc_user_lines("eeee5555-0000",
"A new session was started via /new or /reset. Run your Session Startup sequence.")
eeee_lines += [
{"type": "message", "timestamp": "2026-04-02T01:57:20.000Z",
"message": {"role": "user", "content": [{"type": "text", "text": _oc_wrap + "第二条真提问"}]}},
{"type": "message", "timestamp": "2026-04-02T01:57:22.000Z",
"message": {"role": "assistant", "content": [{"type": "text", "text": "好"}]}},
]
sub_lines = _oc_user_lines("ffff6666-0000",
"[Thu 2026-04-02 09:57 GMT+8] [Subagent Context] You are running as a "
"subagent (depth 1/1). Results auto-announce.\n\n[Subagent Task]: 子代理去干活")
for fname, lines in (("dddd4444-0000.jsonl", _oc_user_lines("dddd4444-0000", _oc_wrap + "你好 openclaw 标题")),
("eeee5555-0000.jsonl", eeee_lines),
("ffff6666-0000.jsonl", sub_lines)):
with open(os.path.join(oc_dir, fname), "w", encoding="utf-8") as f:
for r in lines:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
ocs = read_openclaw(os.path.join(box, "openclaw-home"))
check(len(ocs) == 4, "openclaw:活跃 + reset 孤儿 + 包装会话读回(双快照取最新;子代理默认排除)")
oc0 = next(s for s in ocs if s.source_id == "aaaa1111-0000")
st0 = oc0.turns[0].steps[0]
check(oc0.turns[0].prompt == "建个目录" and any(b["type"] == "reasoning" for b in st0.content)
and st0.tool_calls[0]["name"] == "exec" and st0.tool_results[0].content[0]["text"] == "done",
"openclaw:thinking→reasoning、toolCall/toolResult 配对挂回")
check(oc0.cwd == "C:\\w" and oc0.model == "gpt-test" and oc0.updated_at > oc0.created_at,
"openclaw:session 头 cwd/model + 时间链")
check(oc0.title == "建个目录", "openclaw 标题:无包装首问直接作标题")
check(next(s for s in ocs if s.source_id == "dddd4444-0000").title == "你好 openclaw 标题",
"openclaw 标题:剥离 Sender 元数据块 + 日期戳")
check(next(s for s in ocs if s.source_id == "eeee5555-0000").title == "第二条真提问",
"openclaw 标题:/new 控制条跳过看下一轮")
oc_all = read_openclaw(os.path.join(box, "openclaw-home"), include_subagents=True)
oc_sub = next(s for s in oc_all if s.source_id == "ffff6666-0000")
check(len(oc_all) == 5 and oc_sub.subagent and oc_sub.title == "子代理去干活",
"openclaw:子代理默认排除,include_subagents=True 纳入并带标记")
# openclaw 新版容器(≥2026.7.2):agent sqlite 正典与 jsonl 共存——正典读回 + 同 id 去重
oc_agent = os.path.join(box, "openclaw-home", "agents", "main", "agent")
os.makedirs(oc_agent)
oc_db = os.path.join(oc_agent, "openclaw-agent.sqlite")
con = sqlite3.connect(oc_db)
con.execute("CREATE TABLE transcript_events (session_id TEXT, seq INTEGER, event_json TEXT)")
rows = [(sid, seq, json.dumps(rec, ensure_ascii=False))
for sid, lines in (("aaaa1111-0000", _oc_lines("aaaa1111-0000")), # jsonl 同 id 仍在:正典胜
("cccc3333-0000", _oc_lines("cccc3333-0000"))) # 仅存正典的新会话
for seq, rec in enumerate(lines)]
con.executemany("INSERT INTO transcript_events VALUES (?,?,?)", rows)
con.commit()
con.close()
ocs2 = read_openclaw(os.path.join(box, "openclaw-home"))
check(len(ocs2) == 5, "openclaw 新版:sqlite 正典 + jsonl/快照兜底(同 id 去重不翻倍,子代理仍排除)")
oc_sql = next(s for s in ocs2 if s.source_id == "cccc3333-0000")
check(oc_sql.source_path.endswith("openclaw-agent.sqlite") and oc_sql.turns[0].prompt == "建个目录",
"openclaw 新版:仅存 sqlite 的会话读回")
oc_dup = next(s for s in ocs2 if s.source_id == "aaaa1111-0000")
check(oc_dup.source_path.endswith("openclaw-agent.sqlite") and len(oc_dup.turns) == 1,
"openclaw 新版:sqlite 与 jsonl 同 id 时以正典为准")
# cursor / trae:cursorDiskKV(composerData 头 + bubbleId 消息,键前缀关联)
from agentsync.readers import read_cursor, read_trae
def _kv_db(path, rows):
os.makedirs(os.path.dirname(path), exist_ok=True)
con = sqlite3.connect(path)
con.execute("CREATE TABLE cursorDiskKV (key TEXT PRIMARY KEY, value TEXT)")
con.executemany("INSERT INTO cursorDiskKV VALUES (?,?)", [(k, json.dumps(v, ensure_ascii=False)) for k, v in rows])
con.commit()
con.close()
def _comp(cid, created, archived=False):
return (f"composerData:{cid}", {"composerId": cid, "createdAt": created, "isArchived": archived})
def _bub(cid, bid, btype, text, ts, tool=None, ws=None):
v = {"type": btype, "text": text, "createdAt": ts}
if tool: v["toolFormerData"] = tool
if ws: v["workspaceUris"] = [ws]
return (f"bubbleId:{cid}:{bid}", v)
cur_db = os.path.join(box, "cursor-home", "state.vscdb")