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

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,1029 @@
1
+ <#
2
+ DSH 配置同步 —— 一条命令入口(把原来的「capture + git add + commit + push」和「git pull + apply」各收成一次调用)
3
+
4
+ 用法
5
+ pwsh -File sync.ps1 status # 看仓库状态、版本契约、bundle 数(不改任何东西)
6
+ pwsh -File sync.ps1 push # 本机 → 仓库 → 远端(改完插件/技能/配置后用这个)
7
+ pwsh -File sync.ps1 pull # 远端 → 本机(换机上工 / 另一台更新后同步用这个)
8
+
9
+ pwsh -File sync.ps1 push -AppRoot "D:\DSH" # 客户端不在默认目录时必须显式传(两个子脚本都会收到)
10
+ pwsh -File sync.ps1 push -Message "加了 xx 插件" # 自定义提交信息(默认自动生成带机器名和时间)
11
+ pwsh -File sync.ps1 pull -AllowVersionDrift # 两端客户端版本不同时,只同步配置(剔除实验性 bundle)
12
+ pwsh -File sync.ps1 push -WorkspaceOnly # 只推工作区/会话
13
+ pwsh -File sync.ps1 pull -SkipInstall # 只铺配置,不跑 pnpm install
14
+ pwsh -File sync.ps1 push -DeepVerify # 文件比较强制全量算哈希(默认大小+mtime 快筛)
15
+ pwsh -File sync.ps1 push -ScanHistory # 强制全量重扫历史里的超大文件(默认按提交缓存)
16
+
17
+ 设计要点
18
+ - push 先跑 capture.ps1(本机 → 仓库),再 git add -A / commit / push,任何一步失败就停,不会带着半截状态继续。
19
+ - pull 先 fetch 再 merge --ff-only(等价于 pull --ff-only,但只付一次网络往返;有本地改动或冲突会直接失败,不去猜怎么合并),再跑 apply.ps1(含版本契约校验)。
20
+ - 不动选项语义:所有开关原样透传给 capture.ps1 / apply.ps1,两个脚本仍可单独调用。
21
+ #>
22
+ param(
23
+ [Parameter(Position = 0)]
24
+ [ValidateSet('status', 'push', 'pull')]
25
+ [string]$Action = 'status',
26
+ [string]$RepoRoot,
27
+ [string]$DshHome = $(Join-Path $env:USERPROFILE '.dsh'),
28
+ [string]$ProfileName = 'desktop',
29
+ [string]$AppRoot = '',
30
+ [string]$WorkspaceHome = $(Join-Path $env:USERPROFILE 'Documents\deepseek-harness'),
31
+ [string]$Message,
32
+ [switch]$WorkspaceOnly,
33
+ [switch]$SkipWorkspace,
34
+ [switch]$SkipInstall,
35
+ [switch]$AllowVersionDrift,
36
+ # 推送前强制全量重扫历史里的超大文件(默认只在首次或推送被拒时才扫,省 20s)
37
+ [switch]$ScanHistory,
38
+ # 文件比较强制全量算哈希(默认大小+mtime 快筛,只在可疑时算),透传给 capture.ps1
39
+ [switch]$DeepVerify,
40
+ [switch]$Force
41
+ )
42
+
43
+ $ErrorActionPreference = 'Stop'
44
+ if (-not $RepoRoot) { $RepoRoot = $PSScriptRoot }
45
+ . (Join-Path $PSScriptRoot 'dsh-sync-common.ps1')
46
+
47
+ # 本动作的未同步清单从这里起算(pull 也要清:上一轮 push 的清单不能挂到这次拉取头上)
48
+ Reset-SyncNotices $DshHome $Action
49
+
50
+ # git 位置探测统一在 dsh-sync-common.ps1 里(Get-GitExe),这里只决定找不到时怎么报
51
+ $git = Get-GitExe
52
+ if (-not $git) { Die "找不到 git.exe。请先安装 Git 并加入 PATH。" }
53
+
54
+ # 客户端装哪个盘不是固定的(会被卸载重装到别处),所以 -AppRoot 传进来的值先校验,
55
+ # 对不上就按注册表/常见位置重新定位 —— 老脚本里写死的旧路径因此不会把整条链路带偏。
56
+ $AppRootWasFallback = $false
57
+ $resolvedRoot = Resolve-DshAppRoot $AppRoot
58
+ if (-not $resolvedRoot) {
59
+ Die ("找不到 DSH 客户端目录(传进来的 -AppRoot 对不上,注册表与常见位置也没有)。" +
60
+ "装上客户端后重跑,或显式传 -AppRoot `<客户端根>`(目录里有 resources\app.asar 或 resources\app\package.json)。")
61
+ }
62
+ if ($AppRoot -and ($resolvedRoot -ne $AppRoot.TrimEnd('\', '/'))) {
63
+ Warn "参数里的 -AppRoot($AppRoot)对不上,已自动改用:$resolvedRoot"
64
+ $AppRootWasFallback = $true
65
+ }
66
+ $AppRoot = $resolvedRoot
67
+ Say ""
68
+ Say "== DSH 配置同步 / $Action =="
69
+ Say "仓库:$RepoRoot"
70
+
71
+ function Get-RepoState {
72
+ $branch = (& $git -C $RepoRoot rev-parse --abbrev-ref HEAD 2>$null)
73
+ $head = (& $git -C $RepoRoot log -1 --oneline 2>$null)
74
+ $dirty = @(& $git -C $RepoRoot status --porcelain 2>$null)
75
+ return [pscustomobject]@{ Branch = $branch; Head = $head; Dirty = $dirty.Count }
76
+ }
77
+
78
+ <#
79
+ 本脚本开着 $ErrorActionPreference='Stop':native 命令只要往 stderr 写了东西就会变成终止错误。
80
+ git 的很多"探询"命令(如查 upstream 不存在时)正是往 stderr 报 fatal,会直接把整个脚本打断。
81
+ 所以这类只想要结果的命令统一交给 cmd 转发,丢掉 stderr,只看退出码和标准输出。
82
+ #>
83
+ function Get-GitText([string]$ArgLine) {
84
+ $cmdLine = '"' + $git + '" -C "' + $RepoRoot + '" ' + $ArgLine + ' 2>nul'
85
+ $raw = & "$env:ComSpec" /c $cmdLine
86
+ # 注意:命令没有输出时 $raw 是 AutomationNull,[string] 转出来是 $null 而不是 "",
87
+ # 后面 .Trim() 就崩。用数组 join 兜住。
88
+ $text = (@($raw) -join '').Trim()
89
+ return [pscustomobject]@{ Text = $text; Code = $LASTEXITCODE }
90
+ }
91
+
92
+ # 当前分支与它的上游(新机器上 origin 是插件后补的,upstream 可能不存在,push/pull 都要据此决定带不带 -u)
93
+ function Get-BranchUpstream {
94
+ $b = (Get-GitText 'rev-parse --abbrev-ref HEAD').Text
95
+ $u = Get-GitText 'rev-parse --abbrev-ref --symbolic-full-name "@{upstream}"'
96
+ $up = if ($u.Code -eq 0 -and $u.Text) { $u.Text } else { $null }
97
+ return [pscustomobject]@{ Branch = $b; Upstream = $up }
98
+ }
99
+
100
+ # 记下「上次与本仓库同步成功」的时刻,只写本机、不入库。
101
+ # 面板的「本机待推送」靠它当分水岭:会话/工作区资料写了新东西、但还没 capture 进仓库时,
102
+ # git status 是干净的,只看 git 会显示"一致",把"本机有新内容没推"这件事藏起来。
103
+ function Write-SyncState([string]$Mode) {
104
+ try {
105
+ if (-not (Test-Path -LiteralPath $DshHome)) { New-Item -ItemType Directory -Path $DshHome -Force | Out-Null }
106
+ $head = ''
107
+ try { $head = ((& $git -C $RepoRoot log -1 --format='%h' 2>$null) | Out-String).Trim() } catch {}
108
+ $state = [ordered]@{
109
+ lastSyncAt = (Get-Date).ToString('o')
110
+ mode = $Mode
111
+ repo = $RepoRoot
112
+ head = $head
113
+ }
114
+ $text = ((($state | ConvertTo-Json -Depth 4) -replace "`r`n", "`n") + "`n")
115
+ [IO.File]::WriteAllText((Join-Path $DshHome 'config-sync-state.json'), $text, (New-Object Text.UTF8Encoding($false, $false)))
116
+ } catch {
117
+ Warn ('写同步状态失败(不影响同步本身):{0}' -f $_.Exception.Message)
118
+ }
119
+ }
120
+
121
+ # git 的提交身份是**每台机器**一份:新机器上全局 user.name/email 往往是空的,
122
+ # 直接 commit 只会报 "Author identity unknown",而 commit 的输出被 Out-Null 吞掉,
123
+ # 用户只看到「git commit 失败」,完全查不出原因(真实踩过)。
124
+ # 所以提交前先补仓库级身份:优先沿用已有配置,缺失才补一个能认出来的默认值。
125
+ function Initialize-CommitIdentity {
126
+ $name = (Get-GitText 'config user.name').Text
127
+ $mail = (Get-GitText 'config user.email').Text
128
+ if ($name -and $mail) { return }
129
+ $fallbackName = if ($env:COMPUTERNAME) { $env:COMPUTERNAME } else { 'dsh-config-sync' }
130
+ if (-not $name) {
131
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" config user.name "' + $fallbackName + '" 2>&1') | Out-Null
132
+ Warn ("这台机器没设 git user.name,已给本仓库补上:{0}(只影响本仓库,可用 git config user.name 改)" -f $fallbackName)
133
+ }
134
+ if (-not $mail) {
135
+ $fallbackMail = '{0}@localhost' -f ($fallbackName -replace '[^A-Za-z0-9\-_.]', '')
136
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" config user.email "' + $fallbackMail + '" 2>&1') | Out-Null
137
+ Warn ("这台机器没设 git user.email,已给本仓库补上:{0}" -f $fallbackMail)
138
+ }
139
+ }
140
+
141
+ # ---------- 冲突协调(pull 专用) ----------
142
+ <#
143
+ pull 被本地文件挡住时,git 只甩一句 "would be overwritten by merge" 就 Aborting;
144
+ 旧做法是整仓库 reset 回拉取前 —— 但「失败 → 回滚 → 再失败」会原地打转
145
+ (真实案例:B 机落后 8 个提交,每次快进上去又被回滚打回 84f05a0,十几轮都推不上去)。
146
+ 现在改成:不猜、不硬回滚,先把「谁跟云端撞了」算清楚 + 把本机那份备份好 + 写成清单,
147
+ 面板列出来让用户逐项选「用本机 / 用云端」;选完再跑一次 pull,由本脚本按选择落地。
148
+ #>
149
+
150
+ function Get-ConflictPath { return (Join-Path $DshHome 'sync-conflicts.json') }
151
+
152
+ function Read-ConflictFile {
153
+ $p = Get-ConflictPath
154
+ if (-not (Test-Path -LiteralPath $p)) { return $null }
155
+ try { return (Get-Content -LiteralPath $p -Raw -Encoding utf8 | ConvertFrom-Json) } catch { return $null }
156
+ }
157
+
158
+ function Write-ConflictFile($obj) {
159
+ $text = ((($obj | ConvertTo-Json -Depth 8) -replace "`r`n", "`n") + "`n")
160
+ [IO.File]::WriteAllText((Get-ConflictPath), $text, (New-Object Text.UTF8Encoding($false, $false)))
161
+ }
162
+
163
+ <#
164
+ git 在中文目录下的路径输出会被八进制转义("workspace/DSH\347\240\264..."),
165
+ PowerShell 捕获外部程序输出时还会再按 ANSI 转一次码 —— 直接读 $raw 得到的路径没法用来操作文件。
166
+ 所以凡是要「按路径干活」的查询,一律 core.quotepath=false + cmd 字节重定向到临时文件 + 按 UTF-8 读。
167
+ #>
168
+ function Read-GitLines([string]$ArgLine) {
169
+ $tmp = Join-Path ([IO.Path]::GetTempPath()) ('dsh-sync-' + [guid]::NewGuid().ToString('N') + '.txt')
170
+ $cmdLine = '"' + $git + '" -C "' + $RepoRoot + '" -c core.quotepath=false ' + $ArgLine + ' > "' + $tmp + '" 2>nul'
171
+ & "$env:ComSpec" /c $cmdLine | Out-Null
172
+ $code = $LASTEXITCODE
173
+ $lines = @()
174
+ if (Test-Path -LiteralPath $tmp) {
175
+ try {
176
+ $txt = [IO.File]::ReadAllText($tmp, (New-Object Text.UTF8Encoding($false, $false)))
177
+ $lines = @($txt -split "`n" | ForEach-Object { $_.TrimEnd("`r") } | Where-Object { $_ -ne '' })
178
+ } catch { $lines = @() }
179
+ Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue
180
+ }
181
+ return [pscustomobject]@{ Lines = $lines; Code = $code }
182
+ }
183
+
184
+ # 取云端某版本文件的内容(文本);取不到返回 $null
185
+ function Get-BlobText([string]$Spec) {
186
+ $tmp = Join-Path ([IO.Path]::GetTempPath()) ('dsh-blob-' + [guid]::NewGuid().ToString('N') + '.txt')
187
+ $cmdLine = '"' + $git + '" -C "' + $RepoRoot + '" show "' + $Spec + '" > "' + $tmp + '" 2>nul'
188
+ & "$env:ComSpec" /c $cmdLine | Out-Null
189
+ $code = $LASTEXITCODE
190
+ $text = $null
191
+ if ($code -eq 0 -and (Test-Path -LiteralPath $tmp)) {
192
+ try { $text = [IO.File]::ReadAllText($tmp, (New-Object Text.UTF8Encoding($false, $false))) } catch { $text = $null }
193
+ }
194
+ if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }
195
+ return $text
196
+ }
197
+
198
+ function Test-BinaryPath([string]$Path) {
199
+ $ext = [IO.Path]::GetExtension($Path).ToLowerInvariant()
200
+ return ($ext -in @('.zstd', '.zip', '.tgz', '.gz', '.png', '.jpg', '.jpeg', '.db', '.sqlite', '.bin', '.exe', '.dll', '.node', '.pdf', '.ico', '.wav', '.mp4'))
201
+ }
202
+
203
+ # ---------- 冲突备份目录:命名、本机/云端两份副本 ----------
204
+ # 目录名带中英说明,打开 ~\.dsh\backups 一眼能看出这份是什么;
205
+ # 本机版与云端版分目录存放,面板对两边都能单独还原。
206
+ $ConflictBackupSuffix = '拉取冲突-Pull-conflict'
207
+ $ConflictLocalDirName = '本机-Local'
208
+ $ConflictCloudDirName = '云端-Cloud'
209
+ $ConflictReadmeName = '说明-README.txt'
210
+ $ConflictSnapshotName = '清单-Conflicts.json'
211
+
212
+ function Get-LocalCopyDir([string]$BackupDir) {
213
+ $new = Join-Path $BackupDir $ConflictLocalDirName
214
+ if (Test-Path -LiteralPath $new) { return $new }
215
+ $old = Join-Path $BackupDir 'files' # 0.3.17 最早那版用的目录名
216
+ if (Test-Path -LiteralPath $old) { return $old }
217
+ return $new
218
+ }
219
+
220
+ function Get-CloudCopyDir([string]$BackupDir) {
221
+ $new = Join-Path $BackupDir $ConflictCloudDirName
222
+ if (Test-Path -LiteralPath $new) { return $new }
223
+ $old = Join-Path $BackupDir 'files-cloud'
224
+ if (Test-Path -LiteralPath $old) { return $old }
225
+ return $new
226
+ }
227
+
228
+ <#
229
+ 把 git 里的某个 blob(ref:path)按字节原样落盘。
230
+ 不能用 Get-Content/Set-Content 中转 —— .zstd/.tgz 这类二进制会被转码写坏;
231
+ 这里走 cmd 的 > 重定向(与 Read-GitLines 同一套),写完核对字节数。
232
+ #>
233
+ function Save-BlobToFile([string]$Spec, [string]$DstPath, [int64]$ExpectSize = -1) {
234
+ $dir = Split-Path -Parent $DstPath
235
+ if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
236
+ $cmdLine = '"' + $git + '" -C "' + $RepoRoot + '" cat-file blob "' + $Spec + '" > "' + $DstPath + '" 2>nul'
237
+ & "$env:ComSpec" /c $cmdLine | Out-Null
238
+ if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $DstPath)) { return $false }
239
+ if ($ExpectSize -ge 0) {
240
+ try { if ((Get-Item -LiteralPath $DstPath -Force).Length -ne $ExpectSize) { return $false } } catch { return $false }
241
+ }
242
+ return $true
243
+ }
244
+
245
+ function Write-ConflictReadme([string]$BackupDir, $Report) {
246
+ $lines = @(
247
+ 'DSH 配置同步 —— 拉取冲突备份',
248
+ 'DSH config sync — pull conflict backup',
249
+ '',
250
+ ('生成时间 / Created at : ' + $Report.at),
251
+ ('仓库目录 / Repo directory : ' + $Report.repo),
252
+ ('同步前 HEAD / HEAD before : ' + $Report.head),
253
+ ('云端引用 / Remote ref : ' + $Report.remote),
254
+ ('云端 HEAD / Remote head : ' + $Report.remoteHead),
255
+ ('冲突条目 / Conflicting files : ' + @($Report.items).Count),
256
+ '',
257
+ '目录里有什么 / What is inside',
258
+ (' ' + $ConflictLocalDirName + '\ 每个冲突文件的「本机版本」(冲突发生时工作区的原始内容)'),
259
+ (' ' + $ConflictCloudDirName + '\ 每个冲突文件的「云端版本」(git show ' + $Report.remote + ':<路径>)'),
260
+ (' ' + $ConflictSnapshotName + ' 本次冲突清单快照(JSON,含每项当时的选择)'),
261
+ (' 说明-README.txt 本文件(中英双语)'),
262
+ '',
263
+ '两种副本都在这里,结构与本机仓库一一对应(相对路径相同)。',
264
+ 'Both copies are kept here, mirroring the repo layout (same relative paths).',
265
+ '',
266
+ '怎么还原 / How to restore',
267
+ ' 面板 / Panel:配置同步 → 同步冲突 → 展开任一项 → 「还原本机副本」或「还原云端副本」。',
268
+ ' Config sync → Sync conflicts → expand a row → "Restore local copy" / "Restore cloud copy".',
269
+ ' 命令行 / CLI:把本目录里对应副本复制回仓库的同名路径即可。',
270
+ ' Copy the corresponding file from this folder back to the same path in the repo.',
271
+ '',
272
+ '还原任意一份都不会删除另一份,也不改写 git 历史。',
273
+ 'Restoring one never deletes the other and never rewrites git history.',
274
+ '',
275
+ '条目明细 / Files'
276
+ )
277
+ foreach ($it in @($Report.items)) {
278
+ $lines += (' ' + $it.path + ' [' + $it.kind + '] 本机/Local ' + $it.localSize + 'B(备份 ' + $it.localSaved + ') 云端/Cloud ' + $it.remoteSize + 'B(备份 ' + $it.cloudSaved + ')')
279
+ }
280
+ $text = (($lines -join "`r`n") + "`r`n")
281
+ [IO.File]::WriteAllText((Join-Path $BackupDir $ConflictReadmeName), $text, (New-Object Text.UTF8Encoding($false, $false)))
282
+ }
283
+
284
+ function Get-PreviewText([string]$Text, [int]$Max = 1500) {
285
+ if ($null -eq $Text) { return '' }
286
+ if ($Text.Length -eq 0) { return '' }
287
+ # 二进制内容不往 JSON 里塞:含 NUL 就整体放弃预览
288
+ if ($Text.IndexOf([char]0) -ge 0) { return '' }
289
+ if ($Text.Length -gt $Max) { return ($Text.Substring(0, $Max) + "`n…[已截断,原文共 " + $Text.Length + " 字符]") }
290
+ return $Text
291
+ }
292
+
293
+ <#
294
+ 算出「本地会被云端覆盖、因而挡住快进」的文件,落一份备份 + 清单 JSON,返回条目数(0 = 没冲突)。
295
+ 只认 ff 可行的场景:本地领先远端时不叫冲突,那是另一回事(pull --ff-only 会明确报 not possible to fast-forward)。
296
+ #>
297
+ function New-ConflictReport([string]$RemoteRef, [string]$HeadBefore) {
298
+ $cloud = @((Read-GitLines ('diff --name-only HEAD ' + $RemoteRef)).Lines)
299
+ if ($cloud.Count -eq 0) { return 0 }
300
+ $untracked = @((Read-GitLines 'ls-files --others --exclude-standard').Lines)
301
+ $modified = @((Read-GitLines 'diff --name-only').Lines)
302
+ $remoteHead = (Get-GitText ('rev-parse --short ' + $RemoteRef)).Text
303
+
304
+ $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
305
+ $backupDir = Join-Path (Join-Path $DshHome 'backups') ('conflict-' + $stamp + '-' + $ConflictBackupSuffix)
306
+ $localDir = Join-Path $backupDir $ConflictLocalDirName
307
+ $cloudDir = Join-Path $backupDir $ConflictCloudDirName
308
+ $items = @()
309
+ foreach ($rel in $cloud) {
310
+ $isUntracked = ($untracked -contains $rel)
311
+ $isModified = ($modified -contains $rel)
312
+ if (-not ($isUntracked -or $isModified)) { continue }
313
+ $full = Join-Path $RepoRoot $rel
314
+ $kind = 'modified'
315
+ if ($isUntracked) { $kind = 'untracked' }
316
+ $localSize = 0
317
+ $localSaved = $false
318
+ if (Test-Path -LiteralPath $full) {
319
+ try { $localSize = (Get-Item -LiteralPath $full -Force).Length } catch { $localSize = 0 }
320
+ $dst = Join-Path $localDir $rel
321
+ New-Item -ItemType Directory -Path (Split-Path -Parent $dst) -Force | Out-Null
322
+ Copy-Item -LiteralPath $full -Destination $dst -Force
323
+ try { $localSaved = ((Get-Item -LiteralPath $dst -Force).Length -eq $localSize) } catch { $localSaved = $false }
324
+ if (-not $localSaved) { Warn ('本机副本备份校验失败:' + $rel + '(这一项只能用云端副本)') }
325
+ }
326
+ $remoteSize = 0
327
+ $sz = (Get-GitText ('cat-file -s "' + $RemoteRef + ':' + $rel + '"')).Text
328
+ if ($sz -match '^\d+$') { $remoteSize = [int64]$sz }
329
+ # 云端也留一份,且必须字节原样:Save-BlobToFile 走 cmd 重定向,不经 PowerShell 转码
330
+ $cloudSaved = Save-BlobToFile ($RemoteRef + ':' + $rel) (Join-Path $cloudDir $rel) $remoteSize
331
+ if (-not $cloudSaved) { Warn ('云端副本备份失败:' + $rel + '(这一项只能用本机副本)') }
332
+ $binary = Test-BinaryPath $rel
333
+ $localPreview = ''
334
+ $remotePreview = ''
335
+ if (-not $binary) {
336
+ if (Test-Path -LiteralPath $full) {
337
+ try { $localPreview = Get-PreviewText ([IO.File]::ReadAllText($full, (New-Object Text.UTF8Encoding($false, $false))) ) } catch { $localPreview = '' }
338
+ }
339
+ $remotePreview = Get-PreviewText (Get-BlobText ($RemoteRef + ':' + $rel))
340
+ }
341
+ $items += [ordered]@{
342
+ path = $rel
343
+ kind = $kind
344
+ localSize = $localSize
345
+ remoteSize = $remoteSize
346
+ binary = $binary
347
+ localPreview = $localPreview
348
+ remotePreview = $remotePreview
349
+ localSaved = $localSaved
350
+ cloudSaved = $cloudSaved
351
+ choice = ''
352
+ }
353
+ }
354
+ if ($items.Count -eq 0) { return 0 }
355
+ $report = [ordered]@{
356
+ at = (Get-Date).ToString('o')
357
+ repo = $RepoRoot
358
+ head = $HeadBefore
359
+ remote = $RemoteRef
360
+ remoteHead = $remoteHead
361
+ backupDir = $backupDir
362
+ items = $items
363
+ }
364
+ Write-ConflictFile $report
365
+ Write-ConflictReadme $backupDir $report
366
+ # 清单本身留一份在备份目录里,事后能核对「当时给了哪些选项、选了哪边」
367
+ try { [IO.File]::Copy((Get-ConflictPath), (Join-Path $backupDir $ConflictSnapshotName), $true) } catch { }
368
+ return $items.Count
369
+ }
370
+
371
+ <#
372
+ 按清单里的 choice 落地:
373
+ cloud —— 删掉工作区那份(备份已在 conflict-<ts>\files),让云端版本能落地
374
+ local —— 同样先删(已备份);pull 成功后由 Restore-LocalKept 写回,成为本地改动,下次 push 带上
375
+ '' —— 没选,保持原样(这次 pull 仍会被它挡住)
376
+ 只删普通文件:目录/链接不动,避免误删整棵会话树。
377
+ #>
378
+ function Resolve-ConflictChoices($Report) {
379
+ $cloud = 0; $local = 0; $pending = 0
380
+ foreach ($it in @($Report.items)) {
381
+ $choice = [string]$it.choice
382
+ $full = Join-Path $RepoRoot $it.path
383
+ if ($choice -eq 'cloud' -or $choice -eq 'local') {
384
+ if (Test-Path -LiteralPath $full) {
385
+ try {
386
+ $info = Get-Item -LiteralPath $full -Force
387
+ if (-not $info.PSIsContainer) { Remove-Item -LiteralPath $full -Force }
388
+ } catch { Warn ('清不掉:' + $it.path + ' — ' + $_.Exception.Message) }
389
+ }
390
+ if ($choice -eq 'cloud') { $cloud++ } else { $local++ }
391
+ } else { $pending++ }
392
+ }
393
+ return [pscustomobject]@{ Cloud = $cloud; Local = $local; Pending = $pending }
394
+ }
395
+
396
+ function Restore-LocalKept($Report) {
397
+ $n = 0
398
+ foreach ($it in @($Report.items)) {
399
+ if ([string]$it.choice -ne 'local') { continue }
400
+ $src = Join-Path (Get-LocalCopyDir $Report.backupDir) $it.path
401
+ if (-not (Test-Path -LiteralPath $src)) { continue }
402
+ $dst = Join-Path $RepoRoot $it.path
403
+ New-Item -ItemType Directory -Path (Split-Path -Parent $dst) -Force | Out-Null
404
+ Copy-Item -LiteralPath $src -Destination $dst -Force
405
+ $n++
406
+ }
407
+ return $n
408
+ }
409
+
410
+ # ---------- status ----------
411
+ if ($Action -eq 'status') {
412
+ $st = Get-RepoState
413
+ Say "分支:$($st.Branch)"
414
+ Say "HEAD:$($st.Head)"
415
+ if ($st.Dirty -eq 0) { Ok "工作区干净" } else { Warn "工作区有 $($st.Dirty) 项未提交" }
416
+ $app = Get-HostAppVersion $AppRoot
417
+ $contract = $null
418
+ $cp = Join-Path $RepoRoot 'profile\host-contract.json'
419
+ if (Test-Path -LiteralPath $cp) {
420
+ try { $contract = [string](Get-Content -LiteralPath $cp -Raw -Encoding utf8 | ConvertFrom-Json).appVersion } catch { $contract = $null }
421
+ }
422
+ if ($app -and $contract) {
423
+ if ($app -eq $contract) { Ok "版本一致:app = $app" }
424
+ else { Warn "版本不一致:本机 app = $app,仓库契约 = $contract(pull 会被拒绝,除非加 -AllowVersionDrift)" }
425
+ } else {
426
+ Warn ("版本信息不全:本机 app = {0},仓库契约 = {1}" -f $app, $contract)
427
+ }
428
+ $pkg = Join-Path $RepoRoot 'profile\package.json'
429
+ if (Test-Path -LiteralPath $pkg) {
430
+ $b = @((Get-Content -LiteralPath $pkg -Raw -Encoding utf8 | ConvertFrom-Json).dsh.profile.bundles)
431
+ Say "仓库 bundle 清单:$($b.Count) 项(其中实验性 $(@($b | Where-Object { $_ -like '@deepseek-ai/dsh-experimental-*' }).Count) 项)"
432
+ }
433
+ Say ""
434
+ return
435
+ }
436
+
437
+ # ---------- 公共:判断 DSH 是否在跑(push 抓配置前提醒,pull 铺配置前必须退出) ----------
438
+ function Test-DshRunning {
439
+ return [bool](Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue)
440
+ }
441
+
442
+ # ---------- 公共:仓库还没克隆时自己拉下来(新机器只装了插件的情况) ----------
443
+ <#
444
+ 插件在「本机仓库」里配的路径可能是新建的空目录、甚至还不存在(新机器还没 clone)。
445
+ 这里做首次初始化:建目录 → git init → 补 origin(地址取插件设置里的云端仓库)→ fetch → 切到 main。
446
+ 用 init+fetch+checkout 而不是 git clone,是因为目录里已经躺着插件生成的 同步-*.cmd,
447
+ clone 会拒绝非空目录;这些 .cmd 不在版本库里,checkout 不会动它们。
448
+ #>
449
+ # 云端地址:插件设置里那份(面板保存的就是它)。读不到返回空串,由调用方决定怎么报。
450
+ function Get-SettingsRemoteUrl {
451
+ $settingsFile = Join-Path $DshHome 'dsh-config-sync.json'
452
+ if (-not (Test-Path -LiteralPath $settingsFile)) { return '' }
453
+ try {
454
+ $obj = Get-Content -LiteralPath $settingsFile -Raw -Encoding utf8 | ConvertFrom-Json
455
+ if ($obj.remoteUrl) { return [string]$obj.remoteUrl }
456
+ } catch { }
457
+ return ''
458
+ }
459
+
460
+ <#
461
+ 云端仓库有几个分支:0 = 空仓库(还没推过任何东西),-1 = 连不上/没配地址(判不了)。
462
+ 只服务一处判断:本机还是空目录时,云端到底有没有东西可拉 —— 没有就允许「初始化推送」。
463
+ 用 ls-remote 而不是 fetch:纯查询,不写本地 refs,失败也不留半截状态。
464
+ #>
465
+ function Get-RemoteHeads([string]$RemoteUrl) {
466
+ if (-not $RemoteUrl) { return -1 }
467
+ $line = '"' + $git + '" ls-remote --heads "' + $RemoteUrl + '" 2>&1'
468
+ $out = (@(& "$env:ComSpec" /c $line) -join "`n")
469
+ if ($LASTEXITCODE -ne 0) { return -1 }
470
+ return @($out -split "`n" | Where-Object { $_ -match 'refs/heads/' }).Count
471
+ }
472
+
473
+ function Get-OversizedHistory([long]$Limit) {
474
+ # 全量扫 HEAD 的树,返回超过 Limit 的 blob。5 万文件的仓库约 20s,只在首次/被拒/手动 -ScanHistory 时跑。
475
+ # ls-tree 的路径同样会因 quotepath 被八进制转义,走 Read-GitLines 拿真实路径(-l 不会破坏 tab 分隔)
476
+ $res = @()
477
+ $out = @((Read-GitLines 'ls-tree -r -l HEAD').Lines)
478
+ foreach ($line in $out) {
479
+ if ($line -match '^\d+\s+blob\s+[0-9a-f]+\s+(\d+)\t(.+)$') {
480
+ $sz = [long]$Matches[1]
481
+ if ($sz -ge $Limit) { $res += [pscustomobject]@{ Rel = [string]$Matches[2]; Bytes = $sz } }
482
+ }
483
+ }
484
+ # 注意:不能写 `return ,$res` —— 空结果会被包成「含 1 个空元素」的数组,
485
+ # 调用方 @(...) 之后 Count 变成 1,于是空仓库会误报「历史里有 1 个超限文件(0.0 MB)」。
486
+ return $res
487
+ }
488
+
489
+ function Get-RemoteFileCount([string]$RemoteUrl, [int]$Heads = -2) {
490
+ # 「云端有没有可拉的内容」不能看分支数:远端 main 还在、树被删空了,照样是个空仓库。
491
+ # 真判据是分支树里的文件数。做法:临时 bare 仓库浅取一次再 ls-tree,探完删掉,不碰用户仓库。
492
+ # 返回 -1 = 判不了(连不上/认证失败/没配地址)。
493
+ if (-not $RemoteUrl) { return -1 }
494
+ $h = if ($Heads -eq -2) { Get-RemoteHeads $RemoteUrl } else { $Heads }
495
+ if ($h -lt 0) { return -1 }
496
+ if ($h -eq 0) { return 0 }
497
+ $tmp = Join-Path ([IO.Path]::GetTempPath()) ('dcs-probe-' + [Guid]::NewGuid().ToString('N').Substring(0, 10))
498
+ try {
499
+ & "$env:ComSpec" /c ('"' + $git + '" init --bare --quiet "' + $tmp + '" 2>&1') | Out-Null
500
+ if ($LASTEXITCODE -ne 0) { return -1 }
501
+ # 优先只取树对象(partial clone);远端不认就退回普通浅取
502
+ $line = '"' + $git + '" -C "' + $tmp + '" fetch --depth 1 --no-tags --filter=blob:none "' + $RemoteUrl + '" HEAD 2>&1'
503
+ & "$env:ComSpec" /c $line | Out-Null
504
+ if ($LASTEXITCODE -ne 0) {
505
+ $line = '"' + $git + '" -C "' + $tmp + '" fetch --depth 1 --no-tags "' + $RemoteUrl + '" HEAD 2>&1'
506
+ & "$env:ComSpec" /c $line | Out-Null
507
+ if ($LASTEXITCODE -ne 0) { return -1 }
508
+ }
509
+ $treeLine = '"' + $git + '" -C "' + $tmp + '" ls-tree -r --name-only FETCH_HEAD 2>nul'
510
+ $out = (@(& "$env:ComSpec" /c $treeLine) -join "`n")
511
+ return @($out -split "`n" | Where-Object { $_ -and ([string]$_).Trim() }).Count
512
+ } finally {
513
+ if (Test-Path -LiteralPath $tmp) { try { Remove-Item -LiteralPath $tmp -Recurse -Force } catch { } }
514
+ }
515
+ }
516
+
517
+ <#
518
+ 初始化推送:本机空目录 + 云端空仓库,把本机配置当作仓库的初始内容推上去。
519
+ 骨架要一起带进仓库 —— 历史仓库本来就有 apply.ps1 / capture.ps1 / dsh-sync-common.ps1 这几份副本,
520
+ 少拷了它们,远端就变成「只有 settings 没有执行体」的半截仓库,另一台 pull 下来跑不起来。
521
+ profile\host-contract.json 用本机客户端版本生成(apply 靠它校验两端版本,缺了只会跳过校验)。
522
+ #>
523
+ function Initialize-EmptyRepo([string]$RemoteUrl) {
524
+ if (-not $RemoteUrl) {
525
+ Die ("本机仓库还是空的($RepoRoot),也没读到云端仓库地址:" +
526
+ "请先在面板「云端仓库」里填好地址并保存,再重跑本脚本。")
527
+ }
528
+ if (-not (Test-Path -LiteralPath $RepoRoot)) { New-Item -ItemType Directory -Path $RepoRoot -Force | Out-Null }
529
+ Say ""
530
+ Say "== 初始化仓库(首次推送) =="
531
+ Say " 目录:$RepoRoot"
532
+ Say " 云端:$RemoteUrl(空仓库)"
533
+ if (-not (Test-Path -LiteralPath (Join-Path $RepoRoot '.git'))) {
534
+ $initLine = '"' + $git + '" -C "' + $RepoRoot + '" init --initial-branch=main 2>&1'
535
+ & "$env:ComSpec" /c $initLine | Out-Null
536
+ if ($LASTEXITCODE -ne 0) {
537
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" init 2>&1') | Out-Null
538
+ if ($LASTEXITCODE -ne 0) { Die "git init 失败:$RepoRoot" }
539
+ }
540
+ }
541
+ $originUrl = (@(& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote get-url origin 2>nul')) -join '').Trim()
542
+ if ($originUrl) {
543
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote set-url origin "' + $RemoteUrl + '" 2>&1') | Out-Null
544
+ } else {
545
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote add origin "' + $RemoteUrl + '" 2>&1') | Out-Null
546
+ }
547
+ if ($LASTEXITCODE -ne 0) { Die "给仓库加 origin 失败:$RemoteUrl" }
548
+
549
+ $copied = 0
550
+ foreach ($n in @('apply.ps1', 'capture.ps1', 'sync.ps1', 'restore.ps1', 'post-exit.ps1', 'dsh-sync-common.ps1')) {
551
+ $src = Join-Path $PSScriptRoot $n
552
+ if (Test-Path -LiteralPath $src) {
553
+ Copy-Item -LiteralPath $src -Destination (Join-Path $RepoRoot $n) -Force
554
+ $copied++
555
+ }
556
+ }
557
+ if ($copied -gt 0) { Ok "已写入仓库骨架:$copied 个执行体(apply / capture / sync / restore / post-exit / common)" }
558
+ # tools\fix-session-cwd.mjs 也随仓库同步(apply 在没有插件副本时会用它修会话工作目录),
559
+ # 初始化骨架漏掉它,配置仓库就永远缺这一份,自检的逐字节一致性断言也会一直红。
560
+ $toolSrc = Join-Path (Join-Path $PSScriptRoot 'tools') 'fix-session-cwd.mjs'
561
+ if (Test-Path -LiteralPath $toolSrc) {
562
+ $toolDst = Join-Path $RepoRoot 'tools'
563
+ if (-not (Test-Path -LiteralPath $toolDst)) { New-Item -ItemType Directory -Path $toolDst -Force | Out-Null }
564
+ Copy-Item -LiteralPath $toolSrc -Destination (Join-Path $toolDst 'fix-session-cwd.mjs') -Force
565
+ Ok "已写入仓库骨架:tools\fix-session-cwd.mjs"
566
+ }
567
+
568
+ $contractPath = Join-Path $RepoRoot 'profile\host-contract.json'
569
+ if (-not (Test-Path -LiteralPath $contractPath)) {
570
+ $ver = ''
571
+ $pkg = Join-Path $AppRoot 'resources\app\package.json'
572
+ if (Test-Path -LiteralPath $pkg) {
573
+ try { $ver = [string](Get-Content -LiteralPath $pkg -Raw -Encoding utf8 | ConvertFrom-Json).version } catch { }
574
+ }
575
+ if (-not $ver) {
576
+ $vf = Join-Path $AppRoot 'version'
577
+ if (Test-Path -LiteralPath $vf) { $ver = (Get-Content -LiteralPath $vf -Raw -Encoding utf8).Trim() }
578
+ }
579
+ if ($ver) {
580
+ $dir = Join-Path $RepoRoot 'profile'
581
+ if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
582
+ $obj = [ordered]@{
583
+ appVersion = $ver
584
+ generatedAt = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
585
+ note = '由 dsh-config-sync 首次推送生成(客户端版本契约)'
586
+ }
587
+ [IO.File]::WriteAllText($contractPath, ($obj | ConvertTo-Json -Depth 4), (New-Object Text.UTF8Encoding $false))
588
+ Ok "已写入版本契约:$ver"
589
+ } else {
590
+ Warn "读不到本机客户端版本,跳过 profile\host-contract.json(另一台 pull 时会跳过版本校验)"
591
+ }
592
+ }
593
+ Ok "已初始化空仓库并指向 origin"
594
+ }
595
+
596
+ function Initialize-RepoIfNeeded {
597
+ $gitDir = Join-Path $RepoRoot '.git'
598
+ if ((Test-Path -LiteralPath $gitDir) -and (Test-Path -LiteralPath (Join-Path $RepoRoot 'sync.ps1'))) { return }
599
+ $remote = Get-SettingsRemoteUrl
600
+ if (-not (Test-Path -LiteralPath $RepoRoot)) { New-Item -ItemType Directory -Path $RepoRoot -Force | Out-Null }
601
+ if (-not (Test-Path -LiteralPath $gitDir)) {
602
+ if (-not $remote) { Die ("本机还没有仓库($RepoRoot),也没读到云端仓库地址:" +
603
+ "请先在插件面板「云端仓库」里填好地址并保存,再重跑本脚本。") }
604
+ Say ""
605
+ Say "== 首次初始化仓库 =="
606
+ Say " 目录:$RepoRoot"
607
+ Say " 云端:$remote"
608
+ # 注意:本脚本 ErrorActionPreference=Stop,git 往 stderr 写的正常提示会被包成终止错误,
609
+ # 所以每一步都交给 cmd 转发,只看退出码(和 Get-GitText 同一套做法)。
610
+ $initLine = '"' + $git + '" -C "' + $RepoRoot + '" init --initial-branch=main 2>&1'
611
+ & "$env:ComSpec" /c $initLine | Out-Null
612
+ if ($LASTEXITCODE -ne 0) {
613
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" init 2>&1') | Out-Null
614
+ if ($LASTEXITCODE -ne 0) { Die "git init 失败:$RepoRoot" }
615
+ }
616
+ $originUrl = (@(& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote get-url origin 2>nul')) -join '').Trim()
617
+ if ($originUrl) {
618
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote set-url origin "' + $remote + '" 2>&1') | Out-Null
619
+ } else {
620
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote add origin "' + $remote + '" 2>&1') | Out-Null
621
+ }
622
+ if ($LASTEXITCODE -ne 0) { Die "给仓库加 origin 失败:$remote" }
623
+ Ok "已初始化空仓库并指向 origin"
624
+ }
625
+ Say ""
626
+ Say "== 从云端拉取仓库内容 =="
627
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" fetch origin 2>&1') | Write-Host
628
+ if ($LASTEXITCODE -ne 0) { Die ("git fetch 失败:连不上远端或认证有问题(" + (Get-RemoteAuthHint $remote) + ",再重跑)。") }
629
+ $branchName = 'main'
630
+ $heads = (@(& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" ls-remote --heads origin 2>nul')) -join "`n")
631
+ if ($heads -notmatch 'refs/heads/main') {
632
+ $first = ($heads -split "`n" | Where-Object { $_ -match 'refs/heads/' } | Select-Object -First 1)
633
+ if ($first -and $first -match 'refs/heads/(.+)$') { $branchName = $Matches[1].Trim() }
634
+ }
635
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" checkout -B ' + $branchName + ' origin/' + $branchName + ' 2>&1') | Write-Host
636
+ if ($LASTEXITCODE -ne 0) { Die "从 origin/$branchName 检出失败(原因见上面的 git 输出)。" }
637
+ Ok "仓库已就位:$RepoRoot(分支 $branchName)"
638
+ }
639
+
640
+ # ---------- push ----------
641
+ if ($Action -eq 'push') {
642
+ # 推送的三种起点,判据统一成「本机有没有历史 + 云端有没有内容」:
643
+ # 有仓库有历史 → 正常推送(老逻辑照旧)
644
+ # 本机没内容、云端有内容 → 只能先拉取(硬推会把本机状态写进一份已经在用的历史)
645
+ # 本机没内容、云端也空 → 初始化推送:本机配置就是仓库的初始内容(新需求)
646
+ $hasGit = Test-Path -LiteralPath (Join-Path $RepoRoot '.git')
647
+ # 远端地址:仓库里已有 origin 就以它为准(用户/历史可能已经 remote set-url 过),没有才回落设置文件
648
+ $remoteUrlForPush = ''
649
+ if ($hasGit) {
650
+ $remoteUrlForPush = (@(& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" remote get-url origin 2>nul')) -join '').Trim()
651
+ }
652
+ if (-not $remoteUrlForPush) { $remoteUrlForPush = Get-SettingsRemoteUrl }
653
+ $hasCommit = $false
654
+ $remoteHadEmptyBranch = $false
655
+ if ($hasGit) {
656
+ $probe = @(& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" rev-parse --verify HEAD 2>nul'))
657
+ $hasCommit = (($probe -join '').Trim().Length -gt 0)
658
+ }
659
+ if (-not $hasCommit) {
660
+ # 目录里已经有别的东西(非空、也不是本插件生成的 同步-*.cmd)→ 多半填错路径,别往里写
661
+ if (Test-Path -LiteralPath $RepoRoot) {
662
+ $stray = @(Get-ChildItem -LiteralPath $RepoRoot -Force |
663
+ Where-Object { -not $_.Name.StartsWith('.') -and $_.Name -notmatch '^同步-[\s\S]*\.cmd$' })
664
+ if ($stray.Count -gt 0) {
665
+ # 例外:配置仓库本身就带本插件的脚本(clone 下来的仓库里一直有 sync.ps1 / capture.ps1 /
666
+ # dsh-sync-common.ps1)。初始化推送更常见——capture 刚把 16 项配置写进来,目录当然非空。
667
+ # 真填错路径(桌面、下载目录)不会有这些脚本,所以拿它们当「这是同步仓库」的凭据。
668
+ $isSyncRepo = (Test-Path -LiteralPath (Join-Path $RepoRoot 'dsh-sync-common.ps1')) -or
669
+ (Test-Path -LiteralPath (Join-Path $RepoRoot 'sync.ps1')) -or
670
+ (Test-Path -LiteralPath (Join-Path $RepoRoot 'capture.ps1'))
671
+ if (-not $isSyncRepo) {
672
+ Warn ("这个目录不是空的({0} 项:{1}),也不像 dsh-config 仓库:{2}" -f `
673
+ $stray.Count, (($stray | Select-Object -First 3 | ForEach-Object { $_.Name }) -join '、'), $RepoRoot)
674
+ Die "已停止(未抓取、未提交、未推送)。请在面板「本机仓库」里重新设路径。"
675
+ }
676
+ }
677
+ }
678
+ $headsForPush = Get-RemoteHeads $remoteUrlForPush
679
+ $remoteFiles = Get-RemoteFileCount $remoteUrlForPush $headsForPush
680
+ if ($remoteFiles -lt 0) {
681
+ Warn "连不上云端、或还没配云端地址($remoteUrlForPush):初始化推送要先确认云端是空仓库"
682
+ Die "已停止(未抓取、未提交、未推送)。请先确认「云端仓库」里的地址能访问,再重跑。"
683
+ }
684
+ if ($remoteFiles -gt 0) {
685
+ Warn "云端仓库已经有内容($remoteFiles 个文件):本机还是空的,应该先拉取,而不是推送"
686
+ Warn "硬推会把本机状态写进一份正在使用的历史里;新机器请点「立即拉取」"
687
+ Die "已停止(未抓取、未提交、未推送)。"
688
+ }
689
+ # 远端已经有分支、但树里一个文件都没有(历史被删空过):这次推送要覆盖那个空分支。
690
+ # 树是空的,没有任何数据可丢,所以用 --force-with-lease(仍带远端 ref 校验,比 --force 安全)。
691
+ if ($headsForPush -gt 0) {
692
+ $remoteHadEmptyBranch = $true
693
+ Say ""
694
+ Say (" 云端已有 $headsForPush 个分支,但里面没有任何文件(历史被删空)——本次推送会覆盖这个空分支,不丢数据")
695
+ }
696
+ Initialize-EmptyRepo $remoteUrlForPush
697
+ } else {
698
+ # 有历史但缺仓库骨架:说明这目录本来不是 dsh-config 仓库(老仓库被删过脚本),照老规矩拒推
699
+ if (-not (Test-Path -LiteralPath (Join-Path $RepoRoot 'apply.ps1'))) {
700
+ Warn "仓库目录缺 apply.ps1($RepoRoot):推送只用于把本机改动提交进一个已有的仓库。"
701
+ Die "已停止(未抓取、未提交、未推送)。"
702
+ }
703
+ Initialize-RepoIfNeeded
704
+ }
705
+ if ((Test-DshRunning) -and (-not $Force)) {
706
+ Warn "检测到 DeepSeek Harness 在运行:capture 可能抓到写了一半的配置"
707
+ Warn "建议完全退出(含托盘)后重跑;确认要继续可加 -Force"
708
+ Die "已停止(未抓取、未提交)。"
709
+ }
710
+ $captureArgs = @{ RepoRoot = $RepoRoot; DshHome = $DshHome; ProfileName = $ProfileName; AppRoot = $AppRoot; WorkspaceHome = $WorkspaceHome; NoResetNotices = $true }
711
+ if ($WorkspaceOnly) { $captureArgs['WorkspaceOnly'] = $true }
712
+ if ($SkipWorkspace) { $captureArgs['SkipWorkspace'] = $true }
713
+ if ($DeepVerify) { $captureArgs['DeepVerify'] = $true }
714
+ & (Join-Path $PSScriptRoot 'capture.ps1') @captureArgs
715
+ if ($LASTEXITCODE -ne 0) { Die "capture.ps1 未正常结束,已停止(未提交)。" }
716
+
717
+ Say ""
718
+ Say "== 提交 =="
719
+ Initialize-CommitIdentity
720
+ & $git -C $RepoRoot add -A
721
+ # 走 Read-GitLines:中文目录名若被 quotepath 转义成 "…\347\240\264…",连引号一起拿进
722
+ # Test-Path -LiteralPath 就是「路径中具有非法字符」,整次同步会在这里挂掉
723
+ $pending = @((Read-GitLines 'diff --cached --name-only').Lines)
724
+
725
+ # ---------- 单文件上限预检(提交前) ----------
726
+ # capture 已在源头挡掉 workspace 里 >100MB 的资料,但仓库目录里仍可能有别处来的大文件
727
+ # (手工放的、旧版本留下的、其它插件写的),`git add -A` 会照样收进索引,然后 push 被
728
+ # 服务端 pre-receive 拒掉 —— 而旧版把这种拒收统称成「网络/认证」,把排查带偏。
729
+ # 这里在提交前把超限文件从索引撤回(文件留在磁盘不动),其余内容照常提交、照常推送。
730
+ $pushHardLimit = 95MB # 100MB 是 Gitee/GitHub/GitLab 的判定线,留 5MB 余量,别卡边界
731
+ $pushWarnLimit = 50MB
732
+ if ($pending.Count -gt 0) {
733
+ $tooLarge = @()
734
+ foreach ($rel in $pending) {
735
+ # 单个名字异常(含引号、盘符、控制字符)不该拖垮整次同步:stat 不了就跳过这条
736
+ try {
737
+ $full = Join-Path $RepoRoot $rel
738
+ if (-not (Test-Path -LiteralPath $full)) { continue } # 删除项没有体积
739
+ $len = [long](Get-Item -LiteralPath $full -Force).Length
740
+ } catch { continue }
741
+ if ($len -ge $pushHardLimit) { $tooLarge += [pscustomobject]@{ Rel = [string]$rel; Bytes = $len } }
742
+ elseif ($len -ge $pushWarnLimit) {
743
+ Warn ('文件偏大({0:N1} MB,接近 100 MB 上限):{1}' -f ($len / 1MB), $rel)
744
+ }
745
+ }
746
+ if ($tooLarge.Count -gt 0) {
747
+ $excludeFile = Join-Path $RepoRoot '.git\info\exclude'
748
+ $excludeDir = Split-Path -Parent $excludeFile
749
+ if (-not (Test-Path -LiteralPath $excludeDir)) { New-Item -ItemType Directory -Path $excludeDir -Force | Out-Null }
750
+ foreach ($o in $tooLarge) {
751
+ $relPath = [string]$o.Rel
752
+ & $git -C $RepoRoot reset -q -- $relPath 2>$null
753
+ $exLine = '/' + $relPath.Replace([string][char]92, '/')
754
+ try {
755
+ $cur = if (Test-Path -LiteralPath $excludeFile) { Get-Content -LiteralPath $excludeFile -Raw -Encoding utf8 } else { '' }
756
+ if ($cur -notmatch [regex]::Escape($exLine)) {
757
+ Add-Content -LiteralPath $excludeFile -Value $exLine -Encoding utf8
758
+ }
759
+ } catch { }
760
+ Warn ('超过单文件上限({0:N1} MB ≥ {1:N0} MB),已从本次提交剔除:{2}' -f ($o.Bytes / 1MB), ($pushHardLimit / 1MB), $relPath)
761
+ Add-SyncNotice -Kind 'too-large' -Path $relPath -Bytes $o.Bytes -Reason ('{0:N1} MB ≥ 单文件上限 {1:N0} MB,未提交也未推送' -f ($o.Bytes / 1MB), ($pushHardLimit / 1MB))
762
+ }
763
+ Warn '这些文件仍留在磁盘,只是不进仓库;已写进 .git\info\exclude,下次 add 不会再收进来。'
764
+ $pending = @((Read-GitLines 'diff --cached --name-only').Lines)
765
+ }
766
+ }
767
+
768
+ if ($pending.Count -eq 0) {
769
+ Ok "仓库与仓库文件一致,没有需要提交的改动"
770
+ } else {
771
+ if (-not $Message) {
772
+ $Message = ("sync: capture {0} @ {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm'), $env:COMPUTERNAME)
773
+ } elseif ($Message -notmatch '\d{1,2}:\d{2}') {
774
+ # 面板/命令行给的是人写的说明:执行这一刻自动附上时间,免得写死在脚本里变成旧时间。
775
+ $Message = ("{0} @ {1}" -f $Message.Trim(), (Get-Date -Format 'yyyy-MM-dd HH:mm'))
776
+ }
777
+ # 提交失败要把 git 的原话放出来(身份/钩子/索引锁都可能),别只报一句「commit 失败」。
778
+ # 本脚本是 ErrorActionPreference=Stop,git 写 stderr 会被包成终止错误,所以临时放开。
779
+ $eap = $ErrorActionPreference
780
+ $ErrorActionPreference = 'Continue'
781
+ $commitOut = @(& $git -C $RepoRoot commit -m $Message 2>&1)
782
+ $commitCode = $LASTEXITCODE
783
+ $ErrorActionPreference = $eap
784
+ $commitOut | ForEach-Object { if ($_ -and ([string]$_).Trim()) { Say (" " + ([string]$_).Trim()) } }
785
+ if ($commitCode -ne 0) {
786
+ Die ("git commit 失败(退出码 {0}),原因见上面几行;改动已留在本地工作区,修好后重跑本脚本或手动 " +
787
+ "git -C `"{1}`" commit。常见原因:没配 git user.name/user.email、有 .git/index.lock、pre-commit 钩子报错。" -f $commitCode, $RepoRoot)
788
+ }
789
+ Ok "已提交 $($pending.Count) 个文件:$Message"
790
+ }
791
+
792
+ Say ""
793
+ Say "== 推送 =="
794
+ # git push 的进度和 gitee 的 "remote: Powered by GITEE.COM" 横幅都走 stderr,
795
+ # PowerShell 5.1 直接重定向会把这些行包成 NativeCommandError,明明成功却报失败。
796
+ # 交给 cmd 转发,只看退出码,输出照原样显示。
797
+ # 新机器的分支可能还没有 upstream(origin 是插件后补的),这时 push 要带 -u。
798
+ $bs = Get-BranchUpstream
799
+ $branch = $bs.Branch
800
+ $upstream = $bs.Upstream
801
+
802
+ # ---------- 历史里已有的超限文件:只报告,不改写历史 ----------
803
+ # 远端拒收看的是「这次要推上去的所有对象」,而不只是工作区。索引预检只能挡住本次新增的,
804
+ # 早先某个提交已经把大文件写进历史时,怎么 add / reset 都没用 —— 必须先让用户知道这条死路。
805
+ #
806
+ # 扫描成本:`ls-tree -r -l HEAD` 在 5 万文件的仓库里实测 20~23s,而它查的历史几乎不变
807
+ #(新增文件已经由上面的 pending 预检覆盖)。所以默认按提交缓存:同一段历史里只全量扫一次,
808
+ # 换机器/清缓存/加 -ScanHistory/推送被远端拒绝时才重扫。
809
+ $histTooLarge = @()
810
+ $historyFullyScanned = $false
811
+ $histScanFile = Join-Path $DshHome 'sync-history-scan.json'
812
+ $headNow = (Get-GitText 'rev-parse HEAD').Text
813
+
814
+ $needHistoryScan = $true
815
+ if (-not $ScanHistory -and $histScanFile -and (Test-Path -LiteralPath $histScanFile)) {
816
+ try {
817
+ $rec = Get-Content -LiteralPath $histScanFile -Raw -Encoding UTF8 | ConvertFrom-Json
818
+ if ($rec -and $rec.commit) {
819
+ $recCommit = [string]$rec.commit
820
+ if ($recCommit -eq $headNow) { $needHistoryScan = $false }
821
+ else {
822
+ # 记录的是祖先提交:那段历史早就扫过,本次新增的文件由 pending 预检负责
823
+ $anc = (Get-GitText ('merge-base --is-ancestor ' + $recCommit + ' HEAD'))
824
+ if ($anc.Code -eq 0) { $needHistoryScan = $false }
825
+ }
826
+ }
827
+ } catch { }
828
+ }
829
+
830
+ if ($needHistoryScan) {
831
+ $histTooLarge = @(Get-OversizedHistory $pushHardLimit)
832
+ $historyFullyScanned = $true
833
+ try {
834
+ $rec = [ordered]@{ commit = $headNow; oversized = $histTooLarge.Count; at = (Get-Date -Format 'yyyy-MM-ddTHH:mm:ss') }
835
+ [IO.File]::WriteAllText($histScanFile, (($rec | ConvertTo-Json -Depth 3) + "`n"), (New-Object Text.UTF8Encoding($false)))
836
+ } catch { }
837
+ }
838
+ if ($histTooLarge.Count -gt 0) {
839
+ Warn ('历史提交里有 {0} 个超限文件:远端会拒收整次推送(不是网络问题)' -f $histTooLarge.Count)
840
+ foreach ($o in @($histTooLarge | Select-Object -First 5)) {
841
+ Warn (' - {0}({1:N1} MB)' -f $o.Rel, ($o.Bytes / 1MB))
842
+ }
843
+ if ($histTooLarge.Count -gt 5) { Warn (' …还有 {0} 个' -f ($histTooLarge.Count - 5)) }
844
+ foreach ($o in $histTooLarge) {
845
+ Add-SyncNotice -Kind 'history' -Path $o.Rel -Bytes $o.Bytes -Reason ('历史提交里已有({0:N1} MB),远端会拒收整次推送' -f ($o.Bytes / 1MB))
846
+ }
847
+ Warn '处理办法:①面板「初始化推送」到一份新的空仓库(配置同步不需要旧历史,最省事);'
848
+ Warn ' ②git filter-repo 把大文件从历史里摘掉再推(改写历史,需 force)。'
849
+ }
850
+
851
+ # 覆盖「有分支但空树」的远端:本地是全新历史,和远端没有共同祖先,不加 force 会被 non-fast-forward 拒。
852
+ $forceFlag = if ($remoteHadEmptyBranch) { ' --force-with-lease' } else { '' }
853
+ if ($upstream) {
854
+ $pushLine = '"' + $git + '" -C "' + $RepoRoot + '" push' + $forceFlag + ' 2>&1'
855
+ } else {
856
+ Say " 当前分支 $branch 还没有 upstream,推送时一并建立 origin/$branch"
857
+ $pushLine = '"' + $git + '" -C "' + $RepoRoot + '" push' + $forceFlag + ' -u origin "' + $branch + '" 2>&1'
858
+ }
859
+ # 输出要捕获再打印:旧版直接 Write-Host 之后只看退出码,远端那句
860
+ # 「File xxx is 123MB; this exceeds ... limit」被淹没,失败结论却写成「网络/认证」。
861
+ $eapPush = $ErrorActionPreference
862
+ $ErrorActionPreference = 'Continue'
863
+ $pushOut = (& "$env:ComSpec" /c $pushLine 2>&1 | Out-String)
864
+ $pushCode = $LASTEXITCODE
865
+ $ErrorActionPreference = $eapPush
866
+ foreach ($l in ($pushOut -split "`r?`n")) {
867
+ if ($l -and $l.Trim()) { Say (' ' + $l.TrimEnd()) }
868
+ }
869
+ if ($pushCode -ne 0) {
870
+ if (-not $historyFullyScanned) {
871
+ # 推送被拒:这时才值得花一次全量扫描,把「是不是历史里的大文件在挡」说清楚
872
+ $histTooLarge = @(Get-OversizedHistory $pushHardLimit)
873
+ $historyFullyScanned = $true
874
+ try {
875
+ $rec = [ordered]@{ commit = $headNow; oversized = $histTooLarge.Count; at = (Get-Date -Format 'yyyy-MM-ddTHH:mm:ss') }
876
+ [IO.File]::WriteAllText($histScanFile, (($rec | ConvertTo-Json -Depth 3) + "`n"), (New-Object Text.UTF8Encoding($false)))
877
+ } catch { }
878
+ }
879
+ $remoteOversized = @()
880
+ foreach ($l in ($pushOut -split "`r?`n")) {
881
+ if ($l -match 'File\s+(.+?)\s+is\s+([\d.]+)\s*MB.*exceeds.*limit') {
882
+ $remoteOversized += [pscustomobject]@{ Rel = [string]$Matches[1]; Mb = [double]$Matches[2] }
883
+ }
884
+ }
885
+ foreach ($o in $remoteOversized) {
886
+ Add-SyncNotice -Kind 'too-large' -Path $o.Rel -Bytes ([long]($o.Mb * 1MB)) -Reason ('远端拒收:{0} MB 超过单文件上限' -f $o.Mb)
887
+ }
888
+ $quotaHit = [bool]($pushOut -match 'exceeds .*quota|repository size|total repository size|仓库容量|容量上限')
889
+ $networkHit = [bool]($pushOut -match 'Could not read from remote|Permission denied|publickey|Host key verification|Could not resolve host|timed out|Connection refused|Operation timed out')
890
+ $rejectedHit = [bool]($pushOut -match '\[remote rejected\]|pre-receive hook declined')
891
+
892
+ if ($remoteOversized.Count -gt 0 -or $histTooLarge.Count -gt 0) {
893
+ # 有具体文件名(远端报的)或历史预检命中:这是「文件超限」,不是网络
894
+ $names = if ($remoteOversized.Count -gt 0) { $remoteOversized } else { $histTooLarge }
895
+ $list = @($names | Select-Object -First 5 | ForEach-Object {
896
+ $mb = if ($_.Bytes) { $_.Bytes / 1MB } else { $_.Mb }
897
+ ' - ' + $_.Rel + '(' + ('{0:N1}' -f $mb) + ' MB)'
898
+ })
899
+ $msg = ("git push 被远端拒绝:{0} 个文件超过单文件上限(不是网络/SSH 问题)。" -f $names.Count) +
900
+ "`n" + ($list -join "`n") +
901
+ "`n 处理:①面板「初始化推送」到一份新的空仓库(配置同步不需要旧历史,最省事);" +
902
+ "②git filter-repo 把这些文件从历史摘掉再推(改写历史,需 force)。" +
903
+ "`n 这些文件本身不进仓库,本地原件不动。"
904
+ Die $msg
905
+ }
906
+ if ($quotaHit) {
907
+ Die ("git push 被远端拒绝:仓库总量超限(Gitee 免费仓库 1GB)。当前仓库里有过多大文件或历史提交。" +
908
+ "`n 处理:面板「初始化推送」到新仓库,或按上面的历史清理办法瘦身。")
909
+ }
910
+ if ($rejectedHit) {
911
+ Die ("git push 被远端拒绝(remote rejected / pre-receive hook declined),原因见上面 remote: 那几行。" +
912
+ "`n 改动已提交在本地,处理完远端限制后重跑 git -C `"$RepoRoot`" push 即可。")
913
+ }
914
+ if ($networkHit) {
915
+ Die "git push 失败(网络/认证)。改动已提交在本地,修好网络后重跑:git -C `"$RepoRoot`" push;若是 GIT_SSH_COMMAND 问题,先确认它第一个词是 ssh.exe 本体"
916
+ }
917
+ Die ("git push 失败(原因见上面 remote: 那几行,既不是文件超限也不是已知的网络/认证特征)。" +
918
+ "改动已提交在本地,修好后再重跑。")
919
+ }
920
+ Ok "已推送:$(& $git -C $RepoRoot log -1 --oneline)"
921
+ Write-SyncState 'push'
922
+ Say "另一台机器执行:pwsh -File sync.ps1 pull"
923
+ return
924
+ }
925
+
926
+ # ---------- pull ----------
927
+ Initialize-RepoIfNeeded
928
+ if ((Test-DshRunning) -and (-not $Force)) {
929
+ Die "DeepSeek Harness 仍在运行。请完全退出(含托盘)后重跑,或加 -Force 强制继续。"
930
+ }
931
+ Say ""
932
+ Say "== 拉取 =="
933
+
934
+ # ---- 冲突协调:先把上一轮用户的选择落地,再决定这次能不能直接快进 ----
935
+ $branchNow = (Get-GitText 'rev-parse --abbrev-ref HEAD').Text
936
+ $remoteRef = 'origin/' + $branchNow
937
+ $headBeforePull = (Get-GitText 'rev-parse HEAD').Text
938
+ $report = Read-ConflictFile
939
+ $fetchedThisRun = $false
940
+ if ($report) {
941
+ $rc = Resolve-ConflictChoices $report
942
+ Say (" 上一轮选择:用云端 {0} 项,用本机 {1} 项,未选 {2} 项" -f $rc.Cloud, $rc.Local, $rc.Pending)
943
+ if ($rc.Pending -gt 0) {
944
+ Write-ConflictFile $report
945
+ Die ("还有 {0} 项冲突没选:打开面板「同步冲突」逐项选「用本机 / 用云端」,再点「立即拉取」。`n 清单:{1}" -f $rc.Pending, (Get-ConflictPath))
946
+ }
947
+ } else {
948
+ # 没有清单:先 fetch(让 origin/<branch> 是最新的),再算「谁挡路」。
949
+ # 有冲突就生成清单并停下等用户选,绝不 reset 回滚 —— 回滚会把已经快进上去的提交又打回去,越拉越死。
950
+ $fetchOut = (& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" fetch origin --prune 2>&1') 2>&1 | Out-String)
951
+ if ($LASTEXITCODE -ne 0) {
952
+ Say $fetchOut.TrimEnd()
953
+ Die ("git fetch 失败:连不上远端或认证有问题(" + (Get-RemoteAuthHint (Get-GitText 'remote get-url origin').Text) + ",再重跑)。")
954
+ }
955
+ $fetchedThisRun = $true
956
+ $anc = (Get-GitText ('merge-base --is-ancestor HEAD ' + $remoteRef))
957
+ if ($anc.Code -eq 0) {
958
+ $conflictCount = New-ConflictReport $remoteRef $headBeforePull
959
+ if ($conflictCount -gt 0) {
960
+ $rp = Read-ConflictFile
961
+ Say ""
962
+ Say (" [!] 有 {0} 个本机文件会被云端版本覆盖,已备份本机副本并生成冲突清单" -f $conflictCount)
963
+ Say (" 清单:{0}" -f (Get-ConflictPath))
964
+ Say (" 备份:{0}" -f $rp.backupDir)
965
+ Say " 打开面板「同步冲突」逐项选「用本机 / 用云端」,再点「立即拉取」"
966
+ exit 6
967
+ }
968
+ }
969
+ }
970
+
971
+ # 上面已经 fetch 过(origin/<branch> 就是本机最新);这里不再跑 `git pull` —— 它内部还会再 fetch 一次,
972
+ # 等于每次拉取多付一次网络往返(SSH 握手约 1s)。直接 merge --ff-only,语义完全相同:只认快进,
973
+ # 有本地改动/冲突照样失败,绝不替你合并。
974
+ $bs = Get-BranchUpstream
975
+ $branch = $bs.Branch
976
+ $upstream = $bs.Upstream
977
+ if (-not $fetchedThisRun) {
978
+ # 上一轮带着冲突清单进来(那条路径跳过了前面那次 fetch):这里补一次,保证 merge 用的是最新 refs
979
+ Say " 先同步云端 refs(上一次是带着冲突清单进来的,还没 fetch)"
980
+ $fetchOut = (& "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" fetch origin --prune 2>&1') 2>&1 | Out-String)
981
+ if ($LASTEXITCODE -ne 0) {
982
+ Say $fetchOut.TrimEnd()
983
+ Die ("git fetch 失败:连不上远端或认证有问题(" + (Get-RemoteAuthHint (Get-GitText 'remote get-url origin').Text) + ",再重跑)。")
984
+ }
985
+ $fetchedThisRun = $true
986
+ }
987
+ if (-not $upstream) { Say " 当前分支 $branch 还没有 upstream,按 origin/$branch 拉取并补上跟踪关系" }
988
+ $pullLine = '"' + $git + '" -C "' + $RepoRoot + '" merge --ff-only origin/' + $branch + ' 2>&1'
989
+ # 失败原因要分类再报:把「连不上远端/SSH 命令非法」说成「本地有改动」会把排查带偏
990
+ # (真实案例:GIT_SSH_COMMAND 少了 ssh.exe 本体,git 只说 Could not read from remote repository)。
991
+ $pullOut = (& "$env:ComSpec" /c $pullLine 2>&1 | Out-String)
992
+ Write-Host $pullOut.TrimEnd()
993
+ if ($LASTEXITCODE -ne 0) {
994
+ if ($pullOut -match 'Could not read from remote|Permission denied|invalid option|Host key verification|publickey|Bad owner or permissions') {
995
+ Die ("拉取失败:连不上远端 / SSH 认证或命令有问题(不是本地改动)。先自检:" +
996
+ "①GIT_SSH_COMMAND 第一个词必须是 ssh.exe 本体,可先 set GIT_SSH_COMMAND 什么都不设改用 .ssh\config;" +
997
+ "②" + (Get-RemoteAuthHint (Get-GitText 'remote get-url origin').Text) + ";③再跑 git -C `"$RepoRoot`" ls-remote --heads origin 看退出码。")
998
+ } elseif ($pullOut -match 'CONFLICT|not possible to fast-forward|Not possible to fast-forward|Your local changes|overwritten by merge|would be overwritten') {
999
+ Die ("拉取失败:本地有未提交改动或与远端冲突(merge --ff-only 拒绝非快进)。先处理(git -C `"$RepoRoot`" status / stash / 解决冲突)再重跑;" +
1000
+ "本脚本不会替你合并。")
1001
+ } else {
1002
+ Die "拉取失败(原因见上面的 git 输出)。先把那几行原文看完再决定,别按「本地有改动」的思路瞎猜。"
1003
+ }
1004
+ }
1005
+ if (-not $upstream) {
1006
+ & "$env:ComSpec" /c ('"' + $git + '" -C "' + $RepoRoot + '" branch --set-upstream-to origin/' + $branch + ' 2>&1') | Out-Null
1007
+ if ($LASTEXITCODE -eq 0) { Ok "已把 $branch 的 upstream 设为 origin/$branch" }
1008
+ }
1009
+
1010
+ # 拉取成功:把「用本机」的条目写回工作区(成为本地改动,下次 push 带上),然后清掉清单
1011
+ $reportAfter = Read-ConflictFile
1012
+ if ($reportAfter) {
1013
+ $back = Restore-LocalKept $reportAfter
1014
+ if ($back -gt 0) { Ok ("已把 {0} 个「用本机」的文件写回工作区(下次推送会带上)" -f $back) }
1015
+ Remove-Item -LiteralPath (Get-ConflictPath) -Force -ErrorAction SilentlyContinue
1016
+ Ok ("冲突清单已清除:{0}" -f (Get-ConflictPath))
1017
+ }
1018
+
1019
+ Say ""
1020
+ $applyArgs = @{ RepoRoot = $RepoRoot; DshHome = $DshHome; ProfileName = $ProfileName; AppRoot = $AppRoot; WorkspaceHome = $WorkspaceHome; NoResetNotices = $true }
1021
+ if ($WorkspaceOnly) { $applyArgs['WorkspaceOnly'] = $true }
1022
+ if ($SkipWorkspace) { $applyArgs['SkipWorkspace'] = $true }
1023
+ if ($SkipInstall) { $applyArgs['SkipInstall'] = $true }
1024
+ if ($AllowVersionDrift) { $applyArgs['AllowVersionDrift'] = $true }
1025
+ if ($Force) { $applyArgs['Force'] = $true }
1026
+ & (Join-Path $PSScriptRoot 'apply.ps1') @applyArgs
1027
+ # apply 成功才算这次拉取生效:记下同步时间,面板据此把「本机待推送」清零
1028
+ if ($LASTEXITCODE -eq 0) { Write-SyncState 'pull' }
1029
+ exit $LASTEXITCODE