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
@@ -17,6 +17,7 @@ import { inspectStartup } from './reconcile.js';
17
17
  import { OWNERSHIP_FILE } from '../utils/env-lock.js';
18
18
  import { sha256Hex } from '../utils/hashing.js';
19
19
  import { engineMsg } from './messages-core.js';
20
+ import { isLocalOnlyExternalFailure } from './external-failure.js';
20
21
  /** 存在未收敛的 active transaction → 拒绝创建第二个(active≤1)。 */
21
22
  export class TransactionRecoveryRequiredError extends Error {
22
23
  constructor(opId) {
@@ -566,8 +567,15 @@ export class Phase3Recovery {
566
567
  return { operationId: opId, result };
567
568
  }
568
569
  catch (err) {
569
- this.safeModeActive = true;
570
- await this.store.writeSafeMode(true).catch(() => undefined);
570
+ // 本地可修的配置类失败(如本机没设 git 身份)不升全局阻断:它由本机配置直接修好,
571
+ // 也不会让磁盘停在半写状态。无条件升 durable SAFE MODE 会把「本机缺一个 git 用户名」
572
+ // 放大成「全部写入 423,直到手动解除阻断」,而界面还说是「环境锁被占用」——
573
+ // 真机 issue 的链路就是这样(locks 目录为空却报锁,见 core/external-failure.ts)。
574
+ // 除该判据之外的一切失败保持 fail-closed(照旧 durable SAFE MODE,跨重启生效)。
575
+ if (!isLocalOnlyExternalFailure(err)) {
576
+ this.safeModeActive = true;
577
+ await this.store.writeSafeMode(true).catch(() => undefined);
578
+ }
571
579
  const rolledBack = rollbackOutcome.value;
572
580
  if (rolledBack !== null) {
573
581
  // 引擎已就地回滚但随后抛错:终态仍是 ROLLED_BACK —— 不把「已知结论:已回滚」误报成
@@ -116,7 +116,7 @@ export declare function areaOfPath(entries: readonly {
116
116
  /**
117
117
  * 解析一个已安装插件 package.json 里的自述声明(dsh.dataDirs)—— 「让别的插件自己适配」的钩子。
118
118
  *
119
- * 契约(对外文档见 docs/spec/plugin-data-declaration.md):
119
+ * 契约(对外文档见 docs/contracts/plugin-data-declaration.md):
120
120
  * { "dsh": { "dataDirs": [ { "path": ".my-plugin", "role": "config", "env": ["MY_PLUGIN_DIR"] } ] } }
121
121
  *
122
122
  * 形状不认识就整条丢弃(返回 null),绝不猜;path 非法(绝对路径 / .. / 空段)同样丢弃。
@@ -157,7 +157,7 @@ export function areaOfPath(entries, rel) {
157
157
  /**
158
158
  * 解析一个已安装插件 package.json 里的自述声明(dsh.dataDirs)—— 「让别的插件自己适配」的钩子。
159
159
  *
160
- * 契约(对外文档见 docs/spec/plugin-data-declaration.md):
160
+ * 契约(对外文档见 docs/contracts/plugin-data-declaration.md):
161
161
  * { "dsh": { "dataDirs": [ { "path": ".my-plugin", "role": "config", "env": ["MY_PLUGIN_DIR"] } ] } }
162
162
  *
163
163
  * 形状不认识就整条丢弃(返回 null),绝不猜;path 非法(绝对路径 / .. / 空段)同样丢弃。
@@ -0,0 +1,2 @@
1
+ import type { RestorePlan } from './restore.ts';
2
+ export declare function restorePlanFingerprint(plan: Pick<RestorePlan, 'actions'>): string;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 恢复计划指纹 —— 预览与执行之间的**唯一**一致性判据。
3
+ *
4
+ * 只取「动作类型 + 目标 + blob」三列:描述文案、detail、manualHint 这些展示字段不进指纹
5
+ * (改一句文案不该让用户已经做过的确认失效),动作的**集合**才是实质 —— 多一个
6
+ * hostFileRemove / fileRemove,少一个还原,都说明磁盘在预览之后变了,必须重新确认。
7
+ *
8
+ * 为什么必须只有一处实现:GUI 恢复路由(src/routes/snapshots.ts 的 dry-run 与执行)
9
+ * 与 agent 工具(src/core/model-tools.ts 的 config_restore)算的必须是同一个值。
10
+ * 两处各写一份,只要有一处漏了 blobPath 或换了分隔符,「预览时算的」和「执行时验的」
11
+ * 就不是同一个东西 —— 防呆看着在,实际要么永远不触发,要么永远误触发。
12
+ */
13
+ import { createHash } from 'node:crypto';
14
+ export function restorePlanFingerprint(plan) {
15
+ const lines = plan.actions.map((action) => [action.kind, action.target ?? '', action.blobPath ?? ''].join('\u0000'));
16
+ return createHash('sha256').update(lines.join('\n')).digest('hex');
17
+ }
18
+ //# sourceMappingURL=restore-plan-fingerprint.js.map
@@ -16,7 +16,7 @@
16
16
  * 任何 step ⇒ 上次连第一个写都没发生(WAL 预登记在首个写之前)⇒ 可以整笔重跑;
17
17
  * 一旦出现 step 却处在这两个状态,说明 journal 被外部改过(不可信)⇒ 拒绝。
18
18
  * - NEEDS_ATTENTION / ROLLING_BACK / RECOVERING 一律拒绝:那些是「需要人决策」的态,
19
- * 自动续跑会绕过恢复面板的判定(见 docs/decisions/0004)。
19
+ * 自动续跑会绕过恢复面板的判定(见 docs/adr/0004)。
20
20
  * - pluginRemove 是外部副作用(可能只改了 package.json 还没 prune node_modules),
21
21
  * 无指纹可证 ⇒ 含它的恢复**永不自动续跑**,仍交由恢复面板处理。
22
22
  */
@@ -16,7 +16,7 @@
16
16
  * 任何 step ⇒ 上次连第一个写都没发生(WAL 预登记在首个写之前)⇒ 可以整笔重跑;
17
17
  * 一旦出现 step 却处在这两个状态,说明 journal 被外部改过(不可信)⇒ 拒绝。
18
18
  * - NEEDS_ATTENTION / ROLLING_BACK / RECOVERING 一律拒绝:那些是「需要人决策」的态,
19
- * 自动续跑会绕过恢复面板的判定(见 docs/decisions/0004)。
19
+ * 自动续跑会绕过恢复面板的判定(见 docs/adr/0004)。
20
20
  * - pluginRemove 是外部副作用(可能只改了 package.json 还没 prune node_modules),
21
21
  * 无指纹可证 ⇒ 含它的恢复**永不自动续跑**,仍交由恢复面板处理。
22
22
  */
@@ -143,6 +143,11 @@ export interface SnapshotMeta {
143
143
  entryCount: number;
144
144
  hostFileBackupCount: number;
145
145
  beforePluginCount: number;
146
+ /**
147
+ * 来源档案(originProfile):拍这份快照的进程所属 profile 名。
148
+ * 旧快照 / 宿主不暴露 profile 时缺省 —— 界面按「未标注」展示,绝不写 'unknown' 占位。
149
+ */
150
+ originProfile?: string;
146
151
  /** 置顶标记(P1-⑧):置顶快照不参与自动保留清理(最多保留 N 个时的淘汰豁免) */
147
152
  pinned?: boolean;
148
153
  }
@@ -24,7 +24,7 @@ import { engineMsg } from './messages-core.js';
24
24
  import fssync from 'node:fs';
25
25
  import fs from 'node:fs/promises';
26
26
  import path from 'node:path';
27
- import { normalizeDshVersion, resolveFileTarget, verifySnapshot } from './backup.js';
27
+ import { normalizeDshVersion, normalizeOriginProfile, resolveFileTarget, verifySnapshot } from './backup.js';
28
28
  import { isPatchLayerRel } from './patch-layers.js';
29
29
  import { expectedSessionRefs, sweepGhostSessions } from './ghost-sweep.js';
30
30
  import { zhMsg } from './messages.js';
@@ -915,6 +915,8 @@ export async function listSnapshots(dir, out) {
915
915
  const snapshot = parsed;
916
916
  if (typeof snapshot.id !== 'string' || snapshot.id === '')
917
917
  continue;
918
+ // 来源档案:旧快照没有该字段是常态 → 缺省(不写占位值,列表照常可读)。
919
+ const originProfile = normalizeOriginProfile(snapshot.originProfile);
918
920
  metas.push({
919
921
  id: snapshot.id,
920
922
  createdAt: snapshot.createdAt,
@@ -923,6 +925,7 @@ export async function listSnapshots(dir, out) {
923
925
  entryCount: snapshot.entries?.length ?? 0,
924
926
  hostFileBackupCount: snapshot.hostFileBackups?.length ?? 0,
925
927
  beforePluginCount: snapshot.beforePlugins?.length ?? 0,
928
+ ...(originProfile !== undefined ? { originProfile } : {}),
926
929
  pinned: snapshot.pinned === true,
927
930
  });
928
931
  }
@@ -1062,6 +1062,18 @@ export interface Snapshot {
1062
1062
  * 绝不写 'unknown' 之类的占位值,否则恢复时会拿占位值当「已知版本」误报版本不同。
1063
1063
  */
1064
1064
  dshVersion?: string;
1065
+ /**
1066
+ * 拍这份快照时**所属档案名**(originProfile;可选)。
1067
+ *
1068
+ * 为什么需要:插件数据目录 `$DSH_HOME/dsh-config-manager` 被所有 DSH profile 共用,
1069
+ * 快照库会混进 web / desktop / Test1 等多个档案的条目 —— 不记来源就分不清哪条属于谁。
1070
+ * 三条硬边界(与 dshVersion 同口径):
1071
+ * ① **必须可选**:旧快照没有这个字段是常态,旧快照的列表与恢复路径一字不变;
1072
+ * ② 值只写**能证明的真实档案名**(宿主 `HostContext.profile`);取不到时**不写** ——
1073
+ * 绝不写 'unknown' 之类的占位值,否则界面会把「不知道」当成一个真实档案去分组与筛选;
1074
+ * ③ 只用于**标注与筛选**,绝不参与恢复/保留判定(来自他人档案的快照照样可恢复)。
1075
+ */
1076
+ originProfile?: string;
1065
1077
  /** 置顶标记(P1-⑧):置顶快照在保留清理(自动删最旧)中豁免,需用户手动删除 */
1066
1078
  pinned?: boolean;
1067
1079
  /** 绑定 upgrade operation(journal.operationId ↔ snapshot.operationId) */
@@ -37,7 +37,7 @@
37
37
  * ③ **sessionId 不一致**:`input.recordSessionId` 存在且 ≠ `input.id` → 非致命发现
38
38
  * `session-id-mismatch`(会话 id 仍以文件名 stem 为准,见 `TranscodeResult.findings`)。
39
39
  * ④ **推理块**(Claude Code 的 `thinking` / `redacted_thinking`):共享 IR 没有 reasoning
40
- * 承载位(docs/maintenance/known-gaps.md F-01)→ 计报 `thinking`,**绝不伪装成正文**;非 Claude 原生的
40
+ * 承载位(docs/known-issues/known-gaps.md F-01)→ 计报 `thinking`,**绝不伪装成正文**;非 Claude 原生的
41
41
  * `{type:'reasoning',text:…}` 刻意保持既有口径(理由与切换方式见 `REASONING_BLOCK_TYPES`)。
42
42
  */
43
43
  import type { Stats } from 'node:fs';
@@ -28,7 +28,7 @@ function usageField(usage, key) {
28
28
  * 沿「对象带 text 才算文本」的兜底把它变成一个**空文本块** —— 内容静默丢失,且那个空块还会多插入
29
29
  * 一个换行。本仓其余 20+ 来源一律「推理不伪装成正文、只计数」(read-crush / read-opencode /
30
30
  * read-qwen / read-pi / read-openclaw …),这里对齐同一口径;共享 IR 无 reasoning 承载位这件事
31
- * 记在 docs/maintenance/known-gaps.md 的 F-01。
31
+ * 记在 docs/known-issues/known-gaps.md 的 F-01。
32
32
  *
33
33
  * **为什么不把 `{type:'reasoning', text:'…'}` 一并纳入**(如实记明,别当成漏掉):
34
34
  * ① Claude Code 不写这种块(它是别的导出器的归一命名,各来源自己的解析器已各自计报);
@@ -17,7 +17,7 @@
17
17
  * (回退会让用户以为导的是 A、实际导的是 B)。
18
18
  *
19
19
  * 契约正文(六来源路径真值表 / 冲突语义 / 单元 id 向后兼容)见
20
- * docs/design/2026-10-04-foreign-import-v1.md §8。
20
+ * docs/archive/2026-10-04-foreign-import-v1.md §8。
21
21
  */
22
22
  import fs from 'node:fs/promises';
23
23
  import path from 'node:path';
@@ -28,7 +28,7 @@ import type { ParsedTranscript } from './session-source.ts';
28
28
  * (claude → claude-code、dsh/dsh4 → 同源两代次)。
29
29
  *
30
30
  * **取证强度逐来源如实标注**(见 registry.ts 的 ForeignSource.evidence 与
31
- * docs/design/2026-10-04-foreign-import-v1.md §8.2 的真值表):
31
+ * docs/archive/2026-10-04-foreign-import-v1.md §8.2 的真值表):
32
32
  * - measured :本机实测(目录/库确实存在过,且读盘层据此实现)
33
33
  * - fixture :真机未验证,但有**可复现取证方式**(夹具 + 单测端到端跑同一份布局)
34
34
  * - documented:只有四份调研报告的落点(尚未有可复现夹具时**必须**是这个值)
package/lib/index.d.ts CHANGED
@@ -37,23 +37,20 @@
37
37
  import type { IncomingMessage, ServerResponse } from 'node:http';
38
38
  import type { Context } from '@deepseek-ai/cordis';
39
39
  import type { CredentialProvider } from '@deepseek-ai/dsh-credentials';
40
- import type { RecoveryOrchestrator } from './core/recovery-orchestrator.ts';
41
- import type { Portability } from './core/types.ts';
42
40
  import { Importer } from './core/index.ts';
43
41
  import { DshProfileLauncher, DshProfileManager, DshProfileRuntimeRegistry } from './profiles/index.ts';
44
- import type { BootSafetyReport } from './core/boot-safety.ts';
45
- import { type RecoveryExecutorFns } from './core/recovery-orchestrator.ts';
42
+ import { type BootSafetyReport } from './core/boot-safety.ts';
43
+ import { type RecoveryExecutorFns, type RecoveryOrchestrator } from './core/recovery-orchestrator.ts';
46
44
  import { RunRegistry } from './core/run-registry.ts';
47
- import type { MsgFunc } from './core/messages.ts';
45
+ import { type MsgFunc } from './core/messages.ts';
48
46
  import { runDshPlugin } from './core/plugin-cli.ts';
49
- import type { ConfigAdapter, CredentialsFacade, FileSystemFacade, HostContext, PatchFileFacade, PluginInfo, PluginsFacade, SessionMoveResult, SessionParentRelation, SessionRewriteResult, SessionStoreFacade, SettingsFacade, SkillStoreFacade, WorkspaceFacade } from './core/types.ts';
50
- import type { SelfUpdateOutcome } from './core/self-update.ts';
51
- import type { SessionMetaIndex } from './core/session-meta.ts';
52
- import { type MutationLockContext } from './utils/env-lock.ts';
47
+ import { type ConfigAdapter, type CredentialsFacade, type FileSystemFacade, type HostContext, type PatchFileFacade, type PluginInfo, type PluginsFacade, type Portability, type SessionMoveResult, type SessionParentRelation, type SessionRewriteResult, type SessionStoreFacade, type SettingsFacade, type SkillStoreFacade, type WorkspaceFacade } from './core/types.ts';
48
+ import { type SelfUpdateOutcome } from './core/self-update.ts';
49
+ import { type SessionMetaIndex } from './core/session-meta.ts';
50
+ import { type MutationLockContext, type MutationLockPort } from './utils/env-lock.ts';
51
+ import { type RecursiveListing } from './utils/recursive-walk.ts';
53
52
  import type { JournalRunContext } from './core/phase3-host.ts';
54
- import type { MutationLockPort } from './utils/env-lock.ts';
55
- import type { RecursiveListing } from './utils/recursive-walk.ts';
56
- import type { GitWorkDirFacts } from './sync/git/git-transport.ts';
53
+ import { type GitWorkDirFacts } from './sync/git/git-transport.ts';
57
54
  import { DeviceFlowStore, GitHubAuthClient } from './sync/github-auth.ts';
58
55
  import { SyncEngine } from './sync/sync-engine.ts';
59
56
  import { SyncSessionStore } from './sync/sync-session.ts';
@@ -67,9 +64,10 @@ import type { MarketIndex, MarketSummary } from './market/types.ts';
67
64
  import { GitHubAuthRest } from './market/github-repos.ts';
68
65
  import { MyRepoService } from './market/my-repo.ts';
69
66
  import { StarCache } from './market/star-cache.ts';
70
- import type { ConfiguredSecretPatterns } from './security/secret-scanner.ts';
67
+ import { type ConfiguredSecretPatterns } from './security/secret-scanner.ts';
71
68
  import type { SectionId } from './schema/types.ts';
72
69
  import { type Logger } from './utils/logger.ts';
70
+ import { type SyncScope } from './sync/sync-scope.ts';
73
71
  export { ROUTE_TIMEOUT_MS, REVIEW_KINDS, SYNC_CREDENTIAL_REF, SYNC_ENCRYPT_PASSWORD_REF_PREFIX, SYNC_DECRYPT_PASSWORD_REF_PREFIX, SYNC_WEBDAV_CREDENTIAL_REF, SyncRouteError, buildAutosyncStatus, buildAutosyncStatusByChannel, buildFileDiffBody, buildRestoreBody, credentialRef, decryptErrorText, executeRestorePlan, extractSyncSections, extractSyncSessions, isAutosyncInterval, isControlledPath, isGitHubAuthMissing, isToolchainChangeItem, makeRestoreExecutor, parseMeForm, planToConfirmItems, safeCredentialRef, sessionHealthNextSteps, syncPasswordRef, tryDecryptCredentials, withTimeout, writeProfileError, writeRequestBodyToFile, writeSyncRouteError } from './routes/route-support.ts';
74
72
  export type { AutosyncStatusResponse, BuildFileDiffBodyResult, BuildRestoreBodyResult, RestoreExecutor, SyncConfirmItem } from './routes/route-support.ts';
75
73
  /** Stable cordis plugin name — must match the cordis.patch.yml row id. */
@@ -77,7 +75,7 @@ export declare const name = "config-manager";
77
75
  /** Services required before the engine can mount (present in every profile). */
78
76
  export declare const inject: string[];
79
77
  /** Plugin version, kept in sync with package.json ("version"). */
80
- export declare const PLUGIN_VERSION = "0.4.2";
78
+ export declare const PLUGIN_VERSION = "0.5.0";
81
79
  /**
82
80
  * Star 引导弹窗指向的 GitHub 仓库(用户引导点 Star 的目标)。
83
81
  * 与 package.json 的 repository 字段保持一致;界面不可改(硬编码,参照
@@ -130,7 +128,7 @@ export interface Config {
130
128
  /**
131
129
  * 本文件保留的 7 条路由的路径(被源码级守卫按文件窗口钉住,见下方 routesList 注释)。
132
130
  *
133
- * 其余 77 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
131
+ * 其余 75 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
134
132
  * 新增一条 API 只需那一条声明,不再有「常量表 + 路由对象」两处要同步。
135
133
  */
136
134
  export declare const API: {
@@ -754,6 +752,8 @@ export type RouteEnvInferred = {
754
752
  credentials: CredentialProvider;
755
753
  dataDir: string;
756
754
  exportsDir: string;
755
+ syncRootDir: string;
756
+ syncScope: SyncScope;
757
757
  githubAuth: GitHubAuthClient;
758
758
  githubClientId: string | undefined;
759
759
  githubClientSecret: string | undefined;
package/lib/index.js CHANGED
@@ -38,14 +38,15 @@ import { randomBytes } from 'node:crypto';
38
38
  import { execFile } from 'node:child_process';
39
39
  import { existsSync, mkdirSync, readFileSync } from 'node:fs';
40
40
  import fs from 'node:fs/promises';
41
- import path from 'node:path';
42
- import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
41
+ import path, { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
43
42
  import { homedir } from 'node:os';
44
43
  import { promisify } from 'node:util';
45
44
  import * as dshSettings from '@deepseek-ai/dsh-settings';
46
45
  import { dshHomePath, resolveDshHome } from '@deepseek-ai/dsh-home-paths';
47
46
  import { endpoint, registerRoutes, requireJsonObject, writeJson, readJsonBody, errorMessage, writeMutationError } from './routes/kit.js';
47
+ import { installHostRequestTrust } from './routes/request-trust.js';
48
48
  import { buildRoutes } from './routes/index.js';
49
+ import { createAgentToolDeps } from './routes/model-tools-deps.js';
49
50
  import { Exporter, FileSnapshotStore, Importer, verifySnapshot } from './core/index.js';
50
51
  import { DshProfileLauncher, DshProfileManager, DshProfileRuntimeRegistry } from './profiles/index.js';
51
52
  import { cleanupCaches } from './core/cache-cleaner.js';
@@ -66,7 +67,7 @@ import { JournalStore } from './core/journal.js';
66
67
  import { RunRegistry } from './core/run-registry.js';
67
68
  import { registerModelTools } from './core/model-tools.js';
68
69
  import { msgOf, zhMsg } from './core/messages.js';
69
- import { createExitLockReleaser, reclaimStaleLockAtStartup } from './core/env-lock-lifecycle.js';
70
+ import { createExitLockReleaser, createHostMutationLock, reclaimStaleLockAtStartup } from './core/env-lock-lifecycle.js';
70
71
  import { engineMsg, getEngineLocale, setEngineLanguageSource, setEngineLocale } from './core/engine-locale.js';
71
72
  import { RollbackAutoTracker, RollbackPointEngine, ROLLBACK_POINTS_DIR_NAME, rollbackSessionBindingOf, rollbackTrackedEventOf } from './core/rollback-point.js';
72
73
  import { ROLLBACK_ATTRIBUTION_FILE_NAME, RollbackWriteAttribution } from './core/rollback-attribution.js';
@@ -115,7 +116,7 @@ import { createHistoryPruner } from './core/history-prune.js';
115
116
  import { isWebDavConfig, isS3Config, isGistConfig, channelOf, SYNC_CHANNELS, GIST_PROVIDER, cloudSecretRef } from './sync/sync-config.js';
116
117
  import { resolveSessionFormatDisposition, sessionFormatAbortResponse, } from './routes/session-format.js';
117
118
  import { createPrepareSync } from './sync/config-issue-reporting.js';
118
- import { AUTO_SYNC_OPT_IN_SECTIONS, defaultSyncSelection, effectiveSections, OPT_IN_SYNC_SECTIONS, readAllSyncSelections, readSyncSelection } from './sync/sync-selection.js';
119
+ import { AUTO_SYNC_OPT_IN_SECTIONS, defaultSyncSelection, effectiveSections, OPT_IN_SYNC_SECTIONS, readAllSyncSelections, readAllSyncSelectionsSync, readSyncSelection } from './sync/sync-selection.js';
119
120
  import { GitMarketReader } from './market/reader.js';
120
121
  import { parseMarketIndex } from './market/index-parser.js';
121
122
  import { prepareMarketItem } from './market/prepare.js';
@@ -135,7 +136,10 @@ import { createLogger, parseLogLevel } from './utils/logger.js';
135
136
  // 与 HTTP 路径**同一份**「运行中对话」判据(命令入口绝不能各写一套)
136
137
  import { sessionActiveDenied, sessionActiveGateApplies } from './routes/recovery.js';
137
138
  // P4:路由组共享的纯工具已下沉到 routes/route-support.ts —— 组文件不再反向 import 本文件。
138
- import { ROUTE_TIMEOUT_MS, SYNC_CREDENTIAL_REF, SYNC_WEBDAV_CREDENTIAL_REF, credentialRef, decryptErrorText, executeRestorePlan, isControlledPath, makeRestoreExecutor, safeCredentialRef, syncPasswordRef, tryDecryptCredentials, withTimeout } from './routes/route-support.js';
139
+ import { ROUTE_TIMEOUT_MS, credentialRef, decryptErrorText, executeRestorePlan, isControlledPath, makeRestoreExecutor, safeCredentialRef, syncPasswordRef, tryDecryptCredentials, withTimeout } from './routes/route-support.js';
140
+ // per-profile 同步作用域:单一实现见 src/sync/sync-scope.ts
141
+ import { syncScopeFor } from './sync/sync-scope.js';
142
+ import { bootSyncScope, makeSyncCredentialViews } from './sync/sync-scope-boot.js';
139
143
  export { ROUTE_TIMEOUT_MS, REVIEW_KINDS, SYNC_CREDENTIAL_REF, SYNC_ENCRYPT_PASSWORD_REF_PREFIX, SYNC_DECRYPT_PASSWORD_REF_PREFIX, SYNC_WEBDAV_CREDENTIAL_REF, SyncRouteError, buildAutosyncStatus, buildAutosyncStatusByChannel, buildFileDiffBody, buildRestoreBody, credentialRef, decryptErrorText, executeRestorePlan, extractSyncSections, extractSyncSessions, isAutosyncInterval, isControlledPath, isGitHubAuthMissing, isToolchainChangeItem, makeRestoreExecutor, parseMeForm, planToConfirmItems, safeCredentialRef, sessionHealthNextSteps, syncPasswordRef, tryDecryptCredentials, withTimeout, writeProfileError, writeRequestBodyToFile, writeSyncRouteError } from './routes/route-support.js';
140
144
  /* ---------------------------------------------------------------- identity */
141
145
  /** Stable cordis plugin name — must match the cordis.patch.yml row id. */
@@ -143,7 +147,7 @@ export const name = 'config-manager';
143
147
  /** Services required before the engine can mount (present in every profile). */
144
148
  export const inject = ['settings', 'credentials'];
145
149
  /** Plugin version, kept in sync with package.json ("version"). */
146
- export const PLUGIN_VERSION = '0.4.2';
150
+ export const PLUGIN_VERSION = '0.5.0';
147
151
  /** Plugin own package name — excluded from its own exported plugins list. */
148
152
  const PLUGIN_NAME = 'dsh-config-manager';
149
153
  /**
@@ -165,7 +169,7 @@ export const DEFAULT_GITHUB_CLIENT_ID = 'Ov23liq4i7n8UsylGRfb';
165
169
  /**
166
170
  * 本文件保留的 7 条路由的路径(被源码级守卫按文件窗口钉住,见下方 routesList 注释)。
167
171
  *
168
- * 其余 77 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
172
+ * 其余 75 条路由的路径**声明在各自的组文件里**(src/routes/*.ts 的 endpoint({ path, methods }))——
169
173
  * 新增一条 API 只需那一条声明,不再有「常量表 + 路由对象」两处要同步。
170
174
  */
171
175
  export const API = {
@@ -2026,14 +2030,14 @@ async function sessionHealthKnownIds(host) {
2026
2030
  }
2027
2031
  /** Build the /api/dsh-config-manager route family. */
2028
2032
  function makeRoutes(deps) {
2029
- const { host, adapters, exportsDir, tmpDir, snapshotsDir, runs, syncDir, marketDir, dataDir, credentials, githubClientId, githubClientSecret, backupScheduler, history } = deps;
2033
+ const { host, adapters, exportsDir, tmpDir, snapshotsDir, runs, syncDir, syncRootDir, syncScope, marketDir, dataDir, credentials, githubClientId, githubClientSecret, backupScheduler, history } = deps;
2030
2034
  const roots = [exportsDir, tmpDir];
2031
2035
  /**
2032
2036
  * m-retention:快照保留策略提供者(缺省 = 从 sync/backup-schedule.json 实时读取)。
2033
2037
  * 用户改完策略即时生效(每次 prune 都重读);读取失败 → 缺省策略(引擎侧兜底)。
2034
2038
  */
2035
2039
  const retentionPolicyProvider = deps.retentionPolicy
2036
- ?? (async () => (await readBackupSchedule(syncDir)).retention ?? DEFAULT_RETENTION_POLICY);
2040
+ ?? (async () => (await readBackupSchedule(syncRootDir)).retention ?? DEFAULT_RETENTION_POLICY);
2037
2041
  /**
2038
2042
  * m-retention:GFS 分层选择器(sync 层实现)+ 旧路径快速路径绑定。
2039
2043
  * 为什么由宿主注入:架构边界禁止 core → sync 反向依赖;core 只声明 PruneSelector 契约。
@@ -2169,7 +2173,7 @@ function makeRoutes(deps) {
2169
2173
  /** 已知 adapter id 集合(push 请求体 sections 校验用)。 */
2170
2174
  const knownSyncSectionIds = new Set(adapters.map((a) => a.id));
2171
2175
  /** 可同步分区目录(status 回填 UI「同步分区」勾选列表)。
2172
- * 只含 portable + 显式可选项(OPT_IN_SYNC_SECTIONS,当前 mcp / sessions)——
2176
+ * 只含 portable + 显式可选项(OPT_IN_SYNC_SECTIONS,当前 mcp / workspaces / sessions)——
2173
2177
  * 后者是 deviceSpecific,UI 必须显示设备相关徽章,且只有用户主动勾选才进同步通道。 */
2174
2178
  const syncSectionCatalog = adapters
2175
2179
  .filter((a) => a.portability === 'portable' || OPT_IN_SYNC_SECTIONS.includes(a.id))
@@ -2274,17 +2278,18 @@ function makeRoutes(deps) {
2274
2278
  // 这里只做装配:宿主只提供 credentials、日志出口与配置目录。
2275
2279
  const prepareSync = createPrepareSync({
2276
2280
  syncDir,
2277
- parseBody: (body) => parseSyncBody(body, { credentials }),
2281
+ // scope:git/webdav 的 token/口令、s3/gist 的密钥槽位都按档案取(默认档案 = 历史槽位名)。
2282
+ parseBody: (body) => parseSyncBody(body, { credentials, scope: syncScope }),
2278
2283
  mergeWebDavUsername: mergePersistedWebDavUsername,
2279
2284
  log: (line) => host.log.warn(line),
2280
2285
  });
2281
2286
  /** 同步分区选择缓存(按通道;sync-selection.json;makeSyncEngine 同步读取用,保存路由更新)。
2282
- * 缺失通道 = 尚未加载(启动竞态窗口);读取/使用处兜底 defaultSyncSelection。 */
2287
+ * **必须同步种入**(C6):apply() 同步,异步种入会留窗口 —— 窗口内 makeSyncEngine 兜底
2288
+ * defaultSyncSelection(全部 portable),用户 advanced 的收窄在那一轮被吞(判据见 docs/evidence/sync-channel.md)。 */
2283
2289
  const selectionCache = {};
2284
- void readAllSyncSelections(syncDir).then((all) => {
2285
- for (const channel of SYNC_CHANNELS)
2286
- selectionCache[channel] = all[channel];
2287
- }).catch(() => { });
2290
+ const seededSelections = readAllSyncSelectionsSync(syncDir);
2291
+ for (const channel of SYNC_CHANNELS)
2292
+ selectionCache[channel] = seededSelections[channel];
2288
2293
  /** 确保指定通道缓存已加载(status/save 路由调用;启动竞态兜底)。 */
2289
2294
  const ensureSelectionLoaded = async (channel) => {
2290
2295
  const cached = selectionCache[channel];
@@ -2312,26 +2317,8 @@ function makeRoutes(deps) {
2312
2317
  return undefined;
2313
2318
  }
2314
2319
  };
2315
- /** 某个同步密码槽位是否已配置(只回布尔,永不回值)。 */
2316
- const syncPasswordConfigured = async (ref) => {
2317
- try {
2318
- const info = await credentials.describe(credentialRef(ref));
2319
- return info.configured;
2320
- }
2321
- catch {
2322
- return false;
2323
- }
2324
- };
2325
- /** 全部通道的「同步密码是否已保存」视图(只回布尔;密码值永不进任何响应)。 */
2326
- const syncCredentialsByChannelView = async () => {
2327
- const describe = async (channel) => ({
2328
- encryptPasswordConfigured: await syncPasswordConfigured(syncPasswordRef('ENCRYPT', channel)),
2329
- decryptPasswordConfigured: await syncPasswordConfigured(syncPasswordRef('DECRYPT', channel)),
2330
- });
2331
- // t32/B7:通道集合来自唯一枚举(保持 Promise.all 并发语义)
2332
- const pairs = await Promise.all(SYNC_CHANNELS.map(async (channel) => [channel, await describe(channel)]));
2333
- return Object.fromEntries(pairs);
2334
- };
2320
+ // 同步密码槽位的「是否已保存」视图(按本档案取槽位;实现见 src/sync/sync-scope-boot.ts)
2321
+ const { syncPasswordConfigured, syncCredentialsByChannelView } = makeSyncCredentialViews(credentials, syncScope.profile);
2335
2322
  /** 分区选择视图形状(无 schemaVersion;密码值永不进视图)。 */
2336
2323
  /** 全部通道的分区选择视图(status 路由一次返回;UI 按当前 tab 取对应通道)。 */
2337
2324
  /** 指定通道的分区选择视图。 */
@@ -2385,7 +2372,7 @@ function makeRoutes(deps) {
2385
2372
  workDir: gitWorkDir,
2386
2373
  credentials: {
2387
2374
  getToken: async () => {
2388
- const resolved = await credentials.resolve(credentialRef(SYNC_CREDENTIAL_REF));
2375
+ const resolved = await credentials.resolve(credentialRef(syncScope.tokenRef));
2389
2376
  return resolved?.value ?? '';
2390
2377
  },
2391
2378
  },
@@ -2399,7 +2386,7 @@ function makeRoutes(deps) {
2399
2386
  username: cfg.webdav.username ?? '',
2400
2387
  credentials: {
2401
2388
  getPassword: async () => {
2402
- const resolved = await credentials.resolve(credentialRef(SYNC_WEBDAV_CREDENTIAL_REF));
2389
+ const resolved = await credentials.resolve(credentialRef(syncScope.webdavPasswordRef));
2403
2390
  return resolved?.value ?? '';
2404
2391
  },
2405
2392
  },
@@ -2418,7 +2405,7 @@ function makeRoutes(deps) {
2418
2405
  accessKeyId: cfg.s3.accessKeyId,
2419
2406
  credentials: {
2420
2407
  getSecretAccessKey: async () => {
2421
- const resolved = await credentials.resolve(credentialRef(cloudSecretRef(provider)));
2408
+ const resolved = await credentials.resolve(credentialRef(syncScope.scopeRef(cloudSecretRef(provider))));
2422
2409
  return resolved?.value ?? '';
2423
2410
  },
2424
2411
  },
@@ -2436,7 +2423,7 @@ function makeRoutes(deps) {
2436
2423
  gistId: cfg.gist.gistId,
2437
2424
  credentials: {
2438
2425
  getToken: async () => {
2439
- const resolved = await credentials.resolve(credentialRef(cloudSecretRef(GIST_PROVIDER)));
2426
+ const resolved = await credentials.resolve(credentialRef(syncScope.scopeRef(cloudSecretRef(GIST_PROVIDER))));
2440
2427
  return resolved?.value ?? '';
2441
2428
  },
2442
2429
  },
@@ -2520,7 +2507,7 @@ function makeRoutes(deps) {
2520
2507
  /** 请求级装配只读 GitMarketReader(公开市场无凭据;url = BUILTIN_MARKET_URL,已由 validateRepoUrl 拒绝 userinfo)。 */
2521
2508
  const makeMarketReader = () => new GitMarketReader({ msg, timeoutMs: 60_000 });
2522
2509
  /**
2523
- * 市场条目来源仓库 star 缓存(docs/design/2026-08-21-market-star-filter-sort-design.md §3.1.3)。
2510
+ * 市场条目来源仓库 star 缓存(docs/archive/2026-08-21-market-star-filter-sort-design.md §3.1.3)。
2524
2511
  * - **匿名查询**(getRepoStarsPublic,不注入 token)——守住「市场端点零凭据」安全不变式;
2525
2512
  * - 按仓库 URL 去重 + 1 小时 TTL + 失败降级(单仓失败显示「—」,不影响整体浏览);
2526
2513
  * - tokenProvider 给空函数(requestPublic 不调用它,仅满足构造签名)。
@@ -2572,7 +2559,7 @@ function makeRoutes(deps) {
2572
2559
  // 同一凭据槽),值绝不落盘 / 进日志 / 回传浏览器;gitWriter 写用户仓库与 fork 分支,
2573
2560
  // 安全模式与 GitTransport 一致(credential helper store 临时文件 0600 用后即删)。
2574
2561
  const meTokenProvider = async () => {
2575
- const resolved = await credentials.resolve(credentialRef(SYNC_CREDENTIAL_REF));
2562
+ const resolved = await credentials.resolve(credentialRef(syncScope.tokenRef));
2576
2563
  return resolved?.value ?? '';
2577
2564
  };
2578
2565
  const meGitHubRest = new GitHubAuthRest({ tokenProvider: meTokenProvider });
@@ -2741,6 +2728,8 @@ function makeRoutes(deps) {
2741
2728
  starPromptRepoUrl: STAR_PROMPT_REPO_URL,
2742
2729
  syncCredentialsByChannelView,
2743
2730
  syncDir,
2731
+ syncRootDir,
2732
+ syncScope,
2744
2733
  // issue #79:工作副本自检(只读,挂在 /sync/status)与显式重建(写动作,走 mutation gate)。
2745
2734
  // 路由只传 repoUrl/mode —— 路径、凭据与 git 调用口径都留在宿主这一处。
2746
2735
  syncWorkDir: {
@@ -2792,7 +2781,7 @@ function makeRoutes(deps) {
2792
2781
  /**
2793
2782
  * 路由表:本文件只保留被源码级守卫按**文件窗口**钉住的 7 条(host-entry 审计 F-04 记录的
2794
2783
  * tests/host/**、src/core/model-tools.test.ts、src/core/phase1-wiring.test.ts 的窗口断言)。
2795
- * 其余 77 条已按域拆到 src/routes/*.ts,由 buildRoutes 组装。
2784
+ * 其余 75 条已按域拆到 src/routes/*.ts,由 buildRoutes 组装。
2796
2785
  * 注册顺序不影响匹配:命名路由必须互不相同(webServer 契约)。
2797
2786
  */
2798
2787
  const routeEnv = makeRouteEnv();
@@ -3272,7 +3261,18 @@ function makeRoutes(deps) {
3272
3261
  }),
3273
3262
  ...buildRoutes(routeEnv),
3274
3263
  ];
3275
- return { routes: routesList, scheduler, makeSyncEngine, profileRuntime: routeEnv.profileRuntime };
3264
+ return {
3265
+ routes: routesList,
3266
+ scheduler,
3267
+ makeSyncEngine,
3268
+ profileRuntime: routeEnv.profileRuntime,
3269
+ agentToolDeps: createAgentToolDeps({
3270
+ host, adapters, exportsDir, snapshotsDir, syncDir, makeSyncEngine,
3271
+ resolveSyncPassword, syncPasswordRef, selectionOptInSections, makeImporter, roots,
3272
+ ...(deps.scanner === undefined ? {} : { scanner: deps.scanner }),
3273
+ exporterVersion: PLUGIN_VERSION,
3274
+ }),
3275
+ };
3276
3276
  }
3277
3277
  /* ------------------------------------------------------------------ apply */
3278
3278
  /**
@@ -3291,7 +3291,10 @@ export function apply(ctx, config) {
3291
3291
  const exportsDir = join(dataDir, 'exports');
3292
3292
  const tmpDir = join(dataDir, 'tmp');
3293
3293
  const snapshotsDir = join(dataDir, 'snapshots');
3294
- const syncDir = join(dataDir, 'sync');
3294
+ // 同步作用域按档案分(dataDir 不拆:写锁 / SAFE MODE / 事务日志都长在那棵树上)—— src/sync/sync-scope.ts
3295
+ const syncScope = syncScopeFor(dataDir, resolveProfileName(config, ctx));
3296
+ const syncDir = syncScope.dir;
3297
+ const syncRootDir = syncScope.rootDir;
3295
3298
  /**
3296
3299
  * issue #88 / #89:回合自动留点(回滚点)**缺省关闭**。
3297
3300
  *
@@ -3342,6 +3345,8 @@ export function apply(ctx, config) {
3342
3345
  mkdirSync(marketDir, { recursive: true });
3343
3346
  mkdirSync(historyDir, { recursive: true });
3344
3347
  const host = new ConfigManagerHostContext(ctx, homeDir, resolveProfileName(config, ctx));
3348
+ // 非默认档案首次启动继承历史同步根(配置 + 凭据值,best-effort;见 src/sync/sync-scope-boot.ts)
3349
+ bootSyncScope(syncScope, ctx.credentials, (line) => host.log.warn(line));
3345
3350
  // issue #30:出站代理(插件私有,不改全局)。仅在检测到 HTTP(S)_PROXY 时生效;未配置则完全直连。
3346
3351
  // 打一条脱敏日志,便于用户确认「插件当前到底走没走代理」(凭据不进日志)。
3347
3352
  const proxySummary = activeProxySummary();
@@ -3351,12 +3356,8 @@ export function apply(ctx, config) {
3351
3356
  // Phase 2 跨进程环境锁:全局唯一 GLOBAL EXCLUSIVE MUTATION LOCK(<dataDir>/locks/environment.lock)。
3352
3357
  // 所有 destructive mutation 入口经 runWithMutationLock(host.mutationLock, …) 获取;跨进程/跨 kind 互斥。
3353
3358
  // 随插件生命周期停止:停止 heartbeat 并清除本进程持有(release 由各入口 finally 保证;这里无需额外清理)。
3354
- host.mutationLock = new EnvironmentLockManager({
3355
- dataDir,
3356
- op: 'config-manager',
3357
- target: 'global-mutation',
3358
- lockVersion: PLUGIN_VERSION,
3359
- });
3359
+ // 装配(含「心跳写失败 / 释放失败」留痕)在 core/env-lock-lifecycle.ts:此处只传依赖。
3360
+ host.mutationLock = createHostMutationLock({ dataDir, lockVersion: PLUGIN_VERSION, log: host.log });
3360
3361
  const envLockManager = host.mutationLock;
3361
3362
  // Phase 3:启动 reconcile(只读)+ SAFE MODE。宿主 apply() 为同步 →
3362
3363
  // ① 先同步探测 durable SAFE MODE 标记(scheduler.start() 前即被阻断),
@@ -3537,7 +3538,8 @@ export function apply(ctx, config) {
3537
3538
  const secretScanner = createConfiguredSecretScanner(config?.personalPatterns);
3538
3539
  const runs = new RunRegistry({ msg: host.msg });
3539
3540
  const backupScheduler = new BackupScheduler({
3540
- syncDir,
3541
+ // 定时备份配置是全机一份(不是某个档案的同步态):喂全机根,不喂档案作用域
3542
+ syncDir: syncRootDir,
3541
3543
  exportsDir,
3542
3544
  host,
3543
3545
  adapters,
@@ -3558,7 +3560,7 @@ export function apply(ctx, config) {
3558
3560
  const historyStore = new MigrationStore({ dir: historyDir });
3559
3561
  // 本实例的 web 端口在 webServer 就绪前未知(心跳先报 null,就绪后再报一次)。
3560
3562
  const webPort = { value: null };
3561
- const { routes, scheduler, makeSyncEngine, profileRuntime } = makeRoutes({
3563
+ const { routes, scheduler, profileRuntime, agentToolDeps, } = makeRoutes({
3562
3564
  host,
3563
3565
  adapters,
3564
3566
  exportsDir,
@@ -3566,10 +3568,12 @@ export function apply(ctx, config) {
3566
3568
  snapshotsDir,
3567
3569
  runs,
3568
3570
  syncDir,
3571
+ syncRootDir,
3572
+ syncScope,
3569
3573
  marketDir,
3570
3574
  dataDir,
3571
3575
  runtimePort: () => webPort.value,
3572
- retentionPolicy: async () => (await readBackupSchedule(syncDir)).retention ?? DEFAULT_RETENTION_POLICY,
3576
+ retentionPolicy: async () => (await readBackupSchedule(syncRootDir)).retention ?? DEFAULT_RETENTION_POLICY,
3573
3577
  // F2:部署者 personalPatterns → 强化 secret 扫描器(未配置 = 默认行为)。
3574
3578
  // 该扫描器实现了 scanText(文件类分区文本级扫描,G-09 只告警不改写)——
3575
3579
  // 换成任何没有 scanText 的扫描器都会静默关闭 G-09,改这里务必先看 exporter.ts 的 scanFileSectionText。
@@ -3580,19 +3584,9 @@ export function apply(ctx, config) {
3580
3584
  backupScheduler,
3581
3585
  history: historyStore,
3582
3586
  });
3583
- // Agent 可调用的模型工具(P0-1):复用 src/core 引擎与同一 makeSyncEngine 来源。
3584
- // 不依赖 webServer:host 侧能力在无 Web 部署时仍可用;tools 服务未组合时内部守卫跳过。
3585
- registerModelTools(ctx, {
3586
- host,
3587
- adapters,
3588
- exportsDir,
3589
- snapshotsDir,
3590
- syncDir,
3591
- makeSyncEngine,
3592
- exporterVersion: PLUGIN_VERSION,
3593
- // M1:与 HTTP 导出路由同一个 scanner(G-09 文件类分区凭据告警在两条路径上一致)。
3594
- scanner: secretScanner,
3595
- });
3587
+ // 模型工具(P0-1):与 HTTP 路由同一批依赖(装配见 routes/model-tools-deps.ts);
3588
+ // 不依赖 webServer,tools 服务未组合时内部守卫跳过。
3589
+ registerModelTools(ctx, agentToolDeps);
3596
3590
  // P1-B:backupScheduler 与 autosync scheduler 都不在构造期启动 —— 由启动分类结论驱动(仅 NORMAL)。
3597
3591
  // 启停顺序、卸载清理、退出兜底释放环境锁、实例心跳统一在 lifecycle-hooks 里装配(可单测)。
3598
3592
  const lifecycle = createHostLifecycle({
@@ -3831,13 +3825,12 @@ export function apply(ctx, config) {
3831
3825
  }
3832
3826
  // 端口就绪 → 重新自报一次心跳(其它实例的「运行中」徽章与端口信息靠它;token 永不落盘)。
3833
3827
  webPort.value = webServer.port;
3834
- // F-2:宿主自请求走这个端口(探测/代理 DSH 自己的 /api/session.export)——
3835
- // 必须在注册路由**之前**赋值,否则首次探测拿到 undefined 会如实降级成「拿不到状态码」。
3836
- // 注:本插件是 bundle 包、宿主半没有热重载,端口变化只有重启一次才可能发生。
3837
- // routeEnv 的 sessionExportPort 是**活 getter**(读 host.webPort),因此这里赋值对已构造好的
3838
- // 路由表同样生效 —— 不需要重建路由。
3828
+ // F-2:宿主自请求走这个端口(探测/代理 DSH 自己的 /api/session.export);routeEnv 的
3829
+ // sessionExportPort 是**活 getter**(读 host.webPort),所以这里赋值对已构造好的路由表同样生效、
3830
+ // 无需重建;但必须早于注册(否则首次探测拿到 undefined 会如实降级)。端口变化只有重启才会发生。
3839
3831
  host.webPort = webServer.port;
3840
3832
  profileRuntime.announce();
3833
+ installHostRequestTrust(ctx, host.log);
3841
3834
  ctx.effect(() => {
3842
3835
  const disposers = registerRoutes(webServer, routes);
3843
3836
  return () => {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * m-market:GitFileWriter —— 通用 git 文件写入器(「一键上传/我的配置」专用)。
3
3
  *
4
- * 背景(docs/design/2026-08-20-my-configs-design.md §4.2 / §4.3):
4
+ * 背景(docs/archive/2026-08-20-my-configs-design.md §4.2 / §4.3):
5
5
  * GitTransport(src/sync/git/git-transport.ts)实现的是 SyncTransport 接口,语义是
6
6
  * **快照同步**(list/upload/download/delete,内容提交到 snapshots/ 与 snapshots-encrypted/),
7
7
  * 不是通用 git 文件写入工具。MyRepoService 需要写入自定义目录结构