dsh-config-sync-plugin 0.0.0-stage → 0.3.57

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,537 @@
1
+ <#
2
+ DSH 配置同步 —— 快速还原(把本机 profile 退回到某个备份快照,或直接取 git 某个提交里的配置)
3
+
4
+ 为什么需要它:
5
+ apply.ps1 每次跑之前都会在 ~\.dsh\backups\config-<时间戳>\ 打一份快照,但没有回退入口;
6
+ 真出问题(起不来、插件全挂、依赖半装)时只能手工拷文件,容易漏、且容易把当前状态也弄丢。
7
+ 本脚本把「先自保、再回退、再重装、再核对」收成一步。
8
+
9
+ 用法
10
+ powershell -File restore.ps1 # 取 ~\.dsh\backups 下最新一份快照回退
11
+ powershell -File restore.ps1 -BackupDir "$env:USERPROFILE\.dsh\backups\config-20261109-191310"
12
+ powershell -File restore.ps1 -FromCommit 9acc303 # 没有快照(新机器第一次就崩)时,从仓库某个提交取配置
13
+ powershell -File restore.ps1 -DryRun # 只打印将要做什么,不写任何文件
14
+ powershell -File restore.ps1 -SkipInstall # 只还原文件,不跑 pnpm install
15
+ powershell -File restore.ps1 -WithMnemon # 连 <AppRoot>\mnemon 一起回(快照里有 mnemon-old 才有效)
16
+
17
+ 要点
18
+ - 回退前先把当前状态另存一份 manual-<时间戳>,回退错了还能再回退回来。
19
+ - 只覆盖、不删除:本机多出来的文件不会被清掉(避免误删你后来新增的插件配置)。
20
+ - 还原完按 profile\package.json 的 bundles 逐项检查能否在本机解析,缺就提示/重装依赖。
21
+ #>
22
+ param(
23
+ [string]$RepoRoot = (Split-Path -Parent $PSCommandPath),
24
+ [string]$DshHome = $(Join-Path $env:USERPROFILE '.dsh'),
25
+ [string]$ProfileName = 'desktop',
26
+ [string]$AppRoot = '',
27
+ [string]$BackupDir = '',
28
+ [string]$FromCommit = '',
29
+ [switch]$SkipInstall,
30
+ [switch]$WithMnemon,
31
+ # 时点还原:把快照之后新增的文件 / 插件一并撤走(不是真删,移进 manual-<时间戳>\rollback,可再还原)
32
+ [switch]$RollbackToPoint,
33
+ # 备份类型:profile=配置快照(时点回退,默认);plugin=插件本体备份(回滚插件);session=会话目录备份
34
+ [ValidateSet('profile', 'plugin', 'session')]
35
+ [string]$SnapshotKind = 'profile',
36
+ # plugin 还原的目标:当前插件安装目录(面板会传 <插件根>,不传就按 AppRoot 下最新的 dsh-config-sync* 探测)
37
+ [string]$PluginDir = '',
38
+ [switch]$DryRun,
39
+ [switch]$Force
40
+ )
41
+
42
+ $ErrorActionPreference = 'Stop'
43
+ . (Join-Path $PSScriptRoot 'dsh-sync-common.ps1')
44
+
45
+ $ProfileDir = Join-Path $DshHome ('profiles\' + $ProfileName)
46
+ $ProfileFiles = @('package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml')
47
+ $HomeFiles = @('AGENTS.md', 'prompt-inject.md')
48
+
49
+ # 客户端根:没传就按常见安装位置探测,判据是存在 resources\app\package.json
50
+ function Resolve-AppRoot([string]$explicit) {
51
+ $cands = @()
52
+ if ($explicit) { $cands += $explicit }
53
+ $cands += @('D:\DeepSeekHarness', 'D:\DSH', 'G:\DSH', 'G:\DeepSeekHarness', 'C:\DeepSeekHarness')
54
+ foreach ($c in $cands) {
55
+ if (Test-Path -LiteralPath (Join-Path $c 'resources\app\package.json')) { return $c }
56
+ }
57
+ if ($explicit) { return $explicit }
58
+ return 'D:\DeepSeekHarness'
59
+ }
60
+
61
+ # git 位置探测统一在 dsh-sync-common.ps1 里(Get-GitExe),restore 允许找不到(只影响 pnpm 安装步骤)
62
+
63
+ # 按 profile\package.json 的 bundles 逐项查能否解析(profile\node_modules 优先,再宿主自带 node_modules)
64
+ function Get-UnresolvedBundles {
65
+ $missing = New-Object System.Collections.ArrayList
66
+ $pkgPath = Join-Path $ProfileDir 'package.json'
67
+ if (-not (Test-Path -LiteralPath $pkgPath)) { return $missing }
68
+ try { $pkg = Get-Content -LiteralPath $pkgPath -Raw -Encoding utf8 | ConvertFrom-Json } catch { return $missing }
69
+ $bundles = @($pkg.dsh.profile.bundles)
70
+ $roots = @((Join-Path $ProfileDir 'node_modules'), (Join-Path $AppRoot 'resources\app\dsh\node_modules'))
71
+ foreach ($b in $bundles) {
72
+ if ([string]::IsNullOrWhiteSpace($b)) { continue }
73
+ $rel = [string]($b -replace '/', '\')
74
+ $found = $false
75
+ foreach ($r in $roots) {
76
+ if (Test-Path -LiteralPath (Join-Path $r (Join-Path $rel 'package.json'))) { $found = $true; break }
77
+ }
78
+ if (-not $found) { [void]$missing.Add($b) }
79
+ }
80
+ return $missing
81
+ }
82
+
83
+ $AppRoot = Resolve-AppRoot $AppRoot
84
+
85
+ Say "== DSH 配置同步 / restore =="
86
+ Say "仓库:$RepoRoot"
87
+ Say "DSH home:$DshHome"
88
+ Say "客户端:$AppRoot"
89
+ Say "profile:$ProfileDir"
90
+ if ($DryRun) { Say "模式:DryRun(只看不动)" }
91
+ Say ""
92
+
93
+ # ---------- 0. 前置检查 ----------
94
+ $proc = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue
95
+ if ($proc -and -not $Force) {
96
+ Die "DeepSeek Harness 仍在运行(PID: $(($proc.Id) -join ','))。请完全退出(含托盘)后重试,或加 -Force 强制继续。"
97
+ }
98
+ if (-not (Test-Path -LiteralPath $RepoRoot)) { Warn "仓库目录不存在:$RepoRoot(仅 -FromCommit 需要它)" }
99
+ if ($SnapshotKind -eq 'profile' -and -not (Test-Path -LiteralPath $ProfileDir)) {
100
+ if ($DryRun) { Say " profile 目录不存在(还原时会新建):$ProfileDir" }
101
+ else {
102
+ New-Item -ItemType Directory -Path $ProfileDir -Force | Out-Null
103
+ Warn "profile 目录原本不存在,已新建:$ProfileDir"
104
+ }
105
+ }
106
+
107
+ # ---------- 0. 插件备份 / 会话备份:不走 profile 那套时点回退,各自单独一条分支 ----------
108
+ <#
109
+ 备份根 ~\.dsh\backups 里混着三类东西(配置快照 / 插件本体备份 / 会话目录备份)。
110
+ 0.3.49 起后两类也有还原入口:先整份备份当前状态,再写回,绝不物理删除。
111
+ 为什么必须在 DSH 退出后跑:插件目录与 sessions 在客户端运行时被持有,边跑边写会被回写覆盖。
112
+ #>
113
+ function Get-PluginTarget([string]$explicit) {
114
+ if ($explicit -and (Test-Path -LiteralPath $explicit)) { return $explicit }
115
+ if ($AppRoot) {
116
+ $cands = @(Get-ChildItem -LiteralPath $AppRoot -Directory -Filter 'dsh-config-sync*' -ErrorAction SilentlyContinue |
117
+ Where-Object { -not $_.Name.EndsWith('.old') } | Sort-Object LastWriteTime -Descending)
118
+ if ($cands.Count -gt 0) { return $cands[0].FullName }
119
+ }
120
+ return ''
121
+ }
122
+
123
+ <#
124
+ 目录合并复制:Copy-Item -Recurse 碰到"目标已有同名目录"时,会把整个源目录塞进去(得到 runtime\runtime),
125
+ 实测插件回滚后 runtime\sync.ps1 根本没被覆盖。这里逐层走:同名目录递归合并,文件逐份覆盖。
126
+ #>
127
+ function Copy-Tree([string]$src, [string]$dst) {
128
+ if (-not (Test-Path -LiteralPath $dst)) { New-Item -ItemType Directory -Path $dst -Force | Out-Null }
129
+ foreach ($item in @(Get-ChildItem -LiteralPath $src -Force)) {
130
+ $to = Join-Path $dst $item.Name
131
+ if ($item.PSIsContainer) { Copy-Tree $item.FullName $to }
132
+ else { Copy-Item -LiteralPath $item.FullName -Destination $to -Force }
133
+ }
134
+ }
135
+
136
+ if ($SnapshotKind -eq 'plugin' -or $SnapshotKind -eq 'session') {
137
+ if (-not $BackupDir) { Die "-SnapshotKind $SnapshotKind 必须同时给 -BackupDir(哪一份备份)。面板上点该行还原时会自动带上。" }
138
+ if (-not (Test-Path -LiteralPath $BackupDir)) { Die "备份目录不存在:$BackupDir" }
139
+ $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
140
+
141
+ if ($SnapshotKind -eq 'plugin') {
142
+ $target = Get-PluginTarget $PluginDir
143
+ if (-not $target) { Die "找不到要回滚的插件目录:请传 -PluginDir(例如 <客户端根>\dsh-config-sync-0.1.0)" }
144
+ Say "来源:插件备份 $BackupDir"
145
+ Say "目标:插件目录 $target"
146
+
147
+ # 插件安装失败的半截备份会多一层 dsh-config-sync-<ver>\:真正要写回的是里面的内容
148
+ $srcRoot = $BackupDir
149
+ $kids = @(Get-ChildItem -LiteralPath $srcRoot -Force -ErrorAction SilentlyContinue)
150
+ if ($kids.Count -eq 1 -and $kids[0].PSIsContainer -and $kids[0].Name -match '^dsh-config-sync') {
151
+ $srcRoot = $kids[0].FullName
152
+ $kids = @(Get-ChildItem -LiteralPath $srcRoot -Force -ErrorAction SilentlyContinue)
153
+ Say "备份里只有一层安装目录,取其内容:$srcRoot"
154
+ }
155
+ if ($kids.Count -eq 0) { Die "这份备份里没有任何文件:$BackupDir" }
156
+
157
+ $ver = 'unknown'
158
+ $pkgPath = Join-Path $target 'package.json'
159
+ if (Test-Path -LiteralPath $pkgPath) {
160
+ try { $ver = (Get-Content -LiteralPath $pkgPath -Raw -Encoding utf8 | ConvertFrom-Json).version } catch { }
161
+ }
162
+ $bk = Join-Path $DshHome ('backups\plugin-' + $ver + '-' + $stamp)
163
+ Say "先把当前插件备份到 $bk(回滚错了还能再回滚回来)"
164
+ if ($DryRun) {
165
+ foreach ($item in $kids) { Say (" 将写回 " + $item.Name) }
166
+ Ok "预览完成(未写任何文件)"
167
+ exit 0
168
+ }
169
+ New-Item -ItemType Directory -Path $bk -Force | Out-Null
170
+ # 当前插件整份留底(不删、只拷;用 Copy-Tree 才不会因为同名目录出现 runtime\runtime)
171
+ foreach ($item in @(Get-ChildItem -LiteralPath $target -Force)) {
172
+ $to = Join-Path $bk $item.Name
173
+ if ($item.PSIsContainer) { Copy-Tree $item.FullName $to }
174
+ else { Copy-Item -LiteralPath $item.FullName -Destination $to -Force }
175
+ }
176
+ $n = 0
177
+ foreach ($item in $kids) {
178
+ $to = Join-Path $target $item.Name
179
+ if ($item.PSIsContainer) { Copy-Tree $item.FullName $to }
180
+ else { Copy-Item -LiteralPath $item.FullName -Destination $to -Force }
181
+ $n++
182
+ }
183
+ Ok ("已把插件回滚到 {0} 的内容({1} 个顶层条目);当前插件已备份到 {2}" -f $BackupDir, $n, $bk)
184
+ Warn '重启客户端后生效(面板上的「退出后还原」会自动重启)'
185
+ exit 0
186
+ }
187
+
188
+ # session:把 --<路径编码>-- 会话目录写回 ~\.dsh\sessions
189
+ $sessions = Join-Path $DshHome 'sessions'
190
+ $dirs = @(Get-ChildItem -LiteralPath $BackupDir -Directory -Force -ErrorAction SilentlyContinue)
191
+ if ($dirs.Count -eq 0) { Die "这份备份里没有会话目录(顶层应为 --xxx-- 目录):$BackupDir" }
192
+ Say "来源:会话备份 $BackupDir"
193
+ Say ("目标:会话目录 {0}(共 {1} 个会话目录)" -f $sessions, $dirs.Count)
194
+ $bk = Join-Path $DshHome ('backups\session-' + $stamp)
195
+ if ($DryRun) {
196
+ foreach ($d in $dirs) { Say (" 将写回 " + $d.Name) }
197
+ Ok "预览完成(未写任何文件)"
198
+ exit 0
199
+ }
200
+ if (-not (Test-Path -LiteralPath $sessions)) { New-Item -ItemType Directory -Path $sessions -Force | Out-Null }
201
+ New-Item -ItemType Directory -Path $bk -Force | Out-Null
202
+ $n = 0
203
+ foreach ($d in $dirs) {
204
+ $existing = Join-Path $sessions $d.Name
205
+ # 目标已存在:先整份留底(不删除,只多一份拷贝)
206
+ if (Test-Path -LiteralPath $existing) { Copy-Tree $existing (Join-Path $bk $d.Name) }
207
+ Copy-Tree $d.FullName $existing
208
+ $n++
209
+ }
210
+ Ok ("已把 {0} 个会话目录写回 {1};同名目录先前的状态已备份到 {2}" -f $n, $sessions, $bk)
211
+ Warn '重启客户端后可在这台机器的会话列表里看到还原后的会话'
212
+ exit 0
213
+ }
214
+
215
+ # ---------- 1. 确定还原来源 ----------
216
+ $mode = ''
217
+ if ($FromCommit) {
218
+ $gitExe = Get-GitExe
219
+ if (-not $gitExe) { Die "找不到 git,无法按提交还原。请安装 Git 或改用 -BackupDir。" }
220
+ # 注意:不能用 "{0}^{commit}" -f ,`{commit}` 会被当成格式占位符 → "Error formatting a string"
221
+ & $gitExe -C $RepoRoot rev-parse --verify ($FromCommit + '^{commit}') 2>&1 | Out-Null
222
+ if ($LASTEXITCODE -ne 0) { Die "git 里找不到提交:$FromCommit" }
223
+ $mode = 'git'
224
+ Say "来源:git 提交 $FromCommit 的 profile\"
225
+ } else {
226
+ if (-not $BackupDir) {
227
+ $bkRoot = Join-Path $DshHome 'backups'
228
+ if (-not (Test-Path -LiteralPath $bkRoot)) {
229
+ Die "没有备份目录 $bkRoot,也没有指定 -FromCommit。若这是全新机器,本来就没有旧配置可还原:请跑 sync.ps1 pull,或 apply.ps1 -WorkspaceOnly 先落地资料。"
230
+ }
231
+ $cands = @(Get-ChildItem -LiteralPath $bkRoot -Directory -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending)
232
+ if ($cands.Count -eq 0) {
233
+ Die "$bkRoot 下没有任何快照。若这是全新机器,请跑 sync.ps1 pull,或用 -FromCommit 取仓库历史配置。"
234
+ }
235
+ # 新机器首次拉取时本机还没有 profile 文件,apply 会留下一个空快照;这类快照不能用来还原
236
+ # (否则还原会"一个 profile 文件都没有"直接失败),所以按时间倒序找第一份带 profile 的快照。
237
+ $usable = @($cands | Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName 'package.json') })
238
+ if ($usable.Count -eq 0) {
239
+ Die ("$bkRoot 下 {0} 份快照里都没有 profile 文件(package.json),无法还原配置。全新机器本来就没有旧配置可退:如需回到某个提交的配置,用 -FromCommit。" -f $cands.Count)
240
+ }
241
+ $BackupDir = $usable[0].FullName
242
+ if ($usable[0].Name -ne $cands[0].Name) {
243
+ Warn ("最新一份 {0} 里没有 profile 文件(新机器首次拉取时本机无配置可备份),已改用 {1}" -f $cands[0].Name, $usable[0].Name)
244
+ } else {
245
+ Warn "未指定备份点,取最新一份:$BackupDir"
246
+ }
247
+ }
248
+ if (-not (Test-Path -LiteralPath $BackupDir)) { Die "备份目录不存在:$BackupDir" }
249
+ $mode = 'backup'
250
+ Say "来源:备份快照 $BackupDir"
251
+ }
252
+ Say ""
253
+
254
+ # ---------- 2. 自保:先把当前状态另存一份 ----------
255
+ $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
256
+ $safety = Join-Path $DshHome ('backups\manual-' + $stamp)
257
+ if (-not $DryRun) {
258
+ New-Item -ItemType Directory -Path $safety -Force | Out-Null
259
+ $n = 0
260
+ foreach ($f in $ProfileFiles) {
261
+ $src = Join-Path $ProfileDir $f
262
+ if (Test-Path -LiteralPath $src) { Copy-Item -LiteralPath $src -Destination (Join-Path $safety $f) -Force; $n++ }
263
+ }
264
+ foreach ($f in $HomeFiles) {
265
+ $src = Join-Path $DshHome $f
266
+ if (Test-Path -LiteralPath $src) { Copy-Item -LiteralPath $src -Destination (Join-Path $safety $f) -Force; $n++ }
267
+ }
268
+ if ($n -gt 0) { Ok "已把当前状态另存到 $safety($n 个文件),回退错了还能再回退" }
269
+ else { Warn "当前没有可备份的配置(全新机器?),继续" }
270
+ }
271
+
272
+ # ---------- 3. 还原 profile 配置 ----------
273
+ if ($mode -eq 'git') {
274
+ foreach ($f in $ProfileFiles) {
275
+ if ($DryRun) { Say " 将写入 profile\$f(取自 $FromCommit)"; continue }
276
+ $raw = (& $gitExe -C $RepoRoot show ($FromCommit + ':profile/' + $f)) -join "`n"
277
+ if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($raw)) { Warn "提交 $FromCommit 里没有 profile\$f,跳过"; continue }
278
+ Write-TextPreserveBom (Join-Path $ProfileDir $f) ($raw + "`n")
279
+ Ok "已写回 profile\$f"
280
+ }
281
+ } else {
282
+ $restored = 0
283
+ foreach ($f in $ProfileFiles) {
284
+ $src = Join-Path $BackupDir $f
285
+ if (-not (Test-Path -LiteralPath $src)) { Warn "快照里没有 $f,跳过(该文件保持现状)"; continue }
286
+ if ($DryRun) { Say " 将写回 profile\$f"; continue }
287
+ Copy-Item -LiteralPath $src -Destination (Join-Path $ProfileDir $f) -Force
288
+ $restored++
289
+ }
290
+ if (-not $DryRun -and $restored -eq 0) { Die "快照里一个 profile 文件都没有,$BackupDir 可能不是 apply 生成的备份点。" }
291
+ if (-not $DryRun) { Ok "已写回 profile 配置 $restored 个文件" }
292
+
293
+ foreach ($f in $HomeFiles) {
294
+ $src = Join-Path $BackupDir $f
295
+ if (-not (Test-Path -LiteralPath $src)) { continue }
296
+ if ($DryRun) { Say " 将写回 $f"; continue }
297
+ Copy-Item -LiteralPath $src -Destination (Join-Path $DshHome $f) -Force
298
+ Ok "已写回 $f"
299
+ }
300
+
301
+ $bkSettings = Join-Path $BackupDir 'settings'
302
+ if (Test-Path -LiteralPath $bkSettings) {
303
+ if ($DryRun) { Say " 将写回 settings\ 下的插件设置文件" }
304
+ else {
305
+ $cnt = 0
306
+ Get-ChildItem -LiteralPath $bkSettings -File -Force | ForEach-Object {
307
+ Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $DshHome $_.Name) -Force
308
+ $cnt++
309
+ }
310
+ Ok "已写回 settings 下 $cnt 个插件设置文件"
311
+ }
312
+ }
313
+ }
314
+ Say ""
315
+
316
+ # ---------- 3.5 时点回退:快照之后新增的文件与插件 ----------
317
+ <#
318
+ 「还原」不只是把快照里的文件盖回去,还要把快照之后新增的东西撤掉,否则退回去的只是一层皮:
319
+ profile 里多出来的文件(例如新插件的 cordis 补丁、新版本的 lock)和 node_modules 里多出来的插件,
320
+ 会跟着还原后的 package.json 一起被加载,看起来就像"没还原"。
321
+ 这里把它们移进 manual 备份的 rollback 子目录并写 rollback-manifest.json —— 全部可再还原,绝不物理删除。
322
+ #>
323
+ if ($RollbackToPoint) {
324
+ $rbRoot = Join-Path $safety 'rollback'
325
+ $rbFiles = Join-Path $rbRoot 'files'
326
+ $rbPlugins = Join-Path $rbRoot 'plugins'
327
+ $manifest = [ordered]@{
328
+ at = (Get-Date).ToString('o')
329
+ snapshot = $BackupDir
330
+ profile = $ProfileDir
331
+ files = @()
332
+ plugins = @()
333
+ errors = @()
334
+ }
335
+
336
+ # 快照里出现过的相对路径(restore.ps1 的快照根就是 profile 的内容,结构相同)
337
+ # 基准路径必须先归一成**长名**:$DshHome 常是 8.3 短名(ADMINI~1),而 Get-ChildItem 返回的是长名,
338
+ # 直接拿源字符串长度做 Substring 会把相对路径切错,于是"快照里的文件"一个都匹配不上、
339
+ # 整个 profile 被当成新增文件搬走(隔离测试实测把 package.json 也搬走了)。
340
+ $snapFull = (Get-Item -LiteralPath $BackupDir -Force).FullName
341
+ $profFull = (Get-Item -LiteralPath $ProfileDir -Force).FullName
342
+ $snapSet = @{}
343
+ if ($mode -eq 'backup') {
344
+ Get-ChildItem -LiteralPath $snapFull -Recurse -File -Force -ErrorAction SilentlyContinue | ForEach-Object {
345
+ $rel = $_.FullName.Substring($snapFull.Length + 1)
346
+ $snapSet[$rel] = $true
347
+ }
348
+ }
349
+ # git 模式没有"快照目录",时点回退无从比较,明确跳过而不是瞎猜
350
+ if ($mode -eq 'git') {
351
+ Warn '来自 git 提交的还原不做时点回退(没有可比对的快照目录)'
352
+ } else {
353
+ $nmPrefix = (Join-Path $profFull 'node_modules') + '\'
354
+ $extra = @()
355
+ foreach ($f in @(Get-ChildItem -LiteralPath $profFull -Recurse -File -Force -ErrorAction SilentlyContinue)) {
356
+ $rel = $f.FullName.Substring($profFull.Length + 1)
357
+ if ($f.FullName.StartsWith($nmPrefix, [StringComparison]::OrdinalIgnoreCase)) { continue }
358
+ if ($snapSet.ContainsKey($rel)) { continue }
359
+ $extra += ,@($f.FullName, $rel)
360
+ }
361
+
362
+ if ($extra.Count -gt 0) {
363
+ if ($DryRun) {
364
+ Say (" 将移走 {0} 个快照之后新增的文件:" -f $extra.Count)
365
+ $extra | ForEach-Object { Say (" - {0}" -f $_[1]) }
366
+ } else {
367
+ foreach ($pair in $extra) {
368
+ $full = $pair[0]; $rel = $pair[1]
369
+ try {
370
+ $dest = Join-Path $rbFiles $rel
371
+ $destDir = Split-Path -Parent $dest
372
+ if ($destDir -and -not (Test-Path -LiteralPath $destDir)) { New-Item -ItemType Directory -Path $destDir -Force | Out-Null }
373
+ Move-Item -LiteralPath $full -Destination $dest -Force
374
+ $manifest.files += $rel
375
+ } catch {
376
+ $manifest.errors += ("$rel : " + $_.Exception.Message)
377
+ }
378
+ }
379
+ if ($manifest.files.Count -gt 0) { Ok ("已移走 {0} 个快照之后新增的文件(在 rollback\files 下)" -f $manifest.files.Count) }
380
+ }
381
+ } else {
382
+ Say ' 没有快照之后新增的文件'
383
+ }
384
+
385
+ # 插件收敛:还原后的 package.json 里没有的,就是快照之后装上的
386
+ $pkgPath = Join-Path $ProfileDir 'package.json'
387
+ $wantDeps = @{}
388
+ if (Test-Path -LiteralPath $pkgPath) {
389
+ try {
390
+ $pkg = Get-Content -LiteralPath $pkgPath -Raw -Encoding utf8 | ConvertFrom-Json
391
+ foreach ($p in @($pkg.dependencies.PSObject.Properties)) { $wantDeps[[string]$p.Name] = $true }
392
+ } catch { Warn '还原后的 package.json 读不出来,跳过插件收敛' }
393
+ }
394
+
395
+ $nm = Join-Path $profFull 'node_modules'
396
+ $dropList = @()
397
+ if ($wantDeps.Count -gt 0 -and (Test-Path -LiteralPath $nm)) {
398
+ foreach ($d in @(Get-ChildItem -LiteralPath $nm -Directory -Force -ErrorAction SilentlyContinue)) {
399
+ if ($d.Name.StartsWith('.')) { continue }
400
+ if ($d.Name.StartsWith('@')) {
401
+ foreach ($s in @(Get-ChildItem -LiteralPath $d.FullName -Directory -Force -ErrorAction SilentlyContinue)) {
402
+ $key = $d.Name + '/' + $s.Name
403
+ if (-not $wantDeps.ContainsKey($key)) { $dropList += ,@($s.FullName, ($d.Name + '--' + $s.Name), $key) }
404
+ }
405
+ continue
406
+ }
407
+ if ($d.Name -eq '.bin') { continue }
408
+ if (-not $wantDeps.ContainsKey($d.Name)) { $dropList += ,@($d.FullName, $d.Name, $d.Name) }
409
+ }
410
+ }
411
+
412
+ if ($dropList.Count -gt 0) {
413
+ if ($DryRun) {
414
+ Say (" 将撤走 {0} 个快照之后装上的插件:" -f $dropList.Count)
415
+ $dropList | ForEach-Object { Say (" - {0}" -f $_[2]) }
416
+ } else {
417
+ foreach ($pair in $dropList) {
418
+ $full = $pair[0]; $safeName = $pair[1]; $depName = $pair[2]
419
+ try {
420
+ $item = Get-Item -LiteralPath $full -Force
421
+ if ($item.LinkType) {
422
+ # 链接只删链接本身:穿进链接会把别的插件的安装目录一起删掉(实测过)
423
+ [IO.Directory]::Delete($full)
424
+ $manifest.plugins += ($depName + '(链接已删,目标目录保留)')
425
+ } else {
426
+ $dest = Join-Path $rbPlugins $safeName
427
+ New-Item -ItemType Directory -Path $rbPlugins -Force | Out-Null
428
+ Move-Item -LiteralPath $full -Destination $dest -Force
429
+ $manifest.plugins += ($depName + '(实体目录已移入 rollback\plugins)')
430
+ }
431
+ } catch {
432
+ $manifest.errors += ("$depName : " + $_.Exception.Message)
433
+ }
434
+ }
435
+ if ($manifest.plugins.Count -gt 0) { Ok ("已撤走 {0} 个快照之后装上的插件" -f $manifest.plugins.Count) }
436
+ }
437
+ } else {
438
+ Say ' 没有快照之后装上的插件'
439
+ }
440
+
441
+ if (-not $DryRun) {
442
+ try {
443
+ New-Item -ItemType Directory -Path $rbRoot -Force | Out-Null
444
+ $json = $manifest | ConvertTo-Json -Depth 5
445
+ [IO.File]::WriteAllText((Join-Path $rbRoot 'rollback-manifest.json'), $json, (New-Object Text.UTF8Encoding $false))
446
+ Ok ("回退清单已写入 " + (Join-Path $rbRoot 'rollback-manifest.json'))
447
+ } catch {
448
+ Warn ('写回退清单失败:' + $_.Exception.Message)
449
+ }
450
+ }
451
+ }
452
+ Say ""
453
+ }
454
+
455
+ # ---------- 4. 可选:记忆数据 mnemon ----------
456
+ if ($WithMnemon) {
457
+ $mnSrc = Join-Path $BackupDir 'mnemon-old'
458
+ $mnDst = Join-Path $AppRoot 'mnemon'
459
+ if (-not (Test-Path -LiteralPath $mnSrc)) {
460
+ Warn "快照里没有 mnemon-old,跳过记忆数据(-FromCommit 模式下也不支持)"
461
+ } elseif ($DryRun) {
462
+ Say " 将用 $mnSrc 覆盖 $mnDst"
463
+ } else {
464
+ if (Test-Path -LiteralPath $mnDst) {
465
+ $mnBk = Join-Path $safety 'mnemon-old'
466
+ Copy-Item -LiteralPath $mnDst -Destination $mnBk -Recurse -Force
467
+ Warn "现有 mnemon 已另存到 $mnBk"
468
+ }
469
+ CopyMerge $mnSrc $mnDst
470
+ Ok "已还原记忆数据到 $mnDst"
471
+ }
472
+ Say ""
473
+ }
474
+
475
+ if ($DryRun) {
476
+ Say "== DryRun 结束(没有写任何文件)=="
477
+ exit 0
478
+ }
479
+
480
+ # ---------- 5. 核对:版本契约 + bundle 可解析性 ----------
481
+ $localVer = Get-HostAppVersion $AppRoot
482
+ $contractPath = Join-Path $RepoRoot 'profile\host-contract.json'
483
+ $contractVer = $null
484
+ if (Test-Path -LiteralPath $contractPath) {
485
+ try { $contractVer = [string](Get-Content -LiteralPath $contractPath -Raw -Encoding utf8 | ConvertFrom-Json).appVersion } catch { }
486
+ }
487
+ Say " 本机 app 版本:$localVer;仓库契约:$contractVer"
488
+ if ($localVer -and $contractVer -and $localVer -ne $contractVer) {
489
+ Warn "两端版本不一致:本机 $localVer,仓库契约 $contractVer。还原只修本机文件,拉起后仍可能在 pull 时被版本契约拦下(需升级本机,或 pull 加 -AllowVersionDrift)。"
490
+ }
491
+
492
+ $missing = @(Get-UnresolvedBundles)
493
+ if ($missing.Count -gt 0) {
494
+ Warn "有 $($missing.Count) 个 bundle 在本机解析不到:$($missing -join ', ')"
495
+ } else {
496
+ Ok "所有 bundle 都能在本机解析"
497
+ }
498
+
499
+ # ---------- 6. 重装依赖 ----------
500
+ if ($SkipInstall) {
501
+ Warn "已指定 -SkipInstall,跳过依赖安装(缺的 bundle 若在 profile\node_modules 里,仍需手动 pnpm install)"
502
+ } elseif ($missing.Count -eq 0) {
503
+ Ok "依赖已经齐全,跳过 pnpm install"
504
+ } else {
505
+ $nodeExe = Join-Path $AppRoot 'resources\runtime\primary-runtime\dependencies\node\bin\node.exe'
506
+ $pnpmCjs = Join-Path $AppRoot 'resources\runtime\primary-runtime\dependencies\pnpm\bin\pnpm.cjs'
507
+ Push-Location $ProfileDir
508
+ try {
509
+ if ((Test-Path -LiteralPath $nodeExe) -and (Test-Path -LiteralPath $pnpmCjs)) {
510
+ Say " 使用客户端内置 pnpm 按 lockfile 安装(可能需要几分钟)..."
511
+ & $nodeExe $pnpmCjs install --frozen-lockfile
512
+ if ($LASTEXITCODE -ne 0) {
513
+ Warn "严格模式失败(lockfile 与 package.json 对不上),改为 --no-frozen-lockfile 重试..."
514
+ & $nodeExe $pnpmCjs install --no-frozen-lockfile
515
+ }
516
+ } elseif (Get-Command pnpm -ErrorAction SilentlyContinue) {
517
+ Say " 使用系统 pnpm 安装..."
518
+ & pnpm install --frozen-lockfile
519
+ if ($LASTEXITCODE -ne 0) { & pnpm install --no-frozen-lockfile }
520
+ } else {
521
+ Warn "找不到 pnpm。请手动在 $ProfileDir 执行:pnpm install --frozen-lockfile"
522
+ }
523
+ } finally {
524
+ Pop-Location
525
+ }
526
+
527
+ $missing2 = @(Get-UnresolvedBundles)
528
+ if ($missing2.Count -eq 0) { Ok "重装后所有 bundle 均可解析" }
529
+ else { Warn "重装后仍有 $($missing2.Count) 个解析不到:$($missing2 -join ', ')。检查磁盘空间(scripts 面板会报),或回退到更早的快照。" }
530
+ }
531
+
532
+ Say ""
533
+ Say "== 还原完成 =="
534
+ Say " profile:$ProfileDir"
535
+ Say " 当前状态另存在:$safety"
536
+ Say " 下一步:启动 DSH,确认能进到主界面;如果不正常,用 sync.ps1 status 看版本契约与 bundle 计数。"
537
+ exit 0