lingshu-skill 5.32.0 → 5.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4281 -4173
- package/README.md +1584 -1577
- package/SKILL-lite.md +59 -59
- package/SKILL-tiny.md +38 -38
- package/SKILL.md +356 -317
- package/assets/panel.html +6753 -5698
- package/cordis-plugin/lingshu-cron/plugin.js +1455 -1417
- package/cordis-plugin/lingshu-startup/context-fold.js +170 -0
- package/cordis-plugin/lingshu-startup/context-pressure.js +16 -0
- package/cordis-plugin/lingshu-startup/context-snapshot.js +176 -0
- package/cordis-plugin/lingshu-startup/plugin.js +499 -467
- package/docs/audit_notes//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
- package/docs/audit_notes//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
- package/docs/audit_notes//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
- package/docs/commands.md +278 -247
- package/docs/mechanics.md +610 -610
- package/docs//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
- package/docs//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
- package/package.json +52 -52
- package/scripts/_scratch/_tmp_backup_race.py +70 -0
- package/scripts/_scratch/_tmp_cleanup_move.py +34 -0
- package/scripts/_scratch/_tmp_count_kinds.py +25 -0
- package/scripts/_scratch/_tmp_diag_paths.py +48 -0
- package/scripts/_scratch/_tmp_facts.py +63 -0
- package/scripts/_scratch/_tmp_find_copies.py +31 -0
- package/scripts/_scratch/_tmp_find_pin.py +29 -0
- package/scripts/_scratch/_tmp_fix_pin.py +36 -0
- package/scripts/_scratch/_tmp_fold_fixture.py +55 -0
- package/scripts/_scratch/_tmp_fold_test.mjs +81 -0
- package/scripts/_scratch/_tmp_inject_secs.py +30 -0
- package/scripts/_scratch/_tmp_kb_balance.py +159 -0
- package/scripts/_scratch/_tmp_lines.py +15 -0
- package/scripts/_scratch/_tmp_market_probe.py +13 -0
- package/scripts/_scratch/_tmp_move_partial.py +16 -0
- package/scripts/_scratch/_tmp_patch_b3.py +41 -0
- package/scripts/_scratch/_tmp_patch_b5.py +62 -0
- package/scripts/_scratch/_tmp_patch_crash_excl.py +24 -0
- package/scripts/_scratch/_tmp_patch_handoff.py +21 -0
- package/scripts/_scratch/_tmp_patch_ps1.py +25 -0
- package/scripts/_scratch/_tmp_patch_stat.py +27 -0
- package/scripts/_scratch/_tmp_patch_todo.py +25 -0
- package/scripts/_scratch/_tmp_patch_todo2.py +64 -0
- package/scripts/_scratch/_tmp_probe_session.py +51 -0
- package/scripts/_scratch/_tmp_style_probe.py +40 -0
- package/scripts/_scratch/_tmp_write_note.py +139 -0
- package/scripts/_scratch/_/346/235/245/346/272/220/350/256/260/345/275/225.txt +1 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction-basic__lib__index.js +1044 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction-tool-result-pruner__lib__index.js +194 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction__lib__index.js +175 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction__lib__types__tool-pairing.js +97 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__image-offload.js +47 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__index.js +40 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__project-message.js +37 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__brand.js +9 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__checkpoint.js +36 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__types.js +10 -0
- package/scripts/_scratch/commit_msg_occ.txt +16 -0
- package/scripts/_scratch/commit_msg_struct.txt +16 -0
- package/scripts/_scratch/v5.34_changelog.txt +36 -0
- package/scripts/_sync_trae_cn.py +102 -34
- package/scripts/_tmp_add_s10.py +54 -0
- package/scripts/_tmp_add_s11.py +61 -0
- package/scripts/_tmp_add_s12.py +66 -0
- package/scripts/_tmp_add_s13.py +69 -0
- package/scripts/_tmp_add_s14.py +80 -0
- package/scripts/_tmp_add_s9.py +68 -0
- package/scripts/_tmp_cache_load.py +82 -0
- package/scripts/_tmp_clean_market.py +40 -0
- package/scripts/_tmp_clean_pruned.py +81 -0
- package/scripts/_tmp_cleanup_docs.py +39 -0
- package/scripts/_tmp_cmp_ranker.py +17 -0
- package/scripts/_tmp_dolater_note.py +35 -0
- package/scripts/_tmp_dust_why.py +27 -0
- package/scripts/_tmp_explicit_import.py +40 -0
- package/scripts/_tmp_extract_compaction.py +35 -0
- package/scripts/_tmp_extract_compaction2.py +63 -0
- package/scripts/_tmp_extract_compaction3.py +51 -0
- package/scripts/_tmp_extract_compaction4.py +54 -0
- package/scripts/_tmp_finalize_s14.py +39 -0
- package/scripts/_tmp_find_compaction.py +43 -0
- package/scripts/_tmp_fix_b4.py +22 -0
- package/scripts/_tmp_fix_cli76.py +26 -0
- package/scripts/_tmp_fix_docs.py +38 -0
- package/scripts/_tmp_fix_docs_b.py +46 -0
- package/scripts/_tmp_fix_docs_b2.py +22 -0
- package/scripts/_tmp_fix_i3.py +23 -0
- package/scripts/_tmp_fix_s10.py +83 -0
- package/scripts/_tmp_fix_s11.py +14 -0
- package/scripts/_tmp_fix_s9_status.py +19 -0
- package/scripts/_tmp_fix_shadow_sim.py +37 -0
- package/scripts/_tmp_fix_traits_value.py +41 -0
- package/scripts/_tmp_import_idem.py +106 -0
- package/scripts/_tmp_log_ack.py +45 -0
- package/scripts/_tmp_mark_batch.py +28 -0
- package/scripts/_tmp_mark_batch2.py +32 -0
- package/scripts/_tmp_mark_dolater.py +26 -0
- package/scripts/_tmp_mark_dolater2.py +31 -0
- package/scripts/_tmp_move_self.py +16 -0
- package/scripts/_tmp_occ_cli.py +22 -0
- package/scripts/_tmp_occ_link.py +108 -0
- package/scripts/_tmp_optimize_recall.py +54 -0
- package/scripts/_tmp_panel_audit.py +26 -0
- package/scripts/_tmp_patch_batch3.py +65 -0
- package/scripts/_tmp_patch_rrf.py +46 -0
- package/scripts/_tmp_patch_s2s3.py +80 -0
- package/scripts/_tmp_patch_s4.py +39 -0
- package/scripts/_tmp_patch_s7.py +43 -0
- package/scripts/_tmp_patch_s8.py +91 -0
- package/scripts/_tmp_patch_skill.py +17 -0
- package/scripts/_tmp_release_guard.py +57 -0
- package/scripts/_tmp_rerank_breaker.py +62 -0
- package/scripts/_tmp_s16.py +41 -0
- package/scripts/_tmp_scan_asar.py +41 -0
- package/scripts/_tmp_scan_asar2.py +37 -0
- package/scripts/_tmp_struct_docs.py +49 -0
- package/scripts/_tmp_sum_fallback.py +42 -0
- package/scripts/_tmp_sweep.py +81 -0
- package/scripts/_tmp_sync_check.py +69 -0
- package/scripts/_tmp_sync_tail.py +39 -0
- package/scripts/_tmp_todo_clean.py +67 -0
- package/scripts/_tmp_verify_copy.py +17 -0
- package/scripts/_tmp_wire_extras.py +93 -0
- package/scripts/_tmp_wire_hsum.py +34 -0
- package/scripts/_tmp_wire_occ_b5.py +40 -0
- package/scripts/_tmp_wire_ranker.py +13 -0
- package/scripts/_tmp_wire_shadow_timeline.py +45 -0
- package/scripts/anchor_retention.py +68 -0
- package/scripts/app_context.py +1160 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +38 -22
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +4281 -4173
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1584 -1577
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +356 -317
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +6753 -5698
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +278 -247
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -610
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +102 -34
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s10.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s11.py +61 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s12.py +66 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s13.py +69 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s14.py +80 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s9.py +68 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cache_load.py +82 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_market.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_pruned.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cleanup_docs.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cmp_ranker.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dolater_note.py +35 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dust_why.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_explicit_import.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction.py +35 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction2.py +63 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction3.py +51 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction4.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_finalize_s14.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_find_compaction.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_b4.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_cli76.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs.py +38 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b2.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_i3.py +23 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s10.py +83 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s11.py +14 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s9_status.py +19 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_shadow_sim.py +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_traits_value.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_import_idem.py +106 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_log_ack.py +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch.py +28 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch2.py +32 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater2.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_move_self.py +16 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_cli.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_link.py +108 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_optimize_recall.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_panel_audit.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_batch3.py +65 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_rrf.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s2s3.py +80 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s4.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s7.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s8.py +91 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_skill.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_release_guard.py +57 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_rerank_breaker.py +62 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_s16.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar2.py +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_struct_docs.py +49 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sum_fallback.py +42 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sweep.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_check.py +69 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_tail.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_todo_clean.py +67 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_verify_copy.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_extras.py +93 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_hsum.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_occ_b5.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_ranker.py +13 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_shadow_timeline.py +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/anchor_retention.py +68 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/app_context.py +1160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bigfive.py +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_docs.py +191 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +940 -88
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2468 -2406
- package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +5 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/delivery.py +112 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +41 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +202 -23
- package/scripts/astrbot_plugin_lingshu/engine/scripts/gap_memory.py +186 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +72 -8
- package/scripts/astrbot_plugin_lingshu/engine/scripts/hsum.py +206 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +92 -7
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +533 -60
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory_extras.py +200 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/occ.py +190 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +232 -142
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2498 -2349
- package/scripts/astrbot_plugin_lingshu/engine/scripts/prepublish_tests.py +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +326 -287
- package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +181 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +832 -764
- package/scripts/astrbot_plugin_lingshu/engine/scripts/shadow_memory.py +173 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/style_check.py +220 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +343 -252
- package/scripts/astrbot_plugin_lingshu/engine/scripts/timeline.py +118 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/watchdog.py +110 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +125 -0
- package/scripts/bigfive.py +90 -0
- package/scripts/brain.py +1 -1
- package/scripts/check_docs.py +191 -0
- package/scripts/cli.py +940 -88
- package/scripts/core.py +2468 -2406
- package/scripts/coverage_report.py +5 -0
- package/scripts/delivery.py +112 -0
- package/scripts/dream.py +41 -3
- package/scripts/emotion.py +202 -23
- package/scripts/gap_memory.py +186 -0
- package/scripts/growth.py +72 -8
- package/scripts/hsum.py +206 -0
- package/scripts/mem_score.py +92 -7
- package/scripts/memory.py +533 -60
- package/scripts/memory_extras.py +200 -0
- package/scripts/occ.py +190 -0
- package/scripts/panel_server.py +232 -142
- package/scripts/persona.py +2498 -2349
- package/scripts/prepublish_tests.py +90 -0
- package/scripts/release.py +326 -287
- package/scripts/rss_ingest.py +181 -0
- package/scripts/run_tests.py +13 -0
- package/scripts/session_import.py +832 -764
- package/scripts/shadow_memory.py +173 -0
- package/scripts/style_check.py +220 -0
- package/scripts/summarizer.py +343 -252
- package/scripts/timeline.py +118 -0
- package/scripts/update_dsh_copy.ps1 +110 -107
- package/scripts/watchdog.py +110 -0
- package/scripts/web_research.py +125 -0
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -370
|
@@ -1,764 +1,832 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""附录 B · P1:DSH 会话日志导入(多平台入口 + 工作区隔离)。
|
|
4
|
-
|
|
5
|
-
DSH 把一场会话写成:
|
|
6
|
-
<sessions>/<工作区编码目录>/<会话目录>/session.v4.jsonl.zstd
|
|
7
|
-
|
|
8
|
-
其中有三个必须处理的现实约束:
|
|
9
|
-
1. 文件是**多帧拼接**的 zstd 容器:每行/每批事件一个独立帧。Node 的
|
|
10
|
-
`zlib.zstdDecompressSync` 一次只解第一帧,直接解整个文件只会拿到
|
|
11
|
-
313 字节的 header(本机实测)。所以 Node 侧先做「帧结构扫描」再逐帧解压
|
|
12
|
-
(与 DSH 自己 `scanZstdFrames` 的结构扫描逻辑等价),把明文流式写进临时文件。
|
|
13
|
-
2. 本机系统 Python **没有 zstandard 模块**,因此不把 Python 当解码器。
|
|
14
|
-
3. 会话事件是 `{"type": "...", "time": 毫秒, "data": {...}}`:
|
|
15
|
-
只导入 `user/message` / `assistant/message` 里的 text 片段(role/content/ts),
|
|
16
|
-
`reasoning`、`tool-call`、`tool/result`、`system/message`、`command/*` 等
|
|
17
|
-
非对话条目一律跳过;`user/message` 里 `source.kind` 不是 `user` 的注入块
|
|
18
|
-
(runtime-context / system-reminder)也算系统事件,跳过。
|
|
19
|
-
|
|
20
|
-
解码优先级(都不静默降级):
|
|
21
|
-
Node 22+(先探测 `node -e "require('node:zlib').zstdDecompressSync"`)
|
|
22
|
-
→ 系统 `zstd -d` 命令
|
|
23
|
-
→ 抛 DecoderUnavailable(「需要 Node 22+ 或 zstd 命令」)。
|
|
24
|
-
|
|
25
|
-
导入:`session_rag.ingest_messages(rows, session=会话id, platform="dsh",
|
|
26
|
-
workspace=工作区)`,按内容哈希幂等;解压后的临时文件逐行流式解析,每 500 条
|
|
27
|
-
批量入库,内存不随文件大小增长(8MB 压缩 / 1 万条事件级别实测可用)。
|
|
28
|
-
|
|
29
|
-
CLI:
|
|
30
|
-
python scripts/session_import.py [--sessions-dir PATH] [--limit N]
|
|
31
|
-
[--workspace 名称] [--dry-run] [--json]
|
|
32
|
-
"""
|
|
33
|
-
from __future__ import annotations
|
|
34
|
-
|
|
35
|
-
import argparse
|
|
36
|
-
import
|
|
37
|
-
import
|
|
38
|
-
import
|
|
39
|
-
import
|
|
40
|
-
import
|
|
41
|
-
import
|
|
42
|
-
import
|
|
43
|
-
import
|
|
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
|
-
const
|
|
72
|
-
const
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
off
|
|
85
|
-
if (
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
const
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
if (
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
let
|
|
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
|
-
if
|
|
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
|
-
if
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
return Decoder("node",
|
|
277
|
-
|
|
278
|
-
if
|
|
279
|
-
return Decoder("
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
"
|
|
283
|
-
|
|
284
|
-
"zstd
|
|
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
|
-
line =
|
|
424
|
-
if not line:
|
|
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
|
-
report["
|
|
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
|
-
if
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
if
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""附录 B · P1:DSH 会话日志导入(多平台入口 + 工作区隔离)。
|
|
4
|
+
|
|
5
|
+
DSH 把一场会话写成:
|
|
6
|
+
<sessions>/<工作区编码目录>/<会话目录>/session.v4.jsonl.zstd
|
|
7
|
+
|
|
8
|
+
其中有三个必须处理的现实约束:
|
|
9
|
+
1. 文件是**多帧拼接**的 zstd 容器:每行/每批事件一个独立帧。Node 的
|
|
10
|
+
`zlib.zstdDecompressSync` 一次只解第一帧,直接解整个文件只会拿到
|
|
11
|
+
313 字节的 header(本机实测)。所以 Node 侧先做「帧结构扫描」再逐帧解压
|
|
12
|
+
(与 DSH 自己 `scanZstdFrames` 的结构扫描逻辑等价),把明文流式写进临时文件。
|
|
13
|
+
2. 本机系统 Python **没有 zstandard 模块**,因此不把 Python 当解码器。
|
|
14
|
+
3. 会话事件是 `{"type": "...", "time": 毫秒, "data": {...}}`:
|
|
15
|
+
只导入 `user/message` / `assistant/message` 里的 text 片段(role/content/ts),
|
|
16
|
+
`reasoning`、`tool-call`、`tool/result`、`system/message`、`command/*` 等
|
|
17
|
+
非对话条目一律跳过;`user/message` 里 `source.kind` 不是 `user` 的注入块
|
|
18
|
+
(runtime-context / system-reminder)也算系统事件,跳过。
|
|
19
|
+
|
|
20
|
+
解码优先级(都不静默降级):
|
|
21
|
+
Node 22+(先探测 `node -e "require('node:zlib').zstdDecompressSync"`)
|
|
22
|
+
→ 系统 `zstd -d` 命令
|
|
23
|
+
→ 抛 DecoderUnavailable(「需要 Node 22+ 或 zstd 命令」)。
|
|
24
|
+
|
|
25
|
+
导入:`session_rag.ingest_messages(rows, session=会话id, platform="dsh",
|
|
26
|
+
workspace=工作区)`,按内容哈希幂等;解压后的临时文件逐行流式解析,每 500 条
|
|
27
|
+
批量入库,内存不随文件大小增长(8MB 压缩 / 1 万条事件级别实测可用)。
|
|
28
|
+
|
|
29
|
+
CLI:
|
|
30
|
+
python scripts/session_import.py [--sessions-dir PATH] [--limit N]
|
|
31
|
+
[--workspace 名称] [--dry-run] [--json]
|
|
32
|
+
"""
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import argparse
|
|
36
|
+
import hashlib
|
|
37
|
+
import brain
|
|
38
|
+
import core
|
|
39
|
+
import json
|
|
40
|
+
import os
|
|
41
|
+
import re
|
|
42
|
+
import shutil
|
|
43
|
+
import subprocess
|
|
44
|
+
import sys
|
|
45
|
+
import tempfile
|
|
46
|
+
import time
|
|
47
|
+
from dataclasses import dataclass
|
|
48
|
+
from pathlib import Path
|
|
49
|
+
|
|
50
|
+
HERE = Path(__file__).resolve().parent
|
|
51
|
+
if str(HERE) not in sys.path: # 允许 `python scripts/session_import.py` 与 tests 直接 import
|
|
52
|
+
sys.path.insert(0, str(HERE))
|
|
53
|
+
|
|
54
|
+
import session_rag # noqa: E402
|
|
55
|
+
|
|
56
|
+
PLATFORM = "dsh"
|
|
57
|
+
BATCH_SIZE = 500
|
|
58
|
+
DEFAULT_TIMEOUT = 600.0 # 单文件解码的最长等待(秒)
|
|
59
|
+
|
|
60
|
+
# 只认 DSH 会话日志:session.v4.jsonl.zstd / session.jsonl / 未来版本号
|
|
61
|
+
_SESSION_LOG_RE = re.compile(r"^session(?:\.v\d+)?\.jsonl(\.zstd)?$", re.IGNORECASE)
|
|
62
|
+
|
|
63
|
+
_NODE_PROBE = (
|
|
64
|
+
"process.exit(typeof require('node:zlib').zstdDecompressSync === 'function' ? 0 : 1)"
|
|
65
|
+
)
|
|
66
|
+
_NODE_VERSION = "process.stdout.write(process.version)"
|
|
67
|
+
|
|
68
|
+
# 多帧 zstd 解码器(Node 22+)。先做与 DSH 相同的帧结构扫描,再逐帧解压并
|
|
69
|
+
# 立刻写盘 —— 不把整份明文同时留在内存里。
|
|
70
|
+
_NODE_DECODE_JS = r"""
|
|
71
|
+
const fs = require('node:fs')
|
|
72
|
+
const zlib = require('node:zlib')
|
|
73
|
+
const src = process.argv[2]
|
|
74
|
+
const dst = process.argv[3]
|
|
75
|
+
const MAGIC = 0xFD2FB528
|
|
76
|
+
const buf = fs.readFileSync(src)
|
|
77
|
+
|
|
78
|
+
// 返回完整帧的结束偏移;遇到文件尾部的不完整帧返回 -1(live 会话正在追加)。
|
|
79
|
+
function frameEnd(buffer, start) {
|
|
80
|
+
if (buffer.length - start < 4) return -1
|
|
81
|
+
if (buffer.readUInt32LE(start) !== MAGIC) {
|
|
82
|
+
throw new Error('corrupt Zstandard session log: invalid frame magic at byte ' + start)
|
|
83
|
+
}
|
|
84
|
+
let off = start + 4
|
|
85
|
+
if (off === buffer.length) return -1
|
|
86
|
+
const descriptor = buffer.readUInt8(off)
|
|
87
|
+
off += 1
|
|
88
|
+
if ((descriptor & 0x18) !== 0) {
|
|
89
|
+
throw new Error('corrupt Zstandard session log: reserved frame-header bit at byte ' + (off - 1))
|
|
90
|
+
}
|
|
91
|
+
const contentSizeFlag = descriptor >>> 6
|
|
92
|
+
const singleSegment = (descriptor & 0x20) !== 0
|
|
93
|
+
const checksum = (descriptor & 0x04) !== 0
|
|
94
|
+
const dictionaryFlag = descriptor & 0x03
|
|
95
|
+
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
|
|
96
|
+
const contentSizeBytes = contentSizeFlag === 0
|
|
97
|
+
? (singleSegment ? 1 : 0)
|
|
98
|
+
: (1 << contentSizeFlag)
|
|
99
|
+
const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
|
|
100
|
+
if (buffer.length - off < remainingHeaderBytes) return -1
|
|
101
|
+
off += remainingHeaderBytes
|
|
102
|
+
for (;;) {
|
|
103
|
+
if (buffer.length - off < 3) return -1
|
|
104
|
+
const blockHeader = buffer.readUIntLE(off, 3)
|
|
105
|
+
off += 3
|
|
106
|
+
const lastBlock = (blockHeader & 1) !== 0
|
|
107
|
+
const blockType = (blockHeader >>> 1) & 0x03
|
|
108
|
+
const blockSize = blockHeader >>> 3
|
|
109
|
+
if (blockType === 0x03) {
|
|
110
|
+
throw new Error('corrupt Zstandard session log: reserved block type at byte ' + (off - 3))
|
|
111
|
+
}
|
|
112
|
+
const payloadBytes = blockType === 0x01 ? 1 : blockSize
|
|
113
|
+
if (buffer.length - off < payloadBytes) return -1
|
|
114
|
+
off += payloadBytes
|
|
115
|
+
if (lastBlock) break
|
|
116
|
+
}
|
|
117
|
+
if (checksum) {
|
|
118
|
+
if (buffer.length - off < 4) return -1
|
|
119
|
+
off += 4
|
|
120
|
+
}
|
|
121
|
+
return off
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const fd = fs.openSync(dst, 'w')
|
|
125
|
+
let frames = 0
|
|
126
|
+
let plainBytes = 0
|
|
127
|
+
let tornBytes = 0
|
|
128
|
+
let offset = 0
|
|
129
|
+
try {
|
|
130
|
+
while (offset < buf.length) {
|
|
131
|
+
const end = frameEnd(buf, offset)
|
|
132
|
+
if (end < 0) {
|
|
133
|
+
tornBytes = buf.length - offset
|
|
134
|
+
break
|
|
135
|
+
}
|
|
136
|
+
const plain = zlib.zstdDecompressSync(buf.subarray(offset, end))
|
|
137
|
+
fs.writeSync(fd, plain)
|
|
138
|
+
plainBytes += plain.length
|
|
139
|
+
frames += 1
|
|
140
|
+
offset = end
|
|
141
|
+
}
|
|
142
|
+
} finally {
|
|
143
|
+
fs.closeSync(fd)
|
|
144
|
+
}
|
|
145
|
+
process.stdout.write(JSON.stringify({
|
|
146
|
+
frames: frames,
|
|
147
|
+
plainBytes: plainBytes,
|
|
148
|
+
tornBytes: tornBytes,
|
|
149
|
+
compressedBytes: buf.length,
|
|
150
|
+
}))
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class DecoderUnavailable(RuntimeError):
|
|
155
|
+
"""本机既没有可解 zstd 的 Node(22+),也没有 zstd 命令。"""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@dataclass(frozen=True)
|
|
159
|
+
class Decoder:
|
|
160
|
+
"""已探测通过的 zstd 解码后端。"""
|
|
161
|
+
|
|
162
|
+
backend: str # "node" | "zstd"
|
|
163
|
+
exe: str
|
|
164
|
+
version: str = ""
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass(frozen=True)
|
|
168
|
+
class SessionLog:
|
|
169
|
+
"""一个待导入的 DSH 会话日志文件。"""
|
|
170
|
+
|
|
171
|
+
path: Path
|
|
172
|
+
workspace_dir: str # sessions/<工作区编码目录>/
|
|
173
|
+
session_dir: str # sessions/<工作区编码目录>/<会话目录>/
|
|
174
|
+
compressed: bool
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def default_sessions_dir() -> Path:
|
|
178
|
+
"""DSH 会话根目录:默认 ``~/.dsh/sessions``(尊重 DSH_HOME 自定义安装)。"""
|
|
179
|
+
env_home = str(os.environ.get("DSH_HOME") or "").strip()
|
|
180
|
+
base = Path(env_home) if env_home else (Path.home() / ".dsh")
|
|
181
|
+
return base / "sessions"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ---------------------------------------------------------------- 解码器探测
|
|
185
|
+
|
|
186
|
+
def _run_quiet(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
|
|
187
|
+
return subprocess.run(cmd, capture_output=True, **kwargs)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _node_has_zstd(exe: str, timeout: float = 20.0) -> bool:
|
|
191
|
+
"""探测指定的 node 是否带 node:zlib zstd(Node 22+ / 23.8+ 才有)。"""
|
|
192
|
+
try:
|
|
193
|
+
rep = _run_quiet([exe, "-e", _NODE_PROBE], timeout=timeout)
|
|
194
|
+
except (OSError, subprocess.SubprocessError):
|
|
195
|
+
return False
|
|
196
|
+
return rep.returncode == 0
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _node_version(exe: str) -> str:
|
|
200
|
+
try:
|
|
201
|
+
rep = _run_quiet([exe, "-e", _NODE_VERSION], timeout=20.0)
|
|
202
|
+
except (OSError, subprocess.SubprocessError):
|
|
203
|
+
return ""
|
|
204
|
+
if rep.returncode != 0:
|
|
205
|
+
return ""
|
|
206
|
+
return rep.stdout.decode("utf-8", "replace").strip()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _dsh_runtime_node_candidates() -> list[str]:
|
|
210
|
+
"""DSH 自带的 Node 运行时(PATH 上没有 node 或不支持 zstd 时兜底)。"""
|
|
211
|
+
roots: list[Path] = []
|
|
212
|
+
env_home = str(os.environ.get("DSH_HOME") or "").strip()
|
|
213
|
+
if env_home:
|
|
214
|
+
roots.append(Path(env_home))
|
|
215
|
+
roots.append(Path.home() / ".dsh")
|
|
216
|
+
out: list[str] = []
|
|
217
|
+
seen: set[str] = set()
|
|
218
|
+
for root in roots:
|
|
219
|
+
try:
|
|
220
|
+
runtimes = sorted((root / "dsh-runtimes").glob("*/dependencies/node/bin"))
|
|
221
|
+
except OSError:
|
|
222
|
+
continue
|
|
223
|
+
for bindir in runtimes:
|
|
224
|
+
for name in ("node.exe", "node"):
|
|
225
|
+
cand = bindir / name
|
|
226
|
+
key = os.path.normcase(str(cand))
|
|
227
|
+
if key in seen:
|
|
228
|
+
continue
|
|
229
|
+
seen.add(key)
|
|
230
|
+
if cand.is_file():
|
|
231
|
+
out.append(str(cand))
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def find_node_exe() -> str | None:
|
|
236
|
+
"""返回第一个「node 能解 zstd」的可执行文件;没有则 None。
|
|
237
|
+
|
|
238
|
+
查找顺序:LINGSHU_NODE 环境变量 → PATH 上的 node → DSH 自带运行时。
|
|
239
|
+
每个候选都真跑一次 ``node -e`` 探测,不只看版本号猜。
|
|
240
|
+
"""
|
|
241
|
+
candidates: list[str] = []
|
|
242
|
+
env_node = str(os.environ.get("LINGSHU_NODE") or "").strip()
|
|
243
|
+
if env_node:
|
|
244
|
+
candidates.append(env_node)
|
|
245
|
+
for name in ("node", "node.exe"):
|
|
246
|
+
found = shutil.which(name)
|
|
247
|
+
if found:
|
|
248
|
+
candidates.append(found)
|
|
249
|
+
candidates.extend(_dsh_runtime_node_candidates())
|
|
250
|
+
seen: set[str] = set()
|
|
251
|
+
for cand in candidates:
|
|
252
|
+
key = os.path.normcase(str(cand))
|
|
253
|
+
if not key or key in seen:
|
|
254
|
+
continue
|
|
255
|
+
seen.add(key)
|
|
256
|
+
if _node_has_zstd(str(cand)):
|
|
257
|
+
return str(cand)
|
|
258
|
+
return None
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def find_zstd_exe() -> str | None:
|
|
262
|
+
"""系统 zstd CLI(次选解码器)。没有则 None。"""
|
|
263
|
+
for name in ("zstd", "zstd.exe"):
|
|
264
|
+
found = shutil.which(name)
|
|
265
|
+
if found:
|
|
266
|
+
return found
|
|
267
|
+
return None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def detect_decoder(*, node_exe: str | None = None) -> Decoder:
|
|
271
|
+
"""确定 zstd 解码后端;两者都没有时抛 DecoderUnavailable(绝不静默)。"""
|
|
272
|
+
if node_exe:
|
|
273
|
+
if not _node_has_zstd(str(node_exe)):
|
|
274
|
+
raise DecoderUnavailable(
|
|
275
|
+
f"指定的 Node 不支持 node:zlib zstd:{node_exe}(需要 Node 22+)")
|
|
276
|
+
return Decoder("node", str(node_exe), _node_version(str(node_exe)))
|
|
277
|
+
node = find_node_exe()
|
|
278
|
+
if node:
|
|
279
|
+
return Decoder("node", node, _node_version(node))
|
|
280
|
+
zstd = find_zstd_exe()
|
|
281
|
+
if zstd:
|
|
282
|
+
return Decoder("zstd", zstd, "")
|
|
283
|
+
raise DecoderUnavailable(
|
|
284
|
+
"需要 Node 22+ 或 zstd 命令:本机既没有能解 zstd 的 Node"
|
|
285
|
+
"(node:zlib.zstdDecompressSync 探测失败,PATH 与 DSH 自带运行时都不行),"
|
|
286
|
+
"也没有 zstd 命令。系统 Python 没有 zstandard 模块,安装 Node 22+ 或 "
|
|
287
|
+
"zstd 后重试;不会静默跳过或假装导入成功。")
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
# ---------------------------------------------------------------- 会话发现
|
|
291
|
+
|
|
292
|
+
def discover_sessions(sessions_dir=None, *, limit: int | None = None) -> list[SessionLog]:
|
|
293
|
+
"""遍历 <sessions>/<工作区>/<会话>/session*.jsonl[.zstd],按修改时间倒序。"""
|
|
294
|
+
root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
|
|
295
|
+
if not root.is_dir():
|
|
296
|
+
raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
|
|
297
|
+
logs: list[SessionLog] = []
|
|
298
|
+
try:
|
|
299
|
+
projects = sorted(root.iterdir(), key=lambda p: p.name.lower())
|
|
300
|
+
except OSError as exc:
|
|
301
|
+
raise RuntimeError(f"无法读取会话目录 {root}:{exc}") from exc
|
|
302
|
+
for project in projects:
|
|
303
|
+
if not project.is_dir():
|
|
304
|
+
continue
|
|
305
|
+
try:
|
|
306
|
+
sessions = sorted(project.iterdir(), key=lambda p: p.name.lower())
|
|
307
|
+
except OSError:
|
|
308
|
+
continue
|
|
309
|
+
for sess in sessions:
|
|
310
|
+
if not sess.is_dir():
|
|
311
|
+
continue
|
|
312
|
+
try:
|
|
313
|
+
entries = sorted(sess.iterdir(), key=lambda p: p.name.lower())
|
|
314
|
+
except OSError:
|
|
315
|
+
continue
|
|
316
|
+
for f in entries:
|
|
317
|
+
match = _SESSION_LOG_RE.match(f.name)
|
|
318
|
+
if not match or not f.is_file():
|
|
319
|
+
continue
|
|
320
|
+
logs.append(SessionLog(path=f, workspace_dir=project.name,
|
|
321
|
+
session_dir=sess.name,
|
|
322
|
+
compressed=bool(match.group(1))))
|
|
323
|
+
logs.sort(key=lambda x: _mtime(x.path), reverse=True)
|
|
324
|
+
if limit is not None and int(limit) > 0:
|
|
325
|
+
logs = logs[: int(limit)]
|
|
326
|
+
return logs
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _mtime(path: Path) -> float:
|
|
330
|
+
try:
|
|
331
|
+
return path.stat().st_mtime
|
|
332
|
+
except OSError:
|
|
333
|
+
return 0.0
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
# ---------------------------------------------------------------- zstd 解码
|
|
337
|
+
|
|
338
|
+
def decode_session_file(src, dst, decoder: Decoder) -> dict:
|
|
339
|
+
"""把多帧 zstd 会话日志解成明文 JSONL,写进 dst 临时文件;返回解码元数据。
|
|
340
|
+
|
|
341
|
+
返回统一 snake_case 键:backend/exe/frames/plain_bytes/compressed_bytes/
|
|
342
|
+
torn_bytes(torn_bytes = 文件尾部不完整的 live 帧字节数,已忽略)。
|
|
343
|
+
"""
|
|
344
|
+
src = Path(src)
|
|
345
|
+
dst = Path(dst)
|
|
346
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
347
|
+
raw = _decode_with_node(src, dst, decoder.exe) if decoder.backend == "node" \
|
|
348
|
+
else _decode_with_zstd_cli(src, dst, decoder.exe)
|
|
349
|
+
meta = {
|
|
350
|
+
"backend": str(raw.get("backend") or decoder.backend),
|
|
351
|
+
"exe": str(raw.get("exe") or decoder.exe),
|
|
352
|
+
"frames": raw.get("frames"),
|
|
353
|
+
"plain_bytes": int(raw.get("plainBytes") if raw.get("plainBytes") is not None
|
|
354
|
+
else raw.get("plain_bytes") or 0),
|
|
355
|
+
"compressed_bytes": int(raw.get("compressedBytes")
|
|
356
|
+
if raw.get("compressedBytes") is not None
|
|
357
|
+
else raw.get("compressed_bytes") or 0),
|
|
358
|
+
"torn_bytes": int(raw.get("tornBytes") if raw.get("tornBytes") is not None
|
|
359
|
+
else raw.get("torn_bytes") or 0),
|
|
360
|
+
}
|
|
361
|
+
if raw.get("warning"):
|
|
362
|
+
meta["warning"] = raw["warning"]
|
|
363
|
+
return meta
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _decode_with_node(src: Path, dst: Path, node_exe: str) -> dict:
|
|
367
|
+
with tempfile.TemporaryDirectory(prefix="lingshu-zstd-js-") as td:
|
|
368
|
+
script = Path(td) / "decode_session.js"
|
|
369
|
+
script.write_text(_NODE_DECODE_JS, encoding="utf-8")
|
|
370
|
+
try:
|
|
371
|
+
rep = subprocess.run([node_exe, str(script), str(src), str(dst)],
|
|
372
|
+
capture_output=True, timeout=DEFAULT_TIMEOUT)
|
|
373
|
+
except subprocess.TimeoutExpired as exc:
|
|
374
|
+
raise RuntimeError(f"Node 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
|
|
375
|
+
except OSError as exc:
|
|
376
|
+
raise RuntimeError(f"Node 启动失败({node_exe}):{exc}") from exc
|
|
377
|
+
if rep.returncode != 0:
|
|
378
|
+
err = rep.stderr.decode("utf-8", "replace").strip()
|
|
379
|
+
raise RuntimeError(f"Node 解压失败({src}):{err[:500] or f'rc={rep.returncode}'}")
|
|
380
|
+
try:
|
|
381
|
+
meta = json.loads(rep.stdout.decode("utf-8", "replace") or "{}")
|
|
382
|
+
except ValueError:
|
|
383
|
+
meta = {}
|
|
384
|
+
meta.setdefault("plainBytes", dst.stat().st_size if dst.exists() else 0)
|
|
385
|
+
return meta
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _decode_with_zstd_cli(src: Path, dst: Path, zstd_exe: str) -> dict:
|
|
389
|
+
try:
|
|
390
|
+
with open(dst, "wb") as out:
|
|
391
|
+
rep = subprocess.run([zstd_exe, "-d", "-q", "-c", str(src)],
|
|
392
|
+
stdout=out, stderr=subprocess.PIPE,
|
|
393
|
+
timeout=DEFAULT_TIMEOUT)
|
|
394
|
+
except subprocess.TimeoutExpired as exc:
|
|
395
|
+
raise RuntimeError(f"zstd 解压超时(>{DEFAULT_TIMEOUT:g}s):{src}") from exc
|
|
396
|
+
except OSError as exc:
|
|
397
|
+
raise RuntimeError(f"zstd 启动失败({zstd_exe}):{exc}") from exc
|
|
398
|
+
stderr = (rep.stderr or b"").decode("utf-8", "replace").strip()
|
|
399
|
+
meta = {"frames": None, "torn_bytes": 0,
|
|
400
|
+
"plain_bytes": dst.stat().st_size if dst.exists() else 0,
|
|
401
|
+
"compressed_bytes": src.stat().st_size if src.exists() else 0}
|
|
402
|
+
if rep.returncode != 0:
|
|
403
|
+
# live 会话尾部可能是半帧:zstd CLI 会报错但仍吐出完整帧的明文。
|
|
404
|
+
# 只在明文以换行结尾(最后一帧完整)时接受,否则当失败。
|
|
405
|
+
tail = b""
|
|
406
|
+
if dst.exists() and dst.stat().st_size:
|
|
407
|
+
with open(dst, "rb") as fh:
|
|
408
|
+
fh.seek(max(0, dst.stat().st_size - 1))
|
|
409
|
+
tail = fh.read(1)
|
|
410
|
+
if not tail.endswith(b"\n"):
|
|
411
|
+
raise RuntimeError(f"zstd 解压失败({src}):{stderr[:500] or f'rc={rep.returncode}'}")
|
|
412
|
+
meta["warning"] = f"zstd 返回码 {rep.returncode},已接受以换行结尾的部分输出:{stderr[:200]}"
|
|
413
|
+
return meta
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
# ---------------------------------------------------------------- JSONL 解析
|
|
417
|
+
|
|
418
|
+
def read_session_header(jsonl_file) -> dict:
|
|
419
|
+
"""读解压后 JSONL 的第一条 ``{"type":"session"}``(格式保证是首行,最多扫 64 行)。"""
|
|
420
|
+
try:
|
|
421
|
+
with open(jsonl_file, "r", encoding="utf-8-sig", errors="replace") as fh:
|
|
422
|
+
for _ in range(64):
|
|
423
|
+
line = fh.readline()
|
|
424
|
+
if not line:
|
|
425
|
+
break
|
|
426
|
+
line = line.strip()
|
|
427
|
+
if not line:
|
|
428
|
+
continue
|
|
429
|
+
try:
|
|
430
|
+
event = json.loads(line)
|
|
431
|
+
except ValueError:
|
|
432
|
+
continue
|
|
433
|
+
if isinstance(event, dict) and event.get("type") == "session":
|
|
434
|
+
return event
|
|
435
|
+
except OSError:
|
|
436
|
+
pass
|
|
437
|
+
return {}
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _text_fragments(content) -> str:
|
|
441
|
+
"""content 可能是字符串或 block 数组:只取 text 片段(跳过 reasoning/image/tool-*)。"""
|
|
442
|
+
if isinstance(content, str):
|
|
443
|
+
return content.strip()
|
|
444
|
+
if not isinstance(content, list):
|
|
445
|
+
return ""
|
|
446
|
+
parts: list[str] = []
|
|
447
|
+
for block in content:
|
|
448
|
+
if isinstance(block, str):
|
|
449
|
+
if block.strip():
|
|
450
|
+
parts.append(block.strip())
|
|
451
|
+
elif isinstance(block, dict) and block.get("type") == "text":
|
|
452
|
+
text = block.get("text")
|
|
453
|
+
if text is not None and str(text).strip():
|
|
454
|
+
parts.append(str(text).strip())
|
|
455
|
+
return "\n".join(parts)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _event_to_row(event: dict) -> dict | None:
|
|
459
|
+
"""把一条 DSH 会话事件转成 ingest 行;非对话事件(工具/推理/系统)返回 None。"""
|
|
460
|
+
event_type = event.get("type")
|
|
461
|
+
data = event.get("data")
|
|
462
|
+
if not isinstance(data, dict):
|
|
463
|
+
data = {}
|
|
464
|
+
if event_type == "user/message":
|
|
465
|
+
source = data.get("source")
|
|
466
|
+
kind = str((source or {}).get("kind") or "") if isinstance(source, dict) else ""
|
|
467
|
+
if kind and kind != "user":
|
|
468
|
+
return None # runtime-context / system-reminder 等注入块不是用户发言
|
|
469
|
+
text = _text_fragments(data.get("content"))
|
|
470
|
+
role = "user"
|
|
471
|
+
elif event_type == "assistant/message":
|
|
472
|
+
message = data.get("message")
|
|
473
|
+
if not isinstance(message, dict):
|
|
474
|
+
message = {}
|
|
475
|
+
text = _text_fragments(message.get("content"))
|
|
476
|
+
role = "assistant"
|
|
477
|
+
else:
|
|
478
|
+
return None
|
|
479
|
+
if not text:
|
|
480
|
+
return None # 只有 reasoning / 只有 tool-call 的 assistant 轮次
|
|
481
|
+
time_ms = event.get("time")
|
|
482
|
+
ts = float(time_ms) / 1000.0 if isinstance(time_ms, (int, float)) else 0.0
|
|
483
|
+
return {"role": role, "content": text, "ts": ts}
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
# ---------------------------------------------------------------- 导入
|
|
487
|
+
|
|
488
|
+
def _workspace_matches(want, workspace: str, workspace_dir: str) -> bool:
|
|
489
|
+
"""--workspace 匹配:精确路径 / basename / 原始工作区目录名,且允许子串。"""
|
|
490
|
+
wanted = str(want or "").strip()
|
|
491
|
+
if not wanted:
|
|
492
|
+
return True
|
|
493
|
+
low = wanted.lower().rstrip("\\/")
|
|
494
|
+
names = {str(workspace or "").strip().lower().rstrip("\\/"),
|
|
495
|
+
str(workspace_dir or "").strip().lower()}
|
|
496
|
+
if workspace:
|
|
497
|
+
names.add(Path(workspace).name.lower())
|
|
498
|
+
if low in names:
|
|
499
|
+
return True
|
|
500
|
+
for name in names:
|
|
501
|
+
if name and low in name:
|
|
502
|
+
return True
|
|
503
|
+
return False
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
SEEN_FILE = ".session-import-seen.json"
|
|
507
|
+
SEEN_CAP = 50000
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _seen_path() -> Path:
|
|
511
|
+
return Path(brain.HOME) / SEEN_FILE if "brain" in globals() else Path.home() / SEEN_FILE
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def load_seen_keys() -> set:
|
|
515
|
+
"""跨批次/跨运行的导入幂等键(上次入库过的行不再进)。"""
|
|
516
|
+
try:
|
|
517
|
+
p = _seen_path()
|
|
518
|
+
if not p.is_file():
|
|
519
|
+
return set()
|
|
520
|
+
data = json.loads(p.read_text(encoding="utf-8", errors="replace") or "[]")
|
|
521
|
+
return {str(x) for x in (data or []) if x}
|
|
522
|
+
except Exception:
|
|
523
|
+
return set()
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def save_seen_keys(keys: set) -> None:
|
|
527
|
+
try:
|
|
528
|
+
p = _seen_path()
|
|
529
|
+
tmp = p.with_name(p.name + ".tmp")
|
|
530
|
+
kept = sorted(keys)[-SEEN_CAP:]
|
|
531
|
+
tmp.write_text(json.dumps(kept, ensure_ascii=False), encoding="utf-8")
|
|
532
|
+
os.replace(tmp, p) # 原子替换,避免写一半被读到
|
|
533
|
+
except Exception:
|
|
534
|
+
pass
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def row_key(session_id: str, row: dict, source: str = "") -> str:
|
|
538
|
+
"""一行的幂等键:**源文件** + 会话 + 行内容指纹。
|
|
539
|
+
|
|
540
|
+
为什么要带源文件:去重语义是"重跑同一次导出不重复入库",
|
|
541
|
+
不是"两个不同文件里内容相同的行只留一条"——后者会把合法数据吞掉(实测两个
|
|
542
|
+
测试夹具同内容不同文件,被误判成重复)。行结构变了也不会误判。
|
|
543
|
+
"""
|
|
544
|
+
try:
|
|
545
|
+
basis = f"{source}|{session_id}|" + json.dumps(row, ensure_ascii=False, sort_keys=True)
|
|
546
|
+
except Exception:
|
|
547
|
+
basis = f"{source}|{session_id}|" + str(row)[:500]
|
|
548
|
+
return hashlib.sha1(basis.encode("utf-8", "replace")).hexdigest()[:20]
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def import_session_file(log: SessionLog, *, decoder: Decoder, dry_run: bool = False,
|
|
552
|
+
db=None, workspace_filter: str | None = None,
|
|
553
|
+
batch_size: int = BATCH_SIZE) -> dict:
|
|
554
|
+
"""解压 → 解析 → 批量入库一个会话文件(解压后的明文只在临时目录存活)。"""
|
|
555
|
+
report: dict = {
|
|
556
|
+
"file": str(log.path),
|
|
557
|
+
"workspace_dir": log.workspace_dir,
|
|
558
|
+
"session_dir": log.session_dir,
|
|
559
|
+
"compressed": log.compressed,
|
|
560
|
+
"session": log.session_dir,
|
|
561
|
+
"workspace": log.workspace_dir,
|
|
562
|
+
"messages": 0,
|
|
563
|
+
"added": 0,
|
|
564
|
+
"skipped": 0,
|
|
565
|
+
"bad_lines": 0,
|
|
566
|
+
"workspace_matched": True,
|
|
567
|
+
"torn_bytes": 0,
|
|
568
|
+
}
|
|
569
|
+
with tempfile.TemporaryDirectory(prefix="lingshu-session-decode-") as td:
|
|
570
|
+
plain = Path(td) / "session.jsonl"
|
|
571
|
+
if log.compressed:
|
|
572
|
+
meta = decode_session_file(log.path, plain, decoder)
|
|
573
|
+
else:
|
|
574
|
+
shutil.copyfile(log.path, plain)
|
|
575
|
+
meta = {"backend": "plain", "frames": None, "torn_bytes": 0,
|
|
576
|
+
"plain_bytes": log.path.stat().st_size, "compressed_bytes": 0}
|
|
577
|
+
report["decode"] = {
|
|
578
|
+
"backend": meta.get("backend"),
|
|
579
|
+
"frames": meta.get("frames"),
|
|
580
|
+
"compressed_bytes": meta.get("compressed_bytes"),
|
|
581
|
+
"plain_bytes": meta.get("plain_bytes"),
|
|
582
|
+
}
|
|
583
|
+
report["torn_bytes"] = int(meta.get("torn_bytes") or 0)
|
|
584
|
+
if meta.get("warning"):
|
|
585
|
+
report["warning"] = meta["warning"]
|
|
586
|
+
|
|
587
|
+
header = read_session_header(plain)
|
|
588
|
+
session_id = str(header.get("id") or "").strip() or log.session_dir
|
|
589
|
+
workspace = str(header.get("cwd") or "").strip() or log.workspace_dir
|
|
590
|
+
report["session"] = session_id
|
|
591
|
+
report["workspace"] = workspace
|
|
592
|
+
if not _workspace_matches(workspace_filter, workspace, log.workspace_dir):
|
|
593
|
+
report["workspace_matched"] = False
|
|
594
|
+
return report
|
|
595
|
+
|
|
596
|
+
parsed = added = skipped = bad_lines = 0
|
|
597
|
+
skipped_dup = 0
|
|
598
|
+
# 幂等默认**关闭**:导入的既有语义是"加法"(两个文件里同内容都该进)。
|
|
599
|
+
# 需要"重跑同一次导出不重复入库"时开 config session_import_idempotent: true,
|
|
600
|
+
# 或用 --idempotent。默认开会让状态跨批次残留,改变既有行为(实测 2 个测试挂)。
|
|
601
|
+
try:
|
|
602
|
+
_idem = bool((core.load_config() or {}).get("session_import_idempotent"))
|
|
603
|
+
except Exception:
|
|
604
|
+
_idem = False
|
|
605
|
+
_seen_keys = load_seen_keys() if _idem else set()
|
|
606
|
+
_pending_keys: set = set()
|
|
607
|
+
batch: list[dict] = []
|
|
608
|
+
|
|
609
|
+
def flush() -> None:
|
|
610
|
+
nonlocal added, skipped
|
|
611
|
+
if not batch:
|
|
612
|
+
return
|
|
613
|
+
if not dry_run:
|
|
614
|
+
rep = session_rag.ingest_messages(
|
|
615
|
+
batch, session=session_id, platform=PLATFORM,
|
|
616
|
+
workspace=workspace, path=db)
|
|
617
|
+
added += int(rep.get("added") or 0)
|
|
618
|
+
skipped += int(rep.get("skipped") or 0)
|
|
619
|
+
batch.clear()
|
|
620
|
+
|
|
621
|
+
with open(plain, "r", encoding="utf-8-sig", errors="replace") as fh:
|
|
622
|
+
for line in fh:
|
|
623
|
+
line = line.strip()
|
|
624
|
+
if not line:
|
|
625
|
+
continue
|
|
626
|
+
try:
|
|
627
|
+
event = json.loads(line)
|
|
628
|
+
except ValueError:
|
|
629
|
+
bad_lines += 1
|
|
630
|
+
continue
|
|
631
|
+
if not isinstance(event, dict):
|
|
632
|
+
bad_lines += 1
|
|
633
|
+
continue
|
|
634
|
+
if event.get("type") == "session":
|
|
635
|
+
continue # 首行 header,不是对话
|
|
636
|
+
row = _event_to_row(event)
|
|
637
|
+
if row is None:
|
|
638
|
+
continue
|
|
639
|
+
# parsed 统计"解析到的行数"(保持既有语义不变);
|
|
640
|
+
# #5 持久化幂等只影响"是否入 batch",重复单独记在 already_imported。
|
|
641
|
+
parsed += 1
|
|
642
|
+
_k = row_key(session_id, row, str(log.path))
|
|
643
|
+
if _k in _seen_keys:
|
|
644
|
+
skipped_dup += 1
|
|
645
|
+
continue
|
|
646
|
+
_pending_keys.add(_k)
|
|
647
|
+
batch.append(row)
|
|
648
|
+
if len(batch) >= max(1, int(batch_size)):
|
|
649
|
+
flush()
|
|
650
|
+
flush()
|
|
651
|
+
|
|
652
|
+
report["messages"] = parsed
|
|
653
|
+
report["bad_lines"] = bad_lines
|
|
654
|
+
report["already_imported"] = skipped_dup
|
|
655
|
+
if not dry_run:
|
|
656
|
+
report["added"] = added
|
|
657
|
+
report["skipped"] = skipped
|
|
658
|
+
if _idem and _pending_keys:
|
|
659
|
+
save_seen_keys(_seen_keys | _pending_keys)
|
|
660
|
+
else:
|
|
661
|
+
report["dry_run"] = True
|
|
662
|
+
return report
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def import_sessions(sessions_dir=None, *, limit: int | None = None,
|
|
666
|
+
workspace: str | None = None, dry_run: bool = False,
|
|
667
|
+
db=None, decoder: Decoder | None = None) -> dict:
|
|
668
|
+
"""遍历导入 DSH 会话目录;返回可 JSON 化的报告。
|
|
669
|
+
|
|
670
|
+
``limit`` 限制「最终导入的会话数」而不是「扫描的文件数」:工作区过滤在
|
|
671
|
+
解出会话 header 的 cwd 之后生效,过滤通过的按修改时间倒序取前 N 个。
|
|
672
|
+
"""
|
|
673
|
+
started = time.time()
|
|
674
|
+
root = Path(sessions_dir).expanduser() if sessions_dir else default_sessions_dir()
|
|
675
|
+
if not root.is_dir():
|
|
676
|
+
raise FileNotFoundError(f"DSH 会话目录不存在:{root}")
|
|
677
|
+
logs = discover_sessions(root)
|
|
678
|
+
dec = decoder if decoder is not None else detect_decoder()
|
|
679
|
+
max_sessions = int(limit) if limit is not None and int(limit) > 0 else None
|
|
680
|
+
files: list[dict] = []
|
|
681
|
+
totals = {"files": 0, "sessions": 0, "messages": 0, "added": 0, "skipped": 0,
|
|
682
|
+
"bad_lines": 0, "torn_bytes": 0}
|
|
683
|
+
errors = 0
|
|
684
|
+
for log in logs:
|
|
685
|
+
try:
|
|
686
|
+
rep = import_session_file(log, decoder=dec, dry_run=dry_run, db=db,
|
|
687
|
+
workspace_filter=workspace)
|
|
688
|
+
except RuntimeError as exc:
|
|
689
|
+
errors += 1
|
|
690
|
+
files.append({"file": str(log.path), "error": str(exc), "workspace_dir":
|
|
691
|
+
log.workspace_dir, "session_dir": log.session_dir})
|
|
692
|
+
continue
|
|
693
|
+
files.append(rep)
|
|
694
|
+
if not rep.get("workspace_matched", True):
|
|
695
|
+
continue
|
|
696
|
+
totals["files"] += 1
|
|
697
|
+
totals["sessions"] += 1
|
|
698
|
+
totals["messages"] += int(rep.get("messages") or 0)
|
|
699
|
+
totals["added"] += int(rep.get("added") or 0)
|
|
700
|
+
totals["skipped"] += int(rep.get("skipped") or 0)
|
|
701
|
+
totals["bad_lines"] += int(rep.get("bad_lines") or 0)
|
|
702
|
+
totals["torn_bytes"] += int(rep.get("torn_bytes") or 0)
|
|
703
|
+
if max_sessions is not None and totals["files"] >= max_sessions:
|
|
704
|
+
break
|
|
705
|
+
report = {
|
|
706
|
+
"ok": errors == 0,
|
|
707
|
+
"sessions_dir": str(root),
|
|
708
|
+
"workspace_filter": str(workspace or ""),
|
|
709
|
+
"dry_run": bool(dry_run),
|
|
710
|
+
"decoder": {"backend": dec.backend, "exe": dec.exe, "version": dec.version},
|
|
711
|
+
"files": files,
|
|
712
|
+
"totals": totals,
|
|
713
|
+
"errors": errors,
|
|
714
|
+
"elapsed_ms": int(round((time.time() - started) * 1000)),
|
|
715
|
+
}
|
|
716
|
+
if not dry_run:
|
|
717
|
+
try:
|
|
718
|
+
report["db"] = session_rag.stats(path=db)
|
|
719
|
+
except Exception as exc: # noqa: BLE001 - 统计失败不该抹掉导入结果
|
|
720
|
+
report["db"] = {"error": f"{type(exc).__name__}: {exc}"}
|
|
721
|
+
return report
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
# ---------------------------------------------------------------- CLI
|
|
725
|
+
|
|
726
|
+
def _print_human(report: dict) -> None:
|
|
727
|
+
dec = report.get("decoder") or {}
|
|
728
|
+
version = f" {dec['version']}" if dec.get("version") else ""
|
|
729
|
+
print(f"解码器:{dec.get('backend')}{version}({dec.get('exe')})")
|
|
730
|
+
print(f"会话目录:{report.get('sessions_dir')}")
|
|
731
|
+
if report.get("workspace_filter"):
|
|
732
|
+
print(f"工作区过滤:{report['workspace_filter']}")
|
|
733
|
+
for item in report.get("files") or []:
|
|
734
|
+
if item.get("error"):
|
|
735
|
+
print(f"- [错误] {item.get('session_dir') or item.get('file')}:{item['error']}")
|
|
736
|
+
continue
|
|
737
|
+
if not item.get("workspace_matched", True):
|
|
738
|
+
continue
|
|
739
|
+
tail = f"消息 {item.get('messages', 0)},新增 {item.get('added', 0)}," \
|
|
740
|
+
f"跳过 {item.get('skipped', 0)}"
|
|
741
|
+
if item.get("bad_lines"):
|
|
742
|
+
tail += f",坏行 {item['bad_lines']}"
|
|
743
|
+
if item.get("torn_bytes"):
|
|
744
|
+
tail += f",忽略残帧 {item['torn_bytes']}B"
|
|
745
|
+
if item.get("warning"):
|
|
746
|
+
tail += f",警告:{item['warning'][:120]}"
|
|
747
|
+
print(f"- [{item.get('workspace')}] {item.get('session')}({tail})")
|
|
748
|
+
filtered = sum(1 for item in report.get("files") or []
|
|
749
|
+
if not item.get("error") and not item.get("workspace_matched", True))
|
|
750
|
+
if filtered:
|
|
751
|
+
print(f"(按工作区过滤掉 {filtered} 个会话)")
|
|
752
|
+
totals = report.get("totals") or {}
|
|
753
|
+
suffix = "(dry-run,未写库)" if report.get("dry_run") else ""
|
|
754
|
+
print(f"共 {totals.get('files', 0)} 个会话:解析 {totals.get('messages', 0)} 条,"
|
|
755
|
+
f"新增 {totals.get('added', 0)},跳过 {totals.get('skipped', 0)},"
|
|
756
|
+
f"用时 {report.get('elapsed_ms', 0) / 1000.0:.1f}s{suffix}")
|
|
757
|
+
db = report.get("db")
|
|
758
|
+
if isinstance(db, dict) and not db.get("error"):
|
|
759
|
+
print(f"原文库:{db.get('messages', 0)} 条 / {db.get('sessions', 0)} 场会话"
|
|
760
|
+
f"(platform={db.get('by_platform')})")
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
764
|
+
parser = argparse.ArgumentParser(
|
|
765
|
+
prog="session_import.py",
|
|
766
|
+
description="把 DSH 会话日志(多帧 zstd)导入 session_rag 原文库(附录 B · P1)")
|
|
767
|
+
parser.add_argument("--sessions-dir", default="",
|
|
768
|
+
help="DSH 会话根目录,默认 ~/.dsh/sessions")
|
|
769
|
+
parser.add_argument("--limit", type=int, default=0,
|
|
770
|
+
help="最多导入 N 个会话(工作区过滤后按修改时间倒序,0=全部)")
|
|
771
|
+
parser.add_argument("--workspace", default="",
|
|
772
|
+
help="只导入匹配的工作区(路径/basename/目录名,子串匹配)")
|
|
773
|
+
parser.add_argument("--dry-run", action="store_true", help="只解析不写库")
|
|
774
|
+
parser.add_argument("--json", action="store_true", help="输出 JSON 报告")
|
|
775
|
+
return parser
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def main(argv=None) -> int:
|
|
779
|
+
args = build_parser().parse_args(argv)
|
|
780
|
+
try:
|
|
781
|
+
report = import_sessions(
|
|
782
|
+
sessions_dir=args.sessions_dir or None,
|
|
783
|
+
limit=args.limit or None,
|
|
784
|
+
workspace=args.workspace or None,
|
|
785
|
+
dry_run=bool(args.dry_run),
|
|
786
|
+
)
|
|
787
|
+
except DecoderUnavailable as exc:
|
|
788
|
+
print(f"[错误] {exc}", file=sys.stderr)
|
|
789
|
+
return 2
|
|
790
|
+
except FileNotFoundError as exc:
|
|
791
|
+
print(f"[错误] {exc}", file=sys.stderr)
|
|
792
|
+
return 2
|
|
793
|
+
except RuntimeError as exc:
|
|
794
|
+
print(f"[错误] 导入失败:{exc}", file=sys.stderr)
|
|
795
|
+
return 1
|
|
796
|
+
if args.json:
|
|
797
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
798
|
+
else:
|
|
799
|
+
_print_human(report)
|
|
800
|
+
return 0 if report.get("ok") else 1
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
def _ensure_utf8_stdout() -> None:
|
|
804
|
+
"""把 stdout/stderr 切到 UTF-8,避免 Windows 控制台(cp1252/cp936)编不了中文就崩。
|
|
805
|
+
|
|
806
|
+
CI 的 windows-latest stdout 是 cp1252:脚本一 print 中文就 UnicodeEncodeError
|
|
807
|
+
直接退出(实测 sync_engine.py / make_checksums.py 都因此挂过,Ubuntu 同期正常)。
|
|
808
|
+
这不是业务 bug,是"中文输出 + 非 UTF-8 控制台"的必然结果。
|
|
809
|
+
"""
|
|
810
|
+
for name in ("stdout", "stderr"):
|
|
811
|
+
stream = getattr(sys, name, None)
|
|
812
|
+
fn = getattr(stream, "reconfigure", None)
|
|
813
|
+
if callable(fn):
|
|
814
|
+
try:
|
|
815
|
+
fn(encoding="utf-8", errors="replace")
|
|
816
|
+
continue
|
|
817
|
+
except (OSError, ValueError, AttributeError):
|
|
818
|
+
pass
|
|
819
|
+
try:
|
|
820
|
+
import io
|
|
821
|
+
buf = getattr(stream, "buffer", None)
|
|
822
|
+
if buf is not None:
|
|
823
|
+
setattr(sys, name,
|
|
824
|
+
io.TextIOWrapper(buf, encoding="utf-8", errors="replace",
|
|
825
|
+
line_buffering=True))
|
|
826
|
+
except Exception: # noqa: BLE001
|
|
827
|
+
pass
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
if __name__ == "__main__":
|
|
831
|
+
_ensure_utf8_stdout()
|
|
832
|
+
sys.exit(main())
|