dsh-config-sync-plugin 0.3.66 → 0.3.67

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/README.en.md CHANGED
@@ -19,7 +19,7 @@ The package name is **`dsh-config-sync-plugin`** (the `dsh-config-sync` name on
19
19
 
20
20
  | Way | Command / entry | Notes |
21
21
  |---|---|---|
22
- | npm | `npm i dsh-config-sync-plugin` | Use it as a dependency, or add `"dsh-config-sync-plugin": "^0.3.66"` to the profile's `package.json` and run `pnpm i`. The name matches the `cordis.patch.yml` insert name and the install folder `dsh-config-sync-plugin-<ver>` |
22
+ | npm | `npm i dsh-config-sync-plugin` | Use it as a dependency, or add `"dsh-config-sync-plugin": "^0.3.67"` to the profile's `package.json` and run `pnpm i`. The name matches the `cordis.patch.yml` insert name and the install folder `dsh-config-sync-plugin-<ver>` |
23
23
  | Marketplace | client → Plugins → Discover → “Config Sync” | Installs from the git commit registered in `market-index.json` |
24
24
  | Offline tgz | `releases\dsh-config-sync-plugin-<ver>.tgz` | GitHub Release asset for air-gapped machines; the panel's Update button downloads the same file |
25
25
 
@@ -606,6 +606,28 @@ A clean isolated B machine (approot / dshome / wshome + bundled node runner) sim
606
606
 
607
607
  Benign warnings (confirmed in the log): `--D-DeepSeekHarness-comfyUI--` / `--dsh-im-forward-confirm--` map to no workspace (special session dirs); `-SkipInstall` skipped 21 registry plugins (isolated offline run — without the flag on a networked machine they install); `dsh-config-sync-0.1.0` / `extra/manifest.json` have no archive/definition and are skipped; the `dsh-config-sync` slot has extra local leftovers (removed only with `-PruneWorkspace`).
608
608
 
609
+ ### 2026-11-19: release 0.3.67 (seq reconciliation guard for session logs)
610
+
611
+ **Problem**: when two machines each append to the same session, sync used a whole-file copy. Whichever side pushed last overwrote the other side's tail, the event stream developed a `seq` jump, and DSH refused to open the session: `stored session ... is corrupt: corrupt session log: invalid committed event at line N: released v2 row N has seq gap (expected X, got Y)`.
612
+
613
+ **Fix**: `capture.ps1` (push side) and `apply.ps1` (pull side) no longer `Copy-Item -Force` a `session*.jsonl.zstd`; they hand it to the new seq guard:
614
+
615
+ | Case | Action |
616
+ |---|---|
617
+ | Target is newer or identical | keep target, write nothing |
618
+ | Source is a strict superset | copy source over target |
619
+ | Each side has exclusive events | merge by `seq`; both sides' events survive |
620
+ | Target itself has a hole the source can fill | repair then write (`merge` — rescues an already-damaged session) |
621
+ | Hole cannot be filled (events really lost) | **leave the file untouched**, record `failed` in `sync-notices.json`, flag for manual handling |
622
+
623
+ Implementation: `tools/session-log-lib.mjs` (multi-frame zstd decoding, byte-prefix compare, seq merge) + `tools/session-log-guard.mjs` (`check` / `decide` / `merge` / `batch`; batch mode is what the ps1 scripts call, and results go through a temp JSON file rather than stdout because Electron is a GUI subsystem). A full 11MB session parses in ~0.6s, fast enough for the sync hot path.
624
+
625
+ **Two extras**:
626
+ - `.gitattributes` now marks `conversations/sessions/**/*.zstd binary` and `workspace/** -text`, so Windows `core.autocrlf` or git line-ending normalisation cannot corrupt the binary logs again;
627
+ - `capture.ps1` hoists the tree-compare helpers above their first use: they were defined after the call site, so `-WorkspaceOnly` hit `Test-TreeFileChanged is not recognized` in the session mirror loop.
628
+
629
+ Diagnostic: `node tools/check-session-log.mjs <log>` or `<logA> <logB>` prints self-consistency (rows / seq range / gaps) and the relation between two files (`identical` / `prefix` / `superset` / `fork`).
630
+
609
631
  ### 2026-11-19: release 0.3.66 (.gitattributes silences LF/CRLF warnings)
610
632
  - **Cross-platform line ending noise**: on Windows `core.autocrlf=true` converts LF in `session_projcache/*.json` to CRLF, causing Git to warn "LF will be replaced by CRLF" on push. Added `.gitattributes` marking that directory as binary (`binary`) and all other text files as `eol=lf`, eliminating the warning class entirely.
611
633
  - Pure config change; no sync logic, behavior, or data changes.
package/README.md CHANGED
@@ -15,7 +15,7 @@ DSH 插件:左侧栏多一行「配置同步」,点开是整页体检面板
15
15
 
16
16
  | 方式 | 命令 / 入口 | 说明 |
17
17
  |---|---|---|
18
- | npm | `npm i dsh-config-sync-plugin` | 适合把它当依赖管理,或在 profile 的 `package.json` 里写 `"dsh-config-sync-plugin": "^0.3.66"` 后 `pnpm i`;包名与 `cordis.patch.yml` 里注册的名字、插件目录 `dsh-config-sync-plugin-<ver>` 一致 |
18
+ | npm | `npm i dsh-config-sync-plugin` | 适合把它当依赖管理,或在 profile 的 `package.json` 里写 `"dsh-config-sync-plugin": "^0.3.67"` 后 `pnpm i`;包名与 `cordis.patch.yml` 里注册的名字、插件目录 `dsh-config-sync-plugin-<ver>` 一致 |
19
19
  | 插件市场 | 客户端「插件市场 → 发现」搜「配置同步」 | 走 `market-index.json` 登记的 git 提交,版本与 README 对齐 |
20
20
  | 离线 tgz | `releases\dsh-config-sync-plugin-<ver>.tgz` | GitHub Release 附件,适合内网机器;面板「更新」按钮下载的也是它 |
21
21
 
@@ -582,6 +582,28 @@ pwsh -File sync.ps1 push -ScanHistory
582
582
 
583
583
  非故障警告(日志已确认无害):`--D-DeepSeekHarness-comfyUI--` / `--dsh-im-forward-confirm--` 找不到对应工作区(特殊会话目录);`-SkipInstall` 跳过 21 个 registry 插件(隔离环境离线,真机有网时不加即补齐);`dsh-config-sync-0.1.0` / `extra/manifest.json` 无归档正常跳过;`dsh-config-sync` 槽位有本机多出的残留文件(加 `-PruneWorkspace` 才删)。
584
584
 
585
+ ### 2026-11-19:发版 0.3.67(会话日志 seq 对账护栏)
586
+
587
+ **问题**:两台机器各自往同一个会话写事件时,同步是「整文件覆盖」。谁后 push 谁的内容顶掉对方的后半段,事件流出现 `seq` 跳号,DSH 启动直接报 `stored session ... is corrupt: corrupt session log: invalid committed event at line N: released v2 row N has seq gap (expected X, got Y)`,该会话再也打不开。
588
+
589
+ **修复**:`capture.ps1`(推送侧)与 `apply.ps1`(拉取侧)遇到 `session*.jsonl.zstd` 不再 `Copy-Item -Force`,改为交给新加的 seq 护栏:
590
+
591
+ | 情形 | 处理 |
592
+ |---|---|
593
+ | 目标更全 / 完全相同 | 保留目标,什么都不写 |
594
+ | 源是目标的严格超集 | 用源覆盖目标 |
595
+ | 两边各有独占事件 | 按 `seq` 求并集写入,两边事件全保住 |
596
+ | 目标自身断档、源能补齐 | 先补齐再写(`merge`,可救回已被覆盖坏的会话) |
597
+ | 洞补不回来(事件确实丢了) | **保持原样不覆盖**,记 `sync-notices.json` 的 `failed` 并提示需人工处理 |
598
+
599
+ 护栏实现:`tools/session-log-lib.mjs`(多帧 zstd 逐帧解、字节前缀比较、按 seq 合并)+ `tools/session-log-guard.mjs`(`check` / `decide` / `merge` / `batch` CLI,批量模式给 ps1 调用,结果走临时 JSON 文件而不是 stdout——Electron 是 GUI 子系统)。11MB 会话全量解析 ~0.6s,可进同步热路径。
600
+
601
+ **顺带两处**:
602
+ - `.gitattributes` 补 `conversations/sessions/**/*.zstd binary` 与 `workspace/** -text`,避免 Windows `core.autocrlf` 或 git 的行尾归一再次写坏二进制日志;
603
+ - `capture.ps1` 把「大目录文件比较」几个辅助函数上移到脚本前部——它们原先定义在调用点之后,`-WorkspaceOnly` 跑到会话镜像循环会报 `Test-TreeFileChanged is not recognized`。
604
+
605
+ 诊断工具:`node tools/check-session-log.mjs <日志>` 或 `<日志A> <日志B>`,输出自洽性(行数/seq 范围/gaps)与两份的关系(`identical` / `prefix` / `superset` / `fork`)。
606
+
585
607
  ### 2026-11-19:发版 0.3.66(.gitattributes 消除 LF/CRLF 警告)
586
608
  - **跨平台行尾噪音**:Windows 上 `core.autocrlf=true` 会把仓库里 LF 写入的 `session_projcache/*.json` 自动转成 CRLF,推送时 Git 报 "LF will be replaced by CRLF" 警告。新增 `.gitattributes` 将该目录标记为二进制(`binary`),其余文本文件统一 `eol=lf`,彻底消除该类警告。
587
609
  - 纯配置项改动,不改变任何同步逻辑、行为与数据。
package/client.js CHANGED
@@ -929,7 +929,7 @@ window.__ModuleLoader__.load({
929
929
  }
930
930
  // 「手动还原」指引里的目标位置:认不出类型时按内容猜不到,索性把三类常见落点都摆出来
931
931
  const manualTargets = () => [
932
- M('插件本体 → 插件安装目录(如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.66)', 'Plugin files → the plugin install folder (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.66)'),
932
+ M('插件本体 → 插件安装目录(如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.67)', 'Plugin files → the plugin install folder (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.67)'),
933
933
  M('会话目录(--xxx--)→ ~\\.dsh\\sessions', 'Session folders (--xxx--) → ~\\.dsh\\sessions'),
934
934
  M('配置五件套(package.json / pnpm-lock.yaml / cordis.yml…)→ ~\\.dsh\\profiles\\desktop', 'Config files (package.json / pnpm-lock.yaml / cordis.yml…) → ~\\.dsh\\profiles\\desktop'),
935
935
  ]
package/index.js CHANGED
@@ -976,9 +976,9 @@ async function inspect(config) {
976
976
  const remoteFiles = remoteProbe ? remoteProbe.files : null
977
977
  if (!appRoot) {
978
978
  advice.push(t(
979
- '定位不到客户端根目录:插件不在 <客户端根> 下(如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.66),'
979
+ '定位不到客户端根目录:插件不在 <客户端根> 下(如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.67),'
980
980
  + '或客户端是打包版(resources\\app.asar)而这里没认出来 —— 三份同步脚本会因此生成不了',
981
- 'Cannot locate the client root: the plugin is not under <client root> (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.66), '
981
+ 'Cannot locate the client root: the plugin is not under <client root> (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.67), '
982
982
  + 'or this is a packaged build (resources\\app.asar) that was not recognized — the three sync scripts cannot be generated.',
983
983
  ))
984
984
  }
@@ -3477,9 +3477,9 @@ async function handlePrepare(req, res, config) {
3477
3477
  if (!appRoot) {
3478
3478
  throw new Error(t(
3479
3479
  '定位不到客户端根目录(要能找到 resources\\app\\package.json 或 resources\\app.asar):'
3480
- + '请确认插件装在 <客户端根> 下(例如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.66),或在设置里填客户端根 appRoot',
3480
+ + '请确认插件装在 <客户端根> 下(例如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.67),或在设置里填客户端根 appRoot',
3481
3481
  'Cannot locate the client root (needs resources\\app\\package.json or resources\\app.asar): '
3482
- + 'make sure the plugin is installed under <client root> (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.66), or set appRoot in the settings',
3482
+ + 'make sure the plugin is installed under <client root> (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.67), or set appRoot in the settings',
3483
3483
  ))
3484
3484
  }
3485
3485
  const state = {...await repoState(repo), message}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-sync-plugin",
3
- "version": "0.3.66",
3
+ "version": "0.3.67",
4
4
  "type": "module",
5
5
  "description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。面板与文案跟随客户端语言(中文/English)。",
6
6
  "main": "./index.js",
package/runtime/apply.ps1 CHANGED
@@ -553,6 +553,11 @@ function Sync-ConversationApply {
553
553
  @{ Repo = 'vision_router_session_policy'; Dst = (Join-Path $DshHome 'storages\vision_router_session_policy\policies'); Remap = $false }
554
554
  )
555
555
  $nAdd = 0; $nBk = 0
556
+ # 会话日志不能整文件覆盖:本机可能比仓库更新(本机后面又追加了事件),仓库也可能带着
557
+ # 另一条 lineage。直接覆盖会让一方的事件整段消失或首尾拼接,DSH 启动时报 "seq gap"。
558
+ # 这里先攒成批量任务,交给 seq 护栏对账后再写。
559
+ $guardJobs = [System.Collections.Generic.List[object]]::new()
560
+ $guardBackupDir = Join-Path $BackupDir 'session-log-guard'
556
561
  foreach ($b in $blocks) {
557
562
  $srcRoot = Join-Path $convDir $b.Repo
558
563
  if (-not (Test-Path -LiteralPath $srcRoot)) { continue }
@@ -579,6 +584,10 @@ function Sync-ConversationApply {
579
584
  if (-not (Test-Path -LiteralPath $d)) { $need = $true }
580
585
  elseif ((Get-FileHashFast $f.FullName) -ne (Get-FileHashFast $d)) { $need = $true }
581
586
  if ($need) {
587
+ if (Test-SessionLogFile $dstRel) {
588
+ $guardJobs.Add([ordered]@{ Src = $f.FullName; Dst = $d; WriteTo = $d }) | Out-Null
589
+ continue
590
+ }
582
591
  # 覆盖前备份本机已有文件
583
592
  if (Test-Path -LiteralPath $d) {
584
593
  $bd = Join-Path $BackupDir ("conversations\" + $b.Repo + "\" + $dstRel)
@@ -592,6 +601,29 @@ function Sync-ConversationApply {
592
601
  }
593
602
  }
594
603
  }
604
+ if ($guardJobs.Count -gt 0) {
605
+ $g = Invoke-SessionLogGuard -Jobs $guardJobs.ToArray() -AppRoot $AppRoot -ScriptRoot $PSScriptRoot -RepoRoot $RepoRoot -BackupDir $guardBackupDir
606
+ Write-SessionLogGuardReport $g $DshHome '还原'
607
+ if ($g.Skipped) {
608
+ # 护栏用不了(没 Node/脚本缺失):退回整文件覆盖,至少保持原来的行为,但要先备份
609
+ foreach ($j in $guardJobs) {
610
+ if (Test-Path -LiteralPath $j.WriteTo) {
611
+ $bd = Join-Path $guardBackupDir ([IO.Path]::GetFileName($j.WriteTo))
612
+ $bdd = Split-Path -Parent $bd
613
+ if (-not (Test-Path -LiteralPath $bdd)) { New-Item -ItemType Directory -Path $bdd -Force | Out-Null }
614
+ Copy-Item -LiteralPath $j.WriteTo -Destination $bd -Force
615
+ $nBk++
616
+ }
617
+ Copy-Item -LiteralPath $j.Src -Destination $j.WriteTo -Force
618
+ $nAdd++
619
+ }
620
+ } else {
621
+ foreach ($r in @($g.Results)) {
622
+ if ($r -and $r.wrote) { $nAdd++ }
623
+ if ($r -and $r.backup) { $nBk++ }
624
+ }
625
+ }
626
+ }
595
627
  # 会话是增量数据:只覆盖/新增,不删本机多出的会话文件
596
628
  # 4) 会话文件头部的 cwd 必须改成本机路径,否则 DSH 判 corrupt、整个会话层起不来
597
629
  # projcache 也要一起改:只按 $cwdMap 判断会让「仓库里只有 projcache、没有 sessions」的
@@ -856,7 +888,7 @@ if ($dropped.Count -gt 0) { Ok "已剔除 $($dropped.Count) 个实验性 bundle
856
888
  $localPluginMap = [ordered]@{
857
889
  'dsh-our-free-model-2.8.0' = 'dsh-our-free-model'
858
890
  'dsh-purge-1.4.0' = 'dsh-purge'
859
- 'dsh-config-sync-plugin-0.3.66' = 'dsh-config-sync-plugin'
891
+ 'dsh-config-sync-plugin-0.3.67' = 'dsh-config-sync-plugin'
860
892
  'dsh-config-sync-plugin-0.3.65' = 'dsh-config-sync-plugin'
861
893
  'dsh-config-sync-plugin-0.3.64' = 'dsh-config-sync-plugin'
862
894
  'dsh-config-sync-plugin-0.3.63' = 'dsh-config-sync-plugin'
@@ -54,6 +54,45 @@ $ErrorActionPreference = 'Stop'
54
54
  if (-not $RepoRoot) { $RepoRoot = $PSScriptRoot }
55
55
  . (Join-Path $PSScriptRoot 'dsh-sync-common.ps1')
56
56
 
57
+ function Get-NormalizedHash($path) {
58
+ # 文本文件按"去掉 CRLF/LF 差异后的内容"比较,避免换行转换制造假变更;归档文件按原始字节比较
59
+ $ext = [IO.Path]::GetExtension($path).ToLower()
60
+ if ($ext -in @('.tgz', '.zip')) {
61
+ return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash
62
+ }
63
+ $bytes = [IO.File]::ReadAllBytes($path)
64
+ $text = [Text.Encoding]::UTF8.GetString($bytes)
65
+ $norm = $text -replace "`r`n", "`n"
66
+ $sha = [Security.Cryptography.SHA256]::Create()
67
+ return [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($norm)))
68
+ }
69
+
70
+ # ---------- 大目录文件比较(性能关键路径) ----------
71
+ # 旧写法对每个文件算两次 Get-FileHash(源 + 仓库),5 万个文件实测约 120s。
72
+ # 现在:两个 tree 各枚举一次拿 FileInfo(Length/LastWriteTimeUtc 已在枚举时读好,不再 stat),
73
+ # 内存里比对;只有「大小不同」或「源比仓库新」才对该文件算哈希确认内容。
74
+ # 这与 git 自己的判定策略一致(size+mtime 变了才重算 blob)。
75
+ $script:CmpDeep = [bool]$DeepVerify
76
+ $script:CmpFileCount = 0
77
+ $script:CmpHashCount = 0
78
+
79
+ function Test-TreeFileChanged($srcInfo, $dstInfo) {
80
+ # $srcInfo / $dstInfo 都是 FileInfo($dstInfo 为 $null 表示仓库里没有这个文件)
81
+ $script:CmpFileCount++
82
+ if ($null -eq $dstInfo) { return $true }
83
+ if ($srcInfo.Length -ne $dstInfo.Length) { return $true }
84
+ if ($script:CmpDeep -or ($srcInfo.LastWriteTimeUtc -gt $dstInfo.LastWriteTimeUtc)) {
85
+ $script:CmpHashCount++
86
+ return ((Get-NormalizedHash $srcInfo.FullName) -ne (Get-NormalizedHash $dstInfo.FullName))
87
+ }
88
+ return $false
89
+ }
90
+
91
+ function Get-TreeCmpSummary {
92
+ $deep = if ($script:CmpDeep) { '深校验开' } else { '快筛' }
93
+ return ('文件比较({0}):比对 {1} 个,深哈希 {2} 个' -f $deep, $script:CmpFileCount, $script:CmpHashCount)
94
+ }
95
+
57
96
  if (-not $NoResetNotices) { Reset-SyncNotices $DshHome 'capture' }
58
97
 
59
98
  # 客户端可能被卸载重装到别的盘:-AppRoot 先校验,对不上就自动定位(注册表 → 常见位置)。
@@ -421,6 +460,9 @@ function Sync-ConversationCapture {
421
460
  if ($rel) { $dstRels[$rel] = $rf }
422
461
  }
423
462
  $madeDirs = @{}
463
+ # 会话日志不能整文件覆盖:两台机器可能各自 append 出不同 lineage,直接覆盖会让一方的事件
464
+ # 整段消失,DSH 启动时报 "seq gap"。这里先攒成批量任务,交给 seq 护栏对账后再写。
465
+ $guardJobs = [System.Collections.Generic.List[object]]::new()
424
466
  foreach ($rel in @($srcRels.Keys)) {
425
467
  $si = $srcRels[$rel]
426
468
  if (-not (Test-TreeFileChanged $si $dstRels[$rel])) { continue }
@@ -430,11 +472,37 @@ function Sync-ConversationCapture {
430
472
  if (-not (Test-Path -LiteralPath $dd)) { New-Item -ItemType Directory -Path $dd -Force | Out-Null }
431
473
  $madeDirs[$dd] = $true
432
474
  }
475
+ if (Test-SessionLogFile $rel) {
476
+ $guardJobs.Add([ordered]@{ Src = $si.FullName; Dst = $d; WriteTo = $d }) | Out-Null
477
+ $dstRels[$rel] = [IO.FileInfo]::new($d)
478
+ continue
479
+ }
433
480
  Copy-Item -LiteralPath $si.FullName -Destination $d -Force
434
481
  $changed.Add(('conversations/{0}/{1}' -f $b.Dst, $rel.Replace($BS,'/'))) | Out-Null
435
482
  $nAdd++
436
483
  $dstRels[$rel] = [IO.FileInfo]::new($d)
437
484
  }
485
+ if ($guardJobs.Count -gt 0) {
486
+ $g = Invoke-SessionLogGuard -Jobs $guardJobs.ToArray() -AppRoot $AppRoot -ScriptRoot $PSScriptRoot -RepoRoot $RepoRoot -BackupDir (Join-Path $convDir '_session-log-guard-backup')
487
+ Write-SessionLogGuardReport $g $DshHome '抓取'
488
+ if ($g.Skipped) {
489
+ # 护栏用不了(没 Node/脚本缺失):退回整文件覆盖,至少保持原来的行为
490
+ foreach ($j in $guardJobs) {
491
+ Copy-Item -LiteralPath $j.Src -Destination $j.WriteTo -Force
492
+ $rr = Get-RelPath $dstRoot ([string]$j.WriteTo)
493
+ if ($rr) { $changed.Add(('conversations/{0}/{1}' -f $b.Dst, $rr.Replace($BS,'/'))) | Out-Null }
494
+ $nAdd++
495
+ }
496
+ } else {
497
+ foreach ($r in @($g.Results)) {
498
+ if ($r -and $r.wrote) {
499
+ $rr = Get-RelPath $dstRoot ([string]$r.wrote)
500
+ if ($rr) { $changed.Add(('conversations/{0}/{1}' -f $b.Dst, $rr.Replace($BS,'/'))) | Out-Null }
501
+ $nAdd++
502
+ }
503
+ }
504
+ }
505
+ }
438
506
  # 镜像删除:本机已删的会话文件,仓库里也删
439
507
  foreach ($rel in @($dstRels.Keys)) {
440
508
  if (-not $srcRels.ContainsKey($rel)) {
@@ -515,44 +583,6 @@ if ($WorkspaceOnly) {
515
583
  }
516
584
  return
517
585
  }
518
- function Get-NormalizedHash($path) {
519
- # 文本文件按"去掉 CRLF/LF 差异后的内容"比较,避免换行转换制造假变更;归档文件按原始字节比较
520
- $ext = [IO.Path]::GetExtension($path).ToLower()
521
- if ($ext -in @('.tgz', '.zip')) {
522
- return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash
523
- }
524
- $bytes = [IO.File]::ReadAllBytes($path)
525
- $text = [Text.Encoding]::UTF8.GetString($bytes)
526
- $norm = $text -replace "`r`n", "`n"
527
- $sha = [Security.Cryptography.SHA256]::Create()
528
- return [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($norm)))
529
- }
530
-
531
- # ---------- 大目录文件比较(性能关键路径) ----------
532
- # 旧写法对每个文件算两次 Get-FileHash(源 + 仓库),5 万个文件实测约 120s。
533
- # 现在:两个 tree 各枚举一次拿 FileInfo(Length/LastWriteTimeUtc 已在枚举时读好,不再 stat),
534
- # 内存里比对;只有「大小不同」或「源比仓库新」才对该文件算哈希确认内容。
535
- # 这与 git 自己的判定策略一致(size+mtime 变了才重算 blob)。
536
- $script:CmpDeep = [bool]$DeepVerify
537
- $script:CmpFileCount = 0
538
- $script:CmpHashCount = 0
539
-
540
- function Test-TreeFileChanged($srcInfo, $dstInfo) {
541
- # $srcInfo / $dstInfo 都是 FileInfo($dstInfo 为 $null 表示仓库里没有这个文件)
542
- $script:CmpFileCount++
543
- if ($null -eq $dstInfo) { return $true }
544
- if ($srcInfo.Length -ne $dstInfo.Length) { return $true }
545
- if ($script:CmpDeep -or ($srcInfo.LastWriteTimeUtc -gt $dstInfo.LastWriteTimeUtc)) {
546
- $script:CmpHashCount++
547
- return ((Get-NormalizedHash $srcInfo.FullName) -ne (Get-NormalizedHash $dstInfo.FullName))
548
- }
549
- return $false
550
- }
551
-
552
- function Get-TreeCmpSummary {
553
- $deep = if ($script:CmpDeep) { '深校验开' } else { '快筛' }
554
- return ('文件比较({0}):比对 {1} 个,深哈希 {2} 个' -f $deep, $script:CmpFileCount, $script:CmpHashCount)
555
- }
556
586
  function CopyNormalized($src, $dst) {
557
587
  # 二进制原样拷贝;文本统一写成 LF(与 .gitattributes 的 eol=lf 对齐),并保留原文件的 UTF-8 BOM
558
588
  $ext = [IO.Path]::GetExtension($src).ToLower()
@@ -1010,4 +1010,134 @@ function Get-TokenHint([string]$token) {
1010
1010
  return ('自选目录:' + $key + ' —— 这台机器上对应的路径由你来定')
1011
1011
  }
1012
1012
  }
1013
- }
1013
+ }
1014
+
1015
+ # ---------- 会话日志跨机护栏(按 seq 对账,防 corrupt / seq gap)----------
1016
+ # 为什么需要它:
1017
+ # 会话日志(session.v4.jsonl.zstd)是 append-only 的多帧 zstd,每个事件一行、带连续 seq。
1018
+ # 同步是「整文件覆盖」:capture 把本机整份拷进仓库,apply 把仓库整份铺回本机。
1019
+ # 两台机器同时在同一个会话里跑,各自 append 出不同 lineage;整文件覆盖必然让其中一方的
1020
+ # 事件整段消失。更糟的是「拼接」——本机文件被换成较短版本后 DSH 仍按自己的计数继续
1021
+ # append,于是「A 的前 N 条 + B 从 M 起」首尾相接,启动时报
1022
+ # corrupt session log: released v2 row N has seq gap (expected N, got M)
1023
+ # 写到这一步事件已经丢了,只能人工处理。所以写入之前先做一次 seq 对账。
1024
+ #
1025
+ # 判据(append-only 的硬性质):同源两份日志去掉首帧后,短的那份必然是长的那份的字节前缀。
1026
+ # take_src 源是目标的严格超集 → 覆盖(正常路径,零额外风险)
1027
+ # keep_dst 目标更全或两边相同 → 不写,绝不回退(保护「本机更新」的那一侧)
1028
+ # merge 两边各有对方没有的事件(真分叉),或目标自身已断档但能被源补齐
1029
+ # → 按 seq 求并集后写入,一个事件都不丢
1030
+ # 失败 并集仍有空洞(事件真的丢了)→ 拒绝写,Warn + 记 notices,等人工介入
1031
+ #
1032
+ # 退路:找不到 Node/Electron 执行器、或护栏自身报错时退回原来的整文件覆盖(并 Warn)。
1033
+ # 护栏是多加的一层保护,不能让没装 Node 的机器彻底同步不了。
1034
+
1035
+ # 会话日志文件名判定(与 DSH 的 ARTIFACT_NAMES 对齐:session.v4.jsonl.zstd / session.jsonl.zstd / session.jsonl ...)
1036
+ function Test-SessionLogFile([string]$relOrName) {
1037
+ if (-not $relOrName) { return $false }
1038
+ $leaf = @(($relOrName -replace '/', '\') -split '\\')[-1]
1039
+ return ($leaf -match '^session(\.[A-Za-z0-9]+)*\.jsonl(\.zstd)?$')
1040
+ }
1041
+
1042
+ function Get-SessionLogGuardPath([string]$scriptRoot, [string]$repoRoot) {
1043
+ foreach ($base in @($scriptRoot, $repoRoot)) {
1044
+ if (-not $base) { continue }
1045
+ foreach ($rel in @('tools\session-log-guard.mjs', 'runtime\tools\session-log-guard.mjs')) {
1046
+ $p = Join-Path $base $rel
1047
+ if (Test-Path -LiteralPath $p) { return $p }
1048
+ }
1049
+ }
1050
+ return $null
1051
+ }
1052
+
1053
+ # $Jobs: @( @{ Src = '<要采用的候选>'; Dst = '<当前生效的那份>'; WriteTo = '<把赢家写到哪里>' }, ... )
1054
+ # 返回 [ordered]@{ Ok; Total; Take; Merge; Keep; Failed; Results; Skipped; Reason }
1055
+ # 一次调用把整批会话日志跑完:一台机器几十个会话,逐个起 node 光进程启动就要好几秒。
1056
+ function Invoke-SessionLogGuard {
1057
+ param(
1058
+ [object[]]$Jobs,
1059
+ [string]$AppRoot,
1060
+ [string]$ScriptRoot,
1061
+ [string]$RepoRoot,
1062
+ [string]$BackupDir
1063
+ )
1064
+ $res = [ordered]@{ Ok = $true; Total = 0; Take = 0; Merge = 0; Keep = 0; Failed = 0; Results = @(); Skipped = $true; Reason = '' }
1065
+ if (-not $Jobs -or @($Jobs).Count -eq 0) { $res.Reason = '没有需要带护栏写入的会话日志'; return $res }
1066
+ $jobs = @($Jobs)
1067
+
1068
+ $helper = Get-SessionLogGuardPath $ScriptRoot $RepoRoot
1069
+ if (-not $helper) {
1070
+ $res.Reason = '找不到 tools\session-log-guard.mjs'
1071
+ return $res
1072
+ }
1073
+ $runner = Get-HostNodeRunner $AppRoot
1074
+ if (-not $runner) {
1075
+ $res.Reason = '这台机器既没有 Node 也找不到客户端本体'
1076
+ return $res
1077
+ }
1078
+
1079
+ $stamp = Get-Date -Format 'yyyyMMddHHmmssfff'
1080
+ $jobPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-sessionlog-job-{0}-{1}.json' -f $stamp, $PID)
1081
+ $outPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-sessionlog-out-{0}-{1}.json' -f $stamp, $PID)
1082
+ $spec = [ordered]@{
1083
+ backupDir = [string]$BackupDir
1084
+ jobs = @($jobs | ForEach-Object {
1085
+ [ordered]@{ src = [string]$_.Src; dst = [string]$_.Dst; writeTo = [string]$_.WriteTo }
1086
+ })
1087
+ }
1088
+ [IO.File]::WriteAllText($jobPath, ($spec | ConvertTo-Json -Depth 5 -Compress), (New-Object Text.UTF8Encoding($false)))
1089
+
1090
+ $oldRunAsNode = $env:ELECTRON_RUN_AS_NODE
1091
+ try {
1092
+ if ($runner.Electron) { $env:ELECTRON_RUN_AS_NODE = '1' }
1093
+ else { Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue }
1094
+ # 结果落文件而不是抓 stdout:执行器可能是客户端自带的 Electron(GUI 子系统,stdout 抓不到)
1095
+ & $runner.Exe $helper 'batch' $jobPath $outPath *> $null
1096
+ $code = $LASTEXITCODE
1097
+ if (-not (Test-Path -LiteralPath $outPath)) {
1098
+ $res.Reason = ('护栏没有产出结果文件(执行器退出码 {0})' -f $code)
1099
+ return $res
1100
+ }
1101
+ $r = ([IO.File]::ReadAllText($outPath)) | ConvertFrom-Json -ErrorAction Stop
1102
+ $res.Total = [int]$r.total
1103
+ $res.Take = [int]$r.take
1104
+ $res.Merge = [int]$r.merge
1105
+ $res.Keep = [int]$r.keep
1106
+ $res.Failed = [int]$r.failed
1107
+ $res.Ok = [bool]$r.ok
1108
+ $res.Results = @($r.results)
1109
+ $res.Skipped = $false
1110
+ return $res
1111
+ } catch {
1112
+ $res.Reason = ('护栏执行出错:{0}' -f $_.Exception.Message)
1113
+ return $res
1114
+ } finally {
1115
+ if ($null -eq $oldRunAsNode) { Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue }
1116
+ else { $env:ELECTRON_RUN_AS_NODE = $oldRunAsNode }
1117
+ Remove-Item -LiteralPath $jobPath -Force -ErrorAction SilentlyContinue
1118
+ Remove-Item -LiteralPath $outPath -Force -ErrorAction SilentlyContinue
1119
+ }
1120
+ }
1121
+
1122
+ # 把护栏结果变成给用户看的提示。失败项一律记进 notices —— 面板/收尾汇总才看得到。
1123
+ function Write-SessionLogGuardReport($Guard, [string]$DshHome, [string]$Verb) {
1124
+ if (-not $Guard) { return }
1125
+ if ($Guard.Skipped) {
1126
+ Warn ('会话日志 seq 护栏本次未启用({0}):退回整文件覆盖' -f $Guard.Reason)
1127
+ return
1128
+ }
1129
+ Ok ('会话日志 seq 对账({0}):核对 {1} 个、覆盖 {2} 个、求并集 {3} 个、保留本机 {4} 个' -f $Verb, $Guard.Total, $Guard.Take, $Guard.Merge, $Guard.Keep)
1130
+ if ([int]$Guard.Merge -gt 0) {
1131
+ Ok (' 其中 {0} 个会话两边各有独占事件,已按 seq 求并集写入(两边的事件都保住了)' -f $Guard.Merge)
1132
+ }
1133
+ if ([int]$Guard.Failed -gt 0) {
1134
+ foreach ($item in @($Guard.Results)) {
1135
+ if ($item -and (-not $item.ok)) {
1136
+ Warn (' 会话日志无法自动修复:{0}({1})' -f [string]$item.dst, [string]$item.detail)
1137
+ if ($DshHome) { Add-SyncNotice -Kind 'failed' -Path ([string]$item.dst) -Reason ('会话日志 seq 断档:' + [string]$item.detail) }
1138
+ }
1139
+ }
1140
+ Warn (' 有 {0} 个会话日志的断档补不回来(事件已丢),已保持原样不覆盖;DSH 里这些会话可能报 corrupt' -f $Guard.Failed)
1141
+ }
1142
+ }
1143
+