dsh-config-manager 0.4.3 → 0.5.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 (254) 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 +14 -41
  13. package/lib/client.js +794 -716
  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 +1 -0
  29. package/lib/core/messages.js +6 -0
  30. package/lib/core/model-tool-plans.d.ts +66 -0
  31. package/lib/core/model-tool-plans.js +128 -0
  32. package/lib/core/model-tools.d.ts +96 -8
  33. package/lib/core/model-tools.js +568 -31
  34. package/lib/core/phase3-host.js +10 -2
  35. package/lib/core/plugin-data-registry.d.ts +1 -1
  36. package/lib/core/plugin-data-registry.js +1 -1
  37. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  38. package/lib/core/restore-plan-fingerprint.js +18 -0
  39. package/lib/core/restore-resume.d.ts +1 -1
  40. package/lib/core/restore-resume.js +1 -1
  41. package/lib/core/restore.d.ts +5 -0
  42. package/lib/core/restore.js +4 -1
  43. package/lib/core/types.d.ts +12 -0
  44. package/lib/foreign/claude-sessions.d.ts +1 -1
  45. package/lib/foreign/claude-sessions.js +1 -1
  46. package/lib/foreign/registry.js +1 -1
  47. package/lib/foreign/types.d.ts +1 -1
  48. package/lib/index.d.ts +15 -15
  49. package/lib/index.js +60 -67
  50. package/lib/market/git-file-writer.js +1 -1
  51. package/lib/market/github-repos.js +1 -1
  52. package/lib/market/market-config.js +1 -1
  53. package/lib/market/messages-market.js +1 -1
  54. package/lib/market/my-repo.js +1 -1
  55. package/lib/market/prepare.js +1 -1
  56. package/lib/market/reader.js +2 -2
  57. package/lib/market/repo-url.d.ts +1 -1
  58. package/lib/market/security.js +2 -2
  59. package/lib/market/star-cache.d.ts +1 -1
  60. package/lib/market/types.d.ts +1 -1
  61. package/lib/market/types.js +1 -1
  62. package/lib/market/url.js +1 -1
  63. package/lib/routes/backup.js +17 -9
  64. package/lib/routes/index.d.ts +1 -1
  65. package/lib/routes/kit.d.ts +2 -2
  66. package/lib/routes/market.d.ts +1 -1
  67. package/lib/routes/market.js +3 -60
  68. package/lib/routes/model-tools-deps.d.ts +41 -0
  69. package/lib/routes/model-tools-deps.js +18 -0
  70. package/lib/routes/recovery.js +5 -3
  71. package/lib/routes/route-support.d.ts +18 -26
  72. package/lib/routes/route-support.js +19 -32
  73. package/lib/routes/snapshots.d.ts +1 -1
  74. package/lib/routes/snapshots.js +4 -40
  75. package/lib/routes/sync.js +40 -28
  76. package/lib/schema/index.d.ts +2 -2
  77. package/lib/schema/index.js +2 -2
  78. package/lib/schema/section-registry.d.ts +5 -3
  79. package/lib/schema/section-registry.js +7 -3
  80. package/lib/security/secret-scanner.js +1 -1
  81. package/lib/sync/apply-bundle.d.ts +50 -0
  82. package/lib/sync/apply-bundle.js +60 -0
  83. package/lib/sync/autosync-scheduler.d.ts +9 -0
  84. package/lib/sync/autosync-scheduler.js +118 -89
  85. package/lib/sync/backup-scheduler.js +5 -4
  86. package/lib/sync/blob-store.d.ts +2 -2
  87. package/lib/sync/git/git-transport.d.ts +12 -0
  88. package/lib/sync/git/git-transport.js +50 -2
  89. package/lib/sync/merge.d.ts +2 -0
  90. package/lib/sync/merge.js +28 -0
  91. package/lib/sync/messages.d.ts +4 -0
  92. package/lib/sync/messages.js +9 -2
  93. package/lib/sync/s3/s3-transport.d.ts +1 -1
  94. package/lib/sync/s3/s3-transport.js +1 -1
  95. package/lib/sync/sync-engine.d.ts +4 -4
  96. package/lib/sync/sync-engine.js +25 -26
  97. package/lib/sync/sync-scope-boot.d.ts +34 -0
  98. package/lib/sync/sync-scope-boot.js +71 -0
  99. package/lib/sync/sync-scope.d.ts +103 -0
  100. package/lib/sync/sync-scope.js +229 -0
  101. package/lib/sync/sync-selection.d.ts +17 -4
  102. package/lib/sync/sync-selection.js +40 -14
  103. package/lib/sync/transport.d.ts +4 -1
  104. package/lib/sync/transport.js +6 -0
  105. package/lib/sync/webdav/webdav-transport.js +1 -1
  106. package/lib/sync/workspace-merge.d.ts +36 -0
  107. package/lib/sync/workspace-merge.js +152 -0
  108. package/lib/ui/backup-schedule.d.ts +13 -2
  109. package/lib/ui/backup-schedule.js +3 -0
  110. package/lib/ui/snapshots-view.d.ts +16 -0
  111. package/lib/ui/snapshots-view.js +21 -0
  112. package/lib/utils/env-lock.d.ts +96 -0
  113. package/lib/utils/env-lock.js +332 -111
  114. package/lib/utils/messages-utils.d.ts +6 -0
  115. package/lib/utils/messages-utils.js +17 -1
  116. package/lib/utils/patch-yaml.js +1 -1
  117. package/lib/utils/zip.js +1 -1
  118. package/package.json +3 -2
  119. package/src/adapters/mcp.test.ts +28 -0
  120. package/src/adapters/mcp.ts +33 -0
  121. package/src/adapters/plugins.test.ts +49 -0
  122. package/src/adapters/plugins.ts +9 -1
  123. package/src/adapters/pnpm-workspace.ts +1 -1
  124. package/src/adapters/self.test.ts +39 -1
  125. package/src/adapters/self.ts +20 -2
  126. package/src/adapters/workspaces.ts +1 -1
  127. package/src/cli/restore-resume.ts +1 -1
  128. package/src/cli/web/page.ts +2 -2
  129. package/src/client/about/AboutPanel.tsx +1 -1
  130. package/src/client/about/about-view.test.ts +1 -1
  131. package/src/client/about/about-view.ts +1 -1
  132. package/src/client/api.ts +1 -6
  133. package/src/client/chat/chat-entry-view.test.ts +1 -1
  134. package/src/client/chat/chat-slots.ts +1 -1
  135. package/src/client/chat/rollback-diff-tab.ts +1 -1
  136. package/src/client/client-types.ts +1 -1
  137. package/src/client/common/routes.ts +1 -5
  138. package/src/client/css-scale-guard.test.ts +1 -1
  139. package/src/client/home/HomePanel.tsx +3 -0
  140. package/src/client/library/ArtifactRow.tsx +14 -2
  141. package/src/client/library/LibraryPanel.tsx +44 -0
  142. package/src/client/locales/overview.ts +10 -2
  143. package/src/client/locales/sessions.ts +3 -0
  144. package/src/client/market/MyConfigsView.tsx +1 -1
  145. package/src/client/market/market-api.ts +2 -14
  146. package/src/client/market/market-locales.ts +1 -1
  147. package/src/client/market/market-view.ts +3 -3
  148. package/src/client/market/my-configs-api.ts +1 -1
  149. package/src/client/market/my-configs-view.ts +1 -1
  150. package/src/client/recovery/recovery-locales.test.ts +1 -1
  151. package/src/client/run-store.ts +1 -1
  152. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  153. package/src/client/sync/history-model.test.ts +28 -7
  154. package/src/client/sync/history-model.ts +6 -3
  155. package/src/client/sync/sync-locales.ts +10 -4
  156. package/src/client/sync/sync-view.ts +1 -1
  157. package/src/core/analyzer-cache.test.ts +1 -1
  158. package/src/core/backup.test.ts +45 -1
  159. package/src/core/backup.ts +25 -0
  160. package/src/core/disk-usage.test.ts +2 -0
  161. package/src/core/env-lock-lifecycle.ts +33 -3
  162. package/src/core/external-failure.test.ts +60 -0
  163. package/src/core/external-failure.ts +54 -0
  164. package/src/core/integrity-extra-entries.test.ts +1 -1
  165. package/src/core/local-plugin-host.test.ts +134 -0
  166. package/src/core/local-plugin-host.ts +122 -17
  167. package/src/core/local-plugin-pack.ts +39 -3
  168. package/src/core/mcp-connector-store.ts +26 -1
  169. package/src/core/messages-core.ts +94 -0
  170. package/src/core/messages.ts +6 -0
  171. package/src/core/model-tool-plans.test.ts +111 -0
  172. package/src/core/model-tool-plans.ts +170 -0
  173. package/src/core/model-tools.test.ts +212 -12
  174. package/src/core/model-tools.ts +710 -38
  175. package/src/core/phase3-host.ts +10 -2
  176. package/src/core/phase3-production-integration.test.ts +43 -0
  177. package/src/core/plugin-data-registry.ts +1 -1
  178. package/src/core/restore-plan-fingerprint.ts +19 -0
  179. package/src/core/restore-resume.ts +1 -1
  180. package/src/core/restore.ts +9 -1
  181. package/src/core/types.ts +12 -0
  182. package/src/foreign/claude-sessions.ts +3 -3
  183. package/src/foreign/registry.ts +1 -1
  184. package/src/foreign/types.ts +1 -1
  185. package/src/index.ts +91 -98
  186. package/src/market/git-file-writer.ts +1 -1
  187. package/src/market/github-repos.test.ts +1 -1
  188. package/src/market/github-repos.ts +1 -1
  189. package/src/market/market-config.ts +1 -1
  190. package/src/market/messages-market.ts +1 -1
  191. package/src/market/my-repo.test.ts +1 -1
  192. package/src/market/my-repo.ts +1 -1
  193. package/src/market/prepare.test.ts +1 -1
  194. package/src/market/prepare.ts +1 -1
  195. package/src/market/reader.ts +2 -2
  196. package/src/market/repo-url.ts +1 -1
  197. package/src/market/security.ts +2 -2
  198. package/src/market/star-cache.ts +1 -1
  199. package/src/market/types.ts +1 -1
  200. package/src/market/url.test.ts +1 -1
  201. package/src/market/url.ts +1 -1
  202. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  203. package/src/routes/backup.ts +16 -9
  204. package/src/routes/index.ts +1 -1
  205. package/src/routes/kit.ts +2 -2
  206. package/src/routes/market.ts +2 -59
  207. package/src/routes/model-tools-deps.ts +56 -0
  208. package/src/routes/recovery.ts +5 -3
  209. package/src/routes/route-support.ts +49 -36
  210. package/src/routes/snapshots.ts +4 -40
  211. package/src/routes/sync.ts +39 -27
  212. package/src/schema/index.ts +2 -2
  213. package/src/schema/manifest-schema.test.ts +2 -2
  214. package/src/schema/registry.test.ts +1 -1
  215. package/src/schema/section-registry.ts +9 -4
  216. package/src/security/redaction.test.ts +1 -1
  217. package/src/security/secret-scanner.test.ts +2 -2
  218. package/src/security/secret-scanner.ts +1 -1
  219. package/src/sync/apply-bundle.ts +104 -0
  220. package/src/sync/autosync-scheduler.test.ts +180 -6
  221. package/src/sync/autosync-scheduler.ts +132 -92
  222. package/src/sync/backup-scheduler.test.ts +11 -4
  223. package/src/sync/backup-scheduler.ts +5 -4
  224. package/src/sync/blob-store.ts +2 -2
  225. package/src/sync/git/git-transport.test.ts +62 -0
  226. package/src/sync/git/git-transport.ts +54 -3
  227. package/src/sync/merge.ts +29 -0
  228. package/src/sync/messages.ts +9 -2
  229. package/src/sync/s3/s3-transport.ts +1 -1
  230. package/src/sync/sync-engine.test.ts +238 -2
  231. package/src/sync/sync-engine.ts +25 -26
  232. package/src/sync/sync-preview-push.test.ts +2 -1
  233. package/src/sync/sync-scope-boot.ts +87 -0
  234. package/src/sync/sync-scope.test.ts +154 -0
  235. package/src/sync/sync-scope.ts +256 -0
  236. package/src/sync/sync-selection.test.ts +76 -2
  237. package/src/sync/sync-selection.ts +40 -13
  238. package/src/sync/transport.test.ts +21 -1
  239. package/src/sync/transport.ts +12 -0
  240. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  241. package/src/sync/webdav/webdav-transport.ts +1 -1
  242. package/src/sync/workspace-merge.test.ts +110 -0
  243. package/src/sync/workspace-merge.ts +180 -0
  244. package/src/ui/backup-schedule.test.ts +5 -0
  245. package/src/ui/backup-schedule.ts +21 -2
  246. package/src/ui/session-issue-labels.ts +1 -1
  247. package/src/ui/snapshots-view.test.ts +32 -0
  248. package/src/ui/snapshots-view.ts +34 -0
  249. package/src/utils/env-lock.test.ts +242 -9
  250. package/src/utils/env-lock.ts +247 -13
  251. package/src/utils/messages-utils.ts +17 -1
  252. package/src/utils/patch-yaml.ts +1 -1
  253. package/src/utils/zip.ts +1 -1
  254. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -1,27 +1,18 @@
1
1
  /**
2
- * 路由组:快照与恢复(快照列表 / 恢复 / 删除 / 置顶 / 逐文件差异)。
2
+ * 路由组:快照与恢复(快照列表 / 恢复 / 删除 / 逐文件差异)。
3
3
  *
4
4
  * W1(host-entry#F-02/#F-03):路由只在这里声明一次 —— endpoint({ path, methods }, handler) 的
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
7
  import { endpoint, readJsonBody, writeJson, writeMutationError } from './kit.js';
8
- import { deleteSnapshot, isValidSnapshotId, listSnapshots, planRestore, setSnapshotPinned } from '../core/restore.js';
8
+ import { deleteSnapshot, isValidSnapshotId, listSnapshots, planRestore } from '../core/restore.js';
9
+ // 预览-执行一致性指纹:与 agent 工具(config_restore)共用同一实现,口径分叉会让防呆失效。
10
+ import { restorePlanFingerprint } from '../core/restore-plan-fingerprint.js';
9
11
  import { snapshotFileDiff, summarizeRestoreChanges } from '../core/snapshot-diff.js';
10
12
  import { buildFileDiffBody, buildRestoreBody, executeRestorePlan, makeRestoreExecutor } from './route-support.js';
11
13
  import { probeRestoreResume, runRestoreWithResume } from '../core/restore-resume.js';
12
14
  import { runWithMutationLock } from '../utils/env-lock.js';
13
- import { isENOENT } from '../utils/guards.js';
14
15
  import { join } from 'node:path';
15
- import { createHash } from 'node:crypto';
16
- /**
17
- * 恢复计划指纹(预览-执行一致性):只取「动作类型 + 目标 + blob」三列 —— 描述文案、详情、顺序无关的
18
- * 易变字段一律不进,保证同一份快照 + 同一磁盘状态下指纹稳定。内容变化不会改变指纹(同 kind/target),
19
- * 只有**动作集合真的变了**(文件出现/消失、插件增删)才会不同 —— 那正是需要用户重新确认的情况。
20
- */
21
- function restorePlanFingerprint(plan) {
22
- const lines = plan.actions.map((action) => [action.kind, action.target ?? '', action.blobPath ?? ''].join('\u0000'));
23
- return createHash('sha256').update(lines.join('\n')).digest('hex');
24
- }
25
16
  export function snapshotRoutes(env) {
26
17
  const { host, msg, runs, snapshotEntrySections, snapshotsDir, tryAppendHistory, withMutationGate, } = env;
27
18
  return [
@@ -237,33 +228,6 @@ export function snapshotRoutes(env) {
237
228
  writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) });
238
229
  }
239
230
  })),
240
- // --------------------------------------------- snapshots/pin(P1-⑧)
241
- // 置顶/取消置顶快照:置顶快照豁免「最多保留 N 个」的自动清理(只能手动删除)。
242
- // 纯元数据写(重写 snapshot.json 的 pinned 字段);loopback fence 必备。
243
- endpoint({ path: '/api/dsh-config-manager/snapshots/pin', methods: ['POST'] }, withMutationGate('snapshot-pin', async (req, res) => {
244
- try {
245
- const body = await readJsonBody(req);
246
- const id = typeof body === 'object' && body !== null
247
- ? body['snapshotId']
248
- : undefined;
249
- const pinned = body?.['pinned'] === true;
250
- if (!isValidSnapshotId(id)) {
251
- writeJson(res, 400, { error: 'snapshotId is required and must be a valid snapshot id' });
252
- return;
253
- }
254
- await setSnapshotPinned(snapshotsDir, id, pinned);
255
- writeJson(res, 200, { ok: true, pinned });
256
- }
257
- catch (error) {
258
- // e2e-F4:快照不存在时**不得**把 fs 原始错误(含服务端绝对路径)回给浏览器 ——
259
- // 结构化 404 + 机器可读码,文案由界面按码映射;其余失败也不再回显原始 message。
260
- if (isENOENT(error)) {
261
- writeJson(res, 404, { error: 'snapshot not found', code: 'snapshot-not-found' });
262
- return;
263
- }
264
- writeJson(res, 500, { error: 'failed to update snapshot pin' });
265
- }
266
- })),
267
231
  // --------------------------------------- snapshots/file-diff(git 风格预览)
268
232
  // 单个文件的逐行差异(只读):before = 当前磁盘文件 / after = 快照 blob。
269
233
  // 点开某个文件才请求(列表阶段只做轻量统计),避免会话类快照几百个文件时拖死弹窗。
@@ -37,7 +37,7 @@ function extractPathMappings(body) {
37
37
  }
38
38
  return out;
39
39
  }
40
- import { REVIEW_KINDS, ROUTE_TIMEOUT_MS, SYNC_CREDENTIAL_REF, SYNC_WEBDAV_CREDENTIAL_REF, SyncRouteError, buildAutosyncStatus, buildAutosyncStatusByChannel, credentialRef, extractSyncSections, extractSyncSessions, isAutosyncInterval, isGitHubAuthMissing, isToolchainChangeItem, planToConfirmItems, syncPasswordRef, withTimeout, writeSyncRouteError } from './route-support.js';
40
+ import { REVIEW_KINDS, ROUTE_TIMEOUT_MS, SyncRouteError, buildAutosyncStatus, buildAutosyncStatusByChannel, credentialRef, extractSyncSections, extractSyncSessions, isAutosyncInterval, isGitHubAuthMissing, isToolchainChangeItem, planToConfirmItems, syncScopeOrDefault, withTimeout, writeSyncRouteError } from './route-support.js';
41
41
  import { GitHubApiError } from '../market/github-repos.js';
42
42
  import { redact } from '../security/redaction.js';
43
43
  import { shouldRunOnEnable, readAutosyncConfig, writeAutosyncConfig, clampRemoteCheckMs, clearLastRunResult } from '../sync/autosync-config.js';
@@ -57,14 +57,16 @@ import { dirname, join } from 'node:path';
57
57
  * 云端点通道回传视图(s3 / gist):**只带 secretStored 布尔,绝不带任何密钥值**。
58
58
  * 配置过即返回(与当前活动通道无关),供表单在各通道间切换时回填。
59
59
  */
60
- async function cloudChannelViews(full, credentials) {
60
+ async function cloudChannelViews(full, credentials,
61
+ /** 通道密钥槽位(已按档案作用域;默认档案 = 历史槽位名)。 */
62
+ cloudSecret) {
61
63
  const out = {};
62
64
  if (full?.s3 !== undefined) {
63
- const info = await credentials.describe(credentialRef(cloudSecretRef(full.s3.provider)));
65
+ const info = await credentials.describe(credentialRef(cloudSecret(full.s3.provider)));
64
66
  out.s3 = s3ChannelView(full.s3.provider, full.s3, info.configured);
65
67
  }
66
68
  if (full?.gist !== undefined) {
67
- const info = await credentials.describe(credentialRef(cloudSecretRef(GIST_PROVIDER)));
69
+ const info = await credentials.describe(credentialRef(cloudSecret(GIST_PROVIDER)));
68
70
  out.gist = gistChannelView(full.gist, info.configured);
69
71
  }
70
72
  return out;
@@ -79,6 +81,16 @@ function describeWebDavSlot(cfg, passwordConfigured) {
79
81
  }
80
82
  export function syncRoutes(env) {
81
83
  const { adapters, credentials, githubAuth, githubClientId, githubClientSecret, githubFlows, host, knownSyncSectionIds, makeSyncEngine, meGitHubRest, meTokenProvider, msg, prepareSync, resolveSyncPassword, scheduler, selectionCache, selectionOptInSections, selectionView, selectionViewByChannel, syncCredentialsByChannelView, syncDir, syncPasswordConfigured, syncSectionCatalog, syncSessions, syncWorkDir, tmpDir, tryAppendHistory, withMutationGate, } = env;
84
+ /**
85
+ * 凭据槽位一律按**档案作用域**取(见 src/sync/sync-scope.ts):
86
+ * 默认档案(web)沿用历史槽位名,零迁移;其它档案追加 `__<PROFILE>` 后缀 ——
87
+ * 于是不同 profile 可以各自绑定不同的 GitHub 账号 / 仓库而不互相覆盖。
88
+ */
89
+ const syncScope = syncScopeOrDefault(syncDir, env.syncScope);
90
+ const tokenRef = syncScope.tokenRef;
91
+ const webdavPasswordRef = syncScope.webdavPasswordRef;
92
+ const passwordRef = (kind, channel) => syncScope.passwordRef(kind, channel);
93
+ const cloudSecret = (provider) => syncScope.scopeRef(cloudSecretRef(provider));
82
94
  /** 云端点密钥「只写」端口:值只进 DSH credentials,绝不落盘 / 日志 / 回传(cloudSecretRef 槽位)。 */
83
95
  const cloudSecrets = {
84
96
  set: async (ref, value) => { await credentials.set(credentialRef(ref), value); },
@@ -88,12 +100,12 @@ export function syncRoutes(env) {
88
100
  * T-ui-merge:合并预览 / 合并执行共用的引擎选项。
89
101
  *
90
102
  * 解密密码口径与 /sync/sync 完全一致:请求体优先,其次已保存的 DECRYPT 凭据
91
- * (syncPasswordRef('DECRYPT', channel))。密码只存在于内存,绝不写进响应 / 日志 / 同步文件;
103
+ * (passwordRef('DECRYPT', channel),已按档案作用域)。密码只存在于内存,绝不写进响应 / 日志 / 同步文件;
92
104
  * 明文快照根本不会被解密(引擎只在 manifest.encrypted 时才用密码)。
93
105
  */
94
106
  const mergeEngineOptions = async (body, syncCfg) => {
95
107
  const snapshotId = typeof body['snapshotId'] === 'string' && body['snapshotId'] !== '' ? body['snapshotId'] : undefined;
96
- const savedDecryptPassword = await resolveSyncPassword(syncPasswordRef('DECRYPT', channelOf(syncCfg)));
108
+ const savedDecryptPassword = await resolveSyncPassword(passwordRef('DECRYPT', channelOf(syncCfg)));
97
109
  const decryptPassword = typeof body['decryptPassword'] === 'string' && body['decryptPassword'] !== ''
98
110
  ? body['decryptPassword']
99
111
  : savedDecryptPassword;
@@ -153,8 +165,8 @@ export function syncRoutes(env) {
153
165
  const full = await readFullSyncConfig(syncDir, configIssues);
154
166
  const state = await loadSyncState(syncDir);
155
167
  const [cred, webdavCred] = await Promise.all([
156
- credentials.describe(credentialRef(SYNC_CREDENTIAL_REF)),
157
- credentials.describe(credentialRef(SYNC_WEBDAV_CREDENTIAL_REF)),
168
+ credentials.describe(credentialRef(tokenRef)),
169
+ credentials.describe(credentialRef(webdavPasswordRef)),
158
170
  ]);
159
171
  const transport = parseSyncChannel(full?.transport) ?? 'git';
160
172
  // m-self:插件 UI 偏好(上次选择的同步通道;ui-prefs.json,随 self 分区进备份)
@@ -170,7 +182,7 @@ export function syncRoutes(env) {
170
182
  }
171
183
  : undefined;
172
184
  // 云端点配置视图(只回 secretStored 布尔;与当前通道无关,配置过即回填)
173
- const cloud = await cloudChannelViews(full, credentials);
185
+ const cloud = await cloudChannelViews(full, credentials, cloudSecret);
174
186
  // issue #79 / #104 建议 3:git 工作副本是否已跟随 repoUrl,外加「领先远端提交数 /
175
187
  // 远端快照数」(只读自检;后者是「本地一直没真正备份」的预警依据)。
176
188
  // 读不出来时**如实回传错误**(workDirError),不让状态接口静默少一块信息。
@@ -303,17 +315,17 @@ export function syncRoutes(env) {
303
315
  if (channel === 's3') {
304
316
  // s3 通道断开 → 清掉**全部**兼容商的密钥槽位(该通道不再指向任何一家;幂等)
305
317
  for (const provider of S3_COMPAT_PROVIDERS) {
306
- await credentials.unset(credentialRef(cloudSecretRef(provider)));
318
+ await credentials.unset(credentialRef(cloudSecret(provider)));
307
319
  }
308
320
  }
309
321
  else if (channel === 'gist') {
310
- await credentials.unset(credentialRef(cloudSecretRef(GIST_PROVIDER)));
322
+ await credentials.unset(credentialRef(cloudSecret(GIST_PROVIDER)));
311
323
  }
312
324
  else {
313
- await credentials.unset(credentialRef(channel === 'git' ? SYNC_CREDENTIAL_REF : SYNC_WEBDAV_CREDENTIAL_REF));
325
+ await credentials.unset(credentialRef(channel === 'git' ? tokenRef : webdavPasswordRef));
314
326
  }
315
- await credentials.unset(credentialRef(syncPasswordRef('ENCRYPT', channel)));
316
- await credentials.unset(credentialRef(syncPasswordRef('DECRYPT', channel)));
327
+ await credentials.unset(credentialRef(passwordRef('ENCRYPT', channel)));
328
+ await credentials.unset(credentialRef(passwordRef('DECRYPT', channel)));
317
329
  const auto = await readAutosyncConfig(syncDir, channel);
318
330
  await writeAutosyncConfig(syncDir, channel, { ...auto, enabled: false, consecutiveFailures: 0 });
319
331
  // 立即让调度器丢掉该通道的定时器(否则内存里的旧排期会继续对已删通道发请求)
@@ -337,13 +349,13 @@ export function syncRoutes(env) {
337
349
  // 云端点通道经 CloudSecretWriter 只写端口落库(值绝不进 sync-cloud-config.json / 日志 / 回传)
338
350
  await writeSyncConfig(syncDir, syncCfg, cloudSecrets);
339
351
  const [cred, webdavCred] = await Promise.all([
340
- credentials.describe(credentialRef(SYNC_CREDENTIAL_REF)),
341
- credentials.describe(credentialRef(SYNC_WEBDAV_CREDENTIAL_REF)),
352
+ credentials.describe(credentialRef(tokenRef)),
353
+ credentials.describe(credentialRef(webdavPasswordRef)),
342
354
  ]);
343
355
  // SEC-03:写完就把落盘结果再读一遍(writeSyncConfig 可能因命名空间合并保留旧值),
344
356
  // 成因而非「写成功」才是客户端要显示的真相;字段恒在(默认空数组)。
345
357
  const configIssues = [];
346
- const cloud = await cloudChannelViews(await readFullSyncConfig(syncDir, configIssues), credentials);
358
+ const cloud = await cloudChannelViews(await readFullSyncConfig(syncDir, configIssues), credentials, cloudSecret);
347
359
  writeJson(res, 200, {
348
360
  ok: true,
349
361
  configured: true,
@@ -404,7 +416,7 @@ export function syncRoutes(env) {
404
416
  // 已保存的加密密码兜底(DSH credentials;用户不必每次重输)。请求体里的密码优先,
405
417
  // 因为那是用户此刻输入的覆盖值;两者都没有 → 交给 engine 报「加密需要密码」。
406
418
  const pushChannel = channelOf(syncCfg);
407
- const effectiveEncryptPassword = encryptPassword ?? await resolveSyncPassword(syncPasswordRef('ENCRYPT', pushChannel));
419
+ const effectiveEncryptPassword = encryptPassword ?? await resolveSyncPassword(passwordRef('ENCRYPT', pushChannel));
408
420
  // sessions 的导出参数(「最新 N 个」/ 逐会话点名);**放行**由引擎的 optInSections 决定
409
421
  const sessions = extractSyncSessions(body);
410
422
  const sessionsOpt = sections !== undefined && sections.includes('sessions') && sessions !== undefined
@@ -446,7 +458,7 @@ export function syncRoutes(env) {
446
458
  // 解密密码:请求体 > 已保存(DSH credentials)。明文快照根本不会被解密
447
459
  // (engine.prepareSnapshot 只在 manifest.encrypted 时才用密码),因此「未加密备份
448
460
  // 不会误用密码」是引擎层保证,而不是靠这里猜。密码仅内存,绝不落盘/落日志。
449
- const savedDecryptPassword = await resolveSyncPassword(syncPasswordRef('DECRYPT', channelOf(syncCfg)));
461
+ const savedDecryptPassword = await resolveSyncPassword(passwordRef('DECRYPT', channelOf(syncCfg)));
450
462
  const decryptPassword = typeof body['decryptPassword'] === 'string' && body['decryptPassword'] !== ''
451
463
  ? body['decryptPassword']
452
464
  : savedDecryptPassword;
@@ -501,7 +513,7 @@ export function syncRoutes(env) {
501
513
  }),
502
514
  // -------------------------------------------------- sync/github/poll
503
515
  // m-github-oauth:轮询授权结果。凭 flowId 取回宿主登记的 device_code → GitHub 换 token
504
- // → 成功则立即写入 DSH credentials(SYNC_CREDENTIAL_REF,与手动 token 同槽),
516
+ // → 成功则立即写入 DSH credentials(本档案的 token 槽位,与手动 token 同槽),
505
517
  // token 绝不回传浏览器;pending 返回下次轮询延迟;终止态(denied/expired/error)清理登记。
506
518
  endpoint({ path: '/api/dsh-config-manager/sync/github/poll', methods: ['POST'] }, async (req, res) => {
507
519
  const body = await readJsonBody(req);
@@ -523,7 +535,7 @@ export function syncRoutes(env) {
523
535
  interval: flow.interval,
524
536
  });
525
537
  if (result.status === 'success' && result.accessToken !== undefined) {
526
- await credentials.set(credentialRef(SYNC_CREDENTIAL_REF), result.accessToken);
538
+ await credentials.set(credentialRef(tokenRef), result.accessToken);
527
539
  githubFlows.delete(flowId);
528
540
  host.log.info('GitHub OAuth 登录成功(token 已写入 DSH credentials)');
529
541
  writeJson(res, 200, { status: 'success', credentialConfigured: true });
@@ -558,7 +570,7 @@ export function syncRoutes(env) {
558
570
  writeJson(res, 200, { ok: true });
559
571
  }),
560
572
  // -------------------------------------------------- sync/github/validate
561
- // m-sync-github-valid:校验 SYNC_CREDENTIAL_REF 中已存 token 是否有效(GET /user),
573
+ // m-sync-github-valid:校验本档案 token 槽位中已存 token 是否有效(GET /user),
562
574
  // 供 UI 判定「是否已登录」→ 已登录隐藏 GitHub 登录区块、token 失效则重新展示。
563
575
  // 只回布尔 + 登录名(非敏感),token 值绝不回传;仅 401(无效/过期)→ valid:false,
564
576
  // 其余错误(网络/限流)向上抛,由 UI 兜底(不误判登出)。
@@ -596,7 +608,7 @@ export function syncRoutes(env) {
596
608
  // 仓库选择器(issue:同步通道支持「选择已有仓库 / 新建仓库」):
597
609
  // GET → 列出当前用户可见仓库(按最近更新排序),供 UI 下拉选择;
598
610
  // POST → 新建**私有**仓库(body: { name, description? }),返回仓库信息供回填 repoUrl。
599
- // token 来源与 /sync/github/validate 完全一致(DSH credentials 的 SYNC_CREDENTIAL_REF),
611
+ // token 来源与 /sync/github/validate 完全一致(DSH credentials 的本档案 token 槽位),
600
612
  // 401(未登录 / token 失效)单独映射,其余错误走通用 500 —— 与 me 路由同一口径。
601
613
  // 不进 mutation gate:两步都不写本地文件(只读列举 + 幂等元操作),
602
614
  // 而 gate 在 SAFE MODE 下会直接拒绝,会把「选仓库」变成不可用功能。
@@ -753,7 +765,7 @@ export function syncRoutes(env) {
753
765
  writeJson(res, 400, { error: 'name must be a .zip file name (no path separators)' });
754
766
  return;
755
767
  }
756
- const savedDecryptPassword = await resolveSyncPassword(syncPasswordRef('DECRYPT', channelOf(syncCfg)));
768
+ const savedDecryptPassword = await resolveSyncPassword(passwordRef('DECRYPT', channelOf(syncCfg)));
757
769
  const decryptPassword = typeof body['decryptPassword'] === 'string' && body['decryptPassword'] !== ''
758
770
  ? body['decryptPassword']
759
771
  : savedDecryptPassword;
@@ -846,7 +858,7 @@ export function syncRoutes(env) {
846
858
  // 解密密码:请求体 > 已保存(DSH credentials)。明文快照根本不会被解密
847
859
  // (engine.prepareSnapshot 只在 manifest.encrypted 时才用密码),因此「未加密备份
848
860
  // 不会误用密码」是引擎层保证,而不是靠这里猜。密码仅内存,绝不落盘/落日志。
849
- const savedDecryptPassword = await resolveSyncPassword(syncPasswordRef('DECRYPT', channelOf(syncCfg)));
861
+ const savedDecryptPassword = await resolveSyncPassword(passwordRef('DECRYPT', channelOf(syncCfg)));
850
862
  const decryptPassword = typeof body['decryptPassword'] === 'string' && body['decryptPassword'] !== ''
851
863
  ? body['decryptPassword']
852
864
  : savedDecryptPassword;
@@ -964,7 +976,7 @@ export function syncRoutes(env) {
964
976
  // 拿不到密码就 `suppressAncestor` —— 宁可不留祖先(下轮两方合并),也绝不落明文副本。
965
977
  const applyDecryptPassword = typeof body['decryptPassword'] === 'string' && body['decryptPassword'] !== ''
966
978
  ? body['decryptPassword']
967
- : await resolveSyncPassword(syncPasswordRef('DECRYPT', channelOf(session.config)));
979
+ : await resolveSyncPassword(passwordRef('DECRYPT', channelOf(session.config)));
968
980
  const ancestorOpts = session.encrypted !== true
969
981
  ? {}
970
982
  : applyDecryptPassword !== undefined && applyDecryptPassword !== ''
@@ -1163,8 +1175,8 @@ export function syncRoutes(env) {
1163
1175
  // 加密/解密密码持久化(用户要求:勾选即记住,取消勾选或主动删除才清)。
1164
1176
  // 值只写进 DSH credentials(绝不进 sync-selection.json / 日志 / 响应);
1165
1177
  // 清空优先于写入,避免「同一次请求既清又写」产生歧义。
1166
- const encryptRef = syncPasswordRef('ENCRYPT', channel);
1167
- const decryptRef = syncPasswordRef('DECRYPT', channel);
1178
+ const encryptRef = passwordRef('ENCRYPT', channel);
1179
+ const decryptRef = passwordRef('DECRYPT', channel);
1168
1180
  if (body['clearEncryptPassword'] === true)
1169
1181
  await credentials.unset(credentialRef(encryptRef));
1170
1182
  else if (typeof body['encryptPassword'] === 'string' && body['encryptPassword'] !== '') {
@@ -9,7 +9,7 @@
9
9
  * 据此实现自己的 importer / exporter(ZIP 内路径与文件类分区前缀的唯一权威);
10
10
  * - 取到**分区注册表**(`SECTION_REGISTRY` / `SectionMeta` / `sectionMeta` / `jsonPathOf` /
11
11
  * `PORTABLE_SECTION_IDS` / `OPT_IN_SYNC_SECTION_IDS` / `DEFAULT_INCLUDED_SECTION_IDS` …)——
12
- * 「有哪些分区、各自什么形态/可移植性」的机器可读唯一来源,与 `docs/spec/` 的分区清单对应;
12
+ * 「有哪些分区、各自什么形态/可移植性」的机器可读唯一来源,与 `docs/contracts/` 的分区清单对应;
13
13
  * - 引用 Bundle Format v1 的全部载荷类型。
14
14
  *
15
15
  * 为什么需要它:此前的 `exports["./schema"]` 指向 `./lib/schema/types.js`,而 `types.ts`
@@ -22,7 +22,7 @@
22
22
  * `./versions.ts`)。`section-registry.ts` 自身仍然只 import 一个**类型**(`type { SectionId }`;
23
23
  * 未注册分区的错误文案 t7 起在 `config.ts`,见那里)。
24
24
  * 目标性质是**零 `node:` / 零 npm / 零 @deepseek-ai 依赖**(headless 消费:
25
- * `docs/spec/headless-consumption.md`;client bundle 自包含)。唯一的跨层依赖是本域消息目录
25
+ * `docs/contracts/headless-consumption.md`;client bundle 自包含)。唯一的跨层依赖是本域消息目录
26
26
  * (`./messages.ts` → `../core/engine-locale.ts`,纯函数、零 node / 零 npm),不破坏该性质;
27
27
  * 除此之外不得 import `../core/*`、`node:*` 或任何 UI / DSH 包。
28
28
  */
@@ -9,7 +9,7 @@
9
9
  * 据此实现自己的 importer / exporter(ZIP 内路径与文件类分区前缀的唯一权威);
10
10
  * - 取到**分区注册表**(`SECTION_REGISTRY` / `SectionMeta` / `sectionMeta` / `jsonPathOf` /
11
11
  * `PORTABLE_SECTION_IDS` / `OPT_IN_SYNC_SECTION_IDS` / `DEFAULT_INCLUDED_SECTION_IDS` …)——
12
- * 「有哪些分区、各自什么形态/可移植性」的机器可读唯一来源,与 `docs/spec/` 的分区清单对应;
12
+ * 「有哪些分区、各自什么形态/可移植性」的机器可读唯一来源,与 `docs/contracts/` 的分区清单对应;
13
13
  * - 引用 Bundle Format v1 的全部载荷类型。
14
14
  *
15
15
  * 为什么需要它:此前的 `exports["./schema"]` 指向 `./lib/schema/types.js`,而 `types.ts`
@@ -22,7 +22,7 @@
22
22
  * `./versions.ts`)。`section-registry.ts` 自身仍然只 import 一个**类型**(`type { SectionId }`;
23
23
  * 未注册分区的错误文案 t7 起在 `config.ts`,见那里)。
24
24
  * 目标性质是**零 `node:` / 零 npm / 零 @deepseek-ai 依赖**(headless 消费:
25
- * `docs/spec/headless-consumption.md`;client bundle 自包含)。唯一的跨层依赖是本域消息目录
25
+ * `docs/contracts/headless-consumption.md`;client bundle 自包含)。唯一的跨层依赖是本域消息目录
26
26
  * (`./messages.ts` → `../core/engine-locale.ts`,纯函数、零 node / 零 npm),不破坏该性质;
27
27
  * 除此之外不得 import `../core/*`、`node:*` 或任何 UI / DSH 包。
28
28
  */
@@ -148,7 +148,8 @@ export interface SectionMeta {
148
148
  * 同步准入档位(非 portable 分区的显式准入;portable 分区恒为 'off',走默认通道)。
149
149
  * - 'off' = 永不进入同步通道;
150
150
  * - 'manual' = 必须用户在同步分区弹窗里显式勾选,且**只跟随用户驱动的手动 push/pull**;
151
- * 自动同步永不带(内容隐私 / 设备相关,例如 sessions);
151
+ * 自动同步永不带(内容隐私 / 设备相关,例如 sessions;路径与本机绑定的
152
+ * workspaces 同属 manual —— 它要随会话一起走,但绝不悄悄上下行);
152
153
  * - 'auto' = 用户显式勾选后,手动与自动同步都带(内容可跨机,只是命令 / 路径可能与
153
154
  * 目标机不同,例如 mcp)。
154
155
  * **必填**(Record<SectionId, SectionMeta> 强制):新增分区漏填即 tsc 报错。
@@ -182,7 +183,7 @@ export declare const SECTION_DATA_VERSION: 1;
182
183
  * - `portability` / `defaultIncluded` ← 各 adapter 的 `portability` / `defaultIncluded`,
183
184
  * 以及 `ui/export-flow.ts` 的内置目录、`market/prepare.ts` 的 SECTION_PORTABILITY
184
185
  * (三者此前必须人工保持一致,现以本表为源);
185
- * - `syncOptIn` ← **本表声明**(mcp='auto' / sessions='manual' / 其余 'off'),
186
+ * - `syncOptIn` ← **本表声明**(mcp='auto' / workspaces='manual' / sessions='manual' / 其余 'off'),
186
187
  * `sync/sync-selection.ts` 的 OPT_IN_SYNC_SECTIONS 与 `AUTO_SYNC_OPT_IN_SECTION_IDS` 都是它的派生视图
187
188
  * (此前是两份手写字面量、零护栏 —— issue #78 收敛为单一事实源);
188
189
  * - `applyOrder` ← 历史 SECTION_IDS 数组顺序(1 起,连续)。
@@ -210,7 +211,8 @@ export declare const SECTION_FILE_PREFIXES: Partial<Record<SectionId, string>>;
210
211
  export declare const PORTABLE_SECTION_IDS: readonly SectionId[];
211
212
  /**
212
213
  * 同步「可选分区」:非 portable、必须推/拉两侧显式放行的分区(syncOptIn !== 'off')。
213
- * 当前 = ['mcp', 'sessions']。**顺序按 applyOrder**(mcp=5 在 sessions=14 之前)。
214
+ * 当前 = ['mcp', 'workspaces', 'sessions']。**顺序按 applyOrder**
215
+ * (mcp=5 → workspaces=10 → sessions=14)。
214
216
  */
215
217
  export declare const OPT_IN_SYNC_SECTION_IDS: readonly SectionId[];
216
218
  /**
@@ -8,7 +8,7 @@ export const SECTION_DATA_VERSION = 1;
8
8
  * - `portability` / `defaultIncluded` ← 各 adapter 的 `portability` / `defaultIncluded`,
9
9
  * 以及 `ui/export-flow.ts` 的内置目录、`market/prepare.ts` 的 SECTION_PORTABILITY
10
10
  * (三者此前必须人工保持一致,现以本表为源);
11
- * - `syncOptIn` ← **本表声明**(mcp='auto' / sessions='manual' / 其余 'off'),
11
+ * - `syncOptIn` ← **本表声明**(mcp='auto' / workspaces='manual' / sessions='manual' / 其余 'off'),
12
12
  * `sync/sync-selection.ts` 的 OPT_IN_SYNC_SECTIONS 与 `AUTO_SYNC_OPT_IN_SECTION_IDS` 都是它的派生视图
13
13
  * (此前是两份手写字面量、零护栏 —— issue #78 收敛为单一事实源);
14
14
  * - `applyOrder` ← 历史 SECTION_IDS 数组顺序(1 起,连续)。
@@ -146,7 +146,10 @@ export const SECTION_REGISTRY = {
146
146
  applyOrder: 10,
147
147
  riskTier: 'medium',
148
148
  portability: 'platformSpecific',
149
- syncOptIn: 'off',
149
+ // issue #127:工作区改为**手动可选**同步分区 —— 会话要能在目标机的工作区里显示出来,
150
+ // 包内就必须有指向它 cwd 的工作区记录(DSH 按 realpath(cwd) == workspace.path 归组)。
151
+ // 仍是 platformSpecific(路径与机器绑定,靠 PathMapping 重定基),故只能手动放行、绝不进自动同步。
152
+ syncOptIn: 'manual',
150
153
  defaultIncluded: true,
151
154
  configSnapshot: true,
152
155
  },
@@ -291,7 +294,8 @@ export const SECTION_FILE_PREFIXES = Object.fromEntries(SECTION_IDS
291
294
  export const PORTABLE_SECTION_IDS = SECTION_IDS.filter((id) => SECTION_REGISTRY[id].portability === 'portable');
292
295
  /**
293
296
  * 同步「可选分区」:非 portable、必须推/拉两侧显式放行的分区(syncOptIn !== 'off')。
294
- * 当前 = ['mcp', 'sessions']。**顺序按 applyOrder**(mcp=5 在 sessions=14 之前)。
297
+ * 当前 = ['mcp', 'workspaces', 'sessions']。**顺序按 applyOrder**
298
+ * (mcp=5 → workspaces=10 → sessions=14)。
295
299
  */
296
300
  export const OPT_IN_SYNC_SECTION_IDS = SECTION_IDS.filter((id) => SECTION_REGISTRY[id].syncOptIn !== 'off');
297
301
  /**
@@ -72,7 +72,7 @@ const BEARER_TOKEN_CHARS = '[A-Za-z0-9._~+/=-]';
72
72
  * 于是 `bearer credentials are required` / `bearer authentication failed` / `BEARER HEADER NOT SET`
73
73
  * 这类纯小写或纯大写的英文词**不命中**;而 `bearer abc12345`、`BEARER AbCdEfGh`、`bearer <24+ 字符>` 命中。
74
74
  *
75
- * 已知残余(登记在 `docs/maintenance/known-gaps.md` G-36):scheme 用非规范大小写**且** token 是 8–23 个**纯字母、
75
+ * 已知残余(登记在 `docs/known-issues/known-gaps.md` G-36):scheme 用非规范大小写**且** token 是 8–23 个**纯字母、
76
76
  * 单一大小写**时本条不命中;规范 `Bearer …` 形态不受此限(上面那条 `bearer-token` 只要求 8+ 字符,行为不变)。
77
77
  */
78
78
  const BEARER_TOKEN_ANY_CASE = new RegExp(BEARER_SCHEME_ANY_CASE +
@@ -0,0 +1,50 @@
1
+ /**
2
+ * issue #127:一键同步的临时 ZIP 装配 —— 只装 autoApply 的 merged 载荷,并在「应用了会话」时
3
+ * **伴随**一份 workspaces 载荷。
4
+ *
5
+ * 为什么必须伴随:DSH 把会话显示在工作区里靠「首帧 cwd 的 realpath == workspace.path 且会话 id 在
6
+ * 该记录的 sessionIds 里」,而这条挂接只在导入计划的 workspaces 分区有执行项时才会被
7
+ * `finalizeImport` 触发(analyzer 对零计划项的 adapter 直接跳过)。所以「勾了会话、没勾工作区」
8
+ * 的同步会把会话写进本机,却一条都不显示 —— 用户看到的正是 #127 的现象。
9
+ *
10
+ * 载荷口径:本地现值 ∪ 远端(或本次 merged)记录 —— 走 `mergeWorkspacesSection` 的记录级合并,
11
+ * 于是本机既有工作区不会被覆盖、两侧各自的 sessionIds 都保住(并集)。冲突字段取本地值,
12
+ * 与「不静默覆盖用户本机记录」一致。
13
+ *
14
+ * 边界:本实例没放行 workspaces(构造期 optInSections)或远端压根没有该分区 → 不带伴随载荷,
15
+ * 不越权凭空造工作区。伴随失败**不阻断**主流程(宁可少挂会话,也不让整次同步失败)。
16
+ */
17
+ import type { ConfigAdapter, HostContext } from '../core/types.ts';
18
+ import type { Platform, SectionData, SectionId } from '../schema/types.ts';
19
+ import type { MergeSectionResult } from './merge.ts';
20
+ import type { SyncSnapshot } from './transport.ts';
21
+ /** prepareApplyBundle 的入参:只取装配所需的事实,不把引擎实例漏进来(纯函数好测)。 */
22
+ export interface ApplyBundleInput {
23
+ /** autoApply 的分区(本次真正要写本机的) */
24
+ autoApply: readonly MergeSectionResult[];
25
+ /** 本次 autoApply 的分区 id(返回值会补上伴随分区) */
26
+ baseIds: readonly SectionId[];
27
+ /** 本实例是否放行 workspaces(构造期 optInSections 派生) */
28
+ pullAllowsWorkspaces: boolean;
29
+ /** 计划里待裁决/跳过的项(取其中 merged 作为远端载荷的兜底) */
30
+ planEntries: readonly MergeSectionResult[];
31
+ /** 本次 merge() 记下的远端输入(缺省 = 退回 planEntries 里的 merged) */
32
+ remote: SectionData | undefined;
33
+ ancestor: SectionData | undefined;
34
+ adapter: ConfigAdapter | undefined;
35
+ ctx: HostContext;
36
+ snapshotId: string;
37
+ createdAt: string;
38
+ dshVersion: string;
39
+ platform: Platform;
40
+ /** 远端快照的源机 home('' = 未知,不写进 manifest,跨机重定基自然不发生) */
41
+ sourceHome: string;
42
+ }
43
+ export interface ApplyBundle {
44
+ /** 临时 ZIP 的 sectionIds(可能比 baseIds 多一个 workspaces) */
45
+ sectionIds: SectionId[];
46
+ /** 伴随的 workspaces 载荷(undefined = 本次不需要 / 拿不到) */
47
+ companion: SectionData | undefined;
48
+ tempSnapshot: SyncSnapshot;
49
+ }
50
+ export declare function prepareApplyBundle(input: ApplyBundleInput): Promise<ApplyBundle>;
@@ -0,0 +1,60 @@
1
+ import { CURRENT_SCHEMA_VERSION } from '../schema/versions.js';
2
+ import { mergeWorkspacesSection } from './workspace-merge.js';
3
+ export async function prepareApplyBundle(input) {
4
+ let companion;
5
+ try {
6
+ companion = await companionWorkspaces(input);
7
+ }
8
+ catch {
9
+ companion = undefined;
10
+ }
11
+ const sectionIds = companion === undefined ? [...input.baseIds] : [...input.baseIds, 'workspaces'];
12
+ const sections = {};
13
+ for (const r of input.autoApply) {
14
+ if (r.merged !== undefined)
15
+ sections[r.id] = r.merged;
16
+ }
17
+ if (companion !== undefined)
18
+ sections.workspaces = companion;
19
+ const manifest = {
20
+ schemaVersion: CURRENT_SCHEMA_VERSION,
21
+ dshVersion: input.dshVersion,
22
+ platform: input.platform,
23
+ sectionIds: [...sectionIds],
24
+ containsSecrets: false,
25
+ ...(input.sourceHome !== '' ? { sourceHome: input.sourceHome } : {}),
26
+ };
27
+ return {
28
+ sectionIds,
29
+ companion,
30
+ tempSnapshot: {
31
+ id: input.snapshotId,
32
+ createdAt: input.createdAt,
33
+ manifest,
34
+ sections: sections,
35
+ },
36
+ };
37
+ }
38
+ /** 会话落地时是否/如何带上工作区(口径见文件头;形状不认识就交回远端原样)。 */
39
+ async function companionWorkspaces(input) {
40
+ if (!input.baseIds.includes('sessions') || input.baseIds.includes('workspaces'))
41
+ return undefined;
42
+ if (!input.pullAllowsWorkspaces || input.adapter === undefined)
43
+ return undefined;
44
+ const planEntry = input.planEntries.find((r) => r.id === 'workspaces');
45
+ const remote = input.remote ?? planEntry?.merged;
46
+ if (remote === undefined)
47
+ return undefined;
48
+ let local;
49
+ try {
50
+ local = (await input.adapter.export(input.ctx, { includeSecrets: false })).data;
51
+ }
52
+ catch {
53
+ local = undefined; // 读不到本机现值就只带远端(畸形载荷交给 analyzeImport/validate 如实报错)
54
+ }
55
+ if (local === undefined)
56
+ return remote;
57
+ const merged = mergeWorkspacesSection(local, remote, input.ancestor);
58
+ return merged === undefined ? remote : merged.merged;
59
+ }
60
+ //# sourceMappingURL=apply-bundle.js.map
@@ -268,6 +268,15 @@ export declare class AutoSyncScheduler {
268
268
  * 现在:失败写错误原文;跳过写**结构化原因码**(界面按码取字典,语言在渲染那刻解析);
269
269
  * 成功清空两者(空串/undefined 不进文件,见 autosync-config.toChannelPayload)。
270
270
  */
271
+ /**
272
+ * Phase 1:只读预检 —— 读该通道配置、列远端快照、判断「远端有新 / 本地有改动」。
273
+ *
274
+ * 为什么不持锁:这些步骤全是只读,但 plugins 分区的导出会为本机源(link: / file:)插件跑 npm pack
275
+ * (真机实测 210MB 插件 44.7s/次、每轮重算)。放进 GLOBAL mutation 锁内,60s 一轮的轮询就让锁几乎
276
+ * 全程被占,用户任何 destructive 操作都撞 423(2026-11-07 真机事故的根因)。
277
+ * 结论**不具权威性**:调用方取到锁之后必须重跑一次(见 runOnceInternal 的 Phase 2)。
278
+ */
279
+ private detectPhase;
271
280
  private writeFinalConfig;
272
281
  /**
273
282
  * 连续失败 ≥ 3 → 通知(host.log.warn)。