dsh-profile-config-sync 0.5.0 → 0.6.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-profile-config-sync",
3
- "version": "0.5.0",
3
+ "version": "0.6.41",
4
4
  "type": "module",
5
- "description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。支持 Windows(PowerShell)/ macOS / Linux(Node 引擎),并可选 WebDAV 作为传输层。面板与文案跟随客户端语言(中文/English)。",
5
+ "description": "DeepSeek Harness 客户端的多端配置备份、同步与还原插件:把本机配置按 12 组内容抓取成 Git 仓库快照(profile、全局提示、Skills、Agent 预设、插件设置与工作流、插件数据、工作区、会话记录等),可推送到 GitHub / Gitee / GitLab 或上传 WebDAV;换机重装后一条命令拉回并铺开,误改可选档回滚。同步动作在客户端退出后执行(PowerShell on Windows,Node 引擎 on macOS / Linux),面板与文案跟随客户端语言。",
6
6
  "main": "./index.js",
7
7
  "exports": {
8
8
  ".": "./index.js",
@@ -16,14 +16,20 @@
16
16
  "README.md",
17
17
  "README.en.md",
18
18
  "LICENSE",
19
- "runtime"
19
+ "runtime",
20
+ "docs/*.md"
20
21
  ],
21
22
  "keywords": [
22
23
  "dsh",
23
24
  "dsh-plugin",
24
25
  "deepseek-harness",
25
- "dsh-config",
26
- "sync"
26
+ "backup",
27
+ "restore",
28
+ "sync",
29
+ "webdav",
30
+ "multi-device",
31
+ "migration",
32
+ "dsh-config"
27
33
  ],
28
34
  "engines": {
29
35
  "node": ">=22"
package/runtime/apply.ps1 CHANGED
@@ -1,4 +1,4 @@
1
- <#
1
+ <#
2
2
  DSH 配置同步 —— 应用脚本(把本仓库的配置还原到当前电脑)
3
3
 
4
4
  用法
@@ -59,6 +59,12 @@ $ErrorActionPreference = 'Stop'
59
59
  if (-not $RepoRoot) { $RepoRoot = $PSScriptRoot }
60
60
  . (Join-Path $PSScriptRoot 'dsh-sync-common.ps1')
61
61
 
62
+ # 并发保护:同一 DSH 目录同时只允许一个同步动作(面板按钮 + 自动 watcher 很容易撞车)
63
+ if (-not (Lock-SyncRun $DshHome '还原')) {
64
+ Warn "另一个同步动作正在进行(同一个 DSH 目录),本次 还原 没有执行。等它结束后再试一次。"
65
+ exit 3
66
+ }
67
+
62
68
  if (-not $NoResetNotices) { Reset-SyncNotices $DshHome 'pull' } else { Set-SyncNoticeContext $DshHome 'pull' }
63
69
 
64
70
  # 客户端可能被卸载重装到别的盘:传进来的 -AppRoot 先校验,对不上就自动定位(注册表 → 常见位置)。
@@ -81,13 +87,23 @@ function Expand-AppRoot([string]$text, [string]$rootFwd) {
81
87
  # 宿主解析 YAML 直接 fatal;pnpm-lock.yaml 也会和 package.json 的 specifier 对不上)
82
88
  if ($text.Contains($AppRootToken)) { $text = $text.Replace($AppRootToken, $rootFwd) }
83
89
  if ($text.Contains($WorkspaceHomeToken)) {
84
- $wsFwd = $WorkspaceHome.Replace('\\', '/').TrimEnd('/')
90
+ # 注意:PS 单引号里 '\\' 是「两个反斜杠」字面量(不是转义),只替换连续双斜杠,
91
+ # 单个 \ 原样留下 —— 展开进 .json 就成了非法 JSON 转义。统一走 common 的正斜杠转换。
92
+ $wsFwd = (ConvertTo-FwdPath $WorkspaceHome).TrimEnd('/')
85
93
  $text = $text.Replace($WorkspaceHomeToken, $wsFwd)
86
94
  }
87
95
  # 再兜底老仓库里没迁移过的盘符绝对路径
88
96
  return (Convert-AppRootText $text $AppRoot $rootFwd)
89
97
  }
90
98
 
99
+ # 整表展开:先走 AppRoot 老盘符兜底(历史仓库里可能有裸的盘符路径),再把所有占位符换成本机值。
100
+ # 只用 Expand-AppRoot 会漏掉 {{DSH_HOME}} / {{ROOT:*}} —— 实测 apply 后 cordis.patch.yml 里
101
+ # 还留着 {{ROOT:userHome}}/bin/pwsh7.cmd,工具路径变成字面量占位符,起不来。
102
+ function Expand-AllTokens([string]$text, [string]$rootFwd) {
103
+ $t = Expand-AppRoot $text $rootFwd
104
+ return (Expand-TokenText $t (Get-SyncRoots $DshHome $AppRoot $WorkspaceHome))
105
+ }
106
+
91
107
  function Expand-AppRootFile([string]$path, [string]$rootFwd) {
92
108
  $raw = Read-TextPreserveBom $path
93
109
  if ($raw.Contains($AppRootToken) -or $raw -match $AppRootPattern) {
@@ -366,7 +382,7 @@ function Sync-WorkspaceApply {
366
382
  $regText = (($newReg | ConvertTo-Json -Depth 12) -replace "`r`n", "`n") + "`n"
367
383
  $regParent = Split-Path -Parent $registryDst
368
384
  if (-not (Test-Path -LiteralPath $regParent)) { New-Item -ItemType Directory -Path $regParent -Force | Out-Null }
369
- [IO.File]::WriteAllText($registryDst, $regText, (New-Object Text.UTF8Encoding($false, $false)))
385
+ Write-FileAtomic $registryDst $regText (New-Object Text.UTF8Encoding($false, $false))
370
386
  Ok ('工作区登记表已' + $(if ($ReplaceWorkspaceRegistry) { '整份覆盖' } else { '按 ID 合并' }) + " → $registryDst($($plan.Count) 个工作区)")
371
387
 
372
388
  # 登记了工作区、但仓库里没有它的资料目录时(例如「Gitee同步」这种空工作区),
@@ -631,7 +647,7 @@ function Sync-ConversationApply {
631
647
  if ($cwdMap.Count -gt 0 -or $projMap.Count -gt 0) {
632
648
  $specPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-session-cwd-{0}.json' -f $stamp)
633
649
  $specJson = [ordered]@{ home = $DshHome; dirs = $cwdMap; projcache = $projMap } | ConvertTo-Json -Depth 4 -Compress
634
- [IO.File]::WriteAllText($specPath, $specJson, (New-Object Text.UTF8Encoding($false)))
650
+ Write-FileAtomic $specPath $specJson (New-Object Text.UTF8Encoding($false))
635
651
  $helper = $cwdHelper
636
652
  # 结果落文件而不是抓 stdout:执行器可能是客户端自带的 Electron(GUI 子系统,stdout 抓不到)
637
653
  $resultPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-session-cwd-{0}.out.json' -f $stamp)
@@ -729,22 +745,7 @@ if (-not (Test-Path -LiteralPath $ProfileDir)) {
729
745
 
730
746
  # 需要跨机一致的插件设置 / 工作流:仓库路径 → 本机路径
731
747
  # 0.3.30 起扩到各插件自己的配置;文件里存的是占位符,落到本机前统一展开
732
- $settingsMap = @(
733
- @{ Repo = 'settings\our-free-model.json'; Src = (Join-Path $DshHome 'our-free-model\settings.json'); Label = 'our-free-model 插件设置' },
734
- @{ Repo = 'settings\comfyui-workflows.json'; Src = (Join-Path $DshHome 'data\dsh-comfyui\workflows.json'); Label = 'ComfyUI 工作流库' },
735
- @{ Repo = 'settings\dsh-pet-main-config.jsonc'; Src = (Join-Path $DshHome 'dsh-pet\main-config.jsonc'); Label = '桌宠配置' },
736
- @{ Repo = 'settings\dsh-market-state.json'; Src = (Join-Path $ProfileDir '.dsh-market\state.json'); Label = '插件市场状态' },
737
- @{ Repo = 'settings\dsh-pet-memory.json'; Src = (Join-Path $DshHome 'dsh-pet\memory.json'); Label = '桌宠记忆' },
738
- @{ Repo = 'settings\our-free-model-picks.json'; Src = (Join-Path $DshHome 'our-free-model\picks.json'); Label = 'our-free-model 收藏' },
739
- @{ Repo = 'settings\dsh-im-interface-language.json'; Src = (Join-Path $DshHome 'integrations\dsh-im\interface-language.json'); Label = 'dsh-im 界面语言' },
740
- @{ Repo = 'settings\dsh-qq-config.json'; Src = (Join-Path $DshHome 'integrations\dsh-qq\config.json'); Label = 'QQ 集成配置' },
741
- @{ Repo = 'settings\dsh-qq-workspaces.json'; Src = (Join-Path $DshHome 'integrations\dsh-qq\workspaces.json'); Label = 'QQ 集成工作区' },
742
- @{ Repo = 'settings\redteam-preset-declare.json'; Src = (Join-Path $DshHome 'redteam\preset-declare.json'); Label = '红队预设声明' },
743
- @{ Repo = 'settings\task-board-ledger.json'; Src = (Join-Path $DshHome 'task-board\ledger-v2.json'); Label = '任务板台账' },
744
- @{ Repo = 'settings\task-board-scheduler.json'; Src = (Join-Path $DshHome 'task-board\scheduler-v2.json'); Label = '任务板调度' },
745
- @{ Repo = 'settings\dsh-workspaces.json'; Src = (Join-Path $DshHome 'storages\workspace.json'); Label = 'DSH 工作区登记' },
746
- @{ Repo = 'settings\workspace-archives.json'; Src = (Join-Path $DshHome 'dsh-session-manager\workspace-archives.v1.json'); Label = 'DSH 工作区隐藏状态' }
747
- )
748
+ $settingsMap = Get-SyncSettingsMap $DshHome $ProfileName
748
749
 
749
750
  # ---------- 0.5 宿主版本契约(一切动作之前先校验) ----------
750
751
  # 为什么要在最前面校验:
@@ -757,12 +758,28 @@ $settingsMap = @(
757
758
  $contractPath = Join-Path $RepoRoot 'profile\host-contract.json'
758
759
  $hostAppVersion = Get-HostAppVersion $AppRoot
759
760
  $contractVersion = $null
761
+ # 三种「没有可用契约」的原因要分开说,否则面板/日志会把「老格式」误报成「仓库缺文件」——
762
+ # 同一句措辞描述两种情形,用户会以为仓库坏了。
763
+ $contractState = 'missing' # missing | legacy | ok
760
764
  if (Test-Path -LiteralPath $contractPath) {
761
- try { $contractVersion = [string](Get-Content -LiteralPath $contractPath -Raw -Encoding utf8 | ConvertFrom-Json).appVersion } catch { $contractVersion = $null }
765
+ try {
766
+ $contractDoc = Get-Content -LiteralPath $contractPath -Raw -Encoding utf8 | ConvertFrom-Json
767
+ $cNames = @($contractDoc.PSObject.Properties.Name)
768
+ # 老格式契约(上游手写:只有 appVersion/generatedAt/note,appVersion 常被填成 Electron 版本)
769
+ # 不能拿来判「两端是否同版本」,否则一次工具链错位就永久拦住所有拉取。
770
+ if (($cNames -contains 'electronVersion') -or ($cNames -contains 'platforms')) {
771
+ $contractVersion = [string]$contractDoc.appVersion
772
+ $contractState = if ($contractVersion) { 'ok' } else { 'missing' }
773
+ } else {
774
+ $contractState = 'legacy'
775
+ }
776
+ } catch { $contractState = 'legacy' }
762
777
  }
763
778
  $versionDrift = $false
764
779
  if (-not $hostAppVersion) {
765
780
  Warn "读不到客户端 app 版本($AppRoot\resources\app\package.json 与 resources\app.asar 都没读到)——无法做版本校验"
781
+ } elseif ($contractState -eq 'legacy') {
782
+ Warn "仓库契约是老格式(缺 electronVersion / platforms),忽略它做版本校验;下次推送会按新格式重写"
766
783
  } elseif (-not $contractVersion) {
767
784
  Warn "仓库缺少 profile\host-contract.json(或里面没有 appVersion)——跳过版本校验"
768
785
  } elseif ($hostAppVersion -ne $contractVersion) {
@@ -842,17 +859,19 @@ foreach ($f in @('cordis.yml', 'cordis.patch.yml', 'pnpm-workspace.yaml', 'pnpm-
842
859
  if (-not (Test-Path -LiteralPath $src)) { Warn "仓库里没有 profile\$f,跳过"; continue }
843
860
  # 必须读→替换→写。直接 Copy-Item 会把仓库里的 {{APP_ROOT}} 或别的机器的盘符原样带过来,
844
861
  # 进而让 pnpm-lock.yaml 与 package.json 对不上,--frozen-lockfile 必挂。
845
- $raw = Expand-AppRoot (Read-TextPreserveBom $src) $appRootFwd
862
+ $raw = Expand-AllTokens (Read-TextPreserveBom $src) $appRootFwd
846
863
  # 写完就地核对:占位符没展开会让 cordis.patch.yml 变成非法 YAML(宿主启动直接 fatal),
847
864
  # 也会让 pnpm-lock.yaml 的 specifier 与 package.json 对不上。宁可在这里停,也不要把坏文件铺下去。
848
- if ($raw.Contains($AppRootToken) -or $raw.Contains($WorkspaceHomeToken)) {
849
- Die "展开占位符失败:$f 里仍有 {{APP_ROOT}}/{{WORKSPACE_HOME}}(-AppRoot=$AppRoot)"
865
+ # 任何占位符残留都算失败:只检查 APP_ROOT/WORKSPACE_HOME 会放过 {{DSH_HOME}} / {{ROOT:*}},
866
+ # 那两个漏进本机后,工具路径就是字面量占位符(实测 cordis.patch.yml 的 pwsh7.cmd 这条)。
867
+ if ($raw -match '\{\{[A-Za-z_]+(:[A-Za-z0-9_.\-]+)?\}\}') {
868
+ Die "展开占位符失败:$f 里仍有未展开的占位符(-AppRoot=$AppRoot)"
850
869
  }
851
870
  Write-TextPreserveBom (Join-Path $ProfileDir $f) $raw
852
871
  }
853
872
  Ok "已写入 cordis.yml / cordis.patch.yml / pnpm-workspace.yaml / pnpm-lock.yaml(路径指向 $appRootFwd)"
854
873
 
855
- $pkgRaw = Expand-AppRoot (Read-TextPreserveBom (Join-Path $RepoRoot 'profile\package.json')) $appRootFwd
874
+ $pkgRaw = Expand-AllTokens (Read-TextPreserveBom (Join-Path $RepoRoot 'profile\package.json')) $appRootFwd
856
875
 
857
876
 
858
877
  # 实验性 bundle 门控:@deepseek-ai/dsh-experimental-* 由宿主自带、按 app 版本强绑定,不满足就不写进本机
@@ -927,6 +946,9 @@ foreach ($dirName in $localPluginMap.Keys) {
927
946
  $pattern = 'link:[^"]*' + [regex]::Escape($dirName)
928
947
  $pkgRaw = [regex]::Replace($pkgRaw, $pattern, ('link:' + $appRootFwd + '/' + $dirName), 'IgnoreCase')
929
948
  }
949
+ # 仓库里的 link 可能带占位符(capture 会把 userHome 下的本地插件写成 {{ROOT:userHome}}/…):
950
+ # 写回前必须展开,否则本机 pnpm install 会去装一个字面量 {{ROOT:userHome}} 的路径。
951
+ $pkgRaw = Expand-TokenText $pkgRaw (Get-SyncRoots $DshHome $AppRoot $WorkspaceHome)
930
952
  Write-TextPreserveBom (Join-Path $ProfileDir 'package.json') $pkgRaw
931
953
  Ok "已写入 package.json(link 路径指向 $appRootFwd)"
932
954
  } else { Warn '跳过(未勾选同步):profile 配置(package.json / lock / cordis 保持本机现状)' }
@@ -936,7 +958,19 @@ if (Test-SyncGroupEnabled $Scope 'prompt') {
936
958
  foreach ($f in @('AGENTS.md', 'prompt-inject.md')) {
937
959
  if (-not (Test-SyncItemEnabled $Scope 'prompt' $f)) { continue }
938
960
  $src = Join-Path $RepoRoot "prompt\$f"
939
- if (Test-Path -LiteralPath $src) { Copy-Item -LiteralPath $src -Destination (Join-Path $DshHome $f) -Force; Ok "已写入 $f" }
961
+ if (Test-Path -LiteralPath $src) {
962
+ $rawPrompt = [IO.File]::ReadAllText($src)
963
+ $promptRoots = Get-SyncRoots $DshHome $AppRoot $WorkspaceHome
964
+ $expandedPrompt = Expand-TokenText $rawPrompt $promptRoots
965
+ $missingPrompt = @(Get-MissingTokens $expandedPrompt)
966
+ if ($missingPrompt.Count -gt 0) {
967
+ # 本机还没确认那个根:写进去就是 {{WORKSPACE_HOME}} 字面量,宁可保留本机现状
968
+ Warn ("跳过 $f:需要先确认路径 " + ($missingPrompt -join '、') + "(在面板「本机路径」卡里填好再拉取)")
969
+ } else {
970
+ Write-TextPreserveBom (Join-Path $DshHome $f) $expandedPrompt
971
+ Ok "已写入 $f"
972
+ }
973
+ }
940
974
  }
941
975
  } else { Warn '跳过(未勾选同步):全局提示(AGENTS.md / prompt-inject.md)' }
942
976
 
@@ -1055,7 +1089,7 @@ foreach ($m in $settingsMap) {
1055
1089
  }
1056
1090
  $dir = Split-Path -Parent $m.Src
1057
1091
  if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
1058
- [IO.File]::WriteAllText($m.Src, $expanded, (New-Object Text.UTF8Encoding($false)))
1092
+ Write-FileAtomic $m.Src $expanded (New-Object Text.UTF8Encoding($false))
1059
1093
  }
1060
1094
  Ok "已还原插件设置 / 工作流 / 各插件配置"
1061
1095
  } else { Warn '跳过(未勾选同步):插件设置 / 工作流 / 各插件配置' }
@@ -1219,7 +1253,7 @@ if (-not (Test-SyncGroupEnabled $Scope 'extra')) {
1219
1253
  Ok ('已还原额外路径 ' + $it.id + ':' + $n + ' 个文件 → ' + $dst)
1220
1254
  } else {
1221
1255
  $leaf = Split-Path -Leaf ([string]$it.src)
1222
- $itemSrc = Join-Path $exSrc ($it.id + (Split-Path -Extension $dst))
1256
+ $itemSrc = Join-Path $exSrc ($it.id + [IO.Path]::GetExtension($dst))
1223
1257
  if (-not (Test-Path -LiteralPath $itemSrc)) {
1224
1258
  $itemSrc = Join-Path $exSrc $it.id
1225
1259
  if (-not (Test-Path -LiteralPath $itemSrc)) { continue }
@@ -1234,7 +1268,7 @@ if (-not (Test-SyncGroupEnabled $Scope 'extra')) {
1234
1268
  }
1235
1269
  Copy-Item -LiteralPath $itemSrc -Destination $dst -Force
1236
1270
  # 只展开这一个文件(整目录展开会改到用户同目录下的其他文件)
1237
- if ((Split-Path -Extension $dst).ToLower() -notin @('.tgz', '.zip', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.exe', '.dll', '.wasm', '.pdf')) {
1271
+ if ([IO.Path]::GetExtension($dst).ToLower() -notin @('.tgz', '.zip', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.exe', '.dll', '.wasm', '.pdf')) {
1238
1272
  $raw = Read-TextPreserveBom $dst
1239
1273
  if ($raw -match '\{\{(APP_ROOT|DSH_HOME|WORKSPACE_HOME|ROOT:[A-Za-z0-9_.\-]+)\}\}') { Write-TextPreserveBom $dst (Expand-TokenText $raw $pdRoots) }
1240
1274
  }
@@ -1326,8 +1360,10 @@ foreach ($dirName in $localPluginMap.Keys) {
1326
1360
  } elseif (Test-Path -LiteralPath $arch) {
1327
1361
  # 读不到版本(老归档、结构异常)时退回 mtime,但要求比已部署目录新 10 秒以上,避免每轮误判
1328
1362
  $archTime = (Get-Item -LiteralPath $arch).LastWriteTime
1329
- $depTime = (Get-ChildItem -LiteralPath $target -Recurse -File -Force | Sort-Object LastWriteTime -Descending | Select-Object -First 1).LastWriteTime
1330
- $hasNewVersion = $archTime -gt $depTime.AddSeconds(10)
1363
+ $depTime = (Get-ChildItem -LiteralPath $target -Recurse -File -Force -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1).LastWriteTime
1364
+ # 已部署目录是空壳(上一轮解压失败 / 被手工清空)时 $depTime 为 $null,
1365
+ # $null.AddSeconds() 会抛「不能对 null 值表达式调用方法」并终止整次 apply。
1366
+ if (-not $depTime) { $hasNewVersion = $true } else { $hasNewVersion = $archTime -gt $depTime.AddSeconds(10) }
1331
1367
  }
1332
1368
  if ($hasNewVersion) {
1333
1369
  Warn "本地插件有新版本,将重新部署:$target($depVer → $archVer,旧目录先改名备份)"
@@ -1551,7 +1587,17 @@ if ($missing.Count -eq 0) {
1551
1587
 
1552
1588
  # bundle 可解析性检查:清单里写了、本机却没有 → 启动期 entry loading 必挂(整个应用起不来,不是功能不可用)
1553
1589
  # 解析顺序与 DSH 一致:先 profile\node_modules(pnpm 装的),再 <AppRoot>\resources\app\dsh\node_modules(宿主自带)
1554
- $bundles = @((Get-Content -LiteralPath (Join-Path $ProfileDir 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json).dsh.profile.bundles)
1590
+ # @($null).Count 在 PowerShell 里是 1(不是 0):缺 dsh.profile.bundles 时旧写法会迭代一次 $null,
1591
+ # 报「以下 1 个 bundle 找不到」后面却是空的,然后 Die 挡住整个流程。先过滤掉空值再判。
1592
+ $pkgObj = $null
1593
+ try { $pkgObj = Get-Content -LiteralPath (Join-Path $ProfileDir 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json } catch { $pkgObj = $null }
1594
+ $bundles = @()
1595
+ if ($pkgObj -and $pkgObj.dsh -and $pkgObj.dsh.profile -and $pkgObj.dsh.profile.bundles) {
1596
+ $bundles = @($pkgObj.dsh.profile.bundles | Where-Object { $_ -and ([string]$_).Trim() })
1597
+ }
1598
+ if ($bundles.Count -eq 0) {
1599
+ Warn 'profile\package.json 里没有 dsh.profile.bundles(新 profile 或已被裁剪),跳过 bundle 可解析性检查'
1600
+ }
1555
1601
  $unresolved = @()
1556
1602
  foreach ($b in $bundles) {
1557
1603
  $rel = ($b -replace '/', '\')
@@ -1577,7 +1623,7 @@ if ($unresolved.Count -eq 0) {
1577
1623
  Ok "Skill 目录:$((Get-ChildItem -LiteralPath $skillsDst -Directory -Force -ErrorAction SilentlyContinue | Measure-Object).Count) 个"
1578
1624
  Say ""
1579
1625
  Say "下一步:完全启动 DSH(不是重启窗口,要确认进程全部退出后再开)。"
1580
- if ($hostAppVersion) { Say "版本:本机 app = $hostAppVersion(仓库契约 $contractVersion)" }
1626
+ if ($hostAppVersion) { Say ("版本:本机 app = {0}(仓库契约 {1})" -f $hostAppVersion, $(if ($contractVersion) { $contractVersion } else { if ($contractState -eq 'legacy') { '老格式,已忽略' } else { '无' } })) }
1581
1627
  Say "验证:插件页看 20 项是否齐全、按要求检查 cordis.patch.yml 里的开关是否生效、Skill 列表能列出。"
1582
1628
  Say "如需回滚:把 $BackupDir 里的文件拷回原位置(工作区资料在 workspace\ 子目录、登记表备份为 workspace-registry-before.json)。"
1583
1629
 
@@ -0,0 +1,57 @@
1
+ /**
2
+ * 原子写:先写同目录临时文件,再 rename 覆盖。
3
+ *
4
+ * 为什么需要:面板保存设置(config-sync-extra.json / dsh-config-sync.json)时,
5
+ * capture / sync 可能正在读同一份文件。直接 writeFileSync 会让读者看到「写了一半」的内容 ——
6
+ * 实测 reader 会读到空串或截断 JSON,capture 于是走「解析失败,按默认规则处理」,
7
+ * 用户这次的勾选/排除规则被静默忽略。
8
+ *
9
+ * Windows 注意:目标文件可能正被别的进程以只读方式打开,rename 偶发 EPERM/EBUSY,
10
+ * 所以带短重试;实在换不掉才退回直写(并清理临时文件),保证不会留下垃圾。
11
+ */
12
+ import { chmodSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
13
+
14
+ const sleepSync = (ms) => {
15
+ try {
16
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
17
+ } catch {
18
+ const until = Date.now() + ms
19
+ while (Date.now() < until) { /* 兜底忙等 */ }
20
+ }
21
+ }
22
+
23
+ export function writeFileAtomicSync(file, text, opts = {}) {
24
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`
25
+ // 权限:显式 mode 优先;否则沿用原文件(rename 会带走权限位,不沿用就等于放宽权限)
26
+ let wantMode = opts.mode
27
+ if (!wantMode) {
28
+ try { wantMode = statSync(file).mode & 0o777 } catch { wantMode = 0 }
29
+ }
30
+ writeFileSync(tmp, text, wantMode ? { encoding: 'utf8', mode: wantMode } : 'utf8')
31
+ if (wantMode) {
32
+ // writeFileSync 的 mode 会被 umask 削一刀;这里显式补回,保证 0600 真的是 0600
33
+ try { chmodSync(tmp, wantMode) } catch { }
34
+ }
35
+ for (let i = 0; i < 25; i++) {
36
+ try {
37
+ renameSync(tmp, file)
38
+ return true
39
+ } catch (e) {
40
+ const code = e && e.code
41
+ if (i === 24 || (code && !['EPERM', 'EBUSY', 'EACCES', 'EEXIST'].includes(code))) break
42
+ sleepSync(8 * (i + 1))
43
+ }
44
+ }
45
+ try {
46
+ // 退回直写:读者可能仍会看到半截,但至少内容正确、且不留临时文件
47
+ writeFileSync(file, text, 'utf8')
48
+ return false
49
+ } finally {
50
+ try { unlinkSync(tmp) } catch { }
51
+ }
52
+ }
53
+
54
+ export function writeJsonAtomicSync(file, obj, { pretty = true, trailingNewline = true, mode } = {}) {
55
+ const body = pretty ? JSON.stringify(obj, null, 2) : JSON.stringify(obj)
56
+ return writeFileAtomicSync(file, trailingNewline ? `${body}\n` : body, mode ? { mode } : {})
57
+ }