dsh-config-manager 0.4.3 → 0.6.0

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.
Files changed (286) hide show
  1. package/README.md +10 -0
  2. package/README.zh-CN.md +10 -0
  3. package/lib/adapters/mcp.d.ts +9 -0
  4. package/lib/adapters/mcp.js +37 -0
  5. package/lib/adapters/plugins.js +10 -2
  6. package/lib/adapters/pnpm-workspace.js +1 -1
  7. package/lib/adapters/self.d.ts +2 -0
  8. package/lib/adapters/self.js +18 -2
  9. package/lib/adapters/workspaces.js +1 -1
  10. package/lib/cli/restore-resume.js +1 -1
  11. package/lib/cli/web/page.js +2 -2
  12. package/lib/client.d.ts +17 -41
  13. package/lib/client.js +946 -761
  14. package/lib/core/backup.d.ts +11 -0
  15. package/lib/core/backup.js +27 -0
  16. package/lib/core/env-lock-lifecycle.d.ts +17 -3
  17. package/lib/core/env-lock-lifecycle.js +38 -0
  18. package/lib/core/external-failure.d.ts +9 -0
  19. package/lib/core/external-failure.js +50 -0
  20. package/lib/core/local-plugin-host.d.ts +9 -7
  21. package/lib/core/local-plugin-host.js +109 -15
  22. package/lib/core/local-plugin-pack.d.ts +20 -0
  23. package/lib/core/local-plugin-pack.js +18 -3
  24. package/lib/core/mcp-connector-store.d.ts +13 -0
  25. package/lib/core/mcp-connector-store.js +16 -1
  26. package/lib/core/messages-core.d.ts +45 -0
  27. package/lib/core/messages-core.js +92 -0
  28. package/lib/core/messages.d.ts +5 -0
  29. package/lib/core/messages.js +14 -0
  30. package/lib/core/migration-history.d.ts +40 -0
  31. package/lib/core/migration-history.js +55 -0
  32. package/lib/core/model-tool-plans.d.ts +66 -0
  33. package/lib/core/model-tool-plans.js +128 -0
  34. package/lib/core/model-tools.d.ts +96 -8
  35. package/lib/core/model-tools.js +568 -31
  36. package/lib/core/phase3-host.js +10 -2
  37. package/lib/core/plugin-cli.d.ts +5 -0
  38. package/lib/core/plugin-cli.js +11 -3
  39. package/lib/core/plugin-data-registry.d.ts +1 -1
  40. package/lib/core/plugin-data-registry.js +1 -1
  41. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  42. package/lib/core/restore-plan-fingerprint.js +18 -0
  43. package/lib/core/restore-resume.d.ts +1 -1
  44. package/lib/core/restore-resume.js +1 -1
  45. package/lib/core/restore.d.ts +5 -0
  46. package/lib/core/restore.js +4 -1
  47. package/lib/core/types.d.ts +12 -0
  48. package/lib/foreign/claude-sessions.d.ts +1 -1
  49. package/lib/foreign/claude-sessions.js +1 -1
  50. package/lib/foreign/registry.js +1 -1
  51. package/lib/foreign/types.d.ts +1 -1
  52. package/lib/index.d.ts +19 -15
  53. package/lib/index.js +72 -80
  54. package/lib/market/git-file-writer.js +1 -1
  55. package/lib/market/github-repos.js +1 -1
  56. package/lib/market/market-config.js +1 -1
  57. package/lib/market/messages-market.js +1 -1
  58. package/lib/market/my-repo.js +1 -1
  59. package/lib/market/prepare.js +1 -1
  60. package/lib/market/reader.js +2 -2
  61. package/lib/market/repo-url.d.ts +1 -1
  62. package/lib/market/security.js +2 -2
  63. package/lib/market/star-cache.d.ts +1 -1
  64. package/lib/market/types.d.ts +1 -1
  65. package/lib/market/types.js +1 -1
  66. package/lib/market/url.js +1 -1
  67. package/lib/profiles/dsh-profile-manager.d.ts +1 -1
  68. package/lib/profiles/dsh-profile-manager.js +26 -7
  69. package/lib/profiles/dsh-profile-shared.d.ts +3 -1
  70. package/lib/routes/backup.js +17 -9
  71. package/lib/routes/index.d.ts +1 -1
  72. package/lib/routes/kit.d.ts +2 -2
  73. package/lib/routes/market.d.ts +1 -1
  74. package/lib/routes/market.js +3 -60
  75. package/lib/routes/model-tools-deps.d.ts +41 -0
  76. package/lib/routes/model-tools-deps.js +18 -0
  77. package/lib/routes/recovery.js +5 -3
  78. package/lib/routes/route-support.d.ts +18 -26
  79. package/lib/routes/route-support.js +19 -32
  80. package/lib/routes/snapshots.d.ts +1 -1
  81. package/lib/routes/snapshots.js +4 -40
  82. package/lib/routes/sync.js +40 -28
  83. package/lib/schema/index.d.ts +2 -2
  84. package/lib/schema/index.js +2 -2
  85. package/lib/schema/section-registry.d.ts +5 -3
  86. package/lib/schema/section-registry.js +7 -3
  87. package/lib/security/secret-scanner.js +1 -1
  88. package/lib/sync/apply-bundle.d.ts +50 -0
  89. package/lib/sync/apply-bundle.js +60 -0
  90. package/lib/sync/autosync-scheduler.d.ts +9 -0
  91. package/lib/sync/autosync-scheduler.js +118 -89
  92. package/lib/sync/backup-scheduler.js +5 -4
  93. package/lib/sync/blob-store.d.ts +2 -2
  94. package/lib/sync/git/git-transport.d.ts +12 -0
  95. package/lib/sync/git/git-transport.js +50 -2
  96. package/lib/sync/merge.d.ts +2 -0
  97. package/lib/sync/merge.js +28 -0
  98. package/lib/sync/messages.d.ts +4 -0
  99. package/lib/sync/messages.js +9 -2
  100. package/lib/sync/s3/s3-transport.d.ts +1 -1
  101. package/lib/sync/s3/s3-transport.js +1 -1
  102. package/lib/sync/sync-engine.d.ts +4 -4
  103. package/lib/sync/sync-engine.js +25 -26
  104. package/lib/sync/sync-scope-boot.d.ts +34 -0
  105. package/lib/sync/sync-scope-boot.js +71 -0
  106. package/lib/sync/sync-scope.d.ts +103 -0
  107. package/lib/sync/sync-scope.js +229 -0
  108. package/lib/sync/sync-selection.d.ts +17 -4
  109. package/lib/sync/sync-selection.js +40 -14
  110. package/lib/sync/transport.d.ts +4 -1
  111. package/lib/sync/transport.js +6 -0
  112. package/lib/sync/webdav/webdav-transport.js +1 -1
  113. package/lib/sync/workspace-merge.d.ts +36 -0
  114. package/lib/sync/workspace-merge.js +152 -0
  115. package/lib/ui/backup-schedule.d.ts +13 -2
  116. package/lib/ui/backup-schedule.js +3 -0
  117. package/lib/ui/snapshots-view.d.ts +16 -0
  118. package/lib/ui/snapshots-view.js +21 -0
  119. package/lib/ui/sync-repository-picker.d.ts +21 -0
  120. package/lib/ui/sync-repository-picker.js +18 -0
  121. package/lib/utils/env-lock.d.ts +96 -0
  122. package/lib/utils/env-lock.js +332 -111
  123. package/lib/utils/messages-utils.d.ts +6 -0
  124. package/lib/utils/messages-utils.js +17 -1
  125. package/lib/utils/patch-yaml.js +1 -1
  126. package/lib/utils/remove-tree.d.ts +7 -0
  127. package/lib/utils/remove-tree.js +265 -0
  128. package/lib/utils/zip.js +1 -1
  129. package/package.json +3 -2
  130. package/src/adapters/mcp.test.ts +28 -0
  131. package/src/adapters/mcp.ts +33 -0
  132. package/src/adapters/plugins.test.ts +49 -0
  133. package/src/adapters/plugins.ts +9 -1
  134. package/src/adapters/pnpm-workspace.ts +1 -1
  135. package/src/adapters/self.test.ts +39 -1
  136. package/src/adapters/self.ts +20 -2
  137. package/src/adapters/workspaces.ts +1 -1
  138. package/src/cli/restore-resume.ts +1 -1
  139. package/src/cli/web/page.ts +2 -2
  140. package/src/client/about/AboutPanel.tsx +1 -1
  141. package/src/client/about/about-view.test.ts +1 -1
  142. package/src/client/about/about-view.ts +1 -1
  143. package/src/client/api.ts +1 -6
  144. package/src/client/chat/chat-entry-view.test.ts +1 -1
  145. package/src/client/chat/chat-slots.ts +1 -1
  146. package/src/client/chat/rollback-diff-tab.ts +1 -1
  147. package/src/client/client-types.ts +1 -1
  148. package/src/client/common/routes.ts +1 -5
  149. package/src/client/config-manager.module.css +21 -1
  150. package/src/client/css-scale-guard.test.ts +1 -1
  151. package/src/client/environment/EnvironmentPanel.tsx +2 -2
  152. package/src/client/home/HomePanel.tsx +3 -0
  153. package/src/client/library/ArtifactRow.tsx +14 -2
  154. package/src/client/library/LibraryPanel.tsx +44 -0
  155. package/src/client/locales/overview.ts +10 -2
  156. package/src/client/locales/profiles.ts +2 -0
  157. package/src/client/locales/sessions.ts +3 -0
  158. package/src/client/market/MyConfigsView.tsx +1 -1
  159. package/src/client/market/market-api.ts +2 -14
  160. package/src/client/market/market-locales.ts +1 -1
  161. package/src/client/market/market-view.ts +3 -3
  162. package/src/client/market/my-configs-api.ts +1 -1
  163. package/src/client/market/my-configs-view.ts +1 -1
  164. package/src/client/recovery/recovery-locales.test.ts +1 -1
  165. package/src/client/run-store.ts +1 -1
  166. package/src/client/sync/ChannelConfigDialog.tsx +32 -1
  167. package/src/client/sync/SyncPanel.tsx +11 -30
  168. package/src/client/sync/SyncRepositoryPicker.tsx +34 -13
  169. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  170. package/src/client/sync/SyncSettingsView.test.ts +32 -0
  171. package/src/client/sync/config-save-state.test.ts +99 -0
  172. package/src/client/sync/config-save-state.ts +69 -0
  173. package/src/client/sync/history-model.test.ts +28 -7
  174. package/src/client/sync/history-model.ts +6 -3
  175. package/src/client/sync/sync-locales.ts +14 -4
  176. package/src/client/sync/sync-view.ts +1 -1
  177. package/src/core/analyzer-cache.test.ts +1 -1
  178. package/src/core/backup.test.ts +45 -1
  179. package/src/core/backup.ts +25 -0
  180. package/src/core/disk-usage.test.ts +2 -0
  181. package/src/core/engine-locale.test.ts +4 -0
  182. package/src/core/env-lock-lifecycle.ts +33 -3
  183. package/src/core/external-failure.test.ts +60 -0
  184. package/src/core/external-failure.ts +54 -0
  185. package/src/core/integrity-extra-entries.test.ts +1 -1
  186. package/src/core/local-plugin-host.test.ts +134 -0
  187. package/src/core/local-plugin-host.ts +122 -17
  188. package/src/core/local-plugin-pack.ts +39 -3
  189. package/src/core/mcp-connector-store.ts +26 -1
  190. package/src/core/messages-core.ts +94 -0
  191. package/src/core/messages.ts +14 -0
  192. package/src/core/migration-history.test.ts +65 -0
  193. package/src/core/migration-history.ts +70 -0
  194. package/src/core/model-tool-plans.test.ts +111 -0
  195. package/src/core/model-tool-plans.ts +170 -0
  196. package/src/core/model-tools.test.ts +212 -12
  197. package/src/core/model-tools.ts +710 -38
  198. package/src/core/phase3-host.ts +10 -2
  199. package/src/core/phase3-production-integration.test.ts +43 -0
  200. package/src/core/plugin-cli.fs.test.ts +30 -3
  201. package/src/core/plugin-cli.ts +11 -3
  202. package/src/core/plugin-data-registry.ts +1 -1
  203. package/src/core/restore-plan-fingerprint.ts +19 -0
  204. package/src/core/restore-resume.ts +1 -1
  205. package/src/core/restore.ts +9 -1
  206. package/src/core/types.ts +12 -0
  207. package/src/foreign/claude-sessions.ts +3 -3
  208. package/src/foreign/registry.ts +1 -1
  209. package/src/foreign/types.ts +1 -1
  210. package/src/index.ts +102 -111
  211. package/src/market/git-file-writer.ts +1 -1
  212. package/src/market/github-repos.test.ts +1 -1
  213. package/src/market/github-repos.ts +1 -1
  214. package/src/market/market-config.ts +1 -1
  215. package/src/market/messages-market.ts +1 -1
  216. package/src/market/my-repo.test.ts +1 -1
  217. package/src/market/my-repo.ts +1 -1
  218. package/src/market/prepare.test.ts +1 -1
  219. package/src/market/prepare.ts +1 -1
  220. package/src/market/reader.ts +2 -2
  221. package/src/market/repo-url.ts +1 -1
  222. package/src/market/security.ts +2 -2
  223. package/src/market/star-cache.ts +1 -1
  224. package/src/market/types.ts +1 -1
  225. package/src/market/url.test.ts +1 -1
  226. package/src/market/url.ts +1 -1
  227. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  228. package/src/profiles/dsh-profile-manager.test.ts +20 -0
  229. package/src/profiles/dsh-profile-manager.ts +25 -7
  230. package/src/profiles/dsh-profile-shared.ts +2 -0
  231. package/src/routes/backup.ts +16 -9
  232. package/src/routes/index.ts +1 -1
  233. package/src/routes/kit.ts +2 -2
  234. package/src/routes/market.ts +2 -59
  235. package/src/routes/model-tools-deps.ts +56 -0
  236. package/src/routes/recovery.ts +5 -3
  237. package/src/routes/route-support.ts +49 -36
  238. package/src/routes/snapshots.ts +4 -40
  239. package/src/routes/sync.ts +39 -27
  240. package/src/schema/index.ts +2 -2
  241. package/src/schema/manifest-schema.test.ts +2 -2
  242. package/src/schema/registry.test.ts +1 -1
  243. package/src/schema/section-registry.ts +9 -4
  244. package/src/security/redaction.test.ts +1 -1
  245. package/src/security/secret-scanner.test.ts +2 -2
  246. package/src/security/secret-scanner.ts +1 -1
  247. package/src/sync/apply-bundle.ts +104 -0
  248. package/src/sync/autosync-scheduler.test.ts +180 -6
  249. package/src/sync/autosync-scheduler.ts +132 -92
  250. package/src/sync/backup-scheduler.test.ts +11 -4
  251. package/src/sync/backup-scheduler.ts +5 -4
  252. package/src/sync/blob-store.ts +2 -2
  253. package/src/sync/git/git-transport.test.ts +62 -0
  254. package/src/sync/git/git-transport.ts +54 -3
  255. package/src/sync/merge.ts +29 -0
  256. package/src/sync/messages.ts +9 -2
  257. package/src/sync/s3/s3-transport.ts +1 -1
  258. package/src/sync/sync-engine.test.ts +238 -2
  259. package/src/sync/sync-engine.ts +25 -26
  260. package/src/sync/sync-preview-push.test.ts +2 -1
  261. package/src/sync/sync-scope-boot.ts +87 -0
  262. package/src/sync/sync-scope.test.ts +154 -0
  263. package/src/sync/sync-scope.ts +256 -0
  264. package/src/sync/sync-selection.test.ts +76 -2
  265. package/src/sync/sync-selection.ts +40 -13
  266. package/src/sync/transport.test.ts +21 -1
  267. package/src/sync/transport.ts +12 -0
  268. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  269. package/src/sync/webdav/webdav-transport.ts +1 -1
  270. package/src/sync/workspace-merge.test.ts +110 -0
  271. package/src/sync/workspace-merge.ts +180 -0
  272. package/src/ui/backup-schedule.test.ts +5 -0
  273. package/src/ui/backup-schedule.ts +21 -2
  274. package/src/ui/session-issue-labels.ts +1 -1
  275. package/src/ui/snapshots-view.test.ts +32 -0
  276. package/src/ui/snapshots-view.ts +34 -0
  277. package/src/ui/sync-repository-picker.test.ts +34 -1
  278. package/src/ui/sync-repository-picker.ts +24 -0
  279. package/src/utils/env-lock.test.ts +242 -9
  280. package/src/utils/env-lock.ts +247 -13
  281. package/src/utils/messages-utils.ts +17 -1
  282. package/src/utils/patch-yaml.ts +1 -1
  283. package/src/utils/remove-tree.test.ts +120 -0
  284. package/src/utils/remove-tree.ts +239 -0
  285. package/src/utils/zip.ts +1 -1
  286. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -45,7 +45,7 @@
45
45
  * 连续失败 ≥ 3 → host.log.warn 通知 + 记 notifiedAt。
46
46
  */
47
47
  import crypto from 'node:crypto';
48
- import { withMutationLock, LOCK_BLOCK_MESSAGE } from '../utils/env-lock.js';
48
+ import { withMutationLock, LOCK_BLOCK_MESSAGE, lockSkipToken } from '../utils/env-lock.js';
49
49
  import { engineMsg } from './messages.js';
50
50
  import { readAutosyncConfig, writeAutosyncConfig, clampRemoteCheckMs, DEFAULT_AUTOSYNC_REALTIME, DEFAULT_AUTOSYNC_REMOTE_CHECK_MS, DEFAULT_AUTOSYNC_AUTO_APPLY_TIER, DEFAULT_AUTOSYNC_CONFLICT_POLICY, } from './autosync-config.js';
51
51
  import { readSyncConfigFor, isGitConfig, isWebDavConfig, isS3Config, isGistConfig, SYNC_CHANNELS } from './sync-config.js';
@@ -434,9 +434,19 @@ export class AutoSyncScheduler {
434
434
  /* 尽力而为:收尾失败不影响同步结果 */
435
435
  }
436
436
  };
437
- // Phase 2 锁:autosync 的 apply(写本地配置)与 push(写远端+本地散文件)属 GLOBAL mutation。
438
- // 获取失败(另一项 DSH 任务进行中)→ skipped(mutation-locked);成功则在整个 runOnce 持锁并在 finally 释放。
439
- // 无锁环境(测试未注入 mutationLock)→ 不锁定,直接执行(与旧行为一致)。
437
+ // Phase 1:无锁预检(只读:读配置 + 列远端 + 检测两端变化)。
438
+ //
439
+ // 为什么先检测再取锁(2026-11-07 真机事故):检测里的 plugins 分区导出会为本机源插件跑 npm pack
440
+ // (实测单个 210MB 插件 44.7s/次、每轮重算)。旧实现把这段整个放进 GLOBAL mutation 锁内,60s 一轮的
441
+ // 轮询于是让锁几乎全程被占(45s/60s),用户任何 destructive 操作(删除档案…)都撞 423「另一个任务正在运行」。
442
+ // 现在稳态(upToDate)根本不取锁;命中「有活干」才取,并在锁内重跑检测再写。
443
+ const preflight = await this.detectPhase(channel, cfg, nowIso, historyId);
444
+ if (preflight.kind === 'skip') {
445
+ this.running = false;
446
+ this.watcher?.resume();
447
+ finishRun();
448
+ return preflight.result;
449
+ }
440
450
  let releaseLock = null;
441
451
  if (this.mutationLock !== undefined) {
442
452
  try {
@@ -454,8 +464,9 @@ export class AutoSyncScheduler {
454
464
  // issue #31:与 backup-scheduler 对齐——非 stale 分类也留一行(不再只对 stale 说话);
455
465
  // 更重要的是**补写历史**:此前该分支 return 前不写 sync-history,用户看历史面板
456
466
  // 只能发现「自动同步不再更新」,却看不到任何一条「为什么跳过」(实测 9 天 0 条记录)。
457
- if (lk.reason === 'stale') {
458
- this.host.log.warn(`自动同步已跳过(${channel}):${LOCK_BLOCK_MESSAGE.stale}`);
467
+ // stale 与 stale-degraded 同属「重试不会自愈」,都走 warn(都带显式回收指引)。
468
+ if (lk.reason === 'stale' || lk.reason === 'stale-degraded') {
469
+ this.host.log.warn(`自动同步已跳过(${channel}):${LOCK_BLOCK_MESSAGE[lk.reason]}`);
459
470
  }
460
471
  else if (lk.reason !== undefined) {
461
472
  this.host.log.info(`自动同步已跳过(${channel}):${LOCK_BLOCK_MESSAGE[lk.reason]}`);
@@ -465,13 +476,13 @@ export class AutoSyncScheduler {
465
476
  await this.appendHistory(channel, {
466
477
  direction: 'both',
467
478
  status: 'skipped',
468
- skipReason: 'mutation-locked',
479
+ skipReason: lockSkipToken(lk.reason),
469
480
  createdAt: nowIso,
470
481
  failureCountAtRun: 0,
471
482
  });
472
483
  finishRun();
473
484
  return {
474
- status: 'skipped', direction: 'none', skipReason: 'mutation-locked', historyId,
485
+ status: 'skipped', direction: 'none', skipReason: lockSkipToken(lk.reason), historyId,
475
486
  consecutiveFailures: 0,
476
487
  };
477
488
  }
@@ -485,94 +496,22 @@ export class AutoSyncScheduler {
485
496
  await this.appendHistory(channel, {
486
497
  direction: 'both',
487
498
  status: 'skipped',
488
- skipReason: 'mutation-locked',
499
+ // acquire 本身抛错(锁目录 IO/权限):既不是「被占」也不是「残留」,如实报不可用。
500
+ skipReason: lockSkipToken('unavailable'),
489
501
  createdAt: nowIso,
490
502
  failureCountAtRun: 0,
491
503
  });
492
504
  finishRun();
493
- return { status: 'skipped', direction: 'none', skipReason: 'mutation-locked', historyId, consecutiveFailures: 0 };
505
+ return { status: 'skipped', direction: 'none', skipReason: lockSkipToken('unavailable'), historyId, consecutiveFailures: 0 };
494
506
  }
495
507
  }
496
508
  try {
497
- // 读该通道 sync-config:按通道判定「已配置」——git 看 git.repoUrl、webdav 看 webdav.url。
498
- // SEC-03:「未配置」有两种成因 —— 真的没配,或存过的地址被白名单拒掉(读侧丢弃)。
499
- // 必须区分:后者如果说成前者的「尚未配置」,用户会一遍遍重填同一个被拒地址。
500
- const configIssues = [];
501
- const syncCfg = await this.readSyncConfigFn(channel, configIssues);
502
- if (!syncIsConfigured(syncCfg)) {
503
- const configIssue = describeConfigIssue(configIssues, channel);
504
- if (configIssue !== undefined)
505
- this.reportConfigIssue(channel, configIssue);
506
- const result = {
507
- status: 'skipped', direction: 'none', skipReason: 'unconfigured', historyId,
508
- consecutiveFailures: 0,
509
- ...(configIssue === undefined ? {} : { configIssue }),
510
- };
511
- await this.appendHistory(channel, {
512
- direction: 'both',
513
- status: 'skipped',
514
- skipReason: 'unconfigured',
515
- createdAt: nowIso,
516
- failureCountAtRun: 0,
517
- ...(configIssue === undefined ? {} : { configIssue }),
518
- });
519
- await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
520
- return result;
521
- }
522
- const engine = this.makeSyncEngine(syncCfg);
523
- // 加密快照检测:远端最新快照为加密 → 自动同步无密码无法解密 → 整体跳过,
524
- // 同步历史记录 skipReason='encrypted'(提示需手动输入密码同步)。
525
- // 加密快照只通过手动推送/拉取产生与消费;自动同步仅处理普通快照。
526
- // list 失败宽容处理:视为无加密快照,继续正常流程(网络问题由后续链路暴露为 failed)。
527
- let encryptedRemote = false;
528
- // 本轮远端列表:加密快照检查与「远端是否有新快照」共用同一次 list。
529
- // 每次 list 都是一次真实网络往返(git = `pull --ff-only`,webdav = PROPFIND/GET),
530
- // 缺省 60s 轮询下多 list 一次 = 一天白跑 1440 次往返。
531
- let remoteMetas = null;
532
- try {
533
- const metas = await engine.listSnapshots();
534
- remoteMetas = metas;
535
- const latestMeta = metas.length > 0 ? metas[metas.length - 1] : null;
536
- encryptedRemote = latestMeta !== null && latestMeta.manifest.encrypted === true;
537
- }
538
- catch {
539
- encryptedRemote = false;
540
- }
541
- if (encryptedRemote) {
542
- const result = {
543
- status: 'skipped', direction: 'pull', skipReason: 'encrypted', historyId,
544
- consecutiveFailures: 0,
545
- };
546
- await this.appendHistory(channel, {
547
- direction: 'pull', status: 'skipped', skipReason: 'encrypted',
548
- createdAt: nowIso, failureCountAtRun: 0,
549
- });
550
- await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
551
- return result;
552
- }
553
- // 事件驱动触发(§3.1/§3.2/§3.3 看变化不看时间):
554
- // - remoteNew:远端是否出现比本地祖先更新的快照 → 决定是否做下载合并(Phase A);
555
- // - localDirty:本地 portable 配置相对基线是否真的变了 → 决定是否上传(Phase C)。
556
- // 定时器只是兜底轮询;真正驱动是这两个「变化」信号。
557
- // 列表拿不到(网络失败)时 remoteMetas 为 null → 检测自己再 list 一次,行为与改造前一致
558
- const remoteNew = await this.detectRemoteNew(engine, remoteMetas ?? undefined);
559
- const localDirty = await this.detectLocalChange(engine);
560
- // SYN-05:首轮(从未跑过)与「远端有新快照」是覆盖风险最高的两个时刻 —— 由
561
- // resolveConflictPushPolicy 统一把这两处的 ask 标成 forced。
562
- const firstRun = cfg.lastRunAt === undefined || cfg.lastRunAt === '';
563
- // 两端都无变化 → 什么都不做,记为 upToDate(不重复拉取/不空转)。
564
- if (!remoteNew && !localDirty) {
565
- const result = {
566
- status: 'success', direction: 'none', skipReason: 'upToDate', historyId,
567
- consecutiveFailures: 0,
568
- };
569
- await this.appendHistory(channel, {
570
- direction: 'both', status: 'success', skipReason: 'upToDate',
571
- createdAt: nowIso, failureCountAtRun: 0,
572
- });
573
- await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
574
- return result;
575
- }
509
+ // 锁内重跑一次检测:预检到写入之间可能被别的进程推进(远端新快照 / 本机配置改动),
510
+ // 拿过期结论去写等于覆盖别人的成果。无锁环境(测试)直接用预检结果 —— 同一份数据,没有竞态。
511
+ const phase = releaseLock === null ? preflight : await this.detectPhase(channel, cfg, nowIso, historyId);
512
+ if (phase.kind === 'skip')
513
+ return phase.result;
514
+ const { engine, remoteNew, localDirty, firstRun } = phase;
576
515
  let appliedSections = [];
577
516
  // audit-sync sync-F5:被风险分级扣下、需人工确认的分区(medium/high)。在 Phase A 赋值、
578
517
  // Phase C 与收尾写历史都要用,故声明在两者之外。
@@ -852,6 +791,96 @@ export class AutoSyncScheduler {
852
791
  * 现在:失败写错误原文;跳过写**结构化原因码**(界面按码取字典,语言在渲染那刻解析);
853
792
  * 成功清空两者(空串/undefined 不进文件,见 autosync-config.toChannelPayload)。
854
793
  */
794
+ /**
795
+ * Phase 1:只读预检 —— 读该通道配置、列远端快照、判断「远端有新 / 本地有改动」。
796
+ *
797
+ * 为什么不持锁:这些步骤全是只读,但 plugins 分区的导出会为本机源(link: / file:)插件跑 npm pack
798
+ * (真机实测 210MB 插件 44.7s/次、每轮重算)。放进 GLOBAL mutation 锁内,60s 一轮的轮询就让锁几乎
799
+ * 全程被占,用户任何 destructive 操作都撞 423(2026-11-07 真机事故的根因)。
800
+ * 结论**不具权威性**:调用方取到锁之后必须重跑一次(见 runOnceInternal 的 Phase 2)。
801
+ */
802
+ async detectPhase(channel, cfg, nowIso, historyId) {
803
+ // 读该通道 sync-config:按通道判定「已配置」——git 看 git.repoUrl、webdav 看 webdav.url。
804
+ // SEC-03:「未配置」有两种成因 —— 真的没配,或存过的地址被白名单拒掉(读侧丢弃)。
805
+ // 必须区分:后者如果说成前者的「尚未配置」,用户会一遍遍重填同一个被拒地址。
806
+ const configIssues = [];
807
+ const syncCfg = await this.readSyncConfigFn(channel, configIssues);
808
+ if (!syncIsConfigured(syncCfg)) {
809
+ const configIssue = describeConfigIssue(configIssues, channel);
810
+ if (configIssue !== undefined)
811
+ this.reportConfigIssue(channel, configIssue);
812
+ const result = {
813
+ status: 'skipped', direction: 'none', skipReason: 'unconfigured', historyId,
814
+ consecutiveFailures: 0,
815
+ ...(configIssue === undefined ? {} : { configIssue }),
816
+ };
817
+ await this.appendHistory(channel, {
818
+ direction: 'both',
819
+ status: 'skipped',
820
+ skipReason: 'unconfigured',
821
+ createdAt: nowIso,
822
+ failureCountAtRun: 0,
823
+ ...(configIssue === undefined ? {} : { configIssue }),
824
+ });
825
+ await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
826
+ return { kind: 'skip', result };
827
+ }
828
+ const engine = this.makeSyncEngine(syncCfg);
829
+ // 加密快照检测:远端最新快照为加密 → 自动同步无密码无法解密 → 整体跳过,
830
+ // 同步历史记录 skipReason='encrypted'(提示需手动输入密码同步)。
831
+ // 加密快照只通过手动推送/拉取产生与消费;自动同步仅处理普通快照。
832
+ // list 失败宽容处理:视为无加密快照,继续正常流程(网络问题由后续链路暴露为 failed)。
833
+ let encryptedRemote = false;
834
+ // 本轮远端列表:加密快照检查与「远端是否有新快照」共用同一次 list。
835
+ // 每次 list 都是一次真实网络往返(git = `pull --ff-only`,webdav = PROPFIND/GET),
836
+ // 缺省 60s 轮询下多 list 一次 = 一天白跑 1440 次往返。
837
+ let remoteMetas = null;
838
+ try {
839
+ const metas = await engine.listSnapshots();
840
+ remoteMetas = metas;
841
+ const latestMeta = metas.length > 0 ? metas[metas.length - 1] : null;
842
+ encryptedRemote = latestMeta !== null && latestMeta.manifest.encrypted === true;
843
+ }
844
+ catch {
845
+ encryptedRemote = false;
846
+ }
847
+ if (encryptedRemote) {
848
+ const result = {
849
+ status: 'skipped', direction: 'pull', skipReason: 'encrypted', historyId,
850
+ consecutiveFailures: 0,
851
+ };
852
+ await this.appendHistory(channel, {
853
+ direction: 'pull', status: 'skipped', skipReason: 'encrypted',
854
+ createdAt: nowIso, failureCountAtRun: 0,
855
+ });
856
+ await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
857
+ return { kind: 'skip', result };
858
+ }
859
+ // 事件驱动触发(§3.1/§3.2/§3.3 看变化不看时间):
860
+ // - remoteNew:远端是否出现比本地祖先更新的快照 → 决定是否做下载合并(Phase A);
861
+ // - localDirty:本地 portable 配置相对基线是否真的变了 → 决定是否上传(Phase C)。
862
+ // 定时器只是兜底轮询;真正驱动是这两个「变化」信号。
863
+ // 列表拿不到(网络失败)时 remoteMetas 为 null → 检测自己再 list 一次,行为与改造前一致
864
+ const remoteNew = await this.detectRemoteNew(engine, remoteMetas ?? undefined);
865
+ const localDirty = await this.detectLocalChange(engine);
866
+ // SYN-05:首轮(从未跑过)与「远端有新快照」是覆盖风险最高的两个时刻 —— 由
867
+ // resolveConflictPushPolicy 统一把这两处的 ask 标成 forced。
868
+ const firstRun = cfg.lastRunAt === undefined || cfg.lastRunAt === '';
869
+ // 两端都无变化 → 什么都不做,记为 upToDate(不重复拉取/不空转)。
870
+ if (!remoteNew && !localDirty) {
871
+ const result = {
872
+ status: 'success', direction: 'none', skipReason: 'upToDate', historyId,
873
+ consecutiveFailures: 0,
874
+ };
875
+ await this.appendHistory(channel, {
876
+ direction: 'both', status: 'success', skipReason: 'upToDate',
877
+ createdAt: nowIso, failureCountAtRun: 0,
878
+ });
879
+ await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
880
+ return { kind: 'skip', result };
881
+ }
882
+ return { kind: 'work', engine, remoteNew, localDirty, firstRun };
883
+ }
855
884
  async writeFinalConfig(base, result, nowIso, historyId, channel) {
856
885
  const skipReason = result.status === 'failed' ? undefined : result.skipReason;
857
886
  const countsConflicts = skipReason === 'conflict' || skipReason === 'conflict-kept-local';
@@ -1,5 +1,5 @@
1
1
  import { engineMsg } from './messages.js';
2
- import { runWithMutationLock, EnvironmentLockUnavailableError, LOCK_BLOCK_MESSAGE, LOCK_BLOCK_BRIEF } from '../utils/env-lock.js';
2
+ import { runWithMutationLock, EnvironmentLockUnavailableError, LOCK_BLOCK_MESSAGE, LOCK_BLOCK_BRIEF, lockSkipToken } from '../utils/env-lock.js';
3
3
  import { Exporter } from '../core/exporter.js';
4
4
  import { randomBytes } from 'node:crypto';
5
5
  import { join } from 'node:path';
@@ -238,13 +238,14 @@ export class BackupScheduler {
238
238
  // (LOCK_BLOCK_MESSAGE),避免同一句指引在多条路径上再次漂移(#27 只接了 autosync,
239
239
  // 本路径漏接 → 实测 9 天内 57 次静默跳过,用户无从知道要回收残留锁)。
240
240
  if (err instanceof EnvironmentLockUnavailableError) {
241
- if (err.reason === 'stale') {
242
- this.log.warn(`${trigger}跳过:${LOCK_BLOCK_MESSAGE.stale}`);
241
+ // stale 与 stale-degraded 同属「重试不会自愈」,都走 warn(都带显式回收指引)。
242
+ if (err.reason === 'stale' || err.reason === 'stale-degraded') {
243
+ this.log.warn(`${trigger}跳过:${LOCK_BLOCK_MESSAGE[err.reason]}`);
243
244
  }
244
245
  else {
245
246
  this.log.info(`${trigger}跳过:${LOCK_BLOCK_MESSAGE[err.reason]}`);
246
247
  }
247
- const skipped = { status: 'skipped', skipReason: 'mutation-locked', consecutiveFailures: cfg.consecutiveFailures };
248
+ const skipped = { status: 'skipped', skipReason: lockSkipToken(err.reason), consecutiveFailures: cfg.consecutiveFailures };
248
249
  // skipReason 保持稳定的机器 token(客户端据此本地化);历史摘要用同源**短**文案,
249
250
  // 不留裸 token(issue #31 ②:中文前缀 + 英文 token 的历史行)。
250
251
  await this.appendHistory(skipped, err.reason, manual);
@@ -9,13 +9,13 @@
9
9
  * (`<section>.blobs.json` / WebDAV 的 JSON 载荷里的 blobRefs)。内容没变 = 同一个哈希 =
10
10
  * 已在仓里 = 不再传输。快照保留策略裁剪快照时,无人引用的 blob 由 GC 回收。
11
11
  *
12
- * 兼容性(**这是对外格式变更**,必须同步 docs/spec):
12
+ * 兼容性(**这是对外格式变更**,必须同步 docs/contracts/):
13
13
  * - 外置只发生在**通道侧**:只有 transport 传了 BlobSink 才启用;引擎/导出/导入看到的
14
14
  * 仍是普通 FilesSection(含 data)。本地散文件副本、加密快照、加密载荷一律不外置。
15
15
  * - 旧版插件读新格式:`<section>.blobs.json` 不是 FilesSection,旧版 layout 会当成
16
16
  * 「文件分区目录缺失」—— git 通道 missingFileDir='empty' 会降级为空分区(丢内容但不崩),
17
17
  * WebDAV 通道 blobRefs 也认不出。因此 /sync/status 不下发版本协商,**跨版本混用不被支持**:
18
- * 两端插件版本应当一致(与既有「同步通道不做协议协商」的定位一致,见 docs/spec)。
18
+ * 两端插件版本应当一致(与既有「同步通道不做协议协商」的定位一致,见 docs/contracts/)。
19
19
  */
20
20
  import type { FilesSection, SectionId } from '../schema/types.ts';
21
21
  /**
@@ -168,6 +168,18 @@ export declare class GitTransport implements SyncTransport {
168
168
  */
169
169
  private withWorkdir;
170
170
  private ensureRepo;
171
+ /**
172
+ * 补写工作副本的提交身份(best-effort;只补**缺失**的键,绝不覆盖用户自己配的值)。
173
+ *
174
+ * 为什么需要:git 的提交身份是「仓库级 or 全局」二选一,本插件只写仓库级(不改用户全局配置)。
175
+ * 一旦这个工作副本被别人重建、被 relink、或在没配全局身份的机器上首次同步,仓库级键就没了 ——
176
+ * 之后每次 commit 都 exit 128,而错误面在用户那里只剩一句「备份已跳过」。
177
+ *
178
+ * 纪律:探测(git config --get)失败 → 当作「不知道」而不写(不拿猜测覆盖用户配置);
179
+ * 写入失败 → 静默放过(不是同步失败)。真缺身份时下一条 commit 仍会以 kind='config'
180
+ * 的可操作文案失败,并且**不再升级 SAFE MODE**(见 raiseGitFailure 的 localOnly 标记)。
181
+ */
182
+ private ensureCommitIdentity;
171
183
  /**
172
184
  * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
173
185
  *
@@ -28,6 +28,7 @@ import { BLOB_SECTIONS, gcBlobs, referencedBlobHashes } from '../blob-store.js';
28
28
  import { deserializeSnapshot, serializeSnapshot } from '../snapshot-json.js';
29
29
  import { classifyRepoUrl, isPrivateRepoHost } from '../sync-config.js';
30
30
  import { classifyNetworkErrorText, computeSnapshotMeta, DEFAULT_SYNC_TIMEOUT_MS, isEncryptedSections, SyncTransportError, withSyncRetry, } from '../transport.js';
31
+ import { markLocalOnlyExternalFailure } from '../../core/external-failure.js';
31
32
  import { parseJsonSafe } from '../../utils/json.js';
32
33
  import { atomicWriteFile } from '../../utils/atomic-write.js';
33
34
  import { quoteGitValue } from '../../utils/git-quote.js';
@@ -611,6 +612,11 @@ export class GitTransport {
611
612
  // 而失败面表现为旧地址的网络超时(真机:局域网地址 → Tailscale 地址后同步长期失败),
612
613
  // 用户会误判成网络/凭据问题。
613
614
  await this.reconcileOrigin();
615
+ // 真机 issue:仓库级提交身份此前**只在首次 clone 时**写过(见本方法末尾),已有 .git 的分支
616
+ // 直接 return —— 换机器/换工作副本/用户清过本地配置之后,每次 commit 都以 exit 128 失败
617
+ // ("unable to auto-detect email address"),交易停在 NEEDS_ATTENTION,用户只看到
618
+ // 「备份已跳过:环境锁被占用」。这里在每次进入工作副本时 best-effort 补齐身份。
619
+ await this.ensureCommitIdentity();
614
620
  this.repoReady = true;
615
621
  return;
616
622
  }
@@ -631,6 +637,37 @@ export class GitTransport {
631
637
  await this.runGit(['config', 'user.email', this.o.author.email]);
632
638
  this.repoReady = true;
633
639
  }
640
+ /**
641
+ * 补写工作副本的提交身份(best-effort;只补**缺失**的键,绝不覆盖用户自己配的值)。
642
+ *
643
+ * 为什么需要:git 的提交身份是「仓库级 or 全局」二选一,本插件只写仓库级(不改用户全局配置)。
644
+ * 一旦这个工作副本被别人重建、被 relink、或在没配全局身份的机器上首次同步,仓库级键就没了 ——
645
+ * 之后每次 commit 都 exit 128,而错误面在用户那里只剩一句「备份已跳过」。
646
+ *
647
+ * 纪律:探测(git config --get)失败 → 当作「不知道」而不写(不拿猜测覆盖用户配置);
648
+ * 写入失败 → 静默放过(不是同步失败)。真缺身份时下一条 commit 仍会以 kind='config'
649
+ * 的可操作文案失败,并且**不再升级 SAFE MODE**(见 raiseGitFailure 的 localOnly 标记)。
650
+ */
651
+ async ensureCommitIdentity() {
652
+ const isMissing = async (key) => {
653
+ try {
654
+ const r = await this.runGit(['config', '--get', key], { allowNonZero: true });
655
+ return r.code !== 0 || r.stdout.trim() === '';
656
+ }
657
+ catch {
658
+ return false;
659
+ }
660
+ };
661
+ try {
662
+ if (await isMissing('user.name'))
663
+ await this.runGit(['config', 'user.name', this.o.author.name]);
664
+ if (await isMissing('user.email'))
665
+ await this.runGit(['config', 'user.email', this.o.author.email]);
666
+ }
667
+ catch {
668
+ /* best-effort:写入失败留给后续 commit 以 config 分类暴露,不在这里阻断同步 */
669
+ }
670
+ }
634
671
  /**
635
672
  * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
636
673
  *
@@ -1092,9 +1129,14 @@ export class GitTransport {
1092
1129
  throw err;
1093
1130
  // 注入的 exec 实现可能直接抛错(默认实现只返回非零 code)——同样归一为带分类的传输层错误
1094
1131
  const detail = err instanceof Error ? err.message : String(err);
1095
- throw new GitTransportError(
1132
+ const classified = classifyNetworkErrorText(detail);
1133
+ const failure = new GitTransportError(
1096
1134
  // argv 里含 repoUrl 原文(clone/ls-remote/remote set-url -- <url>)→ 必须经 mask 才进文案
1097
- this.msg('sync.git.cmdFailed', { args: this.mask(args.join(' '), token), code: 'exec', err: this.mask(detail, token) }), { ...classifyNetworkErrorText(detail), cause: err });
1135
+ classified.kind === 'config'
1136
+ ? this.msg('sync.git.identityMissing', { err: this.mask(detail, token) })
1137
+ : this.msg('sync.git.cmdFailed', { args: this.mask(args.join(' '), token), code: 'exec', err: this.mask(detail, token) }), { ...classified, cause: err });
1138
+ // 与 raiseGitFailure 同口径:本机身份缺失不升级全局阻断(localOnly 标记)
1139
+ throw classified.kind === 'config' ? markLocalOnlyExternalFailure(failure, 'git-identity') : failure;
1098
1140
  }
1099
1141
  finally {
1100
1142
  if (cleanup)
@@ -1113,6 +1155,12 @@ export class GitTransport {
1113
1155
  if (SSH_HOST_KEY_RE.test(combined)) {
1114
1156
  throw new GitTransportError(this.hostKeyMessage(), { kind: 'auth', retryable: false });
1115
1157
  }
1158
+ // 本机提交身份缺失(kind='config'):与网络/远端/令牌无关,本机一步配置就能修好。
1159
+ // 文案点名 git config,并打 localOnly 标记 —— phase3 据此不升 durable SAFE MODE
1160
+ // (真机 issue:一个缺 user.email 的 commit 把插件变成「全部写入 423」)。
1161
+ if (classified.kind === 'config') {
1162
+ throw markLocalOnlyExternalFailure(new GitTransportError(this.msg('sync.git.identityMissing', { err: this.mask(result.stderr, token) }), classified), 'git-identity');
1163
+ }
1116
1164
  // 推送 + 鉴权失败:git 原文只说「认证失败」——换成能照做的说明(令牌失效 / 无写权限 / 远端禁用了密码推送)
1117
1165
  // issue #115:clone 的鉴权失败原文(remote: Write access to repository not granted / 403)读不出「缺哪种权限」,
1118
1166
  // 换成点名 Contents: Read and write 的说明 —— 否则用户只会以为令牌坏了(细粒度 PAT 常只勾了 Administration)
@@ -12,6 +12,8 @@
12
12
  * 5. remoteHash == ancestorHash → keepLocal(仅本地改)
13
13
  * 6. 双侧相对祖先都改 → 精细合并:
14
14
  * - JSON 分区:递归对象合并(mergeJsonValues),冲突路径精确到叶子('namespaces.general.value.theme')
15
+ * - 分区专属钩子(GRANULAR_MERGES,当前 = workspaces):按记录 id 做并集(sessionIds 取并集、
16
+ * 其它字段逐键三方取舍),见 workspace-merge.ts —— 通用 JSON 合并对数组只会判冲突
15
17
  * - FilesSection:逐 relativePath 合并,两侧都改的文本文件再走行级三方合并(mergeBytesThreeWay)
16
18
  * - 无残留冲突 → decision='merge'(merged + autoMerged 计数)
17
19
  * - 有残留冲突 → decision='conflict'(merged 为 undefined:绝不把半成品当结果)
package/lib/sync/merge.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { hashSection } from './sync-state.js';
2
2
  import { mergeBytesThreeWay, mergeJsonValues } from './text-merge.js';
3
+ import { mergeWorkspacesSection } from './workspace-merge.js';
3
4
  /** 收集 local/remote/ancestor 三个快照中出现过的所有分区 id。 */
4
5
  function unionSectionIds(local, remote, ancestor) {
5
6
  const ids = new Set();
@@ -213,6 +214,16 @@ function mergeFilesSectionGranular(local, remote, ancestor) {
213
214
  }
214
215
  return { merged: { version: 1, files: mergedFiles }, conflicts, mergePoints };
215
216
  }
217
+ /**
218
+ * 分区专属的记录级合并钩子(issue #127)。
219
+ *
220
+ * 缺省 = 走下面的通用 JSON / 文件合并。当前只有 workspaces:它的 `sessionIds` 必须取并集
221
+ * (通用 JSON 合并对数组一律判冲突 —— 两侧各自挂过会话就永远冲突,且裁决任一侧都会丢另一侧的
222
+ * 会话归属)。钩子返回 undefined = 形状不认识,仍交回通用路径(畸形数据由形状闸门拒绝)。
223
+ */
224
+ const GRANULAR_MERGES = {
225
+ workspaces: mergeWorkspacesSection,
226
+ };
216
227
  /** 单分区三方合并(决策链见文件头注释)。 */
217
228
  function mergeSectionTriple(id, lData, rData, aData, h) {
218
229
  // ⓪ 形状闸门(先于一切取舍):远端载荷来自不可信输入(解析层只保证整体是合法 JSON,
@@ -273,6 +284,23 @@ function mergeSectionTriple(id, lData, rData, aData, h) {
273
284
  conflicts: [{ path: '$', kind: 'key', reason: 'section', autoMergeAttempted: false, local, remote, ancestor: aData }],
274
285
  };
275
286
  }
287
+ // ③' 分区专属记录级合并(**早于 ancestor 闸门**):workspaces 的 sessionIds 是并集语义 ——
288
+ // 没有祖先时也应并集(否则首轮同步就整分区冲突),字段取值分歧由钩子逐键如实报冲突。
289
+ const granular = GRANULAR_MERGES[id];
290
+ if (granular !== undefined) {
291
+ const res = granular(local, remote, aData);
292
+ if (res !== undefined) {
293
+ if (res.conflicts.length > 0)
294
+ return { id, decision: 'conflict', conflicts: res.conflicts };
295
+ const merged = res.merged;
296
+ const mh = hashSection(merged);
297
+ if (mh === h.remote)
298
+ return { id, decision: 'useRemote', merged, conflicts: [] };
299
+ if (mh === h.local)
300
+ return { id, decision: 'keepLocal', merged, conflicts: [] };
301
+ return { id, decision: 'merge', merged, conflicts: [], autoMerged: res.mergePoints };
302
+ }
303
+ }
276
304
  if (h.ancestor === undefined) {
277
305
  return {
278
306
  id,
@@ -21,6 +21,10 @@ export declare const zh: {
21
21
  readonly 'sync.layoutFileSectionDirMissing': '快照缺少文件分区目录 {prefix}({section})';
22
22
  readonly 'sync.blobMissing': '内容的 blob 缺失({hash},{path}):远端仓不完整,拒绝降级为空分区';
23
23
  readonly 'sync.webdav.blobHashInvalid': '内容哈希形状非法,拒绝写入 blob 仓: {hash}';
24
+ readonly 'sync.scopeDirCreateFailed': '无法创建档案同步目录 {dir}:{reason}';
25
+ readonly 'sync.scopeAdoptFailed': '继承 {file} 失败:{reason}';
26
+ readonly 'sync.scopeAdopted': '档案 {profile} 已从历史同步根继承:{files}';
27
+ readonly 'sync.scopeBootFailed': '档案作用域继承失败:{reason}';
24
28
  readonly 'sync.reviewQueueNotObject': 'sync-review-queue.json 损坏:必须是对象';
25
29
  readonly 'sync.reviewQueueItemsNotArray': 'sync-review-queue.json 损坏:items 必须是数组';
26
30
  readonly 'sync.reviewQueueItemNotObject': 'sync-review-queue.json 损坏:每个 item 必须是对象';
@@ -41,7 +41,11 @@ export const zh = {
41
41
  // ---------- 内容寻址 blob 仓 ----------
42
42
  'sync.blobMissing': '内容的 blob 缺失({hash},{path}):远端仓不完整,拒绝降级为空分区',
43
43
  'sync.webdav.blobHashInvalid': '内容哈希形状非法,拒绝写入 blob 仓: {hash}',
44
- // ---------- 审查队列 ----------
44
+ // ---------- 按档案分作用域(sync-scope) ----------
45
+ 'sync.scopeDirCreateFailed': '无法创建档案同步目录 {dir}:{reason}',
46
+ 'sync.scopeAdoptFailed': '继承 {file} 失败:{reason}',
47
+ 'sync.scopeAdopted': '档案 {profile} 已从历史同步根继承:{files}',
48
+ 'sync.scopeBootFailed': '档案作用域继承失败:{reason}', // ---------- 审查队列 ----------
45
49
  'sync.reviewQueueNotObject': 'sync-review-queue.json 损坏:必须是对象',
46
50
  'sync.reviewQueueItemsNotArray': 'sync-review-queue.json 损坏:items 必须是数组',
47
51
  'sync.reviewQueueItemNotObject': 'sync-review-queue.json 损坏:每个 item 必须是对象',
@@ -121,7 +125,10 @@ export const en = {
121
125
  'sync.layoutFileSectionDirMissing': 'Snapshot is missing the file section directory {prefix} ({section})',
122
126
  'sync.blobMissing': 'The blob for {path} is missing ({hash}): the remote store is incomplete, refusing to degrade to an empty section',
123
127
  'sync.webdav.blobHashInvalid': 'Malformed content hash; refusing to write to the blob store: {hash}',
124
- 'sync.reviewQueueNotObject': 'sync-review-queue.json is corrupt: must be an object',
128
+ 'sync.scopeDirCreateFailed': 'Cannot create the profile sync directory {dir}: {reason}',
129
+ 'sync.scopeAdoptFailed': 'Failed to adopt {file}: {reason}',
130
+ 'sync.scopeAdopted': 'Profile {profile} adopted settings from the shared sync root: {files}',
131
+ 'sync.scopeBootFailed': 'Failed to adopt the shared sync settings for this profile: {reason}', 'sync.reviewQueueNotObject': 'sync-review-queue.json is corrupt: must be an object',
125
132
  'sync.reviewQueueItemsNotArray': 'sync-review-queue.json is corrupt: items must be an array',
126
133
  'sync.reviewQueueItemNotObject': 'sync-review-queue.json is corrupt: every item must be an object',
127
134
  'sync.reviewQueueItemFieldsMissing': 'sync-review-queue.json is corrupt: an item must contain the strings id/sectionId/kind/description',
@@ -91,7 +91,7 @@ export declare class S3Transport implements SyncTransport {
91
91
  * 变了 / 对象没了 → 按并发写中止(零写入)。
92
92
  *
93
93
  * **不是原子的**:复核与 PUT 之间仍有窗口(服务端不支持条件写就没有真正的解),
94
- * 比无保护强、比 If-Match 弱 —— 如实登记在 docs/decisions/0003。
94
+ * 比无保护强、比 If-Match 弱 —— 如实登记在 docs/adr/0003。
95
95
  * 其它方言(etag)与「服务端不给 ETag」两种情况一律直接放行,不改既有行为。
96
96
  */
97
97
  private reassertIndexEtag;
@@ -306,7 +306,7 @@ export class S3Transport {
306
306
  * 变了 / 对象没了 → 按并发写中止(零写入)。
307
307
  *
308
308
  * **不是原子的**:复核与 PUT 之间仍有窗口(服务端不支持条件写就没有真正的解),
309
- * 比无保护强、比 If-Match 弱 —— 如实登记在 docs/decisions/0003。
309
+ * 比无保护强、比 If-Match 弱 —— 如实登记在 docs/adr/0003。
310
310
  * 其它方言(etag)与「服务端不给 ETag」两种情况一律直接放行,不改既有行为。
311
311
  */
312
312
  async reassertIndexEtag(etag, secret) {
@@ -610,11 +610,11 @@ export declare class SyncEngine {
610
610
  */
611
611
  probe(): Promise<SyncProbeResult>;
612
612
  /**
613
- * 本地 portable 配置当前内容与上次基线(sync-state.sections hash)相比是否有变化(§3.1 上传「看变化」)。
613
+ * 本地**会进载荷**的配置与上次基线(sync-state.sections hash)相比是否有变化(§3.1 上传「看变化」)。
614
614
  * - 从未同步(sync-state.sections 为空)→ true;
615
- * - 任一 portable 分区当前导出 hash ≠ 基线 hash → true;
616
- * - 全部一致 → false(无本地改动,不上传)。
617
- * 只读本地导出 + sync-state,不写任何东西、不碰远端。
615
+ * - 任一 pushTargets 分区(portable + 本次放行的可选分区)导出 hash ≠ 基线 → true;
616
+ * - 全部一致 → false(无本地改动,不上传)。只读本地导出 + sync-state,不碰远端。
617
+ * 判定集合必须 == 推送载荷集合,且被比较字节必须可复现(细节与实测 → docs/evidence/sync-channel.md)。
618
618
  */
619
619
  hasLocalChanges(): Promise<boolean>;
620
620
  /**
@@ -44,6 +44,7 @@ import { msgOf, zhMsg } from '../core/messages.js';
44
44
  import { engineMsg } from './messages.js';
45
45
  import { DEFAULT_ANCESTOR_KEEP, pruneAncestors, tryLoadAncestor, writeAncestor, writeEncryptedAncestor } from './ancestor.js';
46
46
  import { merge as mergeSections } from './merge.js';
47
+ import { prepareApplyBundle } from './apply-bundle.js';
47
48
  import { previewTextOf } from './merge-preview-text.js';
48
49
  import { gcSkipWarning, readGcSkipCode, reportGcSkipOnce } from './gc-skip.js';
49
50
  import { classifyMergePlan } from './risk.js';
@@ -994,17 +995,17 @@ export class SyncEngine {
994
995
  return await probe.call(this.transport);
995
996
  }
996
997
  /**
997
- * 本地 portable 配置当前内容与上次基线(sync-state.sections hash)相比是否有变化(§3.1 上传「看变化」)。
998
+ * 本地**会进载荷**的配置与上次基线(sync-state.sections hash)相比是否有变化(§3.1 上传「看变化」)。
998
999
  * - 从未同步(sync-state.sections 为空)→ true;
999
- * - 任一 portable 分区当前导出 hash ≠ 基线 hash → true;
1000
- * - 全部一致 → false(无本地改动,不上传)。
1001
- * 只读本地导出 + sync-state,不写任何东西、不碰远端。
1000
+ * - 任一 pushTargets 分区(portable + 本次放行的可选分区)导出 hash ≠ 基线 → true;
1001
+ * - 全部一致 → false(无本地改动,不上传)。只读本地导出 + sync-state,不碰远端。
1002
+ * 判定集合必须 == 推送载荷集合,且被比较字节必须可复现(细节与实测 → docs/evidence/sync-channel.md)。
1002
1003
  */
1003
1004
  async hasLocalChanges() {
1004
1005
  const state = await loadSyncState(this.stateDir, this.fsx, this.msg);
1005
1006
  if (Object.keys(state.sections).length === 0)
1006
1007
  return true;
1007
- for (const adapter of this.portableAdapters()) {
1008
+ for (const adapter of this.pushTargets(undefined, [])) {
1008
1009
  let section;
1009
1010
  try {
1010
1011
  section = await adapter.export(this.ctx, { includeSecrets: false });
@@ -1475,28 +1476,26 @@ export class SyncEngine {
1475
1476
  if (appliedIds.length === 0) {
1476
1477
  return { ok: true, applied: [], restoreId: '', rolledBack: false, review: [], warnings: [] };
1477
1478
  }
1478
- // 1) 构造临时 ZIP(仅含 autoApply 项的 merged payload)+ 分析 + 计划
1479
- const portableIds = this.pullSectionIds();
1480
- // issue #45:临时 ZIP 带上远端快照的 sourceHome → Importer 自动重定基(跨机时才有实际作用)
1481
- const effectiveSourceHome = opts.sourceHome ?? this.lastMergedRemoteSourceHome;
1482
- const tempSnapshot = {
1483
- id: this.snapshotIdFn(),
1479
+ // 0'/1) issue #127:会话落地必须伴随工作区(口径见 apply-bundle.ts);临时 ZIP 只装 autoApply 的 merged 载荷
1480
+ const bundle = await prepareApplyBundle({
1481
+ autoApply: apply.autoApply,
1482
+ baseIds: appliedIds,
1483
+ pullAllowsWorkspaces: this.pullSectionIds().has('workspaces'),
1484
+ planEntries: [...apply.review, ...apply.skipped],
1485
+ remote: this.lastMergeInputs?.remote['workspaces'],
1486
+ ancestor: this.lastMergeInputs?.ancestor['workspaces'],
1487
+ adapter: this.adapters.find((a) => a.id === 'workspaces'),
1488
+ ctx: this.ctx,
1489
+ snapshotId: this.snapshotIdFn(),
1484
1490
  createdAt: this.now().toISOString(),
1485
- manifest: {
1486
- schemaVersion: CURRENT_SCHEMA_VERSION,
1487
- dshVersion: this.ctx.dshVersion,
1488
- platform: this.ctx.platform,
1489
- sectionIds: apply.autoApply.map((r) => r.id),
1490
- containsSecrets: false,
1491
- ...(effectiveSourceHome !== '' ? { sourceHome: effectiveSourceHome } : {}),
1492
- },
1493
- sections: apply.autoApply.reduce((acc, r) => {
1494
- if (r.merged !== undefined)
1495
- acc[r.id] = r.merged;
1496
- return acc;
1497
- }, {}),
1498
- };
1499
- const zipPath = await this.snapshotToZip(tempSnapshot, portableIds);
1491
+ dshVersion: this.ctx.dshVersion,
1492
+ platform: this.ctx.platform,
1493
+ sourceHome: opts.sourceHome ?? this.lastMergedRemoteSourceHome,
1494
+ });
1495
+ if (bundle.companion !== undefined)
1496
+ appliedIds.push('workspaces');
1497
+ const tempSnapshot = bundle.tempSnapshot;
1498
+ const zipPath = await this.snapshotToZip(tempSnapshot, this.pullSectionIds());
1500
1499
  try {
1501
1500
  const plan = await this.importer.createImportPlan(zipPath, {
1502
1501
  strategy: 'replace', // auto 路径:冲突已在外部分流;这里 replace = 接受导入值