dsh-config-manager 0.4.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (286) hide show
  1. package/README.md +10 -0
  2. package/README.zh-CN.md +10 -0
  3. package/lib/adapters/mcp.d.ts +9 -0
  4. package/lib/adapters/mcp.js +37 -0
  5. package/lib/adapters/plugins.js +10 -2
  6. package/lib/adapters/pnpm-workspace.js +1 -1
  7. package/lib/adapters/self.d.ts +2 -0
  8. package/lib/adapters/self.js +18 -2
  9. package/lib/adapters/workspaces.js +1 -1
  10. package/lib/cli/restore-resume.js +1 -1
  11. package/lib/cli/web/page.js +2 -2
  12. package/lib/client.d.ts +17 -41
  13. package/lib/client.js +946 -761
  14. package/lib/core/backup.d.ts +11 -0
  15. package/lib/core/backup.js +27 -0
  16. package/lib/core/env-lock-lifecycle.d.ts +17 -3
  17. package/lib/core/env-lock-lifecycle.js +38 -0
  18. package/lib/core/external-failure.d.ts +9 -0
  19. package/lib/core/external-failure.js +50 -0
  20. package/lib/core/local-plugin-host.d.ts +9 -7
  21. package/lib/core/local-plugin-host.js +109 -15
  22. package/lib/core/local-plugin-pack.d.ts +20 -0
  23. package/lib/core/local-plugin-pack.js +18 -3
  24. package/lib/core/mcp-connector-store.d.ts +13 -0
  25. package/lib/core/mcp-connector-store.js +16 -1
  26. package/lib/core/messages-core.d.ts +45 -0
  27. package/lib/core/messages-core.js +92 -0
  28. package/lib/core/messages.d.ts +5 -0
  29. package/lib/core/messages.js +14 -0
  30. package/lib/core/migration-history.d.ts +40 -0
  31. package/lib/core/migration-history.js +55 -0
  32. package/lib/core/model-tool-plans.d.ts +66 -0
  33. package/lib/core/model-tool-plans.js +128 -0
  34. package/lib/core/model-tools.d.ts +96 -8
  35. package/lib/core/model-tools.js +568 -31
  36. package/lib/core/phase3-host.js +10 -2
  37. package/lib/core/plugin-cli.d.ts +5 -0
  38. package/lib/core/plugin-cli.js +11 -3
  39. package/lib/core/plugin-data-registry.d.ts +1 -1
  40. package/lib/core/plugin-data-registry.js +1 -1
  41. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  42. package/lib/core/restore-plan-fingerprint.js +18 -0
  43. package/lib/core/restore-resume.d.ts +1 -1
  44. package/lib/core/restore-resume.js +1 -1
  45. package/lib/core/restore.d.ts +5 -0
  46. package/lib/core/restore.js +4 -1
  47. package/lib/core/types.d.ts +12 -0
  48. package/lib/foreign/claude-sessions.d.ts +1 -1
  49. package/lib/foreign/claude-sessions.js +1 -1
  50. package/lib/foreign/registry.js +1 -1
  51. package/lib/foreign/types.d.ts +1 -1
  52. package/lib/index.d.ts +19 -15
  53. package/lib/index.js +72 -80
  54. package/lib/market/git-file-writer.js +1 -1
  55. package/lib/market/github-repos.js +1 -1
  56. package/lib/market/market-config.js +1 -1
  57. package/lib/market/messages-market.js +1 -1
  58. package/lib/market/my-repo.js +1 -1
  59. package/lib/market/prepare.js +1 -1
  60. package/lib/market/reader.js +2 -2
  61. package/lib/market/repo-url.d.ts +1 -1
  62. package/lib/market/security.js +2 -2
  63. package/lib/market/star-cache.d.ts +1 -1
  64. package/lib/market/types.d.ts +1 -1
  65. package/lib/market/types.js +1 -1
  66. package/lib/market/url.js +1 -1
  67. package/lib/profiles/dsh-profile-manager.d.ts +1 -1
  68. package/lib/profiles/dsh-profile-manager.js +26 -7
  69. package/lib/profiles/dsh-profile-shared.d.ts +3 -1
  70. package/lib/routes/backup.js +17 -9
  71. package/lib/routes/index.d.ts +1 -1
  72. package/lib/routes/kit.d.ts +2 -2
  73. package/lib/routes/market.d.ts +1 -1
  74. package/lib/routes/market.js +3 -60
  75. package/lib/routes/model-tools-deps.d.ts +41 -0
  76. package/lib/routes/model-tools-deps.js +18 -0
  77. package/lib/routes/recovery.js +5 -3
  78. package/lib/routes/route-support.d.ts +18 -26
  79. package/lib/routes/route-support.js +19 -32
  80. package/lib/routes/snapshots.d.ts +1 -1
  81. package/lib/routes/snapshots.js +4 -40
  82. package/lib/routes/sync.js +40 -28
  83. package/lib/schema/index.d.ts +2 -2
  84. package/lib/schema/index.js +2 -2
  85. package/lib/schema/section-registry.d.ts +5 -3
  86. package/lib/schema/section-registry.js +7 -3
  87. package/lib/security/secret-scanner.js +1 -1
  88. package/lib/sync/apply-bundle.d.ts +50 -0
  89. package/lib/sync/apply-bundle.js +60 -0
  90. package/lib/sync/autosync-scheduler.d.ts +9 -0
  91. package/lib/sync/autosync-scheduler.js +118 -89
  92. package/lib/sync/backup-scheduler.js +5 -4
  93. package/lib/sync/blob-store.d.ts +2 -2
  94. package/lib/sync/git/git-transport.d.ts +12 -0
  95. package/lib/sync/git/git-transport.js +50 -2
  96. package/lib/sync/merge.d.ts +2 -0
  97. package/lib/sync/merge.js +28 -0
  98. package/lib/sync/messages.d.ts +4 -0
  99. package/lib/sync/messages.js +9 -2
  100. package/lib/sync/s3/s3-transport.d.ts +1 -1
  101. package/lib/sync/s3/s3-transport.js +1 -1
  102. package/lib/sync/sync-engine.d.ts +4 -4
  103. package/lib/sync/sync-engine.js +25 -26
  104. package/lib/sync/sync-scope-boot.d.ts +34 -0
  105. package/lib/sync/sync-scope-boot.js +71 -0
  106. package/lib/sync/sync-scope.d.ts +103 -0
  107. package/lib/sync/sync-scope.js +229 -0
  108. package/lib/sync/sync-selection.d.ts +17 -4
  109. package/lib/sync/sync-selection.js +40 -14
  110. package/lib/sync/transport.d.ts +4 -1
  111. package/lib/sync/transport.js +6 -0
  112. package/lib/sync/webdav/webdav-transport.js +1 -1
  113. package/lib/sync/workspace-merge.d.ts +36 -0
  114. package/lib/sync/workspace-merge.js +152 -0
  115. package/lib/ui/backup-schedule.d.ts +13 -2
  116. package/lib/ui/backup-schedule.js +3 -0
  117. package/lib/ui/snapshots-view.d.ts +16 -0
  118. package/lib/ui/snapshots-view.js +21 -0
  119. package/lib/ui/sync-repository-picker.d.ts +21 -0
  120. package/lib/ui/sync-repository-picker.js +18 -0
  121. package/lib/utils/env-lock.d.ts +96 -0
  122. package/lib/utils/env-lock.js +332 -111
  123. package/lib/utils/messages-utils.d.ts +6 -0
  124. package/lib/utils/messages-utils.js +17 -1
  125. package/lib/utils/patch-yaml.js +1 -1
  126. package/lib/utils/remove-tree.d.ts +7 -0
  127. package/lib/utils/remove-tree.js +265 -0
  128. package/lib/utils/zip.js +1 -1
  129. package/package.json +3 -2
  130. package/src/adapters/mcp.test.ts +28 -0
  131. package/src/adapters/mcp.ts +33 -0
  132. package/src/adapters/plugins.test.ts +49 -0
  133. package/src/adapters/plugins.ts +9 -1
  134. package/src/adapters/pnpm-workspace.ts +1 -1
  135. package/src/adapters/self.test.ts +39 -1
  136. package/src/adapters/self.ts +20 -2
  137. package/src/adapters/workspaces.ts +1 -1
  138. package/src/cli/restore-resume.ts +1 -1
  139. package/src/cli/web/page.ts +2 -2
  140. package/src/client/about/AboutPanel.tsx +1 -1
  141. package/src/client/about/about-view.test.ts +1 -1
  142. package/src/client/about/about-view.ts +1 -1
  143. package/src/client/api.ts +1 -6
  144. package/src/client/chat/chat-entry-view.test.ts +1 -1
  145. package/src/client/chat/chat-slots.ts +1 -1
  146. package/src/client/chat/rollback-diff-tab.ts +1 -1
  147. package/src/client/client-types.ts +1 -1
  148. package/src/client/common/routes.ts +1 -5
  149. package/src/client/config-manager.module.css +21 -1
  150. package/src/client/css-scale-guard.test.ts +1 -1
  151. package/src/client/environment/EnvironmentPanel.tsx +2 -2
  152. package/src/client/home/HomePanel.tsx +3 -0
  153. package/src/client/library/ArtifactRow.tsx +14 -2
  154. package/src/client/library/LibraryPanel.tsx +44 -0
  155. package/src/client/locales/overview.ts +10 -2
  156. package/src/client/locales/profiles.ts +2 -0
  157. package/src/client/locales/sessions.ts +3 -0
  158. package/src/client/market/MyConfigsView.tsx +1 -1
  159. package/src/client/market/market-api.ts +2 -14
  160. package/src/client/market/market-locales.ts +1 -1
  161. package/src/client/market/market-view.ts +3 -3
  162. package/src/client/market/my-configs-api.ts +1 -1
  163. package/src/client/market/my-configs-view.ts +1 -1
  164. package/src/client/recovery/recovery-locales.test.ts +1 -1
  165. package/src/client/run-store.ts +1 -1
  166. package/src/client/sync/ChannelConfigDialog.tsx +32 -1
  167. package/src/client/sync/SyncPanel.tsx +11 -30
  168. package/src/client/sync/SyncRepositoryPicker.tsx +34 -13
  169. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  170. package/src/client/sync/SyncSettingsView.test.ts +32 -0
  171. package/src/client/sync/config-save-state.test.ts +99 -0
  172. package/src/client/sync/config-save-state.ts +69 -0
  173. package/src/client/sync/history-model.test.ts +28 -7
  174. package/src/client/sync/history-model.ts +6 -3
  175. package/src/client/sync/sync-locales.ts +14 -4
  176. package/src/client/sync/sync-view.ts +1 -1
  177. package/src/core/analyzer-cache.test.ts +1 -1
  178. package/src/core/backup.test.ts +45 -1
  179. package/src/core/backup.ts +25 -0
  180. package/src/core/disk-usage.test.ts +2 -0
  181. package/src/core/engine-locale.test.ts +4 -0
  182. package/src/core/env-lock-lifecycle.ts +33 -3
  183. package/src/core/external-failure.test.ts +60 -0
  184. package/src/core/external-failure.ts +54 -0
  185. package/src/core/integrity-extra-entries.test.ts +1 -1
  186. package/src/core/local-plugin-host.test.ts +134 -0
  187. package/src/core/local-plugin-host.ts +122 -17
  188. package/src/core/local-plugin-pack.ts +39 -3
  189. package/src/core/mcp-connector-store.ts +26 -1
  190. package/src/core/messages-core.ts +94 -0
  191. package/src/core/messages.ts +14 -0
  192. package/src/core/migration-history.test.ts +65 -0
  193. package/src/core/migration-history.ts +70 -0
  194. package/src/core/model-tool-plans.test.ts +111 -0
  195. package/src/core/model-tool-plans.ts +170 -0
  196. package/src/core/model-tools.test.ts +212 -12
  197. package/src/core/model-tools.ts +710 -38
  198. package/src/core/phase3-host.ts +10 -2
  199. package/src/core/phase3-production-integration.test.ts +43 -0
  200. package/src/core/plugin-cli.fs.test.ts +30 -3
  201. package/src/core/plugin-cli.ts +11 -3
  202. package/src/core/plugin-data-registry.ts +1 -1
  203. package/src/core/restore-plan-fingerprint.ts +19 -0
  204. package/src/core/restore-resume.ts +1 -1
  205. package/src/core/restore.ts +9 -1
  206. package/src/core/types.ts +12 -0
  207. package/src/foreign/claude-sessions.ts +3 -3
  208. package/src/foreign/registry.ts +1 -1
  209. package/src/foreign/types.ts +1 -1
  210. package/src/index.ts +102 -111
  211. package/src/market/git-file-writer.ts +1 -1
  212. package/src/market/github-repos.test.ts +1 -1
  213. package/src/market/github-repos.ts +1 -1
  214. package/src/market/market-config.ts +1 -1
  215. package/src/market/messages-market.ts +1 -1
  216. package/src/market/my-repo.test.ts +1 -1
  217. package/src/market/my-repo.ts +1 -1
  218. package/src/market/prepare.test.ts +1 -1
  219. package/src/market/prepare.ts +1 -1
  220. package/src/market/reader.ts +2 -2
  221. package/src/market/repo-url.ts +1 -1
  222. package/src/market/security.ts +2 -2
  223. package/src/market/star-cache.ts +1 -1
  224. package/src/market/types.ts +1 -1
  225. package/src/market/url.test.ts +1 -1
  226. package/src/market/url.ts +1 -1
  227. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  228. package/src/profiles/dsh-profile-manager.test.ts +20 -0
  229. package/src/profiles/dsh-profile-manager.ts +25 -7
  230. package/src/profiles/dsh-profile-shared.ts +2 -0
  231. package/src/routes/backup.ts +16 -9
  232. package/src/routes/index.ts +1 -1
  233. package/src/routes/kit.ts +2 -2
  234. package/src/routes/market.ts +2 -59
  235. package/src/routes/model-tools-deps.ts +56 -0
  236. package/src/routes/recovery.ts +5 -3
  237. package/src/routes/route-support.ts +49 -36
  238. package/src/routes/snapshots.ts +4 -40
  239. package/src/routes/sync.ts +39 -27
  240. package/src/schema/index.ts +2 -2
  241. package/src/schema/manifest-schema.test.ts +2 -2
  242. package/src/schema/registry.test.ts +1 -1
  243. package/src/schema/section-registry.ts +9 -4
  244. package/src/security/redaction.test.ts +1 -1
  245. package/src/security/secret-scanner.test.ts +2 -2
  246. package/src/security/secret-scanner.ts +1 -1
  247. package/src/sync/apply-bundle.ts +104 -0
  248. package/src/sync/autosync-scheduler.test.ts +180 -6
  249. package/src/sync/autosync-scheduler.ts +132 -92
  250. package/src/sync/backup-scheduler.test.ts +11 -4
  251. package/src/sync/backup-scheduler.ts +5 -4
  252. package/src/sync/blob-store.ts +2 -2
  253. package/src/sync/git/git-transport.test.ts +62 -0
  254. package/src/sync/git/git-transport.ts +54 -3
  255. package/src/sync/merge.ts +29 -0
  256. package/src/sync/messages.ts +9 -2
  257. package/src/sync/s3/s3-transport.ts +1 -1
  258. package/src/sync/sync-engine.test.ts +238 -2
  259. package/src/sync/sync-engine.ts +25 -26
  260. package/src/sync/sync-preview-push.test.ts +2 -1
  261. package/src/sync/sync-scope-boot.ts +87 -0
  262. package/src/sync/sync-scope.test.ts +154 -0
  263. package/src/sync/sync-scope.ts +256 -0
  264. package/src/sync/sync-selection.test.ts +76 -2
  265. package/src/sync/sync-selection.ts +40 -13
  266. package/src/sync/transport.test.ts +21 -1
  267. package/src/sync/transport.ts +12 -0
  268. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  269. package/src/sync/webdav/webdav-transport.ts +1 -1
  270. package/src/sync/workspace-merge.test.ts +110 -0
  271. package/src/sync/workspace-merge.ts +180 -0
  272. package/src/ui/backup-schedule.test.ts +5 -0
  273. package/src/ui/backup-schedule.ts +21 -2
  274. package/src/ui/session-issue-labels.ts +1 -1
  275. package/src/ui/snapshots-view.test.ts +32 -0
  276. package/src/ui/snapshots-view.ts +34 -0
  277. package/src/ui/sync-repository-picker.test.ts +34 -1
  278. package/src/ui/sync-repository-picker.ts +24 -0
  279. package/src/utils/env-lock.test.ts +242 -9
  280. package/src/utils/env-lock.ts +247 -13
  281. package/src/utils/messages-utils.ts +17 -1
  282. package/src/utils/patch-yaml.ts +1 -1
  283. package/src/utils/remove-tree.test.ts +120 -0
  284. package/src/utils/remove-tree.ts +239 -0
  285. package/src/utils/zip.ts +1 -1
  286. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Agent 工具面的「计划句柄」表(planId → 预览时算出的指纹与重放材料)。
3
+ *
4
+ * 为什么 agent 侧需要这张表,而不能只让模型把整个计划回传:
5
+ * - 计划正文可能很大(导入计划动辄上百条 item),塞进模型上下文既贵又容易被截断/改写;
6
+ * - 模型改写过的计划不构成「用户确认过的计划」,服务端必须能从**当前磁盘**重算同一份计划。
7
+ * 于是:预览时返回 planId(= 计划指纹),执行时只带 planId,服务端重算 → 比对指纹 →
8
+ * 不一致就拒绝(plan-changed)并且零写入。等价于 GUI 恢复路由的 409。
9
+ *
10
+ * 存放纪律(安全不变量):
11
+ * - 只在进程内存,绝不落盘、绝不进响应、绝不进日志;
12
+ * - payload 只放「重放所需的最小材料」(快照 id / 通道 / ZIP 路径 / 决策 JSON),
13
+ * **绝不存密码、凭据值、解密明文**;
14
+ * - TTL 30 分钟、上限 8 条:模型隔了很久才执行时应当重新预览,而不是拿到一份
15
+ * 早已过期的确认去写盘。
16
+ */
17
+ import { createHash } from 'node:crypto'
18
+ import type { ImportDecisions, ImportPlan } from './types.ts'
19
+
20
+ /**
21
+ * 指纹只消费三方合并预览的这几个字段 —— 这里用结构化最小类型声明,
22
+ * 而不是 import `../sync/sync-engine.ts` 的 MergePreview:
23
+ * core 不得反向依赖 sync 层(架构边界),且指纹只需要「结论 + 冲突位置」。
24
+ */
25
+ interface MergePreviewShape {
26
+ readonly ok: boolean
27
+ readonly snapshotId?: string | null
28
+ readonly hasAncestor?: boolean
29
+ readonly sections: readonly {
30
+ readonly id: string
31
+ readonly decision: string
32
+ readonly autoMerged?: number
33
+ readonly conflicts: readonly {
34
+ readonly path: string
35
+ readonly kind: string
36
+ readonly reason?: string | null
37
+ }[]
38
+ }[]
39
+ }
40
+
41
+ export type ModelPlanKind = 'restore' | 'sync-merge' | 'import'
42
+
43
+ export interface ModelPlanRecord {
44
+ /** planId = 指纹本身(同一计划重复预览得到同一个 id,天然幂等) */
45
+ id: string
46
+ kind: ModelPlanKind
47
+ fingerprint: string
48
+ /** 重放材料:只放 id / 路径 / 决策,绝不放密码或凭据值 */
49
+ payload: Record<string, string>
50
+ createdAt: number
51
+ expiresAt: number
52
+ }
53
+
54
+ /** 计划句柄存活时长(与同步会话的 30 分钟同档)。 */
55
+ export const MODEL_PLAN_TTL_MS = 30 * 60 * 1000
56
+ /** 同时在册的计划上限(超出淘汰最旧的一条)。 */
57
+ export const MODEL_PLAN_MAX = 8
58
+
59
+ export class ModelPlanStore {
60
+ private readonly records = new Map<string, ModelPlanRecord>()
61
+ private readonly now: () => number
62
+
63
+ constructor(now: () => number = () => Date.now()) {
64
+ this.now = now
65
+ }
66
+
67
+ /** 登记一份预览过的计划;返回 planId(= fingerprint)。同一指纹重复登记只刷新时间。 */
68
+ set(kind: ModelPlanKind, fingerprint: string, payload: Record<string, string>): string {
69
+ const ts = this.now()
70
+ // Map 的迭代序 = 插入序;先删再插让「刚预览的」排到最新,淘汰时才不会把刚发的 id 挤掉。
71
+ this.records.delete(fingerprint)
72
+ this.records.set(fingerprint, {
73
+ id: fingerprint,
74
+ kind,
75
+ fingerprint,
76
+ payload,
77
+ createdAt: ts,
78
+ expiresAt: ts + MODEL_PLAN_TTL_MS,
79
+ })
80
+ this.evict(ts)
81
+ return fingerprint
82
+ }
83
+
84
+ get(id: string): ModelPlanRecord | undefined {
85
+ const record = this.records.get(id)
86
+ if (record === undefined) return undefined
87
+ if (record.expiresAt <= this.now()) {
88
+ this.records.delete(id)
89
+ return undefined
90
+ }
91
+ return record
92
+ }
93
+
94
+ delete(id: string): void {
95
+ this.records.delete(id)
96
+ }
97
+
98
+ get size(): number {
99
+ return this.records.size
100
+ }
101
+
102
+ /** 惰性清理过期项 + 按插入序淘汰最旧(不做定时器:无人调用时不需要清理)。 */
103
+ private evict(ts: number): void {
104
+ for (const [id, record] of this.records) {
105
+ if (record.expiresAt <= ts) this.records.delete(id)
106
+ }
107
+ while (this.records.size > MODEL_PLAN_MAX) {
108
+ const oldest = this.records.keys().next()
109
+ if (oldest.done === true) break
110
+ this.records.delete(oldest.value)
111
+ }
112
+ }
113
+ }
114
+
115
+ /* ------------------------------------------------------------ 指纹 */
116
+
117
+ /** 稳定序列化:对象键按字典序,保证同一份材料在任何构造顺序下得到同一个指纹。 */
118
+ export function stableStringify(value: unknown): string {
119
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null'
120
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
121
+ const record = value as Record<string, unknown>
122
+ const keys = Object.keys(record).sort()
123
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`
124
+ }
125
+
126
+ function digest(kind: ModelPlanKind, material: unknown): string {
127
+ return createHash('sha256').update(kind).update('\n').update(stableStringify(material)).digest('hex')
128
+ }
129
+
130
+ /**
131
+ * 同步合并计划的指纹:只取「分区 id + 结论 + 冲突位置」。
132
+ *
133
+ * **刻意不含三侧预览文本**(localPreview / remotePreview / ancestorPreview):那是给人看的,
134
+ * 同一份计划在不同时刻被截断/脱敏的方式可能变,纳入指纹会让「什么都没变的计划」被误判成变化。
135
+ * 反过来,冲突多出一处路径 = 远端或本机真的动了,必须重新确认。
136
+ */
137
+ export function syncMergeFingerprint(preview: MergePreviewShape): string {
138
+ return digest('sync-merge', {
139
+ ok: preview.ok,
140
+ snapshotId: preview.snapshotId,
141
+ hasAncestor: preview.hasAncestor,
142
+ sections: preview.sections.map((section) => ({
143
+ id: section.id,
144
+ decision: section.decision,
145
+ autoMerged: section.autoMerged ?? 0,
146
+ conflicts: section.conflicts.map((conflict) => [conflict.path, conflict.kind, conflict.reason ?? '']),
147
+ })),
148
+ })
149
+ }
150
+
151
+ /**
152
+ * 导入计划的指纹:取「每条 item 的身份 + 结论」与用户决策。
153
+ *
154
+ * 不含 description / detail 文案(改文案不该让预览失效),但含 target.ref 与 kind ——
155
+ * 计划项从 Create 变成 Conflict、或目标路径变了,都是用户需要重新看一眼的变化。
156
+ */
157
+ export function importPlanFingerprint(plan: ImportPlan, decisions: ImportDecisions): string {
158
+ return digest('import', {
159
+ strategy: decisions.strategy,
160
+ pathMappings: decisions.pathMappings.map((mapping) => [mapping.oldPrefix, mapping.newPrefix, mapping.appliesTo.join(',')]),
161
+ items: plan.items.map((item) => [
162
+ item.id,
163
+ item.kind,
164
+ item.adapter,
165
+ item.target?.ref ?? '',
166
+ item.target?.file ?? '',
167
+ ]),
168
+ missingSecrets: plan.missingSecrets.map((secret) => secret.ref),
169
+ })
170
+ }
@@ -28,6 +28,7 @@ import { EnvironmentLockUnavailableError } from '../utils/env-lock.ts'
28
28
  import type { MutationLockPort } from '../utils/env-lock.ts'
29
29
  import { createSecretScanner } from '../security/secret-scanner.ts'
30
30
  import type { SecretScanner } from './types.ts'
31
+ import type { SectionId } from '../schema/types.ts'
31
32
 
32
33
  /** 内存 SyncTransport(spy:记录方法调用,供断言「pull 不写远端」)。 */
33
34
  class MemSyncTransport implements SyncTransport {
@@ -77,7 +78,8 @@ async function makeDeps(opts: {
77
78
  const adapters = createAdapters({ namespaces: NS })
78
79
  const syncDir = path.join(tmp, 'sync')
79
80
  const transport = opts.transport ?? new MemSyncTransport()
80
- const makeSyncEngine = (cfg: SyncConfig): SyncEngine => {
81
+ // 第二参 engineOpts:agent 侧只按 'auto' 档放行分区(D5),这里必须透传给引擎构造。
82
+ const makeSyncEngine = (cfg: SyncConfig, engineOpts?: { optInSections?: readonly SectionId[] }): SyncEngine => {
81
83
  const importer = new Importer({ ctx, adapters, snapshotStore: new MemSnapshotStore() })
82
84
  return new SyncEngine({
83
85
  ctx,
@@ -87,6 +89,7 @@ async function makeDeps(opts: {
87
89
  zipDir: path.join(tmp, 'tmp'),
88
90
  adapters,
89
91
  importer,
92
+ ...(engineOpts?.optInSections === undefined ? {} : { optInSections: engineOpts.optInSections }),
90
93
  now: () => new Date('2026-08-16T12:00:00.000Z'),
91
94
  })
92
95
  }
@@ -98,6 +101,10 @@ async function makeDeps(opts: {
98
101
  snapshotsDir: path.join(tmp, 'snapshots'),
99
102
  syncDir,
100
103
  makeSyncEngine,
104
+ // D5/D6 真实装配口径:受控根 = 本用例 tmp、导入器与路由同一工厂、agent 只放行 'auto' 档分区。
105
+ roots: [tmp],
106
+ makeImporter: () => new Importer({ ctx, adapters, snapshotStore: new MemSnapshotStore() }),
107
+ optInSections: (): readonly SectionId[] => ['settings'],
101
108
  exporterVersion: '0.1.45',
102
109
  // M1:缺省不传 scanner(保持旧行为:Exporter 落回 defaultSecretScanner,无 scanText)
103
110
  ...(opts.scanner === undefined ? {} : { scanner: opts.scanner }),
@@ -108,6 +115,15 @@ async function makeDeps(opts: {
108
115
  }
109
116
  }
110
117
 
118
+ /** 建一个空快照目录(restore 用例共用;entries 空 = 计划里没有写/删动作)。 */
119
+ async function seedEmptySnapshot(snapshotsDir: string, id = 'snap1'): Promise<void> {
120
+ await fs.mkdir(path.join(snapshotsDir, id), { recursive: true })
121
+ await fs.writeFile(
122
+ path.join(snapshotsDir, id, 'snapshot.json'),
123
+ JSON.stringify({ id, createdAt: '2026-08-16T12:00:00.000Z', sourceZip: 'x.zip', entries: [], beforePlugins: [], hostFileBackups: [] }),
124
+ )
125
+ }
126
+
111
127
  test('config_backup:导出真实 ZIP 到 exports 目录,返回非敏感摘要(无凭据值)', async () => {
112
128
  const { deps, tmp } = await makeDeps()
113
129
  try {
@@ -201,13 +217,17 @@ test('M1 源码守卫:index.ts 把同一个 scanner 实例注入 HTTP 导出
201
217
  const routesBody = source.slice(routesStart, routesEnd)
202
218
  assert.ok(routesBody.includes(`scanner: ${name},`), `makeRoutes 必须注入同一个 scanner 实例(scanner: ${name},)`)
203
219
 
204
- // 4) config_backup 模型工具(registerModelTools 注入 ModelToolsDeps.scanner)
205
- const toolsStart = source.indexOf('registerModelTools(ctx, {')
206
- assert.ok(toolsStart > 0, '应能找到 registerModelTools 调用')
207
- const toolsEnd = source.indexOf('\n })', toolsStart)
208
- assert.ok(toolsEnd > toolsStart, '应能找到 registerModelTools 调用结尾')
220
+ // 4) config_backup 模型工具:装配已下沉到 routes/model-tools-deps.ts,
221
+ // index.ts 只保留「同一实例 → agentToolDeps → registerModelTools」这条链。
222
+ assert.ok(source.includes('registerModelTools(ctx, agentToolDeps)'), 'index.ts 必须把 agentToolDeps 交给 registerModelTools')
223
+ const toolsStart = source.indexOf('agentToolDeps: createAgentToolDeps({')
224
+ assert.ok(toolsStart > 0, '应能找到 agentToolDeps 装配')
225
+ const toolsEnd = source.indexOf('\n }),', toolsStart)
226
+ assert.ok(toolsEnd > toolsStart, '应能找到 agentToolDeps 装配结尾')
209
227
  const toolsBody = source.slice(toolsStart, toolsEnd)
210
- assert.ok(toolsBody.includes(`scanner: ${name},`), `registerModelTools 必须注入同一个 scanner 实例(scanner: ${name},)`)
228
+ assert.ok(toolsBody.includes('scanner: deps.scanner'), `agentToolDeps 必须注入同一个 scanner 实例(scanner: deps.scanner),实际:${toolsBody}`)
229
+ const wiring = (await fs.readFile(new URL('../../src/routes/model-tools-deps.ts', import.meta.url), 'utf8')).replace(/\r\n/g, '\n')
230
+ assert.ok(wiring.includes('scanner: input.scanner'), 'model-tools-deps.ts 必须把 input.scanner 交给 ModelToolsDeps(否则注入了却没接上)')
211
231
 
212
232
  // 5) 路由内部确实把它交给 Exporter(防「注入了 deps 却没接上」)
213
233
  const exportRouteStart = source.indexOf('path: API.export,')
@@ -285,13 +305,19 @@ test('config_restore:confirm:false 只预览(零写入);confirm:true 执
285
305
  await ctx.fs.writeFile('settings.yaml', Buffer.from('foo: bar', 'utf8'))
286
306
 
287
307
  const tools = createModelTools(deps)
288
- const plan = (await tools.restore({ snapshotId: 'snap1', confirm: false })) as { dryRun: boolean; actions: { kind: string }[] }
308
+ const plan = (await tools.restore({ snapshotId: 'snap1', confirm: false })) as {
309
+ dryRun: boolean; planId: string; actions: { kind: string }[]
310
+ }
289
311
  assert.equal(plan.dryRun, true)
290
312
  const WRITE_KINDS = new Set(['hostFileRestore', 'hostFileRemove', 'pluginRemove', 'fileRestore', 'fileRemove'])
291
313
  assert.ok(plan.actions.every((a) => !WRITE_KINDS.has(a.kind)), '预览无任何写/删/卸载动作(只有 skip)')
314
+ assert.ok(plan.planId.length > 0, 'D2:预览必须回 planId(执行侧凭它比对)')
292
315
  assert.ok(await ctx.fs.exists('settings.yaml'), '预览不写不删')
293
316
 
294
- const exec = (await tools.restore({ snapshotId: 'snap1', confirm: true })) as { dryRun: boolean; restored: string[] }
317
+ // D2:执行必须带回预览给的 planId(参数契约见 config_restore 的 planId)。
318
+ const exec = (await tools.restore({
319
+ snapshotId: 'snap1', confirm: true, planId: plan.planId,
320
+ })) as { dryRun: boolean; restored: string[] }
295
321
  assert.equal(exec.dryRun, false)
296
322
  assert.deepEqual(exec.restored, [])
297
323
  } finally {
@@ -357,9 +383,183 @@ test('config_sync_pull:空远端 → 零写入空差异', async () => {
357
383
  }
358
384
  })
359
385
 
386
+ /* ---------------- D2:恢复预览-执行同指纹(GUI 409 的模型面等价物) ---------------- */
387
+
388
+ test('config_restore:confirm:true 缺 planId → plan-required(零写入)', async () => {
389
+ const { deps, tmp, ctx } = await makeDeps()
390
+ try {
391
+ await seedEmptySnapshot(deps.snapshotsDir)
392
+ await ctx.fs.writeFile('settings.yaml', Buffer.from('foo: bar', 'utf8'))
393
+ const tools = createModelTools(deps)
394
+ const out = (await tools.restore({ snapshotId: 'snap1', confirm: true })) as {
395
+ ok: false; code: string; retryable: boolean; nextAction: string
396
+ }
397
+ assert.equal(out.ok, false)
398
+ assert.equal(out.code, 'plan-required')
399
+ assert.equal(out.retryable, true, '补一次预览就能继续 → 可重试')
400
+ assert.ok(out.nextAction.length > 0, '必须告诉模型下一步做什么')
401
+ assert.ok(await ctx.fs.exists('settings.yaml'), '拒绝后零写入')
402
+ } finally {
403
+ await fs.rm(tmp, { recursive: true, force: true })
404
+ }
405
+ })
406
+
407
+ test('config_restore:planId 与当前盘面不符 → plan-changed(零写入)', async () => {
408
+ const { deps, tmp, ctx } = await makeDeps()
409
+ try {
410
+ await seedEmptySnapshot(deps.snapshotsDir)
411
+ await ctx.fs.writeFile('settings.yaml', Buffer.from('foo: bar', 'utf8'))
412
+ const tools = createModelTools(deps)
413
+ // 伪造指纹(等价于「预览后被别的设备/页面改过盘面」)
414
+ const out = (await tools.restore({ snapshotId: 'snap1', confirm: true, planId: 'deadbeef' })) as {
415
+ ok: false; code: string
416
+ }
417
+ assert.equal(out.code, 'plan-changed')
418
+ assert.ok(await ctx.fs.exists('settings.yaml'), '拒绝后零写入')
419
+ } finally {
420
+ await fs.rm(tmp, { recursive: true, force: true })
421
+ }
422
+ })
423
+
424
+ /* ---------------- D3/D4:同步密码槽优先、禁止 agent 触发凭据上行 ---------------- */
425
+
426
+ test('config_sync_push:encrypt 且无已存密码槽、无入参 → sync-password-missing(不写远端)', async () => {
427
+ const { deps, tmp, transport } = await makeDeps()
428
+ try {
429
+ await writeSyncConfig(deps.syncDir, { schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://github.com/u/r.git' } })
430
+ const tools = createModelTools(deps)
431
+ const out = (await tools.syncPush({ channel: 'git', encrypt: true })) as { ok: false; code: string; message: string }
432
+ assert.equal(out.ok, false)
433
+ assert.equal(out.code, 'sync-password-missing')
434
+ assert.ok(out.message.includes('git'), '错误要指明通道,模型才知道去配哪一条')
435
+ assert.ok(!transport.calls.includes('upload'), '拿不到密码就绝不发远端')
436
+ } finally {
437
+ await fs.rm(tmp, { recursive: true, force: true })
438
+ }
439
+ })
440
+
441
+ test('config_sync_push:加密密码优先取已存凭据槽(passwordSource=stored),入参不再是常态来源', async () => {
442
+ const { deps, tmp, transport } = await makeDeps()
443
+ try {
444
+ await writeSyncConfig(deps.syncDir, { schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://github.com/u/r.git' } })
445
+ const asked: string[] = []
446
+ const depsWithSlot: ModelToolsDeps = {
447
+ ...deps,
448
+ syncPassword: async (kind, channel) => { asked.push(kind + ':' + channel); return 'slot-secret' },
449
+ }
450
+ const tools = createModelTools(depsWithSlot)
451
+ const out = (await tools.syncPush({ channel: 'git', encrypt: true, password: 'typed-into-chat' })) as {
452
+ ok: boolean; passwordSource?: string
453
+ }
454
+ assert.deepEqual(asked, ['ENCRYPT:git'], '只问加密槽,不碰解密槽')
455
+ assert.equal(out.passwordSource, 'stored', '槽位优先于入参(入参会进会话历史)')
456
+ assert.equal(out.ok, true)
457
+ assert.ok(transport.calls.includes('upload'))
458
+ } finally {
459
+ await fs.rm(tmp, { recursive: true, force: true })
460
+ }
461
+ })
462
+
463
+ test('config_sync_push:includeSecrets:true → include-secrets-forbidden(不写远端,不构造引擎)', async () => {
464
+ const { deps, tmp, transport } = await makeDeps()
465
+ try {
466
+ const tools = createModelTools(deps)
467
+ const out = (await tools.syncPush({ channel: 'git', includeSecrets: true })) as { ok: false; code: string; retryable: boolean }
468
+ assert.equal(out.code, 'include-secrets-forbidden')
469
+ assert.equal(out.retryable, false, '这是硬边界,重试没有意义')
470
+ assert.deepEqual(transport.calls, [], '连远端探测都不做')
471
+ } finally {
472
+ await fs.rm(tmp, { recursive: true, force: true })
473
+ }
474
+ })
475
+
476
+ /* ---------------- D5:三方合并预览-落地(句柄 + 锁内重比对) ---------------- */
477
+
478
+ test('config_sync_preview / config_sync_apply:planId 句柄贯通;未知句柄 → plan-expired', async () => {
479
+ const { deps, tmp, transport } = await makeDeps()
480
+ try {
481
+ await writeSyncConfig(deps.syncDir, { schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://github.com/u/r.git' } })
482
+ const tools = createModelTools(deps)
483
+ await tools.syncPush({ channel: 'git' })
484
+ assert.ok(transport.calls.includes('upload'))
485
+
486
+ const preview = (await tools.syncPreview({ channel: 'git' })) as {
487
+ ok: boolean; planId: string; preview: { sections: { id: string; decision: string }[] }
488
+ }
489
+ assert.equal(preview.ok, true)
490
+ assert.match(preview.planId, /^[0-9a-f]{64}$/, 'planId = 预览指纹')
491
+ assert.ok(preview.preview.sections.length > 0, '预览要给出分区裁决清单')
492
+ // 不下发三侧预览文本(GUI 逐键对比用的分段文本,体积大且含配置内容)
493
+ const serialized = JSON.stringify(preview)
494
+ assert.ok(!serialized.includes('localPreview'), '不下发 localPreview')
495
+ assert.ok(!serialized.includes('remotePreview'), '不下发 remotePreview')
496
+
497
+ const unknown = (await tools.syncApply({ planId: 'unknown', resolutions: [] })) as { ok: false; code: string }
498
+ assert.equal(unknown.code, 'plan-expired')
499
+
500
+ const badAction = (await tools.syncApply({ planId: preview.planId, resolutions: [{ id: 'settings', action: 'nuke' }] })) as {
501
+ ok: false; code: string
502
+ }
503
+ assert.equal(badAction.code, 'invalid-resolution')
504
+
505
+ const applied = (await tools.syncApply({ planId: preview.planId, resolutions: [] })) as {
506
+ ok: boolean; applied: string[]; pendingConflicts: string[]
507
+ }
508
+ assert.equal(applied.ok, true, '无裁决项 = 全部保持现状(探针实测 9 分区全 skip)')
509
+ assert.deepEqual(applied.applied, [])
510
+ assert.deepEqual(applied.pendingConflicts, [])
511
+ } finally {
512
+ await fs.rm(tmp, { recursive: true, force: true })
513
+ }
514
+ })
515
+
516
+ /* ---------------- D6:导入计划 + 执行(受控路径 + 句柄) ---------------- */
517
+
518
+ test('config_import_plan / config_import_apply:受控 zip → planId → 执行;非受控路径与缺 confirm 拒绝', async () => {
519
+ const { deps, tmp } = await makeDeps()
520
+ try {
521
+ const tools = createModelTools(deps)
522
+ const backup = (await tools.backup({})) as { ok: boolean; zip: string }
523
+ assert.equal(backup.ok, true)
524
+ const zipPath = path.join(deps.exportsDir, backup.zip)
525
+
526
+ const planned = (await tools.importPlan({ zipPath })) as {
527
+ ok: boolean; planId: string; plan: { counts: Record<string, number>; items: { id: string }[] }
528
+ }
529
+ assert.equal(planned.ok, true)
530
+ assert.match(planned.planId, /^[0-9a-f]{64}$/)
531
+ assert.ok(Object.keys(planned.plan.counts).length > 0, '计划要给出各 kind 的计数')
532
+
533
+ const noConfirm = (await tools.importApply({ planId: planned.planId })) as { ok: false; code: string }
534
+ assert.equal(noConfirm.code, 'confirm-required')
535
+
536
+ const applied = (await tools.importApply({ planId: planned.planId, confirm: true })) as {
537
+ ok: boolean; executedCount: number
538
+ }
539
+ assert.equal(applied.ok, true)
540
+ assert.ok(applied.executedCount >= 0)
541
+
542
+ // 句柄已消费:同一 planId 不能重放
543
+ const replay = (await tools.importApply({ planId: planned.planId, confirm: true })) as { ok: false; code: string }
544
+ assert.equal(replay.code, 'plan-expired')
545
+
546
+ // 受控根外的归档一律拒绝(roots 是宿主张有的可写根,不是模型自选路径)
547
+ const outside = path.join(os.tmpdir(), 'not-controlled.zip')
548
+ const denied = (await tools.importPlan({ zipPath: outside })) as { ok: false; code: string; message: string }
549
+ assert.equal(denied.code, 'path-not-controlled')
550
+ assert.ok(denied.message.includes(outside), '错误要带上被拒路径')
551
+
552
+ const noRoots = createModelTools({ ...deps, roots: [] })
553
+ const denied2 = (await noRoots.importPlan({ zipPath })) as { ok: false; code: string }
554
+ assert.equal(denied2.code, 'path-not-controlled', '未装配 roots = 一律拒绝(fail-closed)')
555
+ } finally {
556
+ await fs.rm(tmp, { recursive: true, force: true })
557
+ }
558
+ })
559
+
360
560
  // ------------------------------------------------ 注册层(registerModelTools)
361
561
 
362
- test('registerModelTools:tools 服务存在 → 注册 5 个工具(走 ctx.get 结果,属性访问守卫不崩)', async () => {
562
+ test('registerModelTools:tools 服务存在 → 注册 9 个工具(走 ctx.get 结果,属性访问守卫不崩)', async () => {
363
563
  const { deps, tmp } = await makeDeps()
364
564
  try {
365
565
  const names: string[] = []
@@ -377,8 +577,8 @@ test('registerModelTools:tools 服务存在 → 注册 5 个工具(走 ctx.g
377
577
  // 不抛错 = 注册走 toolsSvc + defineTool schema 全部可编译(无效 schema 会在定义时抛错)
378
578
  registerModelTools(wrapped, deps)
379
579
  assert.deepEqual(names.sort(), [
380
- 'config_backup', 'config_list_snapshots', 'config_restore',
381
- 'config_sync_pull', 'config_sync_push',
580
+ 'config_backup', 'config_import_apply', 'config_import_plan', 'config_list_snapshots',
581
+ 'config_restore', 'config_sync_apply', 'config_sync_preview', 'config_sync_pull', 'config_sync_push',
382
582
  ].sort())
383
583
  } finally {
384
584
  await fs.rm(tmp, { recursive: true, force: true })