dsh-config-sync-plugin 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1646 @@
1
+ <#
2
+ DSH 配置同步 —— 应用脚本(把本仓库的配置还原到当前电脑)
3
+
4
+ 用法
5
+ pwsh -File apply.ps1 # 默认:铺配置 + 全量还原所有工作区
6
+ pwsh -File apply.ps1 -AppRoot D:\DSH # 客户端装在别的目录({{APP_ROOT}} 展开到这里,B 机必传)
7
+ pwsh -File apply.ps1 -DshHome C:\Users\bob\.dsh -ProfileName desktop
8
+ pwsh -File apply.ps1 -SkipInstall # 只铺配置文件和技能,不跑 pnpm install
9
+ pwsh -File apply.ps1 -PruneSkills # 额外删除本机 skills 目录下仓库里没有的 Skill(默认不动)
10
+ pwsh -File apply.ps1 -SkipMnemon # 不还原记忆插件数据(<AppRoot>\mnemon)
11
+ pwsh -File apply.ps1 -WorkspaceOnly # 只还原工作区资料与登记表(不碰配置/插件/预设,无需退出 DSH、无需本机装 profile)
12
+ pwsh -File apply.ps1 -SkipWorkspace # 跳过工作区还原(应急;默认全量还原所有工作区)
13
+ pwsh -File apply.ps1 -PruneWorkspace # 额外删除本机工作区里仓库没有的文件(默认留着并提示)
14
+ pwsh -File apply.ps1 -ReplaceWorkspaceRegistry # 整份覆盖本机 workspace.json(默认按 ID 合并、同路径去重,保留本机自建工作区)
15
+ pwsh -File apply.ps1 -WorkspaceHome "D:\其它\根" # B 机上 {{WORKSPACE_HOME}} 展开到哪个根(默认 %USERPROFILE%\Documents\deepseek-harness)
16
+ pwsh -File apply.ps1 -Force # 检测到 DSH 仍在运行时强制继续(不推荐)
17
+
18
+ 工作区还原(默认开、全量)
19
+ 读仓库里的 workspace\workspace-registry.json,把每个工作区的资料按字节还原到占位符展开后的路径,
20
+ 再按 ID 把登记表合并进 $DshHome\storages\workspace.json(本机自建工作区保留,workspaceIds 取并集,
21
+ sessionIds 取「仓库 + 本机」并集)。合并完还会按 path 去重:DSH 启动时校验 duplicate paths,
22
+ 同一路径留两条会让整张登记表打不开(工作区列表全空、会话也读不出),换机时本机自建的
23
+ default-workspace 与仓库那条 ID 不同正好会撞,所以同路径只保留一条、其余条目的会话并入。
24
+ {{APP_ROOT}} 用 -AppRoot 展开,{{WORKSPACE_HOME}} 用 -WorkspaceHome
25
+ 展开,所以 A/B 机盘符不同也能落地。
26
+
27
+ 对话/会话数据还原(默认开、全量,随工作区一起;-SkipWorkspace 会连会话一起跳过)
28
+ 读仓库里的 conversations\session-index.json,把每块会话数据字节保真还原到 $DshHome 对应位置。
29
+ sessions\ 的一级目录名按「占位符路径 → 本机路径 → 重新编码」重算,否则 B 机换了 -AppRoot 认不出会话;
30
+ 登记表里的 sessionIds 会写回本机 workspace.json,工作台能直接看到并打开历史对话。会话是增量数据,
31
+ 还原只做覆盖/新增,不删本机多出的会话文件。
32
+
33
+ 前置条件:执行前必须完全退出 DeepSeek Harness(窗口 + 托盘图标都要退),
34
+ 否则配置文件写入后会被运行中的进程覆盖,插件也不会重新加载。
35
+ -WorkspaceOnly 只还原工作区与会话,不需要退出 DSH,也不需要本机装过客户端。
36
+ #>
37
+ param(
38
+ [string]$RepoRoot,
39
+ [string]$DshHome = $(Join-Path $env:USERPROFILE '.dsh'),
40
+ [string]$ProfileName = 'desktop',
41
+ [string]$AppRoot = '',
42
+ [switch]$SkipInstall,
43
+ [switch]$PruneSkills,
44
+ [switch]$SkipMnemon,
45
+ [switch]$PruneMnemon,
46
+ [switch]$Force,
47
+ [switch]$WorkspaceOnly,
48
+ [switch]$SkipWorkspace,
49
+ [switch]$PruneWorkspace,
50
+ [switch]$ReplaceWorkspaceRegistry,
51
+ [switch]$AllowVersionDrift,
52
+ [switch]$ForceBundles,
53
+ [string]$WorkspaceHome = $(Join-Path $env:USERPROFILE 'Documents\deepseek-harness'),
54
+ # sync.ps1 调起本脚本时必须传,否则会抹掉父进程已攒下的未同步清单
55
+ [switch]$NoResetNotices
56
+ )
57
+
58
+ $ErrorActionPreference = 'Stop'
59
+ if (-not $RepoRoot) { $RepoRoot = $PSScriptRoot }
60
+ . (Join-Path $PSScriptRoot 'dsh-sync-common.ps1')
61
+
62
+ if (-not $NoResetNotices) { Reset-SyncNotices $DshHome 'pull' } else { Set-SyncNoticeContext $DshHome 'pull' }
63
+
64
+ # 客户端可能被卸载重装到别的盘:传进来的 -AppRoot 先校验,对不上就自动定位(注册表 → 常见位置)。
65
+ $resolvedRoot = Resolve-DshAppRoot $AppRoot
66
+ if (-not $resolvedRoot) {
67
+ Die ("找不到 DSH 客户端目录(传进来的 -AppRoot 对不上,注册表与常见位置也没有)。" +
68
+ "装好客户端后重跑,或显式传 -AppRoot `<客户端根>`(目录里有 resources\app.asar 或 resources\app\package.json)。")
69
+ }
70
+ if ($AppRoot -and ($resolvedRoot -ne $AppRoot.TrimEnd('\', '/'))) { Warn "参数里的 -AppRoot($AppRoot)对不上,已自动改用:$resolvedRoot" }
71
+ $AppRoot = $resolvedRoot
72
+
73
+ # ---------- 客户端安装目录的路径归一化 ----------
74
+ # 仓库里凡是「客户端安装目录」的绝对路径,一律存成 {{APP_ROOT}}/ 前缀。
75
+ # 展开规则由 dsh-sync-common.ps1 的 Convert-AppRootText 提供:按本机 -AppRoot 的实际目录名匹配,
76
+ # 不再写死 DeepSeekHarness(装在 D:\DSH 这类目录也能正确展开)。
77
+ $AppRootPattern = Get-AppRootPattern $AppRoot
78
+
79
+ function Expand-AppRoot([string]$text, [string]$rootFwd) {
80
+ # 先把占位符换成本机路径(漏了这一步会把裸 {{APP_ROOT}} 写进 cordis.patch.yml,
81
+ # 宿主解析 YAML 直接 fatal;pnpm-lock.yaml 也会和 package.json 的 specifier 对不上)
82
+ if ($text.Contains($AppRootToken)) { $text = $text.Replace($AppRootToken, $rootFwd) }
83
+ if ($text.Contains($WorkspaceHomeToken)) {
84
+ $wsFwd = $WorkspaceHome.Replace('\\', '/').TrimEnd('/')
85
+ $text = $text.Replace($WorkspaceHomeToken, $wsFwd)
86
+ }
87
+ # 再兜底老仓库里没迁移过的盘符绝对路径
88
+ return (Convert-AppRootText $text $AppRoot $rootFwd)
89
+ }
90
+
91
+ function Expand-AppRootFile([string]$path, [string]$rootFwd) {
92
+ $raw = Read-TextPreserveBom $path
93
+ if ($raw.Contains($AppRootToken) -or $raw -match $AppRootPattern) {
94
+ Write-TextPreserveBom $path (Expand-AppRoot $raw $rootFwd)
95
+ return $true
96
+ }
97
+ return $false
98
+ }
99
+
100
+ function Expand-AppRootTree([string]$dir, [string]$rootFwd) {
101
+ # 目录里所有文本文件都做一次占位符展开(mnemon 记忆库、插件设置这类被整目录复制的内容)
102
+ if (-not (Test-Path -LiteralPath $dir)) { return }
103
+ Get-ChildItem -LiteralPath $dir -Recurse -File -Force -ErrorAction SilentlyContinue |
104
+ Where-Object { $_.Extension -in @('.json', '.jsonc', '.yaml', '.yml', '.md', '.txt') } |
105
+ ForEach-Object { Expand-AppRootFile $_.FullName $rootFwd | Out-Null }
106
+ }
107
+
108
+ # ---------- 工作区资料同步 ----------
109
+ # 仓库里的 workspace/ 是用户资料,必须字节保真:不走 Expand-AppRootTree(会改文本),
110
+ # 一律 Copy-Item -LiteralPath 原样拷;登记表里的路径占位符在这里展开成本机绝对路径。
111
+ # ($BS / $WorkspaceHomeToken / $wsSkip* / Test-WorkspaceIgnored 都在 dsh-sync-common.ps1 里,两个脚本共用)
112
+
113
+ # 快速 SHA256:复用单个静态实例,比 Get-FileHash cmdlet 快约 6 倍(大批量逐文件比对是拉取主要瓶颈)
114
+ $_dshSha256 = [System.Security.Cryptography.SHA256]::Create()
115
+ function Get-FileHashFast([string]$path) {
116
+ $fs = [System.IO.File]::Open($path, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::ReadWrite)
117
+ try { return [Convert]::ToBase64String($_dshSha256.ComputeHash($fs)) }
118
+ finally { $fs.Dispose() }
119
+ }
120
+ function Sync-WorkspaceApply {
121
+ $wsDir = Join-Path $RepoRoot 'workspace'
122
+ # 登记表 sessionIds 常常滞后于实际会话目录(会话是后来新建的、capture 只抄了当时的快照)。
123
+ # DSH 归属权威就是这里的 sessionIds 成员:没登记的会话即便 cwd 改对也不会挂到工作区。
124
+ # 按 conversations\sessions\--ws-<workspaceId>--\<sessionId>\ 反推补齐,与会话还原段同源。
125
+ $sidByWsDir = @{}
126
+ $defaultSids = @() # 默认工作区会话(仓库稳定名 --default-workspace--)的会话 id
127
+ $convSessionsDir = Join-Path $RepoRoot 'conversations\sessions'
128
+ if (Test-Path -LiteralPath $convSessionsDir) {
129
+ foreach ($wd in @(Get-ChildItem -LiteralPath $convSessionsDir -Directory -Force)) {
130
+ if ($wd.Name -eq '--default-workspace--') {
131
+ foreach ($sd in @(Get-ChildItem -LiteralPath $wd.FullName -Directory -Force)) {
132
+ $defaultSids += [string]$sd.Name
133
+ }
134
+ continue
135
+ }
136
+ if ($wd.Name -notmatch '^--ws-(?<id>.+)--$') { continue }
137
+ $wid = $Matches['id']
138
+ if (-not $sidByWsDir.ContainsKey($wid)) { $sidByWsDir[$wid] = @() }
139
+ foreach ($sd in @(Get-ChildItem -LiteralPath $wd.FullName -Directory -Force)) {
140
+ $sidByWsDir[$wid] += [string]$sd.Name
141
+ }
142
+ }
143
+ }
144
+ $manifestPath = Join-Path $wsDir 'workspace-registry.json'
145
+ if (-not (Test-Path -LiteralPath $manifestPath)) {
146
+ Warn ('仓库里没有 {0},跳过工作区还原(仓库里没有工作区资料)' -f $manifestPath)
147
+ return
148
+ }
149
+ $mf = Get-Content -LiteralPath $manifestPath -Raw -Encoding UTF8 | ConvertFrom-Json
150
+ $appRootFwd = $AppRoot.Replace($BS,'/').TrimEnd('/')
151
+ $wsHomeFwd = $WorkspaceHome.Replace($BS,'/').TrimEnd('/')
152
+
153
+ # 先算好每个工作区的本机落点:{{APP_ROOT}} / {{WORKSPACE_HOME}} → 本机绝对路径
154
+ # 同时带上仓库里的会话与时间戳:B 机工作台要靠这些 sessionIds 才能列出/打开历史对话
155
+ $plan = @()
156
+ foreach ($w in @($mf.workspaces)) {
157
+ $p = ([string]$w.path).Replace($BS,'/')
158
+ $p = $p.Replace($AppRootToken, $appRootFwd).Replace($WorkspaceHomeToken, $wsHomeFwd)
159
+ $localPath = $p.TrimEnd('/').Replace('/', $BS)
160
+ $plan += [pscustomobject]@{
161
+ Id = [string]$w.id
162
+ Title = [string]$w.title
163
+ Slot = [string]$w.slot
164
+ LocalPath = $localPath
165
+ SessionIds = @($w.sessionIds | ForEach-Object { [string]$_ })
166
+ ArchivedSessionIds = @($w.archivedSessionIds | ForEach-Object { [string]$_ })
167
+ PinnedSessionIds = @($w.pinnedSessionIds | ForEach-Object { [string]$_ })
168
+ CreatedAt = [string]$w.createdAt
169
+ UpdatedAt = [string]$w.updatedAt
170
+ }
171
+ }
172
+
173
+ # 同步内容勾选:未勾选的工作区不还原资料、也不并进本机 workspace.json(本机原有登记原样保留)
174
+ $skippedPlan = @($plan | Where-Object { -not (Test-SyncItemEnabled $Scope 'workspace' $_.Id) })
175
+ foreach ($s in $skippedPlan) { Warn ('跳过(未勾选同步)工作区:{0}' -f $s.Title) }
176
+ $plan = @($plan | Where-Object { Test-SyncItemEnabled $Scope 'workspace' $_.Id })
177
+
178
+ # 1) 资料还原(字节保真,覆盖前先备份本机现有文件)
179
+ $nAdd = 0; $nDel = 0; $nBk = 0
180
+ foreach ($e in $plan) {
181
+ $srcRoot = Join-Path $wsDir $e.Slot
182
+ if (-not (Test-Path -LiteralPath $srcRoot)) {
183
+ Warn ('登记表里工作区「{0}」没有对应资料目录,跳过资料还原:{1}' -f $e.Title, $srcRoot)
184
+ continue
185
+ }
186
+ $repoRels = @{}
187
+ foreach ($f in @(Get-ChildItem -LiteralPath $srcRoot -Recurse -File -Force)) {
188
+ $rel = Get-RelPath $srcRoot $f.FullName
189
+ if (-not $rel) { continue }
190
+ # 老仓库里可能还留着模型权重/whl 这类大文件:不铺到本机(本机自己那份才是原件)
191
+ if (Test-WorkspaceIgnored $rel) { continue }
192
+ if ($f.Length -gt $wsMaxFileBytes) {
193
+ Warn ('仓库里这个文件过大,跳过不还原:{0}' -f $rel)
194
+ Add-SyncNotice -Kind 'too-large' -Path $rel -Bytes ([long]$f.Length) -Reason ('仓库里这份 {0:N1} MB > 100 MB,未还原到本机' -f ($f.Length / 1MB))
195
+ continue
196
+ }
197
+ $repoRels[$rel] = $f.FullName
198
+ }
199
+ # 备份策略:不再无条件全量备份整个工作区(二次拉取 4.9 万文件全量备份白耗 ~100 秒)。
200
+ # 真正的回滚点只在文件「即将被覆盖」时逐个备份,见下方 if ($need) 分支。
201
+ if (-not (Test-Path -LiteralPath $e.LocalPath)) { New-Item -ItemType Directory -Path $e.LocalPath -Force | Out-Null }
202
+ foreach ($rel in @($repoRels.Keys)) {
203
+ $s = $repoRels[$rel]
204
+ $d = Join-Path $e.LocalPath $rel
205
+ $dd = Split-Path -Parent $d
206
+ if (-not (Test-Path -LiteralPath $dd)) { New-Item -ItemType Directory -Path $dd -Force | Out-Null }
207
+ $need = $false
208
+ if (-not (Test-Path -LiteralPath $d)) { $need = $true }
209
+ elseif ((Get-FileHashFast $s) -ne (Get-FileHashFast $d)) { $need = $true }
210
+ if ($need) {
211
+ # 仅覆盖前备份这一个文件(目标存在说明是改动而非新增)
212
+ if (Test-Path -LiteralPath $d) {
213
+ $bd = Join-Path (Join-Path $BackupDir ("workspace\" + $e.Slot)) $rel
214
+ $bdd = Split-Path -Parent $bd
215
+ if (-not (Test-Path -LiteralPath $bdd)) { New-Item -ItemType Directory -Path $bdd -Force | Out-Null }
216
+ Copy-Item -LiteralPath $d -Destination $bd -Force
217
+ $nBk++
218
+ }
219
+ Copy-Item -LiteralPath $s -Destination $d -Force; $nAdd++
220
+ }
221
+ }
222
+ # 本机多出的文件:默认不动只提示,加 -PruneWorkspace 才删
223
+ $extra = [System.Collections.Generic.List[string]]::new()
224
+ foreach ($lf in @(Get-ChildItem -LiteralPath $e.LocalPath -Recurse -File -Force -ErrorAction SilentlyContinue)) {
225
+ $rel = Get-RelPath $e.LocalPath $lf.FullName
226
+ if ($rel -and -not $repoRels.ContainsKey($rel) -and -not (Test-WorkspaceIgnored $rel)) { $extra.Add([string]$lf.FullName) }
227
+ }
228
+ if ($extra.Count -gt 0) {
229
+ if ($PruneWorkspace) {
230
+ foreach ($x in $extra) { Remove-Item -LiteralPath $x -Force; $nDel++ }
231
+ } else {
232
+ Warn ('工作区「{0}」本机另有 {1} 个仓库里没有的文件(未动,加 -PruneWorkspace 才删):{2}' -f $e.Title, $extra.Count, (($extra | Select-Object -First 3) -join '、'))
233
+ }
234
+ }
235
+ Ok ('已还原工作区「{0}」→ {1}({2} 个文件,字节保真)' -f $e.Title, $e.LocalPath, $repoRels.Count)
236
+ }
237
+
238
+ # 2) 登记表合并进本机 workspace.json(默认按 ID 合并,保留本机自建工作区)
239
+ $registryDst = Join-Path $DshHome 'storages/workspace.json'
240
+ $regObj = $null
241
+ if (Test-Path -LiteralPath $registryDst) {
242
+ Copy-Item -LiteralPath $registryDst -Destination (Join-Path $BackupDir 'workspace-registry-before.json') -Force
243
+ $regObj = Get-Content -LiteralPath $registryDst -Raw -Encoding UTF8 | ConvertFrom-Json
244
+ }
245
+ $localTable = [ordered]@{}
246
+ $localGlobal = [ordered]@{}
247
+ $unitObj = $null
248
+ if ($regObj) {
249
+ if ($regObj.unit) { $unitObj = $regObj.unit }
250
+ if ($regObj.global) {
251
+ foreach ($p in $regObj.global.PSObject.Properties) { $localGlobal[$p.Name] = $p.Value }
252
+ }
253
+ if ($regObj.tables -and $regObj.tables.workspaces) {
254
+ foreach ($p in $regObj.tables.workspaces.PSObject.Properties) {
255
+ $e2 = [ordered]@{}
256
+ foreach ($q in $p.Value.PSObject.Properties) { $e2[$q.Name] = $q.Value }
257
+ $localTable[$p.Name] = $e2
258
+ }
259
+ }
260
+ }
261
+ if (-not $unitObj) { $unitObj = [ordered]@{ name = 'workspace'; version = 2 } }
262
+ if ($ReplaceWorkspaceRegistry) {
263
+ $localTable = [ordered]@{}
264
+ $localGlobal = [ordered]@{}
265
+ }
266
+ # 记下「合并前本机登记表里已有的工作区 ID」。同一路径被两台机器各自建过工作区时,
267
+ # 两边 ID 必然不同;这时要保留**当前机器在用的那个 ID**,否则本机的 defaultWorkspaceId
268
+ # 会指向一个被丢掉的 ID,登记表校验不过、工作区列表和会话一起读不出来。
269
+ $localIdSet = @{}
270
+ foreach ($k in @($localTable.Keys)) { $localIdSet[[string]$k] = $true }
271
+ # 全局归档/置顶会话:取「仓库 + 本机」并集(-ReplaceWorkspaceRegistry 时本机已清空,只剩仓库)
272
+ # 注意:$null 在管道里会被当成一个元素流过 ForEach-Object,[string]$null 就是 "",
273
+ # 于是缺失的字段会变成 @("") 写进 json。"" 不是合法会话 id,这里统一滤掉。
274
+ $gArchAll = @(); $gPinAll = @()
275
+ if ($mf.global) {
276
+ $gArchAll += @($mf.global.archivedSessionIds | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' })
277
+ $gPinAll += @($mf.global.pinnedSessionIds | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' })
278
+ }
279
+ if ($localGlobal.Contains('archivedSessionIds')) { $gArchAll += @($localGlobal['archivedSessionIds'] | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' }) }
280
+ if ($localGlobal.Contains('pinnedSessionIds')) { $gPinAll += @($localGlobal['pinnedSessionIds'] | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' }) }
281
+
282
+ foreach ($e in $plan) {
283
+ # 运行时字段取「仓库 + 本机」并集:既把 A 机历史会话带过来,也不丢 B 机自建会话
284
+ $repoSess = @($e.SessionIds)
285
+ # 补进按会话目录反推出来的 sid(登记表快照里没有的那些),让 DSH 把这些历史会话
286
+ # 显式登记到本工作区;会话组未勾选同步时不补,尊重同步范围选择。
287
+ if ($sidByWsDir.ContainsKey($e.Id) -and (Test-SyncItemEnabled $Scope 'conversations' $e.Id)) {
288
+ $repoSess += @($sidByWsDir[$e.Id])
289
+ }
290
+ $repoArch = @($e.ArchivedSessionIds)
291
+ $repoPin = @($e.PinnedSessionIds)
292
+ $created = $e.CreatedAt; $updated = $e.UpdatedAt
293
+ if ($localTable.Contains($e.Id)) {
294
+ $prev = $localTable[$e.Id]
295
+ foreach ($k in @('sessionIds','archivedSessionIds','pinnedSessionIds')) {
296
+ if ($prev.Contains($k)) {
297
+ if ($k -eq 'sessionIds') { $repoSess += @($prev[$k] | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' }) }
298
+ elseif ($k -eq 'archivedSessionIds') { $repoArch += @($prev[$k] | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' }) }
299
+ else { $repoPin += @($prev[$k] | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' }) }
300
+ }
301
+ }
302
+ if ($prev.Contains('createdAt')) { $created = [string]$prev['createdAt'] }
303
+ if ($prev.Contains('updatedAt')) { $updated = [string]$prev['updatedAt'] }
304
+ }
305
+ $entry = [ordered]@{
306
+ path = $e.LocalPath
307
+ title = $e.Title
308
+ sessionIds = @($repoSess | Where-Object { $_ -ne '' } | Sort-Object -Unique)
309
+ archivedSessionIds = @($repoArch | Where-Object { $_ -ne '' } | Sort-Object -Unique)
310
+ pinnedSessionIds = @($repoPin | Where-Object { $_ -ne '' } | Sort-Object -Unique)
311
+ createdAt = $created
312
+ updatedAt = $updated
313
+ }
314
+ $localTable[$e.Id] = $entry
315
+ }
316
+ # 同一路径只能登记一个工作区:DSH 启动时会校验 duplicate paths,一张表里出现重复即
317
+ # 整张登记表打不开(表现为左侧工作区列表全空、会话列表也一起读不出来)。
318
+ # 换机时本机自建的 default-workspace 与仓库里同名工作区 ID 不同,按 ID 合并必然撞车,
319
+ # 所以这里按 path 收敛成一条,其余条目的会话并入保留者。
320
+ $pathGroups = [ordered]@{}
321
+ foreach ($id in @($localTable.Keys)) {
322
+ $p = [string]$localTable[$id]['path']
323
+ if (-not $p) { continue }
324
+ $key = $p.Replace('/', '\').TrimEnd('\').ToLowerInvariant()
325
+ if (-not $pathGroups.Contains($key)) { $pathGroups[$key] = @() }
326
+ $pathGroups[$key] += $id
327
+ }
328
+ $mfIdSet = @{}
329
+ foreach ($e in $plan) { $mfIdSet[$e.Id] = $true }
330
+ $dropped = @{}
331
+ foreach ($key in @($pathGroups.Keys)) {
332
+ $group = @($pathGroups[$key])
333
+ if ($group.Count -le 1) { continue }
334
+ # 保留哪一个:优先**本机原有的 ID**(当前机器在用的那个,defaultWorkspaceId 指向它),
335
+ # 本机没有这个路径时才用仓库的 ID,最后退到会话最多的那个。
336
+ # 早先版本反着来(优先仓库 ID),换机 pull 后本机 ID 被丢掉,defaultWorkspaceId 随之悬空。
337
+ $keeper = @($group | Where-Object { $localIdSet.ContainsKey($_) }) | Select-Object -First 1
338
+ if (-not $keeper) {
339
+ $keeper = @($group | Where-Object { $mfIdSet.ContainsKey($_) }) | Select-Object -First 1
340
+ }
341
+ if (-not $keeper) {
342
+ $keeper = @($group | Sort-Object -Property @{ Expression = { @($localTable[$_]['sessionIds']).Count } } -Descending) | Select-Object -First 1
343
+ }
344
+ foreach ($other in @($group | Where-Object { $_ -ne $keeper })) {
345
+ $localTable[$keeper]['sessionIds'] = @(@($localTable[$keeper]['sessionIds']) + @($localTable[$other]['sessionIds']) | Where-Object { $_ -ne '' } | Sort-Object -Unique)
346
+ $localTable[$keeper]['archivedSessionIds'] = @(@($localTable[$keeper]['archivedSessionIds']) + @($localTable[$other]['archivedSessionIds']) | Where-Object { $_ -ne '' } | Sort-Object -Unique)
347
+ $localTable[$keeper]['pinnedSessionIds'] = @(@($localTable[$keeper]['pinnedSessionIds']) + @($localTable[$other]['pinnedSessionIds']) | Where-Object { $_ -ne '' } | Sort-Object -Unique)
348
+ Warn ('同一路径撞了两个工作区,已合并为一条:{0}(ID {1} 的会话并入 ID {2})' -f $localTable[$keeper]['path'], $other, $keeper)
349
+ $dropped[$other] = $true
350
+ $localTable.Remove($other)
351
+ }
352
+ }
353
+ $ids = @($localTable.Keys | ForEach-Object { [string]$_ } | Where-Object { -not $dropped.ContainsKey($_) })
354
+ $mfDefault = if ($mf.global) { [string]$mf.global.defaultWorkspaceId } else { '' }
355
+ $localDefault = if ($localGlobal.Contains('defaultWorkspaceId')) { [string]$localGlobal['defaultWorkspaceId'] } else { '' }
356
+ # defaultWorkspaceId 一律以「当前机器」为准:本机原来那个只要还在表里就原样保留;
357
+ # 只有在它已经不存在(被合并掉/首次迁移)时才退到仓库值,再不行取第一条。
358
+ # 悬空的 defaultWorkspaceId 会让 DSH 的登记表校验失败,症状是工作区列表空、会话全读不出。
359
+ if (-not ($localDefault -and ($ids -contains $localDefault))) {
360
+ if ($mfDefault -and ($ids -contains $mfDefault)) { $localGlobal['defaultWorkspaceId'] = $mfDefault }
361
+ elseif ($ids.Count -gt 0) { $localGlobal['defaultWorkspaceId'] = $ids[0] }
362
+ else { $localGlobal['defaultWorkspaceId'] = '' }
363
+ }
364
+ elseif (-not $localGlobal.Contains('defaultWorkspaceId')) { $localGlobal['defaultWorkspaceId'] = $localDefault }
365
+ # 默认工作区的会话 id 并入「本机」默认工作区条目:普通工作区靠上面 sidByWsDir 反推补进 sessionIds,
366
+ # 默认工作区是稳定名 --default-workspace-- 不那条路,这里用仓库会话目录反推出来的 $defaultSids 补。
367
+ # DSH 归属权威就是 sessionIds,不补的话 cwd 和目录名对了、会话也不会挂到默认工作区下。
368
+ $dwId = [string]$localGlobal['defaultWorkspaceId']
369
+ if ($defaultSids.Count -gt 0 -and $dwId -and $localTable.Contains($dwId)) {
370
+ $localTable[$dwId]['sessionIds'] = @(@($localTable[$dwId]['sessionIds']) + $defaultSids | Where-Object { $_ -ne '' } | Sort-Object -Unique)
371
+ }
372
+ $localGlobal['initialized'] = $true
373
+ $localGlobal['workspaceIds'] = $ids
374
+ $localGlobal['archivedSessionIds'] = @($gArchAll | Sort-Object -Unique)
375
+ $localGlobal['pinnedSessionIds'] = @($gPinAll | Sort-Object -Unique)
376
+ $newReg = [ordered]@{}
377
+ $newReg['unit'] = $unitObj
378
+ $newReg['global'] = $localGlobal
379
+ $newReg['tables'] = [ordered]@{ workspaces = $localTable }
380
+ $regText = (($newReg | ConvertTo-Json -Depth 12) -replace "`r`n", "`n") + "`n"
381
+ $regParent = Split-Path -Parent $registryDst
382
+ if (-not (Test-Path -LiteralPath $regParent)) { New-Item -ItemType Directory -Path $regParent -Force | Out-Null }
383
+ [IO.File]::WriteAllText($registryDst, $regText, (New-Object Text.UTF8Encoding($false, $false)))
384
+ Ok ('工作区登记表已' + $(if ($ReplaceWorkspaceRegistry) { '整份覆盖' } else { '按 ID 合并' }) + " → $registryDst($($plan.Count) 个工作区)")
385
+
386
+ # 登记了工作区、但仓库里没有它的资料目录时(例如「Gitee同步」这种空工作区),
387
+ # 目录本身不会被上面那段铺出来。登记表里却写了这个路径,DSH 打开工作区就会指向一个不存在的目录
388
+ # (表现为工作区点不开/新建会话报错)。所以这里按刚写出的登记表把缺的目录补出来。
389
+ # 读文件而不是读内存里的 $localTable:那份还是占位符形态,直接 New-Item 会报 "path's format is not supported"。
390
+ $written = Get-Content -LiteralPath $registryDst -Raw -Encoding UTF8 | ConvertFrom-Json
391
+ foreach ($w in @($written.tables.workspaces.PSObject.Properties)) {
392
+ $wp = [string]$w.Value.path
393
+ if (-not $wp) { continue }
394
+ if (-not (Test-Path -LiteralPath $wp)) {
395
+ New-Item -ItemType Directory -Path $wp -Force | Out-Null
396
+ Ok ('已补建空工作区目录:{0}' -f $wp)
397
+ }
398
+ }
399
+
400
+ Ok ('工作区全量还原:{0} 个工作区,写入/更新 {1} 个文件、备份 {2} 个、删除 {3} 个' -f $plan.Count, $nAdd, $nBk, $nDel)
401
+ }
402
+
403
+ # ---------- 对话/会话数据还原:常量与函数 ----------
404
+ # sessions\ 一级目录名 = Get-SessionDirName(工作区绝对路径)。编码不可逆,所以 capture
405
+ # 在 conversations\session-index.json 里记了「目录名 ↔ 工作区 ID」;apply 按本机
406
+ # -AppRoot / -WorkspaceHome 展开后的路径重新编码目录名,B 机才能认出这些会话。
407
+ function Get-SessionDirName([string]$path) {
408
+ $sb = New-Object System.Text.StringBuilder
409
+ [void]$sb.Append('--')
410
+ foreach ($ch in $path.ToCharArray()) {
411
+ $c = [int][char]$ch
412
+ if ($c -eq 58) { continue } # ':' 丢弃
413
+ if ($c -eq 92 -or $c -eq 47) { [void]$sb.Append('-'); continue } # \ / → -
414
+ if ($c -lt 128) { [void]$sb.Append($ch) }
415
+ else { [void]$sb.Append(('~{0:X4}' -f $c)) } # 非 ASCII → ~XXXX(连续 CJK 共享 ~ 串联)
416
+ }
417
+ [void]$sb.Append('--')
418
+ return $sb.ToString()
419
+ }
420
+
421
+ function Sync-ConversationApply {
422
+ $convDir = Join-Path $RepoRoot 'conversations'
423
+ $indexPath = Join-Path $convDir 'session-index.json'
424
+ if (-not (Test-Path -LiteralPath $convDir)) {
425
+ Warn ('仓库里没有 {0},跳过会话还原' -f $convDir)
426
+ return
427
+ }
428
+
429
+ # 1) 读工作区登记表,建 workspaceId → 本机绝对路径(占位符展开后)映射
430
+ $appRootFwd = $AppRoot.Replace($BS,'/').TrimEnd('/')
431
+ $wsHomeFwd = $WorkspaceHome.Replace($BS,'/').TrimEnd('/')
432
+ $idToLocal = @{}
433
+ $mfPath = Join-Path $RepoRoot 'workspace\workspace-registry.json'
434
+ if (Test-Path -LiteralPath $mfPath) {
435
+ $mf = Get-Content -LiteralPath $mfPath -Raw -Encoding UTF8 | ConvertFrom-Json
436
+ foreach ($w in @($mf.workspaces)) {
437
+ $p = ([string]$w.path).Replace($BS,'/')
438
+ $p = $p.Replace($AppRootToken, $appRootFwd).Replace($WorkspaceHomeToken, $wsHomeFwd)
439
+ $idToLocal[[string]$w.id] = $p.TrimEnd('/').Replace('/', $BS)
440
+ }
441
+ }
442
+
443
+ # 1b) 本机默认工作区路径:从「本机」workspace.json 的 global.defaultWorkspaceId 反查。
444
+ # 绝不用仓库 registry 里那台机器的 default ID——各机默认工作区 ID 不同;但「本机这一个」
445
+ # 由本机登记表唯一确定。默认工作区会话在仓库里是稳定名 --default-workspace--,
446
+ # 还原时按这里的本机路径重编码目录名 + 改写会话头 cwd,B 机才能认出。
447
+ $localDefaultWsPath = ''
448
+ $localWsReg = Join-Path $DshHome 'storages\workspace.json'
449
+ if (Test-Path -LiteralPath $localWsReg) {
450
+ try {
451
+ $lreg = Get-Content -LiteralPath $localWsReg -Raw -Encoding UTF8 | ConvertFrom-Json
452
+ $ldefId = if ($lreg.global) { [string]$lreg.global.defaultWorkspaceId } else { '' }
453
+ if ($ldefId -and $lreg.tables -and $lreg.tables.workspaces) {
454
+ $lp = $lreg.tables.workspaces.PSObject.Properties[$ldefId]
455
+ if ($lp) { $localDefaultWsPath = [string]$lp.Value.path }
456
+ }
457
+ } catch { }
458
+ }
459
+ if (-not $localDefaultWsPath -and $WorkspaceHome) {
460
+ # 兜底:默认工作区路径固定就是 <WorkspaceHome>\default-workspace
461
+ $localDefaultWsPath = Join-Path $WorkspaceHome 'default-workspace'
462
+ }
463
+
464
+ # 2) 目录名重映射:A 机目录名 → B 机目录名;同时记下 B 机这条目录应对应的 cwd
465
+ # (会话文件 header 里的 cwd 必须与目录名编码一致,否则 DSH 判 corrupt)
466
+ $dirMap = @{}
467
+ $cwdMap = @{}
468
+ $skipConvDirs = @{} # 被“同步内容”取消勾选的工作区会话目录(不铺回本机)
469
+ $imLocal = Join-Path $DshHome 'im'
470
+ if (Test-Path -LiteralPath $indexPath) {
471
+ $idx = Get-Content -LiteralPath $indexPath -Raw -Encoding UTF8 | ConvertFrom-Json
472
+ foreach ($e in @($idx.entries)) {
473
+ $oldDir = [string]$e.dir
474
+ if ($e.workspaceId -and -not (Test-SyncItemEnabled $Scope 'conversations' ([string]$e.workspaceId))) {
475
+ $skipConvDirs[$oldDir] = $true
476
+ Warn ('跳过(未勾选同步)该工作区的会话:{0}' -f $oldDir)
477
+ continue
478
+ }
479
+ if ($e.workspaceId -and $idToLocal.ContainsKey([string]$e.workspaceId)) {
480
+ $localPath = $idToLocal[[string]$e.workspaceId]
481
+ $newDir = Get-SessionDirName $localPath
482
+ $dirMap[$oldDir] = $newDir
483
+ $cwdMap[$newDir] = $localPath
484
+ } elseif ($e.special -eq 'im') {
485
+ $newDir = Get-SessionDirName $imLocal
486
+ $dirMap[$oldDir] = $newDir
487
+ $cwdMap[$newDir] = $imLocal
488
+ } elseif ($e.special -eq 'default') {
489
+ # 默认工作区:按本机路径重编码目录名,会话头 cwd 也指本机默认工作区
490
+ if ($localDefaultWsPath) {
491
+ $newDir = Get-SessionDirName $localDefaultWsPath
492
+ $dirMap[$oldDir] = $newDir
493
+ $cwdMap[$newDir] = $localDefaultWsPath
494
+ } else {
495
+ $dirMap[$oldDir] = $oldDir
496
+ Warn ('默认工作区会话 {0} 找不到本机落点,请先在 DSH 里打开一次默认工作区再拉取' -f $oldDir)
497
+ }
498
+ } else {
499
+ $dirMap[$oldDir] = $oldDir # passthrough / 对应不到的工作区,原名保留
500
+ Warn ('会话目录 {0} 对应不到本机工作区,目录名与文件头 cwd 都无法重算,DSH 可能把它判为损坏:请在本机重新打开该工作区后再同步' -f $oldDir)
501
+ }
502
+ }
503
+ }
504
+ # 2b) 兜底:仓库里出现 --ws-<工作区ID>-- 但 session-index.json 没记(索引缺失/被清)时,直接按 ID 映射
505
+ $repoSessions = Join-Path $convDir 'sessions'
506
+ if (Test-Path -LiteralPath $repoSessions) {
507
+ foreach ($d in @(Get-ChildItem -LiteralPath $repoSessions -Directory -Force)) {
508
+ if ($dirMap.ContainsKey($d.Name)) { continue }
509
+ # 默认工作区稳定名(session-index 缺失时兜底)
510
+ if ($d.Name -eq '--default-workspace--') {
511
+ if ($localDefaultWsPath) {
512
+ $newDir = Get-SessionDirName $localDefaultWsPath
513
+ $dirMap[$d.Name] = $newDir
514
+ $cwdMap[$newDir] = $localDefaultWsPath
515
+ }
516
+ continue
517
+ }
518
+ if ($d.Name -match '^--ws-(?<id>.+)--$') {
519
+ $id = $Matches['id']
520
+ $hit = $null
521
+ foreach ($k in @($idToLocal.Keys)) {
522
+ $safeId = ($k -replace '[^A-Za-z0-9_.-]', '_')
523
+ if ($safeId -eq $id) { $hit = $k; break }
524
+ }
525
+ if ($hit) {
526
+ if (-not (Test-SyncItemEnabled $Scope 'conversations' $hit)) {
527
+ $skipConvDirs[$d.Name] = $true
528
+ Warn ('跳过(未勾选同步)该工作区的会话:{0}' -f $d.Name)
529
+ continue
530
+ }
531
+ $localPath = $idToLocal[$hit]
532
+ $newDir = Get-SessionDirName $localPath
533
+ $dirMap[$d.Name] = $newDir
534
+ $cwdMap[$newDir] = $localPath
535
+ }
536
+ }
537
+ }
538
+ }
539
+
540
+ # 3) 四块数据字节还原(覆盖前备份同名文件;sessions 一级目录按 dirMap 改名)
541
+ # 前置校验:会话文件头部的 cwd 必须展开成本机路径,否则 DSH 判 corrupt,整层会话
542
+ # 都不登记(症状:工作区还在、会话一个都看不到)。这一步只能靠 Node 解 zstd。
543
+ # 找不到 Node / 缺 helper 时**宁可不铺**:铺进去的是 {{APP_ROOT}} 占位符文件,比不铺更糟。
544
+ $cwdHelper = Join-Path $PSScriptRoot 'tools\fix-session-cwd.mjs'
545
+ if (-not (Test-Path -LiteralPath $cwdHelper)) { $cwdHelper = Join-Path $RepoRoot 'tools\fix-session-cwd.mjs' }
546
+ $nodeRunner = Get-HostNodeRunner $AppRoot
547
+ # projcache 也要按「本机的工作区落点」对齐:它的文件名是 sessionId,
548
+ # 登记表里每个工作区带着 sessionIds,所以能直接反查到本机路径。
549
+ # 不换的话 B 机打开这些会话时 cwd 仍指 A 机目录,历史对话回不到正确工作区。
550
+ $projMap = @{}
551
+ if ($mf -and (Test-Path -LiteralPath (Join-Path $DshHome 'storages\session_projcache\sessions'))) {
552
+ foreach ($w in @($mf.workspaces)) {
553
+ $wid = [string]$w.id
554
+ if (-not $idToLocal.ContainsKey($wid)) { continue }
555
+ $lid = $idToLocal[$wid]
556
+ foreach ($sid in @($w.sessionIds)) { if ($sid) { $projMap[[string]$sid] = $lid } }
557
+ }
558
+ }
559
+ # 登记表 sessionIds 可能滞后(会话是后来新建的、capture 只抄了当时的快照),
560
+ # 仅靠它会漏掉大量 projcache → 那些会话 cwd 仍指 A 机目录,点开历史会话跑偏。
561
+ # 兜底:直接按仓库 conversations\sessions 的 --ws-<工作区ID>--\<sessionId>\ 目录反推,
562
+ # sessionId 就是子目录名,工作区落点沿用 2b) 的 safeId 匹配。
563
+ if (Test-Path -LiteralPath $repoSessions) {
564
+ foreach ($wd in @(Get-ChildItem -LiteralPath $repoSessions -Directory -Force)) {
565
+ if ($wd.Name -notmatch '^--ws-(?<id>.+)--$') { continue }
566
+ $wid = $Matches['id']
567
+ $hit = $null
568
+ foreach ($k in @($idToLocal.Keys)) {
569
+ $safeId = ($k -replace '[^A-Za-z0-9_.-]', '_')
570
+ if ($safeId -eq $wid) { $hit = $k; break }
571
+ }
572
+ if (-not $hit) { continue }
573
+ if (-not (Test-SyncItemEnabled $Scope 'conversations' $hit)) { continue }
574
+ $lid = $idToLocal[$hit]
575
+ foreach ($sd in @(Get-ChildItem -LiteralPath $wd.FullName -Directory -Force)) {
576
+ $projMap[[string]$sd.Name] = $lid
577
+ }
578
+ }
579
+ # im 会话(--im-- 顶层)的 projcache 也要指到本机 .dsh\im,
580
+ # 否则这类会话的历史 cwd 仍写死 A 机用户目录,点开跑偏。
581
+ foreach ($wd in @(Get-ChildItem -LiteralPath $repoSessions -Directory -Force)) {
582
+ if ($wd.Name -eq '--im--') {
583
+ foreach ($sd in @(Get-ChildItem -LiteralPath $wd.FullName -Directory -Force)) {
584
+ $projMap[[string]$sd.Name] = $imLocal
585
+ }
586
+ }
587
+ # 默认工作区会话(--default-workspace-- 顶层)的 projcache 指到本机默认工作区
588
+ if ($wd.Name -eq '--default-workspace--' -and $localDefaultWsPath) {
589
+ foreach ($sd in @(Get-ChildItem -LiteralPath $wd.FullName -Directory -Force)) {
590
+ $projMap[[string]$sd.Name] = $localDefaultWsPath
591
+ }
592
+ }
593
+ }
594
+ }
595
+ if ($cwdMap.Count -gt 0 -or $projMap.Count -gt 0) {
596
+ if (-not (Test-Path -LiteralPath $cwdHelper)) {
597
+ Warn ('缺少会话头部修正脚本 {0},本次跳过会话还原(铺进去的会话 DSH 会判为损坏)' -f $cwdHelper)
598
+ return
599
+ }
600
+ if (-not $nodeRunner) {
601
+ Warn '这台机器既没有 Node,也找不到客户端本体,本次跳过会话还原(会话文件里的 {{APP_ROOT}} 占位符无法展开,铺进去 DSH 会全部不登记)'
602
+ Warn '本机配置与工作区资料不受影响;装一个 Node 后重新拉取即可'
603
+ return
604
+ }
605
+ }
606
+ $blocks = @(
607
+ @{ Repo = 'sessions'; Dst = (Join-Path $DshHome 'sessions'); Remap = $true },
608
+ @{ Repo = 'attachments'; Dst = (Join-Path $DshHome 'attachments'); Remap = $false },
609
+ # session_projcache 是可重建的缓存(coldSnapshot);
610
+ # 同步旧 projcache 会带来 A 机的 token 计量状态(如超长 surfaceTokens),
611
+ # 导致 B 机 compaction 无法触发、直接把全量 surface 发给 provider 报 context overflow。
612
+ # 这里跳过同步,让 DSH 启动时从 session log 重建(基于 B 机实际模型配置)。
613
+ @{ Repo = 'vision_router_session_policy'; Dst = (Join-Path $DshHome 'storages\vision_router_session_policy\policies'); Remap = $false }
614
+ )
615
+ $nAdd = 0; $nBk = 0
616
+ # 会话日志不能整文件覆盖:本机可能比仓库更新(本机后面又追加了事件),仓库也可能带着
617
+ # 另一条 lineage。直接覆盖会让一方的事件整段消失或首尾拼接,DSH 启动时报 "seq gap"。
618
+ # 这里先攒成批量任务,交给 seq 护栏对账后再写。
619
+ $guardJobs = [System.Collections.Generic.List[object]]::new()
620
+ $guardBackupDir = Join-Path $BackupDir 'session-log-guard'
621
+ foreach ($b in $blocks) {
622
+ $srcRoot = Join-Path $convDir $b.Repo
623
+ if (-not (Test-Path -LiteralPath $srcRoot)) { continue }
624
+ if (-not (Test-Path -LiteralPath $b.Dst)) { New-Item -ItemType Directory -Path $b.Dst -Force | Out-Null }
625
+ foreach ($f in @(Get-ChildItem -LiteralPath $srcRoot -Recurse -File -Force)) {
626
+ $rel = Get-RelPath $srcRoot $f.FullName
627
+ if (-not $rel) { continue }
628
+ if ($b.Remap) {
629
+ # 相对路径第一段是 A 机的编码目录名,换成 B 机重编码后的名字
630
+ $parts = @($rel -split '\\')
631
+ # 默认工作区会话现在要同步:稳定的 --default-workspace-- 已在 dirMap 里映射到本机编码名,
632
+ # 下面会随 Remap 改写。老仓库里可能还留着「路径式」的默认工作区目录名(本机编码、对不上
633
+ # 任何映射),那种仍跳过不铺——它跨机无法重定位,铺了反而是死目录。
634
+ if ((Test-DefaultWorkspaceDir $parts[0]) -and -not $dirMap.ContainsKey($parts[0])) { continue }
635
+ # 该工作区的会话被取消勾选:不铺回本机(否则等于把未勾选的内容写回来了)
636
+ if (-not $dirMap.ContainsKey($parts[0]) -and $skipConvDirs.ContainsKey($parts[0])) { continue }
637
+ if ($dirMap.ContainsKey($parts[0])) { $parts[0] = $dirMap[$parts[0]] }
638
+ $dstRel = ($parts -join '\')
639
+ } else {
640
+ $dstRel = $rel
641
+ }
642
+ $d = Join-Path $b.Dst $dstRel
643
+ $dd = Split-Path -Parent $d
644
+ if (-not (Test-Path -LiteralPath $dd)) { New-Item -ItemType Directory -Path $dd -Force | Out-Null }
645
+ $need = $false
646
+ if (-not (Test-Path -LiteralPath $d)) { $need = $true }
647
+ elseif ((Get-FileHashFast $f.FullName) -ne (Get-FileHashFast $d)) { $need = $true }
648
+ if ($need) {
649
+ if (Test-SessionLogFile $dstRel) {
650
+ $guardJobs.Add([ordered]@{ Src = $f.FullName; Dst = $d; WriteTo = $d }) | Out-Null
651
+ continue
652
+ }
653
+ # 覆盖前备份本机已有文件
654
+ if (Test-Path -LiteralPath $d) {
655
+ $bd = Join-Path $BackupDir ("conversations\" + $b.Repo + "\" + $dstRel)
656
+ $bdd = Split-Path -Parent $bd
657
+ if (-not (Test-Path -LiteralPath $bdd)) { New-Item -ItemType Directory -Path $bdd -Force | Out-Null }
658
+ Copy-Item -LiteralPath $d -Destination $bd -Force
659
+ $nBk++
660
+ }
661
+ Copy-Item -LiteralPath $f.FullName -Destination $d -Force
662
+ $nAdd++
663
+ }
664
+ }
665
+ }
666
+ if ($guardJobs.Count -gt 0) {
667
+ $g = Invoke-SessionLogGuard -Jobs $guardJobs.ToArray() -AppRoot $AppRoot -ScriptRoot $PSScriptRoot -RepoRoot $RepoRoot -BackupDir $guardBackupDir
668
+ Write-SessionLogGuardReport $g $DshHome '还原'
669
+ if ($g.Skipped) {
670
+ # 护栏用不了(没 Node/脚本缺失):退回整文件覆盖,至少保持原来的行为,但要先备份
671
+ foreach ($j in $guardJobs) {
672
+ if (Test-Path -LiteralPath $j.WriteTo) {
673
+ $bd = Join-Path $guardBackupDir ([IO.Path]::GetFileName($j.WriteTo))
674
+ $bdd = Split-Path -Parent $bd
675
+ if (-not (Test-Path -LiteralPath $bdd)) { New-Item -ItemType Directory -Path $bdd -Force | Out-Null }
676
+ Copy-Item -LiteralPath $j.WriteTo -Destination $bd -Force
677
+ $nBk++
678
+ }
679
+ Copy-Item -LiteralPath $j.Src -Destination $j.WriteTo -Force
680
+ $nAdd++
681
+ }
682
+ } else {
683
+ foreach ($r in @($g.Results)) {
684
+ if ($r -and $r.wrote) { $nAdd++ }
685
+ if ($r -and $r.backup) { $nBk++ }
686
+ }
687
+ }
688
+ }
689
+ # 会话是增量数据:只覆盖/新增,不删本机多出的会话文件
690
+ # 4) 会话文件头部的 cwd 必须改成本机路径,否则 DSH 判 corrupt、整个会话层起不来
691
+ # projcache 也要一起改:只按 $cwdMap 判断会让「仓库里只有 projcache、没有 sessions」的
692
+ # 情况整段跳过(隔离环境实测:工作区还原了,会话 cwd 仍指源机)。两处任一有活就得跑。
693
+ if ($cwdMap.Count -gt 0 -or $projMap.Count -gt 0) {
694
+ $specPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-session-cwd-{0}.json' -f $stamp)
695
+ $specJson = [ordered]@{ home = $DshHome; dirs = $cwdMap; projcache = $projMap } | ConvertTo-Json -Depth 4 -Compress
696
+ [IO.File]::WriteAllText($specPath, $specJson, (New-Object Text.UTF8Encoding($false)))
697
+ $helper = $cwdHelper
698
+ # 结果落文件而不是抓 stdout:执行器可能是客户端自带的 Electron(GUI 子系统,stdout 抓不到)
699
+ $resultPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-session-cwd-{0}.out.json' -f $stamp)
700
+ $oldRunAsNode = $env:ELECTRON_RUN_AS_NODE
701
+ if ((Test-Path -LiteralPath $helper) -and $nodeRunner) {
702
+ try {
703
+ if ($nodeRunner.Electron) { $env:ELECTRON_RUN_AS_NODE = '1' }
704
+ else { Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue }
705
+ & $nodeRunner.Exe $helper $specPath $resultPath | Out-Null
706
+ if (-not (Test-Path -LiteralPath $resultPath)) { throw '执行器没有产出结果文件(可能不是 Node/Electron)' }
707
+ $line = ([IO.File]::ReadAllText($resultPath)).Trim()
708
+ $r = $line | ConvertFrom-Json -ErrorAction Stop
709
+ if (@($r.failed).Count -gt 0) {
710
+ foreach ($fe in @($r.failed)) {
711
+ Warn ('会话头部修正失败:{0}({1})' -f $fe.file, $fe.error)
712
+ Add-SyncNotice -Kind 'failed' -Path ([string]$fe.file) -Reason ('会话头部修正失败:' + [string]$fe.error)
713
+ }
714
+ Warn ('有 {0} 个会话文件没能修正,DSH 里这些会话可能显示为损坏' -f @($r.failed).Count)
715
+ }
716
+ if (@($r.projFailed).Count -gt 0) {
717
+ foreach ($fe in @($r.projFailed)) {
718
+ Warn ('会话 projcache 的 cwd 没改成:{0}({1})' -f $fe.file, $fe.error)
719
+ Add-SyncNotice -Kind 'failed' -Path ([string]$fe.file) -Reason ('会话 projcache 的 cwd 未修正:' + [string]$fe.error)
720
+ }
721
+ }
722
+ Ok ('会话头部 cwd 已对齐本机路径:修正 {0} 个、本就正确 {1} 个(目录 {2} 个)' -f $r.fixed, $r.alreadyOk, $cwdMap.Count)
723
+ Ok ('会话 projcache 的 cwd 已对齐本机路径:修正 {0} 个、本就正确 {1} 个(会话 {2} 个)' -f ([int]$r.projFixed), ([int]$r.projAlreadyOk), $projMap.Count)
724
+ } catch {
725
+ Warn ('会话头部修正执行失败:{0}' -f $_.Exception.Message)
726
+ Warn '未修正的会话会在 DSH 里被判为损坏,导致工作区/会话列表为空,请先跑一次拉取再还原'
727
+ } finally {
728
+ if ($null -eq $oldRunAsNode) { Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue }
729
+ else { $env:ELECTRON_RUN_AS_NODE = $oldRunAsNode }
730
+ Remove-Item -LiteralPath $specPath -Force -ErrorAction SilentlyContinue
731
+ Remove-Item -LiteralPath $resultPath -Force -ErrorAction SilentlyContinue
732
+ }
733
+ } else {
734
+ Warn ('没找到可用于修正会话头部的执行器(Node / 客户端 Electron 都没找到,AppRoot={0}),本次未修正' -f $AppRoot)
735
+ }
736
+ }
737
+ # 5) billion-context 压缩状态:DSH 原生 compaction 被 bili 接管后,真正的压缩记录在 bili 自己的
738
+ # SQLite(…\billion-context\sessions\index.db)里,不在 .dsh 下。不带这份状态,长会话在本机
739
+ # 继续时会以未压缩的全量 surface 发给 provider,报 CONTEXT_WINDOW_EXCEEDED。
740
+ $biliRepo = Join-Path $convDir 'billion_context'
741
+ if (Test-Path -LiteralPath $biliRepo) {
742
+ $bs = Invoke-BiliStateSync -Mode 'import' -RepoDir $biliRepo -AppRoot $AppRoot -ScriptRoot $PSScriptRoot -RepoRoot $RepoRoot
743
+ Write-BiliStateSyncReport $bs $DshHome
744
+ } else {
745
+ Say ' 仓库里没有 billion-context 压缩状态(首次导出前为空,属正常)'
746
+ }
747
+ Ok ('会话数据全量还原:{0} 个目录映射,写入/更新 {1} 个文件、备份 {2} 个(四块数据字节保真,会话只增不删)' -f $dirMap.Count, $nAdd, $nBk)
748
+ }
749
+
750
+ Say "== DSH 配置同步 / apply =="
751
+ Say "仓库:$RepoRoot"
752
+ Say "DSH home:$DshHome"
753
+ Say "客户端:$AppRoot"
754
+ Say ""
755
+
756
+ # 同步内容勾选(面板「同步内容」卡写在本机 ~\.dsh\config-sync-scope.json):未勾选的组不还原,本机数据原地不动
757
+ $Scope = Get-SyncScope $DshHome
758
+
759
+ # 备份目录统一在脚本开头建立(工作区覆盖前的快照也放这里)
760
+ $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
761
+ $BackupDir = Join-Path $DshHome "backups\config-$stamp"
762
+ New-Item -ItemType Directory -Path $BackupDir -Force | Out-Null
763
+
764
+ # -WorkspaceOnly:只还原工作区 + 会话(B 机没装 DSH 也能先落地资料),做完直接结束
765
+ if ($WorkspaceOnly) {
766
+ if ($SkipWorkspace) { Die "-WorkspaceOnly 与 -SkipWorkspace 不能同时使用" }
767
+ if (Test-SyncGroupEnabled $Scope 'workspace') { Sync-WorkspaceApply } else { Warn '跳过(未勾选同步):工作区资料' }
768
+ if (Test-SyncGroupEnabled $Scope 'conversations') { Sync-ConversationApply } else { Warn '跳过(未勾选同步):会话记录' }
769
+ Say ""
770
+ Say "== 完成(仅工作区 + 会话)=="
771
+ Say "如需回滚:把 $BackupDir 里的 workspace\ / conversations\ 拷回原位置。"
772
+ return
773
+ }
774
+
775
+ # ---------- 0. 前置检查 ----------
776
+ $proc = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue
777
+ if ($proc -and -not $Force) {
778
+ Die "检测到 DeepSeek Harness 仍在运行(PID: $(($proc.Id) -join ','))。请完全退出(含托盘)后重新执行,或加 -Force 强制继续。"
779
+ }
780
+ foreach ($p in @("$RepoRoot\profile\package.json", "$RepoRoot\profile\cordis.patch.yml")) {
781
+ if (-not (Test-Path -LiteralPath $p)) {
782
+ if (Test-SyncGroupEnabled $Scope 'profile') { Die "仓库内容不完整,缺少:$p" }
783
+ Warn ("仓库里没有 " + $p + "(本机未勾选同步 profile,按跳过处理)")
784
+ }
785
+ }
786
+ $ProfileDir = Join-Path $DshHome ("profiles\" + $ProfileName)
787
+ if (-not (Test-Path -LiteralPath $ProfileDir)) {
788
+ Warn "目标 profile 不存在:$ProfileDir(本机还没装过 DSH?)"
789
+ Die "请先在当前电脑安装同版本 DSH 客户端,启动一次让它生成 profile 目录,再跑本脚本。"
790
+ }
791
+
792
+ # 需要跨机一致的插件设置 / 工作流:仓库路径 → 本机路径
793
+ # 0.3.30 起扩到各插件自己的配置;文件里存的是占位符,落到本机前统一展开
794
+ $settingsMap = @(
795
+ @{ Repo = 'settings\our-free-model.json'; Src = (Join-Path $DshHome 'our-free-model\settings.json'); Label = 'our-free-model 插件设置' },
796
+ @{ Repo = 'settings\comfyui-workflows.json'; Src = (Join-Path $DshHome 'data\dsh-comfyui\workflows.json'); Label = 'ComfyUI 工作流库' },
797
+ @{ Repo = 'settings\dsh-pet-main-config.jsonc'; Src = (Join-Path $DshHome 'dsh-pet\main-config.jsonc'); Label = '桌宠配置' },
798
+ @{ Repo = 'settings\dsh-market-state.json'; Src = (Join-Path $ProfileDir '.dsh-market\state.json'); Label = '插件市场状态' },
799
+ @{ Repo = 'settings\dsh-pet-memory.json'; Src = (Join-Path $DshHome 'dsh-pet\memory.json'); Label = '桌宠记忆' },
800
+ @{ Repo = 'settings\our-free-model-picks.json'; Src = (Join-Path $DshHome 'our-free-model\picks.json'); Label = 'our-free-model 收藏' },
801
+ @{ Repo = 'settings\dsh-im-interface-language.json'; Src = (Join-Path $DshHome 'integrations\dsh-im\interface-language.json'); Label = 'dsh-im 界面语言' },
802
+ @{ Repo = 'settings\dsh-qq-config.json'; Src = (Join-Path $DshHome 'integrations\dsh-qq\config.json'); Label = 'QQ 集成配置' },
803
+ @{ Repo = 'settings\dsh-qq-workspaces.json'; Src = (Join-Path $DshHome 'integrations\dsh-qq\workspaces.json'); Label = 'QQ 集成工作区' },
804
+ @{ Repo = 'settings\redteam-preset-declare.json'; Src = (Join-Path $DshHome 'redteam\preset-declare.json'); Label = '红队预设声明' },
805
+ @{ Repo = 'settings\task-board-ledger.json'; Src = (Join-Path $DshHome 'task-board\ledger-v2.json'); Label = '任务板台账' },
806
+ @{ Repo = 'settings\task-board-scheduler.json'; Src = (Join-Path $DshHome 'task-board\scheduler-v2.json'); Label = '任务板调度' },
807
+ @{ Repo = 'settings\dsh-workspaces.json'; Src = (Join-Path $DshHome 'storages\workspace.json'); Label = 'DSH 工作区登记' },
808
+ @{ Repo = 'settings\workspace-archives.json'; Src = (Join-Path $DshHome 'dsh-session-manager\workspace-archives.v1.json'); Label = 'DSH 工作区隐藏状态' }
809
+ )
810
+
811
+ # ---------- 0.5 宿主版本契约(一切动作之前先校验) ----------
812
+ # 为什么要在最前面校验:
813
+ # 仓库的 bundle 清单里有 @deepseek-ai/dsh-experimental-* 这类「宿主自带、按版本强绑定」的项
814
+ # (例如 cot-translation 需要主进程同版本的 typert 服务)。它们不经过 pnpm、不在 dependencies 里,
815
+ # 目标机的客户端构建只要不同,启动期就会在 entry loading 阶段抛错,整个应用起不来。
816
+ # 旧脚本对此毫无校验:清单整表覆盖、自检只数数量,故障要等双击图标才暴露。
817
+ # 现在的规则:版本对不上 → 直接拒绝(可显式 -AllowVersionDrift 放行,但实验性 bundle 一律剔除),
818
+ # 拒绝发生在备份、还原、写文件之前。
819
+ $contractPath = Join-Path $RepoRoot 'profile\host-contract.json'
820
+ $hostAppVersion = Get-HostAppVersion $AppRoot
821
+ $contractVersion = $null
822
+ if (Test-Path -LiteralPath $contractPath) {
823
+ try { $contractVersion = [string](Get-Content -LiteralPath $contractPath -Raw -Encoding utf8 | ConvertFrom-Json).appVersion } catch { $contractVersion = $null }
824
+ }
825
+ $versionDrift = $false
826
+ if (-not $hostAppVersion) {
827
+ Warn "读不到客户端 app 版本($AppRoot\resources\app\package.json 与 resources\app.asar 都没读到)——无法做版本校验"
828
+ } elseif (-not $contractVersion) {
829
+ Warn "仓库缺少 profile\host-contract.json(或里面没有 appVersion)——跳过版本校验"
830
+ } elseif ($hostAppVersion -ne $contractVersion) {
831
+ $versionDrift = $true
832
+ Warn "宿主版本不一致:本机 app = $hostAppVersion,仓库契约 = $contractVersion"
833
+ if (-not $AllowVersionDrift) {
834
+ Die ("两端客户端不是同一版,未改动任何文件。请先把两台升到同一版;" +
835
+ "或加 -AllowVersionDrift 只同步配置/技能/资料(会剔除全部实验性 bundle,避免启动期崩溃)。")
836
+ }
837
+ Warn "已加 -AllowVersionDrift:继续同步,但剔除实验性 bundle"
838
+ } else {
839
+ Ok "宿主版本一致(app = $hostAppVersion)"
840
+ }
841
+
842
+ # ---------- 1. 备份现有配置($BackupDir 已在脚本开头统一建立) ----------
843
+ $backedUp = 0
844
+ foreach ($f in @('package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml')) {
845
+ $src = Join-Path $ProfileDir $f
846
+ if (Test-Path -LiteralPath $src) { Copy-Item -LiteralPath $src -Destination (Join-Path $BackupDir $f) -Force; $backedUp++ }
847
+ }
848
+ foreach ($f in @('AGENTS.md', 'prompt-inject.md')) {
849
+ $src = Join-Path $DshHome $f
850
+ if (Test-Path -LiteralPath $src) { Copy-Item -LiteralPath $src -Destination (Join-Path $BackupDir $f) -Force; $backedUp++ }
851
+ }
852
+ $settingsBackupManifest = [ordered]@{}
853
+ foreach ($m in $settingsMap) {
854
+ if (Test-Path -LiteralPath $m.Src) {
855
+ $bc = Join-Path $BackupDir 'settings'
856
+ if (-not (Test-Path -LiteralPath $bc)) { New-Item -ItemType Directory -Path $bc -Force | Out-Null }
857
+ $leaf = Split-Path -Leaf $m.Src
858
+ Copy-Item -LiteralPath $m.Src -Destination (Join-Path $bc $leaf) -Force
859
+ # 记下「备份文件名 → 相对 DshHome 的原路径」。旧版只留文件名,还原时全堆到 DshHome 根
860
+ # (storages\workspace.json 变根 workspace.json),这里把原位记进清单,还原按它写回。
861
+ $settingsBackupManifest[$leaf] = $m.Src.Substring($DshHome.Length).TrimStart([char]92, [char]47)
862
+ $backedUp++
863
+ }
864
+ }
865
+ if ($settingsBackupManifest.Count -gt 0) {
866
+ try {
867
+ $mfPath = Join-Path (Join-Path $BackupDir 'settings') '__backup_manifest.json'
868
+ [IO.File]::WriteAllText($mfPath, ($settingsBackupManifest | ConvertTo-Json -Depth 3), (New-Object Text.UTF8Encoding($false)))
869
+ } catch { Warn ('写 settings 备份清单失败(还原时只能按旧规则写回根):' + $_.Exception.Message) }
870
+ }
871
+ if ($backedUp -gt 0) {
872
+ Ok "已备份 $backedUp 个文件到 $BackupDir"
873
+ } else {
874
+ Ok "本机还没有这些配置文件(全新机器),无需备份;快照目录 $BackupDir 会是空的,还原脚本会自动跳过它"
875
+ }
876
+
877
+ # Skill / 预设目录同样会被覆盖(同名)或删除(-PruneSkills),覆盖前一并备份
878
+ foreach ($pair in @(@{ Local = (Join-Path $DshHome 'skills'); Repo = (Join-Path $RepoRoot 'skills'); Name = 'skills' },
879
+ @{ Local = (Join-Path $DshHome '.agent-presets'); Repo = (Join-Path $RepoRoot 'presets'); Name = 'presets' })) {
880
+ if (-not (Test-Path -LiteralPath $pair.Local)) { continue }
881
+ $names = @(Get-ChildItem -LiteralPath $pair.Local -Directory -Force | Where-Object {
882
+ $PruneSkills -or (Test-Path -LiteralPath (Join-Path $pair.Repo $_.Name))
883
+ } | Select-Object -ExpandProperty Name)
884
+ if ($names.Count -eq 0) { continue }
885
+ $bk = Join-Path $BackupDir $pair.Name
886
+ New-Item -ItemType Directory -Path $bk -Force | Out-Null
887
+ foreach ($n in $names) { Copy-Item -LiteralPath (Join-Path $pair.Local $n) -Destination (Join-Path $bk $n) -Recurse -Force }
888
+ Ok "已备份 $($names.Count) 个将被覆盖的$($pair.Name) 目录到 $bk"
889
+ }
890
+
891
+ # ---------- 1.5 工作区 + 会话还原(默认开、全量;在铺配置文件之前单独跑) ----------
892
+ if (-not $SkipWorkspace) {
893
+ if (Test-SyncGroupEnabled $Scope 'workspace') { Sync-WorkspaceApply } else { Warn '跳过(未勾选同步):工作区资料' }
894
+ if (Test-SyncGroupEnabled $Scope 'conversations') { Sync-ConversationApply } else { Warn '跳过(未勾选同步):会话记录' }
895
+ } else {
896
+ Warn "已指定 -SkipWorkspace,跳过全部工作区与会话还原"
897
+ }
898
+
899
+ # ---------- 2. 铺 profile 配置(把 {{APP_ROOT}} 展开成本机客户端路径) ----------
900
+ $appRootFwd = ($AppRoot -replace '\\', '/').TrimEnd('/')
901
+ if (Test-SyncGroupEnabled $Scope 'profile') {
902
+ foreach ($f in @('cordis.yml', 'cordis.patch.yml', 'pnpm-workspace.yaml', 'pnpm-lock.yaml')) {
903
+ $src = Join-Path $RepoRoot "profile\$f"
904
+ if (-not (Test-Path -LiteralPath $src)) { Warn "仓库里没有 profile\$f,跳过"; continue }
905
+ # 必须读→替换→写。直接 Copy-Item 会把仓库里的 {{APP_ROOT}} 或别的机器的盘符原样带过来,
906
+ # 进而让 pnpm-lock.yaml 与 package.json 对不上,--frozen-lockfile 必挂。
907
+ $raw = Expand-AppRoot (Read-TextPreserveBom $src) $appRootFwd
908
+ # 写完就地核对:占位符没展开会让 cordis.patch.yml 变成非法 YAML(宿主启动直接 fatal),
909
+ # 也会让 pnpm-lock.yaml 的 specifier 与 package.json 对不上。宁可在这里停,也不要把坏文件铺下去。
910
+ if ($raw.Contains($AppRootToken) -or $raw.Contains($WorkspaceHomeToken)) {
911
+ Die "展开占位符失败:$f 里仍有 {{APP_ROOT}}/{{WORKSPACE_HOME}}(-AppRoot=$AppRoot)"
912
+ }
913
+ Write-TextPreserveBom (Join-Path $ProfileDir $f) $raw
914
+ }
915
+ Ok "已写入 cordis.yml / cordis.patch.yml / pnpm-workspace.yaml / pnpm-lock.yaml(路径指向 $appRootFwd)"
916
+
917
+ $pkgRaw = Expand-AppRoot (Read-TextPreserveBom (Join-Path $RepoRoot 'profile\package.json')) $appRootFwd
918
+
919
+
920
+ # 实验性 bundle 门控:@deepseek-ai/dsh-experimental-* 由宿主自带、按 app 版本强绑定,不满足就不写进本机
921
+ $bundlesInRepo = @()
922
+ try { $bundlesInRepo = @(($pkgRaw | ConvertFrom-Json).dsh.profile.bundles) }
923
+ catch { Die "仓库 profile\package.json 不是合法 JSON:$($_.Exception.Message)" }
924
+
925
+ $dropped = @()
926
+ foreach ($b in $bundlesInRepo) {
927
+ if ($b -notlike '@deepseek-ai/dsh-experimental-*') { continue }
928
+ $why = $null
929
+ if ($versionDrift) {
930
+ $why = "本机 app 版本不同($hostAppVersion ≠ $contractVersion)"
931
+ } else {
932
+ # 宿主自带 bundle 的落点因构建而异:解包版在 resources\app\dsh\node_modules,
933
+ # 打包版整包塞在 app.asar 里(磁盘上没有目录)——所以交给 Test-HostBundle 统一判断,别只查路径。
934
+ $bv = $null
935
+ $bundlePkg = $null
936
+ foreach ($hostModules in (Get-HostDshNodeModules $AppRoot)) {
937
+ $probe = Join-Path $hostModules ((($b -replace '/', '\')) + '\package.json')
938
+ if (Test-Path -LiteralPath $probe) { $bundlePkg = $probe; break }
939
+ }
940
+ if ($bundlePkg) {
941
+ try { $bv = [string](Get-Content -LiteralPath $bundlePkg -Raw -Encoding utf8 | ConvertFrom-Json).version } catch { $bv = $null }
942
+ if ($bv -and $hostAppVersion -and ($bv -ne $hostAppVersion)) {
943
+ $why = "该 bundle 版本 $bv 与宿主 $hostAppVersion 不一致"
944
+ }
945
+ } elseif (-not (Test-HostBundle $AppRoot $b)) {
946
+ $why = "客户端自带包里没有这一项"
947
+ }
948
+ }
949
+ if ($why) { $dropped += $b; Warn "剔除实验性 bundle:$b($why)" }
950
+ }
951
+
952
+ foreach ($b in $dropped) {
953
+ $pkgRaw = [regex]::Replace($pkgRaw, '(?m)^[ \t]*"' + [regex]::Escape($b) + '"[ \t]*,?[ \t]*\r?\n', '')
954
+ }
955
+ # 删掉末项后可能留下数组尾逗号,JSON 会因此不合法
956
+ $pkgRaw = [regex]::Replace($pkgRaw, ',[ \t]*(\r?\n[ \t]*\])', '$1')
957
+ try { $finalBundles = @(($pkgRaw | ConvertFrom-Json).dsh.profile.bundles) }
958
+ catch { Die "剔除实验性 bundle 后 package.json 不再是合法 JSON(请手动核对 profile\package.json)" }
959
+ if ($dropped.Count -gt 0) { Ok "已剔除 $($dropped.Count) 个实验性 bundle,清单剩 $($finalBundles.Count) 项" }
960
+
961
+ $localPluginMap = [ordered]@{
962
+ 'dsh-our-free-model-2.8.0' = 'dsh-our-free-model'
963
+ 'dsh-purge-1.4.0' = 'dsh-purge'
964
+ 'dsh-config-sync-plugin-0.3.69' = 'dsh-config-sync-plugin'
965
+ 'dsh-config-sync-plugin-0.3.81' = 'dsh-config-sync-plugin'
966
+ 'dsh-config-sync-plugin-0.3.80' = 'dsh-config-sync-plugin'
967
+ 'dsh-config-sync-plugin-0.3.79' = 'dsh-config-sync-plugin'
968
+ 'dsh-config-sync-plugin-0.3.78' = 'dsh-config-sync-plugin'
969
+ 'dsh-config-sync-plugin-0.3.77' = 'dsh-config-sync-plugin'
970
+ 'dsh-config-sync-plugin-0.3.76' = 'dsh-config-sync-plugin'
971
+ 'dsh-config-sync-plugin-0.3.75' = 'dsh-config-sync-plugin'
972
+ 'dsh-config-sync-plugin-0.3.74' = 'dsh-config-sync-plugin'
973
+ 'dsh-config-sync-plugin-0.3.73' = 'dsh-config-sync-plugin'
974
+ 'dsh-config-sync-plugin-0.3.70' = 'dsh-config-sync-plugin'
975
+ 'dsh-config-sync-plugin-0.3.68' = 'dsh-config-sync-plugin'
976
+ 'dsh-config-sync-plugin-0.3.67' = 'dsh-config-sync-plugin'
977
+ 'dsh-config-sync-plugin-0.3.66' = 'dsh-config-sync-plugin'
978
+ 'dsh-config-sync-plugin-0.3.65' = 'dsh-config-sync-plugin'
979
+ 'dsh-config-sync-plugin-0.3.64' = 'dsh-config-sync-plugin'
980
+ 'dsh-config-sync-plugin-0.3.63' = 'dsh-config-sync-plugin'
981
+ 'dsh-config-sync-plugin-0.3.62' = 'dsh-config-sync-plugin'
982
+ 'dsh-config-sync-plugin-0.3.61' = 'dsh-config-sync-plugin'
983
+ 'dsh-config-sync-plugin-0.3.59' = 'dsh-config-sync-plugin'
984
+ 'dsh-config-sync-plugin-0.3.58' = 'dsh-config-sync-plugin'
985
+ 'dsh-config-sync-plugin-0.3.57' = 'dsh-config-sync-plugin'
986
+ 'dsh-config-sync-plugin-0.3.56' = 'dsh-config-sync-plugin'
987
+ }
988
+ foreach ($dirName in $localPluginMap.Keys) {
989
+ $pattern = 'link:[^"]*' + [regex]::Escape($dirName)
990
+ $pkgRaw = [regex]::Replace($pkgRaw, $pattern, ('link:' + $appRootFwd + '/' + $dirName), 'IgnoreCase')
991
+ }
992
+ Write-TextPreserveBom (Join-Path $ProfileDir 'package.json') $pkgRaw
993
+ Ok "已写入 package.json(link 路径指向 $appRootFwd)"
994
+ } else { Warn '跳过(未勾选同步):profile 配置(package.json / lock / cordis 保持本机现状)' }
995
+
996
+ # ---------- 4. 铺全局提示 ----------
997
+ if (Test-SyncGroupEnabled $Scope 'prompt') {
998
+ foreach ($f in @('AGENTS.md', 'prompt-inject.md')) {
999
+ if (-not (Test-SyncItemEnabled $Scope 'prompt' $f)) { continue }
1000
+ $src = Join-Path $RepoRoot "prompt\$f"
1001
+ if (Test-Path -LiteralPath $src) { Copy-Item -LiteralPath $src -Destination (Join-Path $DshHome $f) -Force; Ok "已写入 $f" }
1002
+ }
1003
+ } else { Warn '跳过(未勾选同步):全局提示(AGENTS.md / prompt-inject.md)' }
1004
+
1005
+ # ---------- 5. 铺 Skills ----------
1006
+ if (Test-SyncGroupEnabled $Scope 'skills') {
1007
+ $skillsSrc = Join-Path $RepoRoot 'skills'
1008
+ $skillsDst = Join-Path $DshHome 'skills'
1009
+ if (Test-Path -LiteralPath $skillsSrc) {
1010
+ New-Item -ItemType Directory -Path $skillsDst -Force | Out-Null
1011
+ $n = 0
1012
+ Get-ChildItem -LiteralPath $skillsSrc -Directory -Force | ForEach-Object {
1013
+ if (-not (Test-SyncItemEnabled $Scope 'skills' $_.Name)) { return }
1014
+ $dstDir = Join-Path $skillsDst $_.Name
1015
+ if (Test-Path -LiteralPath $dstDir) { Remove-Item -LiteralPath $dstDir -Recurse -Force }
1016
+ Copy-Item -LiteralPath $_.FullName -Destination $dstDir -Recurse -Force
1017
+ $n++
1018
+ }
1019
+ Ok "已铺 $n 个 Skill 到 $skillsDst"
1020
+ if ($PruneSkills) {
1021
+ Get-ChildItem -LiteralPath $skillsDst -Directory -Force | Where-Object {
1022
+ (-not (Test-Path -LiteralPath (Join-Path $skillsSrc $_.Name))) -and (Test-SyncItemEnabled $Scope 'skills' $_.Name)
1023
+ } | ForEach-Object {
1024
+ Remove-Item -LiteralPath $_.FullName -Recurse -Force
1025
+ Warn "已按 -PruneSkills 移除本机多余的 Skill:$($_.Name)"
1026
+ }
1027
+ } else {
1028
+ $extraSkills = @(Get-ChildItem -LiteralPath $skillsDst -Directory -Force | Where-Object {
1029
+ -not (Test-Path -LiteralPath (Join-Path $skillsSrc $_.Name))
1030
+ } | Select-Object -ExpandProperty Name)
1031
+ if ($extraSkills.Count -gt 0) {
1032
+ Warn ("本机另有 " + $extraSkills.Count + " 个仓库里没有的 Skill(未动,加 -PruneSkills 才删:" + ($extraSkills -join ', ') + ")")
1033
+ }
1034
+ }
1035
+ }
1036
+ } else { Warn '跳过(未勾选同步):Skills(本机 skills 目录保持现状)' }
1037
+
1038
+ # ---------- 6. 铺 Agent 预设 ----------
1039
+ if (Test-SyncGroupEnabled $Scope 'presets') {
1040
+ $presetSrc = Join-Path $RepoRoot 'presets'
1041
+ $presetDst = Join-Path $DshHome '.agent-presets'
1042
+ if (Test-Path -LiteralPath $presetSrc) {
1043
+ New-Item -ItemType Directory -Path $presetDst -Force | Out-Null
1044
+ Get-ChildItem -LiteralPath $presetSrc -Directory -Force | ForEach-Object {
1045
+ if (-not (Test-SyncItemEnabled $Scope 'presets' $_.Name)) { return }
1046
+ $dstDir = Join-Path $presetDst $_.Name
1047
+ if (Test-Path -LiteralPath $dstDir) { Remove-Item -LiteralPath $dstDir -Recurse -Force }
1048
+ Copy-Item -LiteralPath $_.FullName -Destination $dstDir -Recurse -Force
1049
+ }
1050
+ Ok "已铺 Agent 预设:$((Get-ChildItem -LiteralPath $presetSrc -Directory -Force | Select-Object -ExpandProperty Name) -join ', ')"
1051
+ }
1052
+ } else { Warn '跳过(未勾选同步):Agent 预设' }
1053
+
1054
+ # ---------- 7. 还原技能市场台账 ----------
1055
+ if (Test-SyncGroupEnabled $Scope 'storages-record') {
1056
+ $ledgerSrc = Join-Path $RepoRoot 'storages-record\skill-market-installed.json'
1057
+ $ledgerDir = Join-Path $DshHome 'storages\@montersy123\dsh-skill-market\data'
1058
+ if ((Test-Path -LiteralPath $ledgerSrc) -and (Test-SyncItemEnabled $Scope 'storages-record' 'skill-market-installed.json')) {
1059
+ # 新机器上这个目录由插件首次运行时创建,apply 先跑就得自己建,否则台账会被静默丢掉
1060
+ if (-not (Test-Path -LiteralPath $ledgerDir)) { New-Item -ItemType Directory -Path $ledgerDir -Force | Out-Null }
1061
+ Copy-Item -LiteralPath $ledgerSrc -Destination (Join-Path $ledgerDir 'installed.json') -Force
1062
+ $panelSrc = Join-Path $RepoRoot 'storages-record\skill-market-panel.json'
1063
+ if ((Test-Path -LiteralPath $panelSrc) -and (Test-SyncItemEnabled $Scope 'storages-record' 'skill-market-panel.json')) {
1064
+ Copy-Item -LiteralPath $panelSrc -Destination (Join-Path $ledgerDir 'panel.json') -Force
1065
+ }
1066
+ Ok "已还原技能市场安装台账"
1067
+ } else {
1068
+ Warn "仓库里没有技能市场台账,跳过"
1069
+ }
1070
+ } else { Warn '跳过(未勾选同步):技能市场台账' }
1071
+
1072
+ # ---------- 7.6. 还原插件设置与工作流 ----------
1073
+ # 仓库里存的是占位符({{APP_ROOT}} / {{DSH_HOME}} / {{WORKSPACE_HOME}} / {{ROOT:<key>}}),
1074
+ # 先展开成本机路径再写。展开完还剩占位符的,说明这台机器还没确认过那个根 —— 宁可不写:
1075
+ # 把 {{ROOT:xxx}} 字面量写进配置,插件读到会当成真实路径,报错比不写更难查。
1076
+ $roots = Get-SyncRoots $DshHome $AppRoot $WorkspaceHome
1077
+ $pendingItems = New-Object System.Collections.ArrayList
1078
+ # 覆盖前体检(0.3.36 起):这一步是「整份覆盖」本机文件,本机若改了路径还没推送,改完会被盖回去。
1079
+ # 所以覆盖前把「本机现状(归一化)」和「仓库版本」比一次,不同的记成清单 —— 备份早就有,
1080
+ # 缺的一直是「告知」:不让人事后翻备份目录才发现自己刚改的东西没了。
1081
+ $overwriteItems = New-Object System.Collections.ArrayList
1082
+ if (Test-SyncGroupEnabled $Scope 'settings') {
1083
+ foreach ($m in $settingsMap) {
1084
+ if (-not (Test-SyncItemEnabled $Scope 'settings' ($m.Repo -replace '^settings\\', ''))) { continue }
1085
+ if ($m.Repo -eq 'settings\dsh-workspaces.json' -and (Test-SyncGroupEnabled $Scope 'workspace')) { continue } # workspace registry merged by Sync-WorkspaceApply; do not overwrite with stale repo snapshot
1086
+ $srcRepo = Join-Path $RepoRoot $m.Repo
1087
+ if (-not (Test-Path -LiteralPath $srcRepo)) { Warn ("仓库里没有 " + $m.Repo + ",跳过"); continue }
1088
+ $txt = [IO.File]::ReadAllText($srcRepo)
1089
+ $expanded = Expand-TokenText $txt $roots
1090
+ $missing = @(Get-MissingTokens $expanded)
1091
+ if ($missing.Count -gt 0) {
1092
+ # 缺什么就别写什么:写进去的是占位符字面量,插件读到会当成真实路径
1093
+ foreach ($k in $missing) {
1094
+ $pendingItems.Add([pscustomobject][ordered]@{ token = $k; file = $m.Repo; label = $m.Label; hint = (Get-TokenHint $k) }) | Out-Null
1095
+ }
1096
+ Warn ("跳过 " + $m.Repo + ":需要先确认路径 " + ($missing -join '、'))
1097
+ continue
1098
+ }
1099
+ # 本机已有这份文件、且归一化后与仓库版本不同 → 本次会盖掉本机改动
1100
+ if (Test-Path -LiteralPath $m.Src) {
1101
+ $localRaw = ''
1102
+ try { $localRaw = [IO.File]::ReadAllText($m.Src) } catch { $localRaw = '' }
1103
+ if ($localRaw) {
1104
+ $localNorm = ConvertTo-TokenText $localRaw $roots
1105
+ if ($m.Repo -eq 'settings\our-free-model.json') {
1106
+ foreach ($k in @('catalogSyncedAt', 'reloadedAt', 'reloadCount')) {
1107
+ $localNorm = $localNorm -replace ('("' + $k + '"\s*:\s*)[0-9]+'), '${1}0'
1108
+ }
1109
+ }
1110
+ $localNorm = ($localNorm -replace "`r`n", "`n").TrimEnd()
1111
+ $repoNorm = ($txt -replace "`r`n", "`n").TrimEnd()
1112
+ if ($localNorm -ne $repoNorm) {
1113
+ $bkFile = Join-Path (Join-Path $BackupDir 'settings') (Split-Path -Leaf $m.Src)
1114
+ [void]$overwriteItems.Add([pscustomobject][ordered]@{ repo = $m.Repo; src = $m.Src; label = $m.Label; backup = $bkFile })
1115
+ }
1116
+ }
1117
+ }
1118
+ $dir = Split-Path -Parent $m.Src
1119
+ if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
1120
+ [IO.File]::WriteAllText($m.Src, $expanded, (New-Object Text.UTF8Encoding($false)))
1121
+ }
1122
+ Ok "已还原插件设置 / 工作流 / 各插件配置"
1123
+ } else { Warn '跳过(未勾选同步):插件设置 / 工作流 / 各插件配置' }
1124
+ if ($pendingItems.Count -gt 0) {
1125
+ $pf = Write-PendingPaths $DshHome $pendingItems
1126
+ Warn ("有 " + $pendingItems.Count + " 项配置等待确认路径,本次未写入。已记到 " + $pf + ",到面板「本机路径」选好目录,之后再拉取一次即可。")
1127
+ } elseif (Test-SyncGroupEnabled $Scope 'settings') {
1128
+ Clear-PendingPaths $DshHome
1129
+ }
1130
+ # 覆盖报告:本机这些文件在本次拉取里被仓库版本整份盖掉了(备份路径一并写进去,方便回退)
1131
+ $overwriteReport = Join-Path $DshHome 'config-sync-overwrite.json'
1132
+ if ($overwriteItems.Count -gt 0) {
1133
+ $ovObj = [ordered]@{
1134
+ at = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
1135
+ total = $overwriteItems.Count
1136
+ items = @($overwriteItems)
1137
+ }
1138
+ [IO.File]::WriteAllText($overwriteReport, ($ovObj | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($false)))
1139
+ Warn ("有 " + $overwriteItems.Count + " 份配置被仓库版本覆盖(本机改动已先备份):")
1140
+ foreach ($it in @($overwriteItems | Select-Object -First 5)) { Warn (" - " + $it.label + ":" + $it.repo + "(备份 " + $it.backup + ")") }
1141
+ if ($overwriteItems.Count -gt 5) { Warn (" …还有 " + ($overwriteItems.Count - 5) + " 份,清单:" + $overwriteReport) }
1142
+ Warn " 想保留本机改动就先「推送」再「拉取」,别反过来。"
1143
+ } else {
1144
+ if (Test-Path -LiteralPath $overwriteReport) { try { Remove-Item -LiteralPath $overwriteReport -Force } catch { } }
1145
+ }
1146
+
1147
+ # ---------- 7.5. 还原记忆插件数据目录 mnemon ----------
1148
+ $mnemonSrc = Join-Path $RepoRoot 'mnemon'
1149
+ $mnemonDst = Join-Path $AppRoot 'mnemon'
1150
+ if (-not (Test-SyncGroupEnabled $Scope 'mnemon')) {
1151
+ Warn '跳过(未勾选同步):记忆数据(mnemon)'
1152
+ } elseif ($SkipMnemon) {
1153
+ Warn "已指定 -SkipMnemon,跳过记忆数据(mnemon)还原"
1154
+ } elseif ((Test-Path -LiteralPath $mnemonSrc) -and ((Get-ChildItem -LiteralPath $mnemonSrc -Recurse -File -Force | Measure-Object).Count -gt 0)) {
1155
+ if (Test-Path -LiteralPath $mnemonDst) {
1156
+ # 目标不存在时 Copy-Item 才按目录名落地,不会再套一层 mnemon\mnemon
1157
+ $mnBackup = Join-Path $BackupDir 'mnemon-old'
1158
+ Copy-Item -LiteralPath $mnemonDst -Destination $mnBackup -Recurse -Force
1159
+ Ok "已备份现有 mnemon 到 $mnBackup"
1160
+ } else {
1161
+ New-Item -ItemType Directory -Path $mnemonDst -Force | Out-Null
1162
+ }
1163
+ # 逐个子项合并复制:-LiteralPath 不展开 '*' 万用符,且目标已有同名子目录时 -Recurse 会套娃
1164
+ CopyMerge $mnemonSrc $mnemonDst
1165
+ # 记忆库里存着 holographic store 的绝对路径(D:\\DeepSeekHarness\\mnemon\\...),必须换成本机路径
1166
+ Expand-AppRootTree $mnemonDst $appRootFwd
1167
+ # 本机有、仓库没有的记忆文件:默认保留并提示(它可能是本机新写的、还没 capture 的记忆)
1168
+ $extra = @()
1169
+ Get-ChildItem -LiteralPath $mnemonDst -Recurse -File -Force | ForEach-Object {
1170
+ $rel = Get-RelPath $mnemonDst $_.FullName
1171
+ if ($rel -and -not (Test-Path -LiteralPath (Join-Path $mnemonSrc $rel))) { $extra += $rel }
1172
+ }
1173
+ if ($extra.Count -gt 0) {
1174
+ if ($PruneMnemon) {
1175
+ $extra | ForEach-Object { Remove-Item -LiteralPath (Join-Path $mnemonDst $_) -Force }
1176
+ Warn ("已按 -PruneMnemon 删除本机多出的 " + $extra.Count + " 个记忆文件:" + ($extra -join ', '))
1177
+ } else {
1178
+ Warn ("本机另有 " + $extra.Count + " 个仓库里没有的记忆文件(未动,建议稍后在主力机 capture:" + ($extra -join ', ') + ")")
1179
+ }
1180
+ }
1181
+ $mnCount = (Get-ChildItem -LiteralPath $mnemonDst -Recurse -File -Force | Measure-Object).Count
1182
+ Ok "已还原记忆数据(mnemon)$mnCount 个文件到 $mnemonDst"
1183
+ } else {
1184
+ Warn "仓库里没有 mnemon 数据,跳过记忆目录还原"
1185
+ }
1186
+
1187
+ # ---------- 7.6. 还原插件数据(plugin-data)与额外路径(extra) ----------
1188
+ # capture 时文本已经占位符化,写回前统一展开成本机路径;落盘前把目标侧旧文件留底,
1189
+ # 万一拉错了还能从 $BackupDir 里捞回来。
1190
+ function Expand-TokenTree([string]$dir, $roots) {
1191
+ if (-not (Test-Path -LiteralPath $dir)) { return }
1192
+ $binExt = @('.tgz', '.zip', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.bmp', '.webp', '.exe', '.dll', '.wasm', '.pdf', '.dat', '.woff', '.woff2', '.ttf', '.otf')
1193
+ Get-ChildItem -LiteralPath $dir -Recurse -File -Force -ErrorAction SilentlyContinue | ForEach-Object {
1194
+ if ($_.Extension.ToLower() -in $binExt) { return }
1195
+ $raw = Read-TextPreserveBom $_.FullName
1196
+ if ($raw -match '\{\{(APP_ROOT|DSH_HOME|WORKSPACE_HOME|ROOT:[A-Za-z0-9_.\-]+)\}\}') {
1197
+ Write-TextPreserveBom $_.FullName (Expand-TokenText $raw $roots)
1198
+ }
1199
+ }
1200
+ }
1201
+
1202
+ function Copy-TreeInto([string]$srcRoot, [string]$dstRoot, [string]$backupRoot) {
1203
+ # 逐文件合并:目标已有同名文件先备份到 backupRoot,再覆盖(-Recurse 到已存在目录会套娃,所以不用它)
1204
+ $n = 0
1205
+ if (-not (Test-Path -LiteralPath $srcRoot)) { return 0 }
1206
+ Get-ChildItem -LiteralPath $srcRoot -Recurse -File -Force -ErrorAction SilentlyContinue | ForEach-Object {
1207
+ $rel = Get-RelPath $srcRoot $_.FullName
1208
+ if (-not $rel) { return }
1209
+ $dst = Join-Path $dstRoot $rel
1210
+ $dstParent = Split-Path -Parent $dst
1211
+ if (-not (Test-Path -LiteralPath $dstParent)) { New-Item -ItemType Directory -Path $dstParent -Force | Out-Null }
1212
+ if (Test-Path -LiteralPath $dst) {
1213
+ $bk = Join-Path $backupRoot $rel
1214
+ $bkParent = Split-Path -Parent $bk
1215
+ if (-not (Test-Path -LiteralPath $bkParent)) { New-Item -ItemType Directory -Path $bkParent -Force | Out-Null }
1216
+ Copy-Item -LiteralPath $dst -Destination $bk -Force
1217
+ }
1218
+ Copy-Item -LiteralPath $_.FullName -Destination $dst -Force
1219
+ $n++
1220
+ }
1221
+ return $n
1222
+ }
1223
+
1224
+ $pdRoots = Get-SyncRoots $DshHome $AppRoot $WorkspaceHome
1225
+
1226
+ if (-not (Test-SyncGroupEnabled $Scope 'plugin-data')) {
1227
+ Warn '跳过(未勾选同步):插件数据(plugin-data)'
1228
+ } else {
1229
+ $pdSrc = Join-Path $RepoRoot 'plugin-data'
1230
+ $pdMf = Join-Path $pdSrc 'manifest.json'
1231
+ if (-not (Test-Path -LiteralPath $pdMf)) {
1232
+ Warn '仓库里没有 plugin-data\manifest.json,跳过插件数据还原'
1233
+ } else {
1234
+ $pdManifest = Get-Content -LiteralPath $pdMf -Raw -Encoding utf8 | ConvertFrom-Json
1235
+ $pdDone = 0
1236
+ foreach ($slot in @($pdManifest.slots)) {
1237
+ if (-not $slot.id -or -not $slot.src) { continue }
1238
+ if (-not (Test-SyncItemEnabled $Scope 'plugin-data' $slot.id)) { Warn ('跳过(已排除):插件数据 ' + $slot.id); continue }
1239
+ $slotSrc = Join-Path $pdSrc $slot.id
1240
+ if (-not (Test-Path -LiteralPath $slotSrc)) { continue }
1241
+ $expanded = Expand-TokenText ([string]$slot.src) $pdRoots
1242
+ $miss = @(Get-MissingTokens $expanded)
1243
+ if ($miss.Count -gt 0) { Warn ('插件数据 ' + $slot.id + ' 的目标路径展开后仍有未配置占位符:' + ($miss -join ',')); continue }
1244
+ $dst = $expanded.Replace('/', $BS)
1245
+ if (-not $dst) { continue }
1246
+ if (-not (Test-Path -LiteralPath $dst)) { New-Item -ItemType Directory -Path $dst -Force | Out-Null }
1247
+ $bk = Join-Path $BackupDir ('plugin-data-' + $slot.id)
1248
+ $n = Copy-TreeInto $slotSrc $dst $bk
1249
+ Expand-TokenTree $dst $pdRoots
1250
+ $pdDone++
1251
+ Ok ('已还原插件数据 ' + $slot.id + ':' + $n + ' 个文件 → ' + $dst)
1252
+ }
1253
+ if ($pdDone -eq 0) { Warn '插件数据:没有可还原的槽(仓库里没有内容或都被排除)' }
1254
+ }
1255
+ }
1256
+
1257
+ if (-not (Test-SyncGroupEnabled $Scope 'extra')) {
1258
+ Warn '跳过(未勾选同步):额外路径(extra)'
1259
+ } else {
1260
+ $exSrc = Join-Path $RepoRoot 'extra'
1261
+ $exMf = Join-Path $exSrc 'manifest.json'
1262
+ if (-not (Test-Path -LiteralPath $exMf)) {
1263
+ Warn '仓库里没有 extra\manifest.json,跳过额外路径还原'
1264
+ } else {
1265
+ $exManifest = Get-Content -LiteralPath $exMf -Raw -Encoding utf8 | ConvertFrom-Json
1266
+ foreach ($it in @($exManifest.items)) {
1267
+ if (-not $it.id -or -not $it.src) { continue }
1268
+ if (-not (Test-SyncItemEnabled $Scope 'extra' $it.id)) { Warn ('跳过(已排除):额外路径 ' + $it.id); continue }
1269
+ $expanded = Expand-TokenText ([string]$it.src) $pdRoots
1270
+ $miss = @(Get-MissingTokens $expanded)
1271
+ if ($miss.Count -gt 0) { Warn ('额外路径 ' + $it.id + ' 的目标路径展开后仍有未配置占位符:' + ($miss -join ',')); continue }
1272
+ $dst = $expanded.Replace('/', $BS)
1273
+ if (-not $dst) { continue }
1274
+ if ($it.kind -eq 'dir') {
1275
+ $itemSrc = Join-Path $exSrc $it.id
1276
+ if (-not (Test-Path -LiteralPath $itemSrc)) { continue }
1277
+ if (-not (Test-Path -LiteralPath $dst)) { New-Item -ItemType Directory -Path $dst -Force | Out-Null }
1278
+ $bk = Join-Path $BackupDir ('extra-' + $it.id)
1279
+ $n = Copy-TreeInto $itemSrc $dst $bk
1280
+ Expand-TokenTree $dst $pdRoots
1281
+ Ok ('已还原额外路径 ' + $it.id + ':' + $n + ' 个文件 → ' + $dst)
1282
+ } else {
1283
+ $leaf = Split-Path -Leaf ([string]$it.src)
1284
+ $itemSrc = Join-Path $exSrc ($it.id + (Split-Path -Extension $dst))
1285
+ if (-not (Test-Path -LiteralPath $itemSrc)) {
1286
+ $itemSrc = Join-Path $exSrc $it.id
1287
+ if (-not (Test-Path -LiteralPath $itemSrc)) { continue }
1288
+ }
1289
+ $dstParent = Split-Path -Parent $dst
1290
+ if ($dstParent -and -not (Test-Path -LiteralPath $dstParent)) { New-Item -ItemType Directory -Path $dstParent -Force | Out-Null }
1291
+ if (Test-Path -LiteralPath $dst) {
1292
+ $bk = Join-Path $BackupDir ('extra-' + $leaf)
1293
+ $bkParent = Split-Path -Parent $bk
1294
+ if ($bkParent -and -not (Test-Path -LiteralPath $bkParent)) { New-Item -ItemType Directory -Path $bkParent -Force | Out-Null }
1295
+ Copy-Item -LiteralPath $dst -Destination $bk -Force
1296
+ }
1297
+ Copy-Item -LiteralPath $itemSrc -Destination $dst -Force
1298
+ # 只展开这一个文件(整目录展开会改到用户同目录下的其他文件)
1299
+ if ((Split-Path -Extension $dst).ToLower() -notin @('.tgz', '.zip', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.exe', '.dll', '.wasm', '.pdf')) {
1300
+ $raw = Read-TextPreserveBom $dst
1301
+ if ($raw -match '\{\{(APP_ROOT|DSH_HOME|WORKSPACE_HOME|ROOT:[A-Za-z0-9_.\-]+)\}\}') { Write-TextPreserveBom $dst (Expand-TokenText $raw $pdRoots) }
1302
+ }
1303
+ Ok ('已还原额外路径 ' + $it.id + ':单个文件 → ' + $dst)
1304
+ }
1305
+ }
1306
+ }
1307
+ }
1308
+
1309
+
1310
+ # 读归档里的插件版本:tgz 里是 package/package.json,zip 里是 <目录名>/package.json 或根 package.json。
1311
+ # 读不出来返回 $null,调用方回退到 mtime 判据(不因为读不到就盲目重铺)。
1312
+ function Compare-PluginVersion([string]$a, [string]$b) {
1313
+ $pa = $null; $pb = $null
1314
+ if ($a -match '^v?(\d+)\.(\d+)\.(\d+)') { $pa = @([int]$matches[1], [int]$matches[2], [int]$matches[3]) }
1315
+ if ($b -match '^v?(\d+)\.(\d+)\.(\d+)') { $pb = @([int]$matches[1], [int]$matches[2], [int]$matches[3]) }
1316
+ if ((-not $pa) -or (-not $pb)) { return $null }
1317
+ for ($i = 0; $i -lt 3; $i++) { if ($pa[$i] -gt $pb[$i]) { return 1 }; if ($pa[$i] -lt $pb[$i]) { return -1 } }
1318
+ return 0
1319
+ }
1320
+
1321
+ function Get-ArchivePluginVersion([string]$archPath, [string]$dirName) {
1322
+ try {
1323
+ if ($archPath -like '*.tgz' -or $archPath -like '*.tar.gz') {
1324
+ $tar = Join-Path $env:SystemRoot 'System32\tar.exe'
1325
+ if (-not (Test-Path -LiteralPath $tar)) { return $null }
1326
+ $json = & $tar -xzf $archPath -O package/package.json 2>$null
1327
+ if ($LASTEXITCODE -ne 0 -or -not $json) { return $null }
1328
+ return [string]((($json -join "`n")) | ConvertFrom-Json).version
1329
+ }
1330
+ if ($archPath -like '*.zip') {
1331
+ try { Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop } catch { }
1332
+ $zip = [IO.Compression.ZipFile]::OpenRead($archPath)
1333
+ try {
1334
+ $entry = $zip.Entries | Where-Object { $_.FullName -match ("(^|[\\/])" + [regex]::Escape($dirName) + "[\\/]package\.json$") } | Select-Object -First 1
1335
+ if (-not $entry) { $entry = $zip.Entries | Where-Object { $_.FullName -match '^(package[\\/])?package\.json$' } | Select-Object -First 1 }
1336
+ if (-not $entry) { return $null }
1337
+ $sr = New-Object IO.StreamReader($entry.Open())
1338
+ try { return [string](($sr.ReadToEnd()) | ConvertFrom-Json).version } finally { $sr.Dispose() }
1339
+ } finally { $zip.Dispose() }
1340
+ }
1341
+ } catch { return $null }
1342
+ return $null
1343
+ }
1344
+
1345
+ # ---------- 8. 就位本地插件(link: 依赖) ----------
1346
+ if (Test-SyncGroupEnabled $Scope 'local-plugins') {
1347
+ $needExtract = @()
1348
+
1349
+ # 新增:预先扫描本机已部署的插件基础名,避免同一插件的不同历史版本号重复报「没装」。
1350
+ # 例如本机已装 dsh-config-sync-plugin-0.3.70,就不再为 0.3.57~0.3.69 各发一次 plugin-missing。
1351
+ $installedBaseNames = @{}
1352
+ Get-ChildItem -LiteralPath $AppRoot -Directory -Force -ErrorAction SilentlyContinue | ForEach-Object {
1353
+ $dName = $_.Name
1354
+ if ($dName -match '^(.+?)(-\d+\.\d+.*)$') {
1355
+ $installedBaseNames[$matches[1]] = $true
1356
+ }
1357
+ }
1358
+
1359
+ foreach ($dirName in $localPluginMap.Keys) {
1360
+ if (-not (Test-SyncItemEnabled $Scope 'local-plugins' $dirName)) { continue }
1361
+ $target = Join-Path $AppRoot $dirName
1362
+
1363
+ # 新增:若目录不存在,但同一插件的其他版本已装,跳过旧版本号的缺失检查
1364
+ if (-not (Test-Path -LiteralPath $target)) {
1365
+ $baseName = $localPluginMap[$dirName]
1366
+ if ($installedBaseNames.ContainsKey($baseName)) {
1367
+ continue
1368
+ }
1369
+ }
1370
+
1371
+ if (Test-Path -LiteralPath $target) {
1372
+ # 已部署的目录不会被覆盖,否则插件升级永远到不了本机(仓库里的 tgz 更新了也没用)。
1373
+ # 判据改成比版本号:归档里的 package.json version vs 已部署目录的 version,不同才算新版本。
1374
+ # 以前比 mtime,而 git checkout/fetch 会把归档的 mtime 刷成当前时间 → 每轮同步都误判「有新版本」,
1375
+ # 于是反复改名备份 + 重新解压(实测 dsh-purge-1.1.92 与 .bak-时间戳 并存、每轮多搬一次目录就是这么来的)。
1376
+ $arch = Join-Path $RepoRoot "local-plugins\$dirName.tgz"
1377
+ if (-not (Test-Path -LiteralPath $arch)) { $arch = Join-Path $RepoRoot "local-plugins\$dirName.zip" }
1378
+ $archVer = if (Test-Path -LiteralPath $arch) { Get-ArchivePluginVersion $arch $dirName } else { $null }
1379
+ $depVer = $null
1380
+ $depPkgFile = Join-Path $target 'package.json'
1381
+ if (Test-Path -LiteralPath $depPkgFile) {
1382
+ try { $depVer = [string]((Get-Content -LiteralPath $depPkgFile -Raw -Encoding utf8 | ConvertFrom-Json).version) } catch { $depVer = $null }
1383
+ }
1384
+ $hasNewVersion = $false
1385
+ if ((Test-Path -LiteralPath $arch) -and $archVer -and $depVer) {
1386
+ $cmpVer = Compare-PluginVersion $archVer $depVer
1387
+ if ($null -ne $cmpVer) { $hasNewVersion = ($cmpVer -gt 0) } else { $hasNewVersion = ($archVer -ne $depVer) }
1388
+ } elseif (Test-Path -LiteralPath $arch) {
1389
+ # 读不到版本(老归档、结构异常)时退回 mtime,但要求比已部署目录新 10 秒以上,避免每轮误判
1390
+ $archTime = (Get-Item -LiteralPath $arch).LastWriteTime
1391
+ $depTime = (Get-ChildItem -LiteralPath $target -Recurse -File -Force | Sort-Object LastWriteTime -Descending | Select-Object -First 1).LastWriteTime
1392
+ $hasNewVersion = $archTime -gt $depTime.AddSeconds(10)
1393
+ }
1394
+ if ($hasNewVersion) {
1395
+ Warn "本地插件有新版本,将重新部署:$target($depVer → $archVer,旧目录先改名备份)"
1396
+ $bak = "$target.bak-" + (Get-Date -Format 'yyyyMMddHHmmss')
1397
+ Move-Item -LiteralPath $target -Destination $bak
1398
+ Ok "旧版本已备份为:$bak"
1399
+ # 同一插件只留刚生成的这一份备份:这些目录动辄几十兆,攒几次会把小盘塞满
1400
+ Get-ChildItem -LiteralPath $AppRoot -Directory -Force -ErrorAction SilentlyContinue |
1401
+ Where-Object { $_.Name -like "$dirName.bak-*" -and $_.FullName -ne $bak } |
1402
+ ForEach-Object {
1403
+ Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue
1404
+ Warn ("已清理更旧的插件备份:" + $_.Name)
1405
+ }
1406
+ $needExtract += $dirName
1407
+ } else {
1408
+ Ok "本地插件已存在:$target"
1409
+ }
1410
+ } else {
1411
+ $needExtract += $dirName
1412
+ }
1413
+ }
1414
+ if ($needExtract.Count -gt 0) {
1415
+ # tar 在部分机器(精简 PATH、服务账户、非交互进程)里不在 PATH,必须用绝对路径
1416
+ $tarExe = Join-Path $env:SystemRoot 'System32\tar.exe'
1417
+ if (-not (Test-Path -LiteralPath $tarExe)) {
1418
+ $alt = Join-Path $env:SystemRoot 'System32\bsdtar.exe'
1419
+ if (Test-Path -LiteralPath $alt) { $tarExe = $alt } else { $tarExe = '' }
1420
+ }
1421
+ $staging = Join-Path $env:TEMP ("dshcfg-" + [guid]::NewGuid().ToString('N').Substring(0, 8))
1422
+ New-Item -ItemType Directory -Path $staging -Force | Out-Null
1423
+ foreach ($dirName in $needExtract) {
1424
+ $tgz = Join-Path $RepoRoot "local-plugins\$dirName.tgz"
1425
+ $zip = Join-Path $RepoRoot "local-plugins\$dirName.zip"
1426
+ $out = Join-Path $staging $dirName
1427
+ if (Test-Path -LiteralPath $tgz) {
1428
+ if ([string]::IsNullOrEmpty($tarExe)) { Die "找不到 tar.exe($env:SystemRoot\System32\tar.exe),无法解压 $tgz" }
1429
+ New-Item -ItemType Directory -Path $out -Force | Out-Null
1430
+ & $tarExe -xzf $tgz -C $out
1431
+ if ($LASTEXITCODE -ne 0) { Die "解压失败:$tgz(tar 退出码 $LASTEXITCODE)" }
1432
+ # npm tgz 的根目录是 package/,需要摊平
1433
+ $pkgDir = Join-Path $out 'package'
1434
+ if (Test-Path -LiteralPath $pkgDir) {
1435
+ $final = Join-Path $AppRoot $dirName
1436
+ if (Test-Path -LiteralPath $final) { Remove-Item -LiteralPath $final -Recurse -Force }
1437
+ Move-Item -LiteralPath $pkgDir -Destination $final
1438
+ }
1439
+ Ok "已解压并部署:$final"
1440
+ } elseif (Test-Path -LiteralPath $zip) {
1441
+ Expand-Archive -LiteralPath $zip -DestinationPath $out -Force
1442
+ $inner = Join-Path $out $dirName
1443
+ if (-not (Test-Path -LiteralPath $inner)) { $inner = $out }
1444
+ $final = Join-Path $AppRoot $dirName
1445
+ if (Test-Path -LiteralPath $final) { Remove-Item -LiteralPath $final -Recurse -Force }
1446
+ Move-Item -LiteralPath $inner -Destination $final
1447
+ Ok "已解压并部署:$final"
1448
+ } else {
1449
+ Warn "仓库里没有 $dirName 的归档,跳过(该插件会装不上)"
1450
+ Add-SyncNotice -Kind 'plugin-missing' -Path $dirName -Reason ('仓库的 local-plugins\ 里没有这个源码插件包的归档(.tgz/.zip),本机装不上。在主力机跑 capture.ps1 -PackLocalPlugins 打包并推送,然后在本机重新拉取一次。')
1451
+ }
1452
+ }
1453
+ Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue
1454
+ }
1455
+ } else { Warn '跳过(未勾选同步):本地源码插件包(local-plugins)' }
1456
+
1457
+ # ---------- 9. pnpm install ----------
1458
+ if ($SkipInstall) {
1459
+ Warn "已指定 -SkipInstall,跳过依赖安装。插件需要手动处理后再启动。"
1460
+ } else {
1461
+ $nodeExe = Join-Path $AppRoot 'resources\runtime\primary-runtime\dependencies\node\bin\node.exe'
1462
+ $pnpmCjs = Join-Path $AppRoot 'resources\runtime\primary-runtime\dependencies\pnpm\bin\pnpm.cjs'
1463
+ Push-Location $ProfileDir
1464
+ try {
1465
+ $installed = $false
1466
+ $skipBecauseReady = $false
1467
+ if ((Test-Path -LiteralPath $nodeExe) -and (Test-Path -LiteralPath $pnpmCjs)) {
1468
+ Say " 使用客户端内置 pnpm 安装依赖(严格按 lockfile)..."
1469
+ & $nodeExe $pnpmCjs install --frozen-lockfile
1470
+ $code = $LASTEXITCODE
1471
+ if ($code -ne 0) {
1472
+ # 严格模式失败最常见的原因是 lockfile 与 package.json 的 specifier 对不上(老仓库的盘符残留、
1473
+ # 或捕获机和本机的依赖清单本来就有差异)。这时按 package.json 重新解析一次并重写 lockfile。
1474
+ Warn "pnpm install --frozen-lockfile 返回 $code,改为 --no-frozen-lockfile 重试(会就地重写 pnpm-lock.yaml)..."
1475
+ & $nodeExe $pnpmCjs install --no-frozen-lockfile
1476
+ $code = $LASTEXITCODE
1477
+ if ($code -eq 0) { Warn "已用 --no-frozen-lockfile 装好;记得回主力机跑 capture,把新 lockfile 提交回仓库" }
1478
+ }
1479
+ $installed = ($code -eq 0)
1480
+ } elseif (Get-Command pnpm -ErrorAction SilentlyContinue) {
1481
+ Say " 使用系统 pnpm 安装依赖..."
1482
+ & pnpm install --frozen-lockfile
1483
+ if ($LASTEXITCODE -ne 0) { & pnpm install --no-frozen-lockfile }
1484
+ $installed = ($LASTEXITCODE -eq 0)
1485
+ } else {
1486
+ # 找不到 pnpm(客户端内置路径随版本变、系统也可能没装)时不能一律 exit 1:
1487
+ # post-exit 会把 apply 的非零退出码当成「拉取失败」,接着自动回滚仓库和配置,
1488
+ # 于是拉取明明成功了却被打回原状(真实故障:18 项全选云端、快进完成后又被回滚)。
1489
+ # 只要 profile 里 node_modules 已经存在,依赖就是可用的,按成功处理。
1490
+ $nodeModules = Join-Path $ProfileDir 'node_modules'
1491
+ if (Test-Path -LiteralPath $nodeModules) {
1492
+ $installed = $true
1493
+ $skipBecauseReady = $true
1494
+ } else {
1495
+ Warn "找不到 pnpm,且 $nodeModules 不存在,跳过安装。请手动在 $ProfileDir 执行 pnpm install --frozen-lockfile"
1496
+ Pop-Location
1497
+ exit 1
1498
+ }
1499
+ }
1500
+ if ($installed) {
1501
+ if ($skipBecauseReady) { Ok '依赖已就绪(profile 里已有 node_modules),无需 pnpm 安装' }
1502
+ else { Ok '依赖安装完成' }
1503
+ }
1504
+ else { Warn "pnpm install 仍未成功,依赖没装上(下面的自检会把缺的插件列出来)" }
1505
+ } finally {
1506
+ Pop-Location
1507
+ }
1508
+ }
1509
+
1510
+ # ---------- 9.5 内置运行时链接修复 ----------
1511
+ # 客户端升级会清空 resources\runtime,装卸插件所依赖的 pnpm 路径随之失效
1512
+ # (报错形如 Cannot find module ...\dependencies\pnpm\bin\pnpm.mjs)。
1513
+ # 每次落地都幂等补回一次链接;已在就别动,是真实目录也别动。
1514
+ Repair-PrimaryRuntimeLink $AppRoot $DshHome
1515
+
1516
+ # ---------- 9.6 清理卸载残留:孤儿链接 + 冗余插件备份 ----------
1517
+ # 插件卸载会删安装目录、package.json 依赖、cordis 段,却常常漏掉 profile\node_modules 里那条
1518
+ # junction(实测 dsh-image-search:目标目录删了、链接还指着它)。这类断链 pnpm 管不着——平铺布局下
1519
+ # 它只按 lockfile 重装,而链接不是它建的;同步过去也从来不清理,于是一直挂到下次重装。
1520
+ # 判据只认同时成立的三种情况,宁可漏删也不误删正常依赖:
1521
+ # ① 是链接(Junction / SymbolicLink)
1522
+ # ② 所有 Target 都不存在
1523
+ # ③ 不在 package.json 的 dependencies 里
1524
+ if (Test-SyncGroupEnabled $Scope 'profile') {
1525
+ $nmDir = Join-Path $ProfileDir 'node_modules'
1526
+ if (Test-Path -LiteralPath $nmDir) {
1527
+ $depNames = @()
1528
+ try { $depNames = @((Get-Content -LiteralPath (Join-Path $ProfileDir 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json).dependencies.PSObject.Properties.Name) } catch { $depNames = @() }
1529
+
1530
+ $candidates = New-Object System.Collections.ArrayList
1531
+ Get-ChildItem -LiteralPath $nmDir -Force -ErrorAction SilentlyContinue | ForEach-Object {
1532
+ [void]$candidates.Add([pscustomobject]@{ Rel = $_.Name; Item = $_ })
1533
+ }
1534
+ foreach ($sc in (Get-ChildItem -LiteralPath $nmDir -Force -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like '@*' -and -not $_.LinkType })) {
1535
+ Get-ChildItem -LiteralPath $sc.FullName -Force -ErrorAction SilentlyContinue | ForEach-Object {
1536
+ [void]$candidates.Add([pscustomobject]@{ Rel = ($sc.Name + '/' + $_.Name); Item = $_ })
1537
+ }
1538
+ }
1539
+
1540
+ $pruned = 0
1541
+ foreach ($c in $candidates) {
1542
+ $it = $c.Item
1543
+ if (-not $it.LinkType) { continue }
1544
+ if ($depNames -contains $c.Rel) { continue }
1545
+ $alive = $false
1546
+ foreach ($tg in @($it.Target)) { if ($tg -and (Test-Path -LiteralPath $tg)) { $alive = $true; break } }
1547
+ if ($alive) { continue }
1548
+ try {
1549
+ # junction 必须用 Directory.Delete 删链接本身;Remove-Item -Recurse 在旧实现里可能顺着链接删到目标
1550
+ if ($it.PSIsContainer) { [IO.Directory]::Delete($it.FullName, $false) }
1551
+ else { [IO.File]::Delete($it.FullName) }
1552
+ $pruned++
1553
+ Warn ("已清理孤儿链接(卸载残留):{0} → 目标不存在 {1}" -f $c.Rel, ($it.Target -join ','))
1554
+ } catch {
1555
+ Warn ("孤儿链接删不掉(可能被占用):{0} → {1}" -f $c.Rel, $_.Exception.Message)
1556
+ }
1557
+ }
1558
+ if ($pruned -gt 0) { Ok "已清理 $pruned 个孤儿链接" } else { Ok '没有孤儿链接' }
1559
+ }
1560
+
1561
+ # 插件备份:<目录>.bak-<时间戳> 是「旧目录先改名备份」留下的。同版本备份毫无价值(内容就是刚
1562
+ # 铺上去的那一份),直接清掉;版本不同的只留最新一份。主目录已不存在的备份保留(可能是唯一回滚点)。
1563
+ $bakDirs = @(Get-ChildItem -LiteralPath $AppRoot -Directory -Force -ErrorAction SilentlyContinue | Where-Object { $_.Name -match '^(.+)\.bak-\d{14}$' })
1564
+ if ($bakDirs.Count -gt 0) {
1565
+ $bm = 0
1566
+ foreach ($g in ($bakDirs | Group-Object { [regex]::Match($_.Name, '^(.+)\.bak-\d{14}$').Groups[1].Value })) {
1567
+ $livePkg = Join-Path (Join-Path $AppRoot $g.Name) 'package.json'
1568
+ $liveVer = $null
1569
+ if (Test-Path -LiteralPath $livePkg) { try { $liveVer = [string]((Get-Content -LiteralPath $livePkg -Raw -Encoding utf8 | ConvertFrom-Json).version) } catch { } }
1570
+ if (-not $liveVer) { continue }
1571
+ $keep = ($g.Group | Sort-Object Name -Descending | Select-Object -First 1)
1572
+ foreach ($b in $g.Group) {
1573
+ $bPkg = Join-Path $b.FullName 'package.json'
1574
+ $bVer = $null
1575
+ if (Test-Path -LiteralPath $bPkg) { try { $bVer = [string]((Get-Content -LiteralPath $bPkg -Raw -Encoding utf8 | ConvertFrom-Json).version) } catch { } }
1576
+ $same = ($bVer -and ($bVer -eq $liveVer))
1577
+ $latest = ($b.FullName -eq $keep.FullName)
1578
+ if ($same -or (-not $latest)) {
1579
+ Remove-Item -LiteralPath $b.FullName -Recurse -Force -ErrorAction SilentlyContinue
1580
+ $bm++
1581
+ Warn ("已清理插件备份:{0}({1})" -f $b.Name, $(if ($same) { '与在用版本相同,冗余' } else { '只保留最新一份' }))
1582
+ }
1583
+ }
1584
+ }
1585
+ if ($bm -eq 0) { Ok '插件备份无需清理' }
1586
+ }
1587
+ }
1588
+ # ---------- 10. 自检 ----------
1589
+ Say ""
1590
+ Say "== 自检 =="
1591
+ $deps = (Get-Content -LiteralPath (Join-Path $ProfileDir 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json).dependencies
1592
+ $missing = @()
1593
+ foreach ($name in $deps.PSObject.Properties.Name) {
1594
+ # 包名里的 / 要换成 \ 才是真实的 node_modules 路径(@scope/name → @scope\name)
1595
+ $probe = Join-Path $ProfileDir ("node_modules\" + ($name -replace '/', '\'))
1596
+ if (-not (Test-Path -LiteralPath $probe)) { $missing += $name }
1597
+ }
1598
+ if ($missing.Count -eq 0) {
1599
+ Ok "全部 $(@($deps.PSObject.Properties).Count) 个插件依赖已就位"
1600
+ } else {
1601
+ Warn ("缺少 $($missing.Count) 个插件:" + ($missing -join ', '))
1602
+ # 拉取只还原配置文件,不会替本机安装依赖:仓库里没有这些插件的实体(它们该由 pnpm install 从
1603
+ # registry 装,或从 local-plugins 的归档解压)。把每一个都记进未同步清单,面板会常驻提示
1604
+ # 「装好插件后再拉取一次」,否则用户只看到插件页少几项、不知道下一步做什么。
1605
+ foreach ($nm in $missing) {
1606
+ $why = '插件未安装到本机:拉取不会替你装依赖。'
1607
+ if ($SkipInstall) { $why += '本次带了 -SkipInstall,pnpm install 被跳过;' }
1608
+ $why += '在 profile 目录执行一次 pnpm install(或去掉 -SkipInstall 重跑本脚本),装好后重新拉取一次。'
1609
+ Add-SyncNotice -Kind 'plugin-missing' -Path $nm -Reason $why
1610
+ }
1611
+ Warn '已把这些插件记进未同步清单(sync-notices.json),面板会一直提示到装好并重新拉取为止。'
1612
+ }
1613
+
1614
+ # bundle 可解析性检查:清单里写了、本机却没有 → 启动期 entry loading 必挂(整个应用起不来,不是功能不可用)
1615
+ # 解析顺序与 DSH 一致:先 profile\node_modules(pnpm 装的),再 <AppRoot>\resources\app\dsh\node_modules(宿主自带)
1616
+ $bundles = @((Get-Content -LiteralPath (Join-Path $ProfileDir 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json).dsh.profile.bundles)
1617
+ $unresolved = @()
1618
+ foreach ($b in $bundles) {
1619
+ $rel = ($b -replace '/', '\')
1620
+ if (Test-Path -LiteralPath (Join-Path (Join-Path $ProfileDir 'node_modules') ($rel + '\package.json'))) { continue }
1621
+ if (Test-HostBundle $AppRoot $b) { continue }
1622
+ $unresolved += $b
1623
+ }
1624
+ if ($unresolved.Count -eq 0) {
1625
+ Ok "bundle 清单 $($bundles.Count) 项,全部可解析"
1626
+ } else {
1627
+ Warn "以下 $($unresolved.Count) 个 bundle 在本机找不到,启动会在 entry loading 阶段失败:"
1628
+ $unresolved | ForEach-Object { Warn " - $_" }
1629
+ foreach ($ub in $unresolved) {
1630
+ Add-SyncNotice -Kind 'plugin-missing' -Path $ub -Reason ('bundle 在本机解析不到:插件没装好(pnpm install 没成功,或仓库里没有这个插件的归档)。装好后重新拉取一次;若它是宿主绑定的实验性 bundle,删掉本机 profile\package.json 里那一行。')
1631
+ }
1632
+ if (-not $ForceBundles) {
1633
+ Die ("已停止,先别启动。处理:①若上面「缺少插件」不为空,说明 pnpm install 没成功;" +
1634
+ "②若是宿主绑定的实验性 bundle,直接删掉本机 profile\package.json 里那一行;" +
1635
+ "③确认无误后可加 -ForceBundles 跳过本检查(启动仍有崩溃风险)。")
1636
+ }
1637
+ Warn "已加 -ForceBundles,跳过该检查(启动仍可能崩溃)"
1638
+ }
1639
+ Ok "Skill 目录:$((Get-ChildItem -LiteralPath $skillsDst -Directory -Force -ErrorAction SilentlyContinue | Measure-Object).Count) 个"
1640
+ Say ""
1641
+ Say "下一步:完全启动 DSH(不是重启窗口,要确认进程全部退出后再开)。"
1642
+ if ($hostAppVersion) { Say "版本:本机 app = $hostAppVersion(仓库契约 $contractVersion)" }
1643
+ Say "验证:插件页看 20 项是否齐全、按要求检查 cordis.patch.yml 里的开关是否生效、Skill 列表能列出。"
1644
+ Say "如需回滚:把 $BackupDir 里的文件拷回原位置(工作区资料在 workspace\ 子目录、登记表备份为 workspace-registry-before.json)。"
1645
+
1646
+ exit 0