dsh-config-manager 0.4.2 → 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 (263) hide show
  1. package/README.md +24 -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 +19 -41
  13. package/lib/client.js +863 -722
  14. package/lib/core/access-mode.d.ts +25 -0
  15. package/lib/core/access-mode.js +28 -0
  16. package/lib/core/backup.d.ts +11 -0
  17. package/lib/core/backup.js +27 -0
  18. package/lib/core/env-lock-lifecycle.d.ts +17 -3
  19. package/lib/core/env-lock-lifecycle.js +38 -0
  20. package/lib/core/external-failure.d.ts +9 -0
  21. package/lib/core/external-failure.js +50 -0
  22. package/lib/core/local-plugin-host.d.ts +9 -7
  23. package/lib/core/local-plugin-host.js +109 -15
  24. package/lib/core/local-plugin-pack.d.ts +20 -0
  25. package/lib/core/local-plugin-pack.js +18 -3
  26. package/lib/core/mcp-connector-store.d.ts +13 -0
  27. package/lib/core/mcp-connector-store.js +16 -1
  28. package/lib/core/messages-core.d.ts +45 -0
  29. package/lib/core/messages-core.js +92 -0
  30. package/lib/core/messages.d.ts +1 -0
  31. package/lib/core/messages.js +6 -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-data-registry.d.ts +1 -1
  38. package/lib/core/plugin-data-registry.js +1 -1
  39. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  40. package/lib/core/restore-plan-fingerprint.js +18 -0
  41. package/lib/core/restore-resume.d.ts +1 -1
  42. package/lib/core/restore-resume.js +1 -1
  43. package/lib/core/restore.d.ts +5 -0
  44. package/lib/core/restore.js +4 -1
  45. package/lib/core/types.d.ts +12 -0
  46. package/lib/foreign/claude-sessions.d.ts +1 -1
  47. package/lib/foreign/claude-sessions.js +1 -1
  48. package/lib/foreign/registry.js +1 -1
  49. package/lib/foreign/types.d.ts +1 -1
  50. package/lib/index.d.ts +15 -15
  51. package/lib/index.js +65 -72
  52. package/lib/market/git-file-writer.js +1 -1
  53. package/lib/market/github-repos.js +1 -1
  54. package/lib/market/market-config.js +1 -1
  55. package/lib/market/messages-market.js +1 -1
  56. package/lib/market/my-repo.js +1 -1
  57. package/lib/market/prepare.js +1 -1
  58. package/lib/market/reader.js +2 -2
  59. package/lib/market/repo-url.d.ts +1 -1
  60. package/lib/market/security.js +2 -2
  61. package/lib/market/star-cache.d.ts +1 -1
  62. package/lib/market/types.d.ts +1 -1
  63. package/lib/market/types.js +1 -1
  64. package/lib/market/url.js +1 -1
  65. package/lib/routes/backup.js +17 -9
  66. package/lib/routes/index.d.ts +1 -1
  67. package/lib/routes/kit.d.ts +42 -3
  68. package/lib/routes/kit.js +43 -3
  69. package/lib/routes/market.d.ts +1 -1
  70. package/lib/routes/market.js +3 -60
  71. package/lib/routes/model-tools-deps.d.ts +41 -0
  72. package/lib/routes/model-tools-deps.js +18 -0
  73. package/lib/routes/recovery.js +5 -3
  74. package/lib/routes/request-trust.d.ts +28 -0
  75. package/lib/routes/request-trust.js +65 -0
  76. package/lib/routes/route-support.d.ts +18 -26
  77. package/lib/routes/route-support.js +19 -32
  78. package/lib/routes/snapshots.d.ts +1 -1
  79. package/lib/routes/snapshots.js +4 -40
  80. package/lib/routes/sync.js +40 -28
  81. package/lib/schema/index.d.ts +2 -2
  82. package/lib/schema/index.js +2 -2
  83. package/lib/schema/section-registry.d.ts +5 -3
  84. package/lib/schema/section-registry.js +7 -3
  85. package/lib/security/secret-scanner.js +1 -1
  86. package/lib/sync/apply-bundle.d.ts +50 -0
  87. package/lib/sync/apply-bundle.js +60 -0
  88. package/lib/sync/autosync-scheduler.d.ts +9 -0
  89. package/lib/sync/autosync-scheduler.js +118 -89
  90. package/lib/sync/backup-scheduler.js +5 -4
  91. package/lib/sync/blob-store.d.ts +2 -2
  92. package/lib/sync/git/git-transport.d.ts +12 -0
  93. package/lib/sync/git/git-transport.js +50 -2
  94. package/lib/sync/merge.d.ts +2 -0
  95. package/lib/sync/merge.js +28 -0
  96. package/lib/sync/messages.d.ts +4 -0
  97. package/lib/sync/messages.js +9 -2
  98. package/lib/sync/s3/s3-transport.d.ts +1 -1
  99. package/lib/sync/s3/s3-transport.js +1 -1
  100. package/lib/sync/sync-engine.d.ts +4 -4
  101. package/lib/sync/sync-engine.js +25 -26
  102. package/lib/sync/sync-scope-boot.d.ts +34 -0
  103. package/lib/sync/sync-scope-boot.js +71 -0
  104. package/lib/sync/sync-scope.d.ts +103 -0
  105. package/lib/sync/sync-scope.js +229 -0
  106. package/lib/sync/sync-selection.d.ts +17 -4
  107. package/lib/sync/sync-selection.js +40 -14
  108. package/lib/sync/transport.d.ts +4 -1
  109. package/lib/sync/transport.js +6 -0
  110. package/lib/sync/webdav/webdav-transport.js +1 -1
  111. package/lib/sync/workspace-merge.d.ts +36 -0
  112. package/lib/sync/workspace-merge.js +152 -0
  113. package/lib/ui/backup-schedule.d.ts +13 -2
  114. package/lib/ui/backup-schedule.js +3 -0
  115. package/lib/ui/snapshots-view.d.ts +16 -0
  116. package/lib/ui/snapshots-view.js +21 -0
  117. package/lib/utils/env-lock.d.ts +96 -0
  118. package/lib/utils/env-lock.js +332 -111
  119. package/lib/utils/messages-utils.d.ts +6 -0
  120. package/lib/utils/messages-utils.js +17 -1
  121. package/lib/utils/patch-yaml.js +1 -1
  122. package/lib/utils/zip.js +1 -1
  123. package/package.json +3 -2
  124. package/src/adapters/mcp.test.ts +28 -0
  125. package/src/adapters/mcp.ts +33 -0
  126. package/src/adapters/plugins.test.ts +49 -0
  127. package/src/adapters/plugins.ts +9 -1
  128. package/src/adapters/pnpm-workspace.ts +1 -1
  129. package/src/adapters/self.test.ts +39 -1
  130. package/src/adapters/self.ts +20 -2
  131. package/src/adapters/workspaces.ts +1 -1
  132. package/src/cli/restore-resume.ts +1 -1
  133. package/src/cli/web/page.ts +2 -2
  134. package/src/client/about/AboutPanel.tsx +8 -1
  135. package/src/client/about/about-view.test.ts +1 -1
  136. package/src/client/about/about-view.ts +1 -1
  137. package/src/client/api.ts +1 -6
  138. package/src/client/chat/chat-entry-view.test.ts +1 -1
  139. package/src/client/chat/chat-slots.ts +1 -1
  140. package/src/client/chat/rollback-diff-tab.ts +1 -1
  141. package/src/client/client-types.ts +1 -1
  142. package/src/client/common/access-mode.ts +21 -0
  143. package/src/client/common/routes.ts +1 -5
  144. package/src/client/css-scale-guard.test.ts +1 -1
  145. package/src/client/home/HomePanel.tsx +34 -6
  146. package/src/client/library/ArtifactRow.tsx +14 -2
  147. package/src/client/library/LibraryPanel.tsx +44 -0
  148. package/src/client/locales/about.ts +6 -0
  149. package/src/client/locales/overview.ts +18 -2
  150. package/src/client/locales/sessions.ts +3 -0
  151. package/src/client/market/MyConfigsView.tsx +1 -1
  152. package/src/client/market/market-api.ts +2 -14
  153. package/src/client/market/market-locales.ts +1 -1
  154. package/src/client/market/market-view.ts +3 -3
  155. package/src/client/market/my-configs-api.ts +1 -1
  156. package/src/client/market/my-configs-view.ts +1 -1
  157. package/src/client/recovery/recovery-locales.test.ts +1 -1
  158. package/src/client/run-store.ts +1 -1
  159. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  160. package/src/client/sync/history-model.test.ts +28 -7
  161. package/src/client/sync/history-model.ts +6 -3
  162. package/src/client/sync/sync-locales.ts +10 -4
  163. package/src/client/sync/sync-view.ts +1 -1
  164. package/src/core/access-mode.ts +37 -0
  165. package/src/core/analyzer-cache.test.ts +1 -1
  166. package/src/core/backup.test.ts +45 -1
  167. package/src/core/backup.ts +25 -0
  168. package/src/core/disk-usage.test.ts +2 -0
  169. package/src/core/env-lock-lifecycle.ts +33 -3
  170. package/src/core/external-failure.test.ts +60 -0
  171. package/src/core/external-failure.ts +54 -0
  172. package/src/core/integrity-extra-entries.test.ts +1 -1
  173. package/src/core/local-plugin-host.test.ts +134 -0
  174. package/src/core/local-plugin-host.ts +122 -17
  175. package/src/core/local-plugin-pack.ts +39 -3
  176. package/src/core/mcp-connector-store.ts +26 -1
  177. package/src/core/messages-core.ts +94 -0
  178. package/src/core/messages.ts +6 -0
  179. package/src/core/model-tool-plans.test.ts +111 -0
  180. package/src/core/model-tool-plans.ts +170 -0
  181. package/src/core/model-tools.test.ts +212 -12
  182. package/src/core/model-tools.ts +710 -38
  183. package/src/core/phase3-host.ts +10 -2
  184. package/src/core/phase3-production-integration.test.ts +43 -0
  185. package/src/core/plugin-data-registry.ts +1 -1
  186. package/src/core/restore-plan-fingerprint.ts +19 -0
  187. package/src/core/restore-resume.ts +1 -1
  188. package/src/core/restore.ts +9 -1
  189. package/src/core/types.ts +12 -0
  190. package/src/foreign/claude-sessions.ts +3 -3
  191. package/src/foreign/registry.ts +1 -1
  192. package/src/foreign/types.ts +1 -1
  193. package/src/index.ts +96 -103
  194. package/src/market/git-file-writer.ts +1 -1
  195. package/src/market/github-repos.test.ts +1 -1
  196. package/src/market/github-repos.ts +1 -1
  197. package/src/market/market-config.ts +1 -1
  198. package/src/market/messages-market.ts +1 -1
  199. package/src/market/my-repo.test.ts +1 -1
  200. package/src/market/my-repo.ts +1 -1
  201. package/src/market/prepare.test.ts +1 -1
  202. package/src/market/prepare.ts +1 -1
  203. package/src/market/reader.ts +2 -2
  204. package/src/market/repo-url.ts +1 -1
  205. package/src/market/security.ts +2 -2
  206. package/src/market/star-cache.ts +1 -1
  207. package/src/market/types.ts +1 -1
  208. package/src/market/url.test.ts +1 -1
  209. package/src/market/url.ts +1 -1
  210. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  211. package/src/routes/backup.ts +16 -9
  212. package/src/routes/index.ts +1 -1
  213. package/src/routes/kit.ts +71 -5
  214. package/src/routes/market.ts +2 -59
  215. package/src/routes/model-tools-deps.ts +56 -0
  216. package/src/routes/recovery.ts +5 -3
  217. package/src/routes/request-trust.ts +97 -0
  218. package/src/routes/route-support.ts +49 -36
  219. package/src/routes/snapshots.ts +4 -40
  220. package/src/routes/sync.ts +39 -27
  221. package/src/schema/index.ts +2 -2
  222. package/src/schema/manifest-schema.test.ts +2 -2
  223. package/src/schema/registry.test.ts +1 -1
  224. package/src/schema/section-registry.ts +9 -4
  225. package/src/security/redaction.test.ts +1 -1
  226. package/src/security/secret-scanner.test.ts +2 -2
  227. package/src/security/secret-scanner.ts +1 -1
  228. package/src/sync/apply-bundle.ts +104 -0
  229. package/src/sync/autosync-scheduler.test.ts +180 -6
  230. package/src/sync/autosync-scheduler.ts +132 -92
  231. package/src/sync/backup-scheduler.test.ts +11 -4
  232. package/src/sync/backup-scheduler.ts +5 -4
  233. package/src/sync/blob-store.ts +2 -2
  234. package/src/sync/git/git-transport.test.ts +62 -0
  235. package/src/sync/git/git-transport.ts +54 -3
  236. package/src/sync/merge.ts +29 -0
  237. package/src/sync/messages.ts +9 -2
  238. package/src/sync/s3/s3-transport.ts +1 -1
  239. package/src/sync/sync-engine.test.ts +238 -2
  240. package/src/sync/sync-engine.ts +25 -26
  241. package/src/sync/sync-preview-push.test.ts +2 -1
  242. package/src/sync/sync-scope-boot.ts +87 -0
  243. package/src/sync/sync-scope.test.ts +154 -0
  244. package/src/sync/sync-scope.ts +256 -0
  245. package/src/sync/sync-selection.test.ts +76 -2
  246. package/src/sync/sync-selection.ts +40 -13
  247. package/src/sync/transport.test.ts +21 -1
  248. package/src/sync/transport.ts +12 -0
  249. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  250. package/src/sync/webdav/webdav-transport.ts +1 -1
  251. package/src/sync/workspace-merge.test.ts +110 -0
  252. package/src/sync/workspace-merge.ts +180 -0
  253. package/src/ui/backup-schedule.test.ts +5 -0
  254. package/src/ui/backup-schedule.ts +21 -2
  255. package/src/ui/session-issue-labels.ts +1 -1
  256. package/src/ui/snapshots-view.test.ts +32 -0
  257. package/src/ui/snapshots-view.ts +34 -0
  258. package/src/utils/env-lock.test.ts +242 -9
  259. package/src/utils/env-lock.ts +247 -13
  260. package/src/utils/messages-utils.ts +17 -1
  261. package/src/utils/patch-yaml.ts +1 -1
  262. package/src/utils/zip.ts +1 -1
  263. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -21,31 +21,7 @@ import type { RestoreResumeHint } from '../core/restore-resume.ts';
21
21
  import type { RestoreJournalPort } from '../core/restore-wal.ts';
22
22
  import type { SyncConfig, SyncTransportType } from '../sync/sync-config.ts';
23
23
  import type { AutosyncAutoApplyTier, AutosyncConflictPolicy, AutosyncInterval, AutosyncRunStatus } from '../sync/autosync-config.ts';
24
- /**
25
- * 同步 token 的 DSH credentials 引用名(POSIX env-var 形态,满足 CredentialRef 品牌要求)。
26
- * token 只经 credentialRef 读写(写入由请求体触发,读取在每次 git 网络操作时 resolve),
27
- * 永不进 repoUrl / argv / commit / 同步文件 / 日志。
28
- */
29
- export declare const SYNC_CREDENTIAL_REF = "DSH_CONFIG_MANAGER_SYNC_TOKEN";
30
- /**
31
- * WebDAV 通道口令的独立 DSH credentials 引用(与 git token 槽位分离)。
32
- * 口令只经 credentialRef 读写(写入由请求体触发,读取在每次 WebDAV 网络操作时
33
- * by WebDavTransport 经注入的 getPassword() resolve),永不进 URL / 请求头 / 日志。
34
- */
35
- export declare const SYNC_WEBDAV_CREDENTIAL_REF = "DSH_CONFIG_MANAGER_SYNC_WEBDAV_PASSWORD";
36
- /**
37
- * 同步快照「加密密码 / 解密密码」的 DSH credentials 引用名前缀(按通道各自独立)。
38
- *
39
- * 为什么放 DSH credentials:加密/解密密码跨会话必须可用(否则每次推送都要重新输入),
40
- * 但**绝不允许**写进 sync-selection.json 一类同步文件(那等于把密码推上远端)。
41
- * 与本插件既有的 token / WebDAV 口令同一套做法:值只存在于 DSH 凭据库,
42
- * 宿主内部按需 resolve,**永不回传浏览器**(UI 只拿到 configured 布尔)。
43
- * 引用名形如 DSH_CONFIG_MANAGER_SYNC_ENCRYPT_PASSWORD_GIT。
44
- */
45
- export declare const SYNC_ENCRYPT_PASSWORD_REF_PREFIX = "DSH_CONFIG_MANAGER_SYNC_ENCRYPT_PASSWORD";
46
- export declare const SYNC_DECRYPT_PASSWORD_REF_PREFIX = "DSH_CONFIG_MANAGER_SYNC_DECRYPT_PASSWORD";
47
- /** ('ENCRYPT'|'DECRYPT', 'git'|'webdav') → 该通道的凭据引用名。 */
48
- export declare function syncPasswordRef(kind: 'ENCRYPT' | 'DECRYPT', channel: SyncTransportType): string;
24
+ export { SYNC_CREDENTIAL_REF, SYNC_DECRYPT_PASSWORD_REF_PREFIX, SYNC_ENCRYPT_PASSWORD_REF_PREFIX, SYNC_WEBDAV_CREDENTIAL_REF, scopedSyncRef, syncPasswordRef, syncScopeOrDefault, } from '../sync/sync-scope.ts';
49
25
  /**
50
26
  * 档案路由的错误响应:engine 的 DshProfileError 带 code(UI 据此映射本地化文案,
51
27
  * 不显示裸英文码);其它异常按 500 处理。
@@ -274,9 +250,25 @@ export declare function executeRestorePlan(plan: RestorePlan, exec: RestoreExecu
274
250
  }) => void, journal?: RestoreJournalPort, resumeHint?: RestoreResumeHint): Promise<RestoreReport>;
275
251
  /** 宿主 restore 执行器装配:ctx.fs(home-relative)+ 快照目录(node fs)+ runDshPlugin。 */
276
252
  export declare function makeRestoreExecutor(snapshotDir: string, host: HostContext, profile: string): RestoreExecutor;
277
- /** parseSyncBody 的凭据写入依赖(只用到 set;测试可注入内存 mock)。 */
253
+ /**
254
+ * parseSyncBody 的凭据写入依赖(只用到 set;测试可注入内存 mock)。
255
+ */
278
256
  export interface ParseSyncBodyDeps {
279
257
  credentials: Pick<CredentialProvider, 'set'>;
258
+ /**
259
+ * per-profile 作用域:只决定**写哪个凭据槽位**,不影响请求体形状与返回值。
260
+ * 缺省 = 历史(不带后缀)槽位名 —— 单档案用户与既有测试的行为逐字不变。
261
+ */
262
+ scope?: SyncRefScope;
263
+ }
264
+ /** 把历史槽位名映射到当前档案的最小接口(`SyncScope` 结构上即满足)。 */
265
+ export interface SyncRefScope {
266
+ /** 本档案的 git / GitHub token 槽位 */
267
+ tokenRef: string;
268
+ /** 本档案的 WebDAV 口令槽位 */
269
+ webdavPasswordRef: string;
270
+ /** 历史槽位名 → 本档案槽位名(云端点密钥等按需映射) */
271
+ scopeRef(ref: string): string;
280
272
  }
281
273
  /**
282
274
  * 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
@@ -33,33 +33,12 @@ import { resolveProfileDir, runDshPlugin } from '../core/plugin-cli.js';
33
33
  import { isSameOrChild } from '../utils/paths.js';
34
34
  import { parseZip } from '../utils/zip.js';
35
35
  /**
36
- * 同步 token 的 DSH credentials 引用名(POSIX env-var 形态,满足 CredentialRef 品牌要求)。
37
- * token 只经 credentialRef 读写(写入由请求体触发,读取在每次 git 网络操作时 resolve),
38
- * 永不进 repoUrl / argv / commit / 同步文件 / 日志。
36
+ * 同步凭据槽位名与 per-profile 作用域:**唯一声明处已迁到 `src/sync/sync-scope.ts`**
37
+ * (那里也持有 `syncScopeFor` / `adoptLegacySyncScope`)。此文件只 re-export,
38
+ * 保持 `src/index.ts` 与测试既有的 import 面与符号名不变(值不变,只是多了可选档案后缀)。
39
39
  */
40
- export const SYNC_CREDENTIAL_REF = 'DSH_CONFIG_MANAGER_SYNC_TOKEN';
41
- /**
42
- * WebDAV 通道口令的独立 DSH credentials 引用(与 git token 槽位分离)。
43
- * 口令只经 credentialRef 读写(写入由请求体触发,读取在每次 WebDAV 网络操作时
44
- * by WebDavTransport 经注入的 getPassword() resolve),永不进 URL / 请求头 / 日志。
45
- */
46
- export const SYNC_WEBDAV_CREDENTIAL_REF = 'DSH_CONFIG_MANAGER_SYNC_WEBDAV_PASSWORD';
47
- /**
48
- * 同步快照「加密密码 / 解密密码」的 DSH credentials 引用名前缀(按通道各自独立)。
49
- *
50
- * 为什么放 DSH credentials:加密/解密密码跨会话必须可用(否则每次推送都要重新输入),
51
- * 但**绝不允许**写进 sync-selection.json 一类同步文件(那等于把密码推上远端)。
52
- * 与本插件既有的 token / WebDAV 口令同一套做法:值只存在于 DSH 凭据库,
53
- * 宿主内部按需 resolve,**永不回传浏览器**(UI 只拿到 configured 布尔)。
54
- * 引用名形如 DSH_CONFIG_MANAGER_SYNC_ENCRYPT_PASSWORD_GIT。
55
- */
56
- export const SYNC_ENCRYPT_PASSWORD_REF_PREFIX = 'DSH_CONFIG_MANAGER_SYNC_ENCRYPT_PASSWORD';
57
- export const SYNC_DECRYPT_PASSWORD_REF_PREFIX = 'DSH_CONFIG_MANAGER_SYNC_DECRYPT_PASSWORD';
58
- /** ('ENCRYPT'|'DECRYPT', 'git'|'webdav') → 该通道的凭据引用名。 */
59
- export function syncPasswordRef(kind, channel) {
60
- const prefix = kind === 'ENCRYPT' ? SYNC_ENCRYPT_PASSWORD_REF_PREFIX : SYNC_DECRYPT_PASSWORD_REF_PREFIX;
61
- return prefix + '_' + channel.toUpperCase();
62
- }
40
+ import { SYNC_CREDENTIAL_REF, SYNC_WEBDAV_CREDENTIAL_REF, } from '../sync/sync-scope.js';
41
+ export { SYNC_CREDENTIAL_REF, SYNC_DECRYPT_PASSWORD_REF_PREFIX, SYNC_ENCRYPT_PASSWORD_REF_PREFIX, SYNC_WEBDAV_CREDENTIAL_REF, scopedSyncRef, syncPasswordRef, syncScopeOrDefault, } from '../sync/sync-scope.js';
63
42
  /* 路由基础设施(loopback 围栏 / writeJson / readJsonBody / queryParam / endpoint / 错误映射)
64
43
  * 已收敛到 src/routes/kit.ts —— 全仓只有那一份实现。 */
65
44
  /**
@@ -644,6 +623,10 @@ export function makeRestoreExecutor(snapshotDir, host, profile) {
644
623
  * 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
645
624
  */
646
625
  export async function parseSyncBody(body, deps) {
626
+ // per-profile 槽位(缺省 = 历史槽位名;请求体形状与返回值与档案无关)
627
+ const scope = deps.scope;
628
+ const tokenRef = scope === undefined ? SYNC_CREDENTIAL_REF : scope.tokenRef;
629
+ const webdavPasswordRef = scope === undefined ? SYNC_WEBDAV_CREDENTIAL_REF : scope.webdavPasswordRef;
647
630
  const rawTransport = body['transport'];
648
631
  // 通道值解析:接受通道名(s3/gist);也接受**具体兼容商**(oss/cos/minio/kodo)直接落到 s3 通道
649
632
  const transport = parseSyncChannel(rawTransport) ?? (isS3CompatProvider(rawTransport) ? 's3' : 'git');
@@ -662,11 +645,11 @@ export async function parseSyncBody(body, deps) {
662
645
  const password = typeof body['password'] === 'string' && body['password'] !== '' ? body['password'] : undefined;
663
646
  if (password !== undefined) {
664
647
  try {
665
- await deps.credentials.set(credentialRef(SYNC_WEBDAV_CREDENTIAL_REF), password);
648
+ await deps.credentials.set(credentialRef(webdavPasswordRef), password);
666
649
  }
667
650
  catch (error) {
668
651
  const reason = error instanceof Error ? error.message : String(error);
669
- throw new SyncRouteError(engineMsg('host.syncWebdavPasswordWriteFailed', { reason, ref: SYNC_WEBDAV_CREDENTIAL_REF }));
652
+ throw new SyncRouteError(engineMsg('host.syncWebdavPasswordWriteFailed', { reason, ref: webdavPasswordRef }));
670
653
  }
671
654
  }
672
655
  return {
@@ -685,11 +668,11 @@ export async function parseSyncBody(body, deps) {
685
668
  const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined;
686
669
  if (token !== undefined) {
687
670
  try {
688
- await deps.credentials.set(credentialRef(SYNC_CREDENTIAL_REF), token);
671
+ await deps.credentials.set(credentialRef(tokenRef), token);
689
672
  }
690
673
  catch (error) {
691
674
  const reason = error instanceof Error ? error.message : String(error);
692
- throw new SyncRouteError(engineMsg('host.syncTokenWriteFailed', { reason, ref: SYNC_CREDENTIAL_REF }));
675
+ throw new SyncRouteError(engineMsg('host.syncTokenWriteFailed', { reason, ref: tokenRef }));
693
676
  }
694
677
  }
695
678
  return {
@@ -702,6 +685,10 @@ export async function parseSyncBody(body, deps) {
702
685
  function syncStr(value) {
703
686
  return typeof value === 'string' ? value.trim() : '';
704
687
  }
688
+ /** 云端点密钥槽位按档案映射(无 scope = 历史槽位名,单档案行为逐字不变)。 */
689
+ function scopedCloudSecretRef(ref, deps) {
690
+ return deps.scope === undefined ? ref : deps.scope.scopeRef(ref);
691
+ }
705
692
  /** 云端点密钥写入失败 → 可操作错误(**含 ref 名、绝不含密钥值**)。 */
706
693
  function cloudCredentialWriteError(ref, kind, error) {
707
694
  const reason = error instanceof Error ? error.message : String(error);
@@ -739,7 +726,7 @@ async function parseCloudS3Body(body, rawTransport, deps) {
739
726
  throw new SyncRouteError(issue, 400, issue);
740
727
  const secret = typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined;
741
728
  if (secret !== undefined) {
742
- const ref = cloudSecretRef(provider);
729
+ const ref = scopedCloudSecretRef(cloudSecretRef(provider), deps);
743
730
  try {
744
731
  await deps.credentials.set(credentialRef(ref), secret);
745
732
  }
@@ -781,7 +768,7 @@ async function parseCloudGistBody(body, deps) {
781
768
  ? body['token']
782
769
  : (typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined);
783
770
  if (token !== undefined) {
784
- const ref = cloudSecretRef(GIST_PROVIDER);
771
+ const ref = scopedCloudSecretRef(cloudSecretRef(GIST_PROVIDER), deps);
785
772
  try {
786
773
  await deps.credentials.set(credentialRef(ref), token);
787
774
  }
@@ -1,5 +1,5 @@
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 在注册点统一提供。
@@ -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>;