dsh-config-manager 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/README.md +10 -0
  2. package/README.zh-CN.md +10 -0
  3. package/lib/adapters/mcp.d.ts +9 -0
  4. package/lib/adapters/mcp.js +37 -0
  5. package/lib/adapters/plugins.js +10 -2
  6. package/lib/adapters/pnpm-workspace.js +1 -1
  7. package/lib/adapters/self.d.ts +2 -0
  8. package/lib/adapters/self.js +18 -2
  9. package/lib/adapters/workspaces.js +1 -1
  10. package/lib/cli/restore-resume.js +1 -1
  11. package/lib/cli/web/page.js +2 -2
  12. package/lib/client.d.ts +14 -41
  13. package/lib/client.js +794 -716
  14. package/lib/core/backup.d.ts +11 -0
  15. package/lib/core/backup.js +27 -0
  16. package/lib/core/env-lock-lifecycle.d.ts +17 -3
  17. package/lib/core/env-lock-lifecycle.js +38 -0
  18. package/lib/core/external-failure.d.ts +9 -0
  19. package/lib/core/external-failure.js +50 -0
  20. package/lib/core/local-plugin-host.d.ts +9 -7
  21. package/lib/core/local-plugin-host.js +109 -15
  22. package/lib/core/local-plugin-pack.d.ts +20 -0
  23. package/lib/core/local-plugin-pack.js +18 -3
  24. package/lib/core/mcp-connector-store.d.ts +13 -0
  25. package/lib/core/mcp-connector-store.js +16 -1
  26. package/lib/core/messages-core.d.ts +45 -0
  27. package/lib/core/messages-core.js +92 -0
  28. package/lib/core/messages.d.ts +1 -0
  29. package/lib/core/messages.js +6 -0
  30. package/lib/core/model-tool-plans.d.ts +66 -0
  31. package/lib/core/model-tool-plans.js +128 -0
  32. package/lib/core/model-tools.d.ts +96 -8
  33. package/lib/core/model-tools.js +568 -31
  34. package/lib/core/phase3-host.js +10 -2
  35. package/lib/core/plugin-data-registry.d.ts +1 -1
  36. package/lib/core/plugin-data-registry.js +1 -1
  37. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  38. package/lib/core/restore-plan-fingerprint.js +18 -0
  39. package/lib/core/restore-resume.d.ts +1 -1
  40. package/lib/core/restore-resume.js +1 -1
  41. package/lib/core/restore.d.ts +5 -0
  42. package/lib/core/restore.js +4 -1
  43. package/lib/core/types.d.ts +12 -0
  44. package/lib/foreign/claude-sessions.d.ts +1 -1
  45. package/lib/foreign/claude-sessions.js +1 -1
  46. package/lib/foreign/registry.js +1 -1
  47. package/lib/foreign/types.d.ts +1 -1
  48. package/lib/index.d.ts +15 -15
  49. package/lib/index.js +60 -67
  50. package/lib/market/git-file-writer.js +1 -1
  51. package/lib/market/github-repos.js +1 -1
  52. package/lib/market/market-config.js +1 -1
  53. package/lib/market/messages-market.js +1 -1
  54. package/lib/market/my-repo.js +1 -1
  55. package/lib/market/prepare.js +1 -1
  56. package/lib/market/reader.js +2 -2
  57. package/lib/market/repo-url.d.ts +1 -1
  58. package/lib/market/security.js +2 -2
  59. package/lib/market/star-cache.d.ts +1 -1
  60. package/lib/market/types.d.ts +1 -1
  61. package/lib/market/types.js +1 -1
  62. package/lib/market/url.js +1 -1
  63. package/lib/routes/backup.js +17 -9
  64. package/lib/routes/index.d.ts +1 -1
  65. package/lib/routes/kit.d.ts +2 -2
  66. package/lib/routes/market.d.ts +1 -1
  67. package/lib/routes/market.js +3 -60
  68. package/lib/routes/model-tools-deps.d.ts +41 -0
  69. package/lib/routes/model-tools-deps.js +18 -0
  70. package/lib/routes/recovery.js +5 -3
  71. package/lib/routes/route-support.d.ts +18 -26
  72. package/lib/routes/route-support.js +19 -32
  73. package/lib/routes/snapshots.d.ts +1 -1
  74. package/lib/routes/snapshots.js +4 -40
  75. package/lib/routes/sync.js +40 -28
  76. package/lib/schema/index.d.ts +2 -2
  77. package/lib/schema/index.js +2 -2
  78. package/lib/schema/section-registry.d.ts +5 -3
  79. package/lib/schema/section-registry.js +7 -3
  80. package/lib/security/secret-scanner.js +1 -1
  81. package/lib/sync/apply-bundle.d.ts +50 -0
  82. package/lib/sync/apply-bundle.js +60 -0
  83. package/lib/sync/autosync-scheduler.d.ts +9 -0
  84. package/lib/sync/autosync-scheduler.js +118 -89
  85. package/lib/sync/backup-scheduler.js +5 -4
  86. package/lib/sync/blob-store.d.ts +2 -2
  87. package/lib/sync/git/git-transport.d.ts +12 -0
  88. package/lib/sync/git/git-transport.js +50 -2
  89. package/lib/sync/merge.d.ts +2 -0
  90. package/lib/sync/merge.js +28 -0
  91. package/lib/sync/messages.d.ts +4 -0
  92. package/lib/sync/messages.js +9 -2
  93. package/lib/sync/s3/s3-transport.d.ts +1 -1
  94. package/lib/sync/s3/s3-transport.js +1 -1
  95. package/lib/sync/sync-engine.d.ts +4 -4
  96. package/lib/sync/sync-engine.js +25 -26
  97. package/lib/sync/sync-scope-boot.d.ts +34 -0
  98. package/lib/sync/sync-scope-boot.js +71 -0
  99. package/lib/sync/sync-scope.d.ts +103 -0
  100. package/lib/sync/sync-scope.js +229 -0
  101. package/lib/sync/sync-selection.d.ts +17 -4
  102. package/lib/sync/sync-selection.js +40 -14
  103. package/lib/sync/transport.d.ts +4 -1
  104. package/lib/sync/transport.js +6 -0
  105. package/lib/sync/webdav/webdav-transport.js +1 -1
  106. package/lib/sync/workspace-merge.d.ts +36 -0
  107. package/lib/sync/workspace-merge.js +152 -0
  108. package/lib/ui/backup-schedule.d.ts +13 -2
  109. package/lib/ui/backup-schedule.js +3 -0
  110. package/lib/ui/snapshots-view.d.ts +16 -0
  111. package/lib/ui/snapshots-view.js +21 -0
  112. package/lib/utils/env-lock.d.ts +96 -0
  113. package/lib/utils/env-lock.js +332 -111
  114. package/lib/utils/messages-utils.d.ts +6 -0
  115. package/lib/utils/messages-utils.js +17 -1
  116. package/lib/utils/patch-yaml.js +1 -1
  117. package/lib/utils/zip.js +1 -1
  118. package/package.json +3 -2
  119. package/src/adapters/mcp.test.ts +28 -0
  120. package/src/adapters/mcp.ts +33 -0
  121. package/src/adapters/plugins.test.ts +49 -0
  122. package/src/adapters/plugins.ts +9 -1
  123. package/src/adapters/pnpm-workspace.ts +1 -1
  124. package/src/adapters/self.test.ts +39 -1
  125. package/src/adapters/self.ts +20 -2
  126. package/src/adapters/workspaces.ts +1 -1
  127. package/src/cli/restore-resume.ts +1 -1
  128. package/src/cli/web/page.ts +2 -2
  129. package/src/client/about/AboutPanel.tsx +1 -1
  130. package/src/client/about/about-view.test.ts +1 -1
  131. package/src/client/about/about-view.ts +1 -1
  132. package/src/client/api.ts +1 -6
  133. package/src/client/chat/chat-entry-view.test.ts +1 -1
  134. package/src/client/chat/chat-slots.ts +1 -1
  135. package/src/client/chat/rollback-diff-tab.ts +1 -1
  136. package/src/client/client-types.ts +1 -1
  137. package/src/client/common/routes.ts +1 -5
  138. package/src/client/css-scale-guard.test.ts +1 -1
  139. package/src/client/home/HomePanel.tsx +3 -0
  140. package/src/client/library/ArtifactRow.tsx +14 -2
  141. package/src/client/library/LibraryPanel.tsx +44 -0
  142. package/src/client/locales/overview.ts +10 -2
  143. package/src/client/locales/sessions.ts +3 -0
  144. package/src/client/market/MyConfigsView.tsx +1 -1
  145. package/src/client/market/market-api.ts +2 -14
  146. package/src/client/market/market-locales.ts +1 -1
  147. package/src/client/market/market-view.ts +3 -3
  148. package/src/client/market/my-configs-api.ts +1 -1
  149. package/src/client/market/my-configs-view.ts +1 -1
  150. package/src/client/recovery/recovery-locales.test.ts +1 -1
  151. package/src/client/run-store.ts +1 -1
  152. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  153. package/src/client/sync/history-model.test.ts +28 -7
  154. package/src/client/sync/history-model.ts +6 -3
  155. package/src/client/sync/sync-locales.ts +10 -4
  156. package/src/client/sync/sync-view.ts +1 -1
  157. package/src/core/analyzer-cache.test.ts +1 -1
  158. package/src/core/backup.test.ts +45 -1
  159. package/src/core/backup.ts +25 -0
  160. package/src/core/disk-usage.test.ts +2 -0
  161. package/src/core/env-lock-lifecycle.ts +33 -3
  162. package/src/core/external-failure.test.ts +60 -0
  163. package/src/core/external-failure.ts +54 -0
  164. package/src/core/integrity-extra-entries.test.ts +1 -1
  165. package/src/core/local-plugin-host.test.ts +134 -0
  166. package/src/core/local-plugin-host.ts +122 -17
  167. package/src/core/local-plugin-pack.ts +39 -3
  168. package/src/core/mcp-connector-store.ts +26 -1
  169. package/src/core/messages-core.ts +94 -0
  170. package/src/core/messages.ts +6 -0
  171. package/src/core/model-tool-plans.test.ts +111 -0
  172. package/src/core/model-tool-plans.ts +170 -0
  173. package/src/core/model-tools.test.ts +212 -12
  174. package/src/core/model-tools.ts +710 -38
  175. package/src/core/phase3-host.ts +10 -2
  176. package/src/core/phase3-production-integration.test.ts +43 -0
  177. package/src/core/plugin-data-registry.ts +1 -1
  178. package/src/core/restore-plan-fingerprint.ts +19 -0
  179. package/src/core/restore-resume.ts +1 -1
  180. package/src/core/restore.ts +9 -1
  181. package/src/core/types.ts +12 -0
  182. package/src/foreign/claude-sessions.ts +3 -3
  183. package/src/foreign/registry.ts +1 -1
  184. package/src/foreign/types.ts +1 -1
  185. package/src/index.ts +91 -98
  186. package/src/market/git-file-writer.ts +1 -1
  187. package/src/market/github-repos.test.ts +1 -1
  188. package/src/market/github-repos.ts +1 -1
  189. package/src/market/market-config.ts +1 -1
  190. package/src/market/messages-market.ts +1 -1
  191. package/src/market/my-repo.test.ts +1 -1
  192. package/src/market/my-repo.ts +1 -1
  193. package/src/market/prepare.test.ts +1 -1
  194. package/src/market/prepare.ts +1 -1
  195. package/src/market/reader.ts +2 -2
  196. package/src/market/repo-url.ts +1 -1
  197. package/src/market/security.ts +2 -2
  198. package/src/market/star-cache.ts +1 -1
  199. package/src/market/types.ts +1 -1
  200. package/src/market/url.test.ts +1 -1
  201. package/src/market/url.ts +1 -1
  202. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  203. package/src/routes/backup.ts +16 -9
  204. package/src/routes/index.ts +1 -1
  205. package/src/routes/kit.ts +2 -2
  206. package/src/routes/market.ts +2 -59
  207. package/src/routes/model-tools-deps.ts +56 -0
  208. package/src/routes/recovery.ts +5 -3
  209. package/src/routes/route-support.ts +49 -36
  210. package/src/routes/snapshots.ts +4 -40
  211. package/src/routes/sync.ts +39 -27
  212. package/src/schema/index.ts +2 -2
  213. package/src/schema/manifest-schema.test.ts +2 -2
  214. package/src/schema/registry.test.ts +1 -1
  215. package/src/schema/section-registry.ts +9 -4
  216. package/src/security/redaction.test.ts +1 -1
  217. package/src/security/secret-scanner.test.ts +2 -2
  218. package/src/security/secret-scanner.ts +1 -1
  219. package/src/sync/apply-bundle.ts +104 -0
  220. package/src/sync/autosync-scheduler.test.ts +180 -6
  221. package/src/sync/autosync-scheduler.ts +132 -92
  222. package/src/sync/backup-scheduler.test.ts +11 -4
  223. package/src/sync/backup-scheduler.ts +5 -4
  224. package/src/sync/blob-store.ts +2 -2
  225. package/src/sync/git/git-transport.test.ts +62 -0
  226. package/src/sync/git/git-transport.ts +54 -3
  227. package/src/sync/merge.ts +29 -0
  228. package/src/sync/messages.ts +9 -2
  229. package/src/sync/s3/s3-transport.ts +1 -1
  230. package/src/sync/sync-engine.test.ts +238 -2
  231. package/src/sync/sync-engine.ts +25 -26
  232. package/src/sync/sync-preview-push.test.ts +2 -1
  233. package/src/sync/sync-scope-boot.ts +87 -0
  234. package/src/sync/sync-scope.test.ts +154 -0
  235. package/src/sync/sync-scope.ts +256 -0
  236. package/src/sync/sync-selection.test.ts +76 -2
  237. package/src/sync/sync-selection.ts +40 -13
  238. package/src/sync/transport.test.ts +21 -1
  239. package/src/sync/transport.ts +12 -0
  240. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  241. package/src/sync/webdav/webdav-transport.ts +1 -1
  242. package/src/sync/workspace-merge.test.ts +110 -0
  243. package/src/sync/workspace-merge.ts +180 -0
  244. package/src/ui/backup-schedule.test.ts +5 -0
  245. package/src/ui/backup-schedule.ts +21 -2
  246. package/src/ui/session-issue-labels.ts +1 -1
  247. package/src/ui/snapshots-view.test.ts +32 -0
  248. package/src/ui/snapshots-view.ts +34 -0
  249. package/src/utils/env-lock.test.ts +242 -9
  250. package/src/utils/env-lock.ts +247 -13
  251. package/src/utils/messages-utils.ts +17 -1
  252. package/src/utils/patch-yaml.ts +1 -1
  253. package/src/utils/zip.ts +1 -1
  254. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -18,6 +18,7 @@
18
18
  * 持久化原因:自动同步调度器运行于 Host 进程(浏览器关闭也在跑),必须从磁盘读
19
19
  * 用户选择,而不是依赖浏览器 localStorage。
20
20
  */
21
+ import { readFileSync } from 'node:fs';
21
22
  import fs from 'node:fs/promises';
22
23
  import path from 'node:path';
23
24
 
@@ -71,7 +72,9 @@ export type SyncSelectionByChannel = Record<SyncTransportType, SyncSelection>;
71
72
  * \`['sessions']\`,与 \`section-registry.ts\` 的同名字段是**两份字面量、零护栏**
72
73
  * (改一处漏一处不会报错)—— issue #78 收敛为派生视图,并在测试里钉住。
73
74
  *
74
- * 当前 = mcp('auto',命令 / 路径可能机器相关)+ sessions('manual',内容敏感 + 设备相关)。
75
+ * 当前 = mcp('auto',命令 / 路径可能机器相关)
76
+ * + workspaces('manual',路径与机器绑定,但会话要显示在工作区里就必须随行)
77
+ * + sessions('manual',内容敏感 + 设备相关)。
75
78
  * 凭据 / 密钥分区不在此列(结构性拒绝,永不进同步)。
76
79
  */
77
80
  export const OPT_IN_SYNC_SECTIONS: readonly SectionId[] = OPT_IN_SYNC_SECTION_IDS;
@@ -79,9 +82,9 @@ export const OPT_IN_SYNC_SECTIONS: readonly SectionId[] = OPT_IN_SYNC_SECTION_ID
79
82
  /**
80
83
  * 「可选分区」里**允许参与自动同步**的子集(当前 = mcp)。
81
84
  *
82
- * 手动与自动的差别只在这里:sessions 是内容隐私 / 设备相关,自动同步绝不带
83
- * (「会话绝不悄悄下行」从注释变成可测断言);mcp 只是命令 / 路径可能与目标机不同,
84
- * 用户显式勾选后手动与自动都带。
85
+ * 手动与自动的差别只在这里:sessions 是内容隐私 / 设备相关、workspaces 与本机路径绑定,
86
+ * 两者自动同步绝不带(「会话绝不悄悄下行」从注释变成可测断言);mcp 只是命令 / 路径可能与
87
+ * 目标机不同,用户显式勾选后手动与自动都带。
85
88
  */
86
89
  export const AUTO_SYNC_OPT_IN_SECTIONS: readonly SectionId[] = AUTO_SYNC_OPT_IN_SECTION_IDS;
87
90
 
@@ -157,15 +160,8 @@ function parseChannelSelection(obj: Record<string, unknown>): SyncSelection {
157
160
  return sel;
158
161
  }
159
162
 
160
- /** 读取全部通道的分区选择配置;文件不存在 / 损坏 / 不支持 schema → 缺省值(不抛错)。 */
161
- export async function readAllSyncSelections(dir: string): Promise<SyncSelectionByChannel> {
162
- const file = path.join(dir, SYNC_SELECTION_FILE);
163
- let raw: string;
164
- try {
165
- raw = await fs.readFile(file, 'utf8');
166
- } catch {
167
- return channelMap(() => defaultSyncSelection());
168
- }
163
+ /** 解析持久化文本(v1/v2、损坏、不支持 schema 全在这里归一);同步/异步两条读取路径共用这一份。 */
164
+ function parseSelectionFile(raw: string): SyncSelectionByChannel {
169
165
  let parsed: unknown;
170
166
  try {
171
167
  parsed = parseJsonSafe(raw);
@@ -197,6 +193,37 @@ export async function readAllSyncSelections(dir: string): Promise<SyncSelectionB
197
193
  });
198
194
  }
199
195
 
196
+ /** 读取全部通道的分区选择配置;文件不存在 / 损坏 / 不支持 schema → 缺省值(不抛错)。 */
197
+ export async function readAllSyncSelections(dir: string): Promise<SyncSelectionByChannel> {
198
+ let raw: string;
199
+ try {
200
+ raw = await fs.readFile(path.join(dir, SYNC_SELECTION_FILE), 'utf8');
201
+ } catch {
202
+ return channelMap(() => defaultSyncSelection());
203
+ }
204
+ return parseSelectionFile(raw);
205
+ }
206
+
207
+ /**
208
+ * 同步读取全部通道的分区选择(apply 期「同步种入缓存」用,2026-11「C6」)。
209
+ *
210
+ * 为什么必须是同步:`apply()` 是同步的,而缓存消费者(调度器首轮 / 手动 push 路由 /
211
+ * model tool)都**同步**读缓存。异步种入会留下一个窗口:窗口内 `selectionCache[ch]` 是
212
+ * undefined ⇒ 引擎兜底 `defaultSyncSelection()` ⇒ `effectiveSections` 返回 undefined
213
+ * (全部 portable),用户 advanced 勾的收窄在那一轮被吞掉(探针
214
+ * `.tmp/probe-c6-race.ts` 复现:同一 tick 读到 undefined,20ms 后才变 `["settings"]`)。
215
+ * 解析与 `readAllSyncSelections` 完全同一份(`parseSelectionFile`),不是第二套口径。
216
+ */
217
+ export function readAllSyncSelectionsSync(dir: string): SyncSelectionByChannel {
218
+ let raw: string;
219
+ try {
220
+ raw = readFileSync(path.join(dir, SYNC_SELECTION_FILE), 'utf8');
221
+ } catch {
222
+ return channelMap(() => defaultSyncSelection());
223
+ }
224
+ return parseSelectionFile(raw);
225
+ }
226
+
200
227
  /** 读取指定通道的分区选择配置;文件不存在 / 损坏 / 不支持 schema → 缺省值(不抛错)。 */
201
228
  export async function readSyncSelection(dir: string, channel: SyncTransportType): Promise<SyncSelection> {
202
229
  const all = await readAllSyncSelections(dir);
@@ -7,7 +7,7 @@
7
7
  import test from 'node:test';
8
8
  import assert from 'node:assert/strict';
9
9
 
10
- import { computeSnapshotMeta, manifestSummaryFrom } from './transport.ts';
10
+ import { classifyNetworkErrorText, computeSnapshotMeta, manifestSummaryFrom } from './transport.ts';
11
11
  import { hashSection } from './sync-state.ts';
12
12
  import type { ManifestSummary, SyncSnapshot, SyncTransport } from './transport.ts';
13
13
  import type { Manifest, SectionData, SectionId } from '../schema/types.ts';
@@ -99,6 +99,26 @@ test('SyncTransport 契约形状:实现对象必须具备 list/upload/download
99
99
  assert.doesNotThrow(() => fake.delete('x'));
100
100
  });
101
101
 
102
+ test('本机 git 身份缺失(unable to auto-detect email / empty ident name)→ config,不是 auth/notfound', () => {
103
+ // 真机 issue:commit exit 128 只因本机没配 user.name/user.email,却被当成普通 git 失败
104
+ // (→ 交易 NEEDS_ATTENTION → durable SAFE MODE → 全部写入 423)。分类必须先认出它。
105
+ const cases = [
106
+ "fatal: unable to auto-detect email address (got 'runner@BUILD.(none)')",
107
+ '*** Please tell me who you are.\nfatal: empty ident name (for <>) not allowed',
108
+ 'Author identity unknown',
109
+ 'fatal: no name was given and auto-detection is disabled',
110
+ ];
111
+ for (const text of cases) {
112
+ const c = classifyNetworkErrorText(text);
113
+ assert.equal(c.kind, 'config', text);
114
+ assert.equal(c.retryable, false, '本机配置问题重试无意义: ' + text);
115
+ }
116
+ // 回归:新分支不得吃掉既有分类(身份文案里常混着 'permission denied' 之外的宽泛词)
117
+ assert.equal(classifyNetworkErrorText('fatal: Authentication failed for https://x/y.git').kind, 'auth');
118
+ assert.equal(classifyNetworkErrorText('fatal: repository https://x/y.git not found').kind, 'notfound');
119
+ assert.equal(classifyNetworkErrorText('fatal: Could not resolve host: github.com').kind, 'network');
120
+ });
121
+
102
122
  test('ManifestSummary 类型形状(编译期保证 + 运行期检查)', () => {
103
123
  const s: ManifestSummary = {
104
124
  schemaVersion: 1,
@@ -148,6 +148,9 @@ export interface SyncTransport {
148
148
  * - auth:认证 / 授权失败 —— 重试无意义;
149
149
  * - notfound:远端实体不存在 —— 重试无意义;
150
150
  * - conflict:并发 / 非快进 / 锁冲突 —— 需人工决策;
151
+ * - config:**本机配置缺失**(如 git 没配 user.name/user.email 导致 commit exit 128)——
152
+ * 重试无意义、但**本机一步就能修好**,且不代表环境进入半写状态;上层据此收窄处置
153
+ * (标记为 localOnly,不升全局 SAFE MODE,见 core/external-failure.ts);
151
154
  * - client:其它 4xx(请求本身有问题)—— 重试无意义;
152
155
  * - protocol:响应或载荷不符合契约(解析失败、目录缺 manifest、重定向超限);
153
156
  * - unknown:无法归类(宁可当不可重试)。 */
@@ -156,6 +159,7 @@ export type SyncTransportErrorKind =
156
159
  | 'timeout'
157
160
  | 'server'
158
161
  | 'auth'
162
+ | 'config'
159
163
  | 'notfound'
160
164
  | 'conflict'
161
165
  | 'client'
@@ -321,6 +325,14 @@ export function classifyNetworkErrorText(text: string): { kind: SyncTransportErr
321
325
  'support for password authentication was removed')) {
322
326
  return { kind: 'auth', retryable: false };
323
327
  }
328
+ // 本机 git 身份缺失(真机 issue:commit exit 128 ⇒ 交易 NEEDS_ATTENTION ⇒ 误升 SAFE MODE)。
329
+ // 放在 auth/notfound 之前:这类 stderr 里也可能带 'permission denied' 之外的宽泛词,
330
+ // 但它与远端鉴权无关 —— 远端根本没被访问到,唯一修法是本机 git config。
331
+ if (has('unable to auto-detect email address', 'empty ident name', 'tell me who you are',
332
+ 'author identity unknown', 'committer identity unknown', 'please configure your identity',
333
+ 'no name was given and auto-detection is disabled')) {
334
+ return { kind: 'config', retryable: false };
335
+ }
324
336
  if (status(404) || has('not found', 'does not exist', 'no such file')) {
325
337
  return { kind: 'notfound', retryable: false };
326
338
  }
@@ -6,7 +6,7 @@
6
6
  * 删掉仍被其它快照引用的会话 blob(不可恢复)。
7
7
  * → 索引读不出来必须**中止删除**,绝不重写 index.json、绝不触发 blob GC。
8
8
  * sync-F3(P1):blob 仓 URL 此前多一个斜杠(…/dsh-config-manager//blobs/…),与
9
- * docs/spec/sync-channel-v1.md §3 的 \`<col>/blobs/<sha256>\` 及其它通道不一致。
9
+ * docs/contracts/sync-channel-v1.md §3 的 \`<col>/blobs/<sha256>\` 及其它通道不一致。
10
10
  */
11
11
  import test from 'node:test';
12
12
  import assert from 'node:assert/strict';
@@ -122,7 +122,7 @@ test('sync-F1:索引读不出来时绝不重写 index.json、绝不删除被
122
122
  assert.equal(state.blobs.has(BLOB_HASH), true, '被引用的 blob 必须仍在仓里');
123
123
  });
124
124
 
125
- test('sync-F3:blob 仓 URL 不得含空路径段(<col>/blobs/…,与 docs/spec §3 一致)', async () => {
125
+ test('sync-F3:blob 仓 URL 不得含空路径段(<col>/blobs/…,与 docs/contracts/sync-channel-v1.md §3 一致)', async () => {
126
126
  const urls: string[] = [];
127
127
  const request: WebDavRequestFn = async (method, url) => {
128
128
  urls.push(url);
@@ -504,7 +504,7 @@ export class WebDavTransport implements SyncTransport {
504
504
 
505
505
  // audit-sync sync-F3(P1):一律以 snapshotsBase()(**无尾斜杠**)为基准拼 blob 路径。
506
506
  // snapshotsColUrl() 自带尾斜杠,再拼一层会产生空路径段(…/dsh-config-manager//blobs/…),
507
- // 与 docs/spec/sync-channel-v1.md §3 的 <col>/blobs/<sha256> 及其它通道(git/s3)不一致;
507
+ // 与 docs/contracts/sync-channel-v1.md §3 的 <col>/blobs/<sha256> 及其它通道(git/s3)不一致;
508
508
  // 不归并空路径段的 WebDAV 服务端会直接拒绝 MKCOL/PUT,使 sessions 外置整体不可用。
509
509
  private blobsColUrl(): string {
510
510
  return `${this.snapshotsBase()}/${BLOBS_SEG}`;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * issue #127:workspaces 分区的记录级合并(`workspace-merge.ts`)单测。
3
+ *
4
+ * 覆盖「为什么不能走通用 JSON 合并」这件事本身:sessionIds 必须取并集(两侧各自挂过会话不该冲突),
5
+ * 其余字段按三方取舍、双侧都改才冲突,单侧删除只在「另一侧未改」时生效。
6
+ */
7
+ import test from 'node:test';
8
+ import assert from 'node:assert/strict';
9
+
10
+ import { mergeWorkspacesSection } from './workspace-merge.ts';
11
+ import { merge as mergeSections } from './merge.ts';
12
+ import type { SectionData, WorkspaceRecord, WorkspacesSection } from '../schema/types.ts';
13
+
14
+ function ws(records: WorkspaceRecord[]): WorkspacesSection {
15
+ return { version: 1, workspaces: records };
16
+ }
17
+
18
+ function rec(id: string, path: string, sessionIds: string[], extra: Partial<WorkspaceRecord> = {}): WorkspaceRecord {
19
+ return { id, path, sessionIds, ...extra };
20
+ }
21
+
22
+ function asWs(data: SectionData | undefined): WorkspacesSection {
23
+ assert.ok(data !== undefined, '合并结果必须有载荷');
24
+ return data as WorkspacesSection;
25
+ }
26
+
27
+ test('#127 记录级合并:两侧各自新增的 sessionIds 取并集 → decision=merge(不冲突、不丢归属)', () => {
28
+ const local = ws([rec('w1', 'C:/proj', ['s-local'])]);
29
+ const remote = ws([rec('w1', 'C:/proj', ['s-remote'])]);
30
+ const plan = mergeSections({ workspaces: local }, { workspaces: remote });
31
+ const section = plan.sections[0];
32
+ assert.ok(section !== undefined);
33
+ assert.equal(section.decision, 'merge', '并集必须能自动合并(通用 JSON 合并这里会判 array 冲突)');
34
+ assert.deepEqual(asWs(section.merged).workspaces[0]?.sessionIds, ['s-local', 's-remote'], '本地在前、远端追加');
35
+ assert.ok((section.autoMerged ?? 0) > 0, '自动并入的变更点必须被计数(UI 据此区分「整分区覆盖」)');
36
+ });
37
+
38
+ test('#127 记录级合并:sessionIds 按裸键去重(大小写不同算同一条会话)', () => {
39
+ const out = mergeWorkspacesSection(
40
+ ws([rec('w1', 'C:/proj', ['S1'])]),
41
+ ws([rec('w1', 'C:/proj', ['s1', 's2'])]),
42
+ undefined,
43
+ );
44
+ assert.ok(out !== undefined);
45
+ assert.deepEqual(out.conflicts, []);
46
+ assert.deepEqual(asWs(out.merged).workspaces[0]?.sessionIds, ['S1', 's2']);
47
+ });
48
+
49
+ test('#127 记录级合并:无祖先时只有 sessionIds 不同也能并集(首轮同步不该整分区冲突)', () => {
50
+ const out = mergeWorkspacesSection(
51
+ ws([rec('w1', 'C:/proj', ['s1'])]),
52
+ ws([rec('w1', 'C:/proj', ['s1', 's2'])]),
53
+ undefined,
54
+ );
55
+ assert.ok(out !== undefined);
56
+ assert.deepEqual(out.conflicts, [], '并集不是冲突:两侧都没删没改别人的数据');
57
+ assert.deepEqual(asWs(out.merged).workspaces[0]?.sessionIds, ['s1', 's2']);
58
+ });
59
+
60
+ test('#127 记录级合并:单侧改标题取变更侧;双侧改同一字段 → conflict(点号路径到记录字段)', () => {
61
+ const onlyRemote = mergeWorkspacesSection(
62
+ ws([rec('w1', 'C:/proj', [], { title: 'T' })]),
63
+ ws([rec('w1', 'C:/proj', [], { title: 'T2' })]),
64
+ ws([rec('w1', 'C:/proj', [], { title: 'T' })]),
65
+ );
66
+ assert.ok(onlyRemote !== undefined);
67
+ assert.deepEqual(onlyRemote.conflicts, []);
68
+ assert.equal(asWs(onlyRemote.merged).workspaces[0]?.title, 'T2', '仅远端改了 → 取远端');
69
+
70
+ const both = mergeWorkspacesSection(
71
+ ws([rec('w1', 'C:/proj', [], { title: 'mine' })]),
72
+ ws([rec('w1', 'C:/proj', [], { title: 'theirs' })]),
73
+ ws([rec('w1', 'C:/proj', [], { title: 'base' })]),
74
+ );
75
+ assert.ok(both !== undefined);
76
+ assert.equal(both.conflicts.length, 1);
77
+ assert.equal(both.conflicts[0]?.path, 'workspaces.w1.title');
78
+ assert.equal(both.conflicts[0]?.reason, 'both-modified');
79
+ });
80
+
81
+ test('#127 记录级合并:删除语义 —— 一侧删了且另一侧未改才真删;另一侧改过 → modify-delete 冲突', () => {
82
+ const base = rec('w1', 'C:/proj', ['s1'], { title: 'base' });
83
+ const untouched = mergeWorkspacesSection(ws([base]), ws([]), ws([base]));
84
+ assert.ok(untouched !== undefined);
85
+ assert.deepEqual(untouched.conflicts, []);
86
+ assert.deepEqual(asWs(untouched.merged).workspaces, [], '本地未改 → 跟随远端的删除');
87
+
88
+ const modified = mergeWorkspacesSection(
89
+ ws([{ ...base, title: 'renamed' }]),
90
+ ws([]),
91
+ ws([base]),
92
+ );
93
+ assert.ok(modified !== undefined);
94
+ assert.equal(modified.conflicts.length, 1);
95
+ assert.equal(modified.conflicts[0]?.path, 'workspaces.w1');
96
+ assert.equal(modified.conflicts[0]?.reason, 'modify-delete');
97
+ assert.equal(asWs(modified.merged).workspaces.length, 1, '有冲突时也不丢记录(交用户裁决)');
98
+ });
99
+
100
+ test('#127 记录级合并:无祖先且只在单侧存在 → 保留(不猜「对方删了」)', () => {
101
+ const out = mergeWorkspacesSection(ws([rec('w1', 'C:/proj', ['s1'])]), ws([]), undefined);
102
+ assert.ok(out !== undefined);
103
+ assert.deepEqual(out.conflicts, []);
104
+ assert.equal(asWs(out.merged).workspaces.length, 1);
105
+ });
106
+
107
+ test('#127 记录级合并:形状不认识 → 返回 undefined(交回通用路径,不另造一套判定)', () => {
108
+ assert.equal(mergeWorkspacesSection({ version: 2 } as unknown as SectionData, ws([]), undefined), undefined);
109
+ assert.equal(mergeWorkspacesSection(ws([]), null as unknown as SectionData, undefined), undefined);
110
+ });
@@ -0,0 +1,180 @@
1
+ /**
2
+ * workspaces 分区的**记录级**三方合并(issue #127)。
3
+ *
4
+ * 为什么不能走通用 JSON 合并:`merge.ts` 的 `mergeJsonValues` 对数组一律「双侧都改且不逐字相等
5
+ * → 冲突」(数组绝不按索引合并,见该文件头)。而 workspaces 的 `sessionIds` 天生两侧都会各自增长
6
+ * ——A 机把会话挂进工作区、B 机也挂,两条记录就永远冲突,用户每轮同步都要手工裁决,且无论选哪
7
+ * 一侧都会**静默丢掉另一侧的会话归属**(丢归属 = 那几次对话在目标机的工作区里看不见)。
8
+ *
9
+ * 因此这里按「记录 id」做并集,规则逐条如下(与 git 的三方口径一致,祖先只用于判断「谁改了这一
10
+ * 字段」,**绝不猜**):
11
+ * - `sessionIds`:恒取两侧并集(本地在前、远端新增按原序追加,按裸键去重)。这是本分区唯一的
12
+ * 「合并」语义:挂接只是提示,多余的 id 最多 attach 不到会话,而少了 id 会让本地已有会话直接
13
+ * 从工作区消失;
14
+ * - 其它字段(path / title / createdAt / updatedAt / 未来新增字段):两侧相同即取该值;不同时
15
+ * 看祖先 —— 只有一侧相对祖先变了取变更侧;两侧都变了(或没有祖先)→ **冲突**(点号路径
16
+ * `workspaces.<id>.<field>`,交用户裁决),绝不按「先到者 / 本地优先」静默取舍;
17
+ * - 只在单侧存在的记录:有祖先且该侧与祖先逐字相同 → 跟随另一侧的删除(真删除);否则保留它
18
+ * —— 无祖先时无法区分「对方删了」与「本机独有」,保留是唯一不丢数据的解释;有祖先且该侧
19
+ * 与祖先不同则记冲突(modify-delete),交用户裁决。
20
+ *
21
+ * 纯函数、零 I/O;形状不认识(非 `{version:1, workspaces:[]}`)时返回 undefined,交回通用合并
22
+ * 路径处理(畸形数据由通用路径的形状闸门拒绝,这里不另造一套判定)。
23
+ */
24
+ import type { SectionData, WorkspaceRecord, WorkspacesSection } from '../schema/types.ts';
25
+ import type { MergeConflict } from './merge.ts';
26
+
27
+ /** 记录级合并结果:`merged` 为整分区数据;`conflicts` 非空时上层按 conflict 处置(不半应用)。 */
28
+ export interface GranularMergeOutcome {
29
+ merged: SectionData;
30
+ conflicts: MergeConflict[];
31
+ /** 自动并入的变更点(口径 = 用户能感知的「两侧各自的改动都保住了」处数) */
32
+ mergePoints: number;
33
+ }
34
+
35
+ /** 记录级合并钩子签名(`merge.ts` 按分区 id 调用;返回 undefined = 不参与,走通用路径)。 */
36
+ export type GranularMerger = (
37
+ local: SectionData,
38
+ remote: SectionData,
39
+ ancestor: SectionData | undefined,
40
+ ) => GranularMergeOutcome | undefined;
41
+
42
+ function isWorkspaces(data: SectionData | undefined): data is WorkspacesSection {
43
+ if (data === null || typeof data !== 'object') return false;
44
+ const obj = data as { version?: unknown; workspaces?: unknown };
45
+ return obj.version === 1 && Array.isArray(obj.workspaces);
46
+ }
47
+
48
+ function recordsById(list: readonly WorkspaceRecord[]): Map<string, WorkspaceRecord> {
49
+ const map = new Map<string, WorkspaceRecord>();
50
+ for (const rec of list) {
51
+ if (rec !== null && typeof rec === 'object' && typeof rec.id === 'string') map.set(rec.id, rec);
52
+ }
53
+ return map;
54
+ }
55
+
56
+ /** 深度判等(本分区只有标量与字符串数组,够用;不引入通用深比较的第二份实现)。 */
57
+ function sameValue(a: unknown, b: unknown): boolean {
58
+ if (a === b) return true;
59
+ if (Array.isArray(a) && Array.isArray(b)) {
60
+ if (a.length !== b.length) return false;
61
+ for (let i = 0; i < a.length; i++) if (!sameValue(a[i], b[i])) return false;
62
+ return true;
63
+ }
64
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
65
+ const ao = a as Record<string, unknown>;
66
+ const bo = b as Record<string, unknown>;
67
+ const keys = new Set([...Object.keys(ao), ...Object.keys(bo)]);
68
+ for (const k of keys) if (!sameValue(ao[k], bo[k])) return false;
69
+ return true;
70
+ }
71
+
72
+ /** sessionIds 并集:本地在前、远端新增按原序追加,按裸 id 去重。 */
73
+ function unionSessionIds(local: readonly string[], remote: readonly string[]): string[] {
74
+ const out: string[] = [];
75
+ const seen = new Set<string>();
76
+ for (const id of [...local, ...remote]) {
77
+ if (typeof id !== 'string') continue;
78
+ const key = id.toLowerCase();
79
+ if (seen.has(key)) continue;
80
+ seen.add(key);
81
+ out.push(id);
82
+ }
83
+ return out;
84
+ }
85
+
86
+ /**
87
+ * 单个记录合并:字段级三方取舍 + sessionIds 并集。
88
+ * @returns 合并后的记录与「相对本地改动的字段数」(供 autoMerged 计数)。
89
+ */
90
+ function mergeRecord(
91
+ id: string,
92
+ local: WorkspaceRecord,
93
+ remote: WorkspaceRecord,
94
+ ancestor: WorkspaceRecord | undefined,
95
+ conflicts: MergeConflict[],
96
+ ): { rec: WorkspaceRecord; changedFields: number } {
97
+ const out: Record<string, unknown> = {};
98
+ let changedFields = 0;
99
+ const keys = new Set<string>([...Object.keys(local), ...Object.keys(remote)]);
100
+ for (const key of keys) {
101
+ const lv = (local as unknown as Record<string, unknown>)[key];
102
+ const rv = (remote as unknown as Record<string, unknown>)[key];
103
+ const av = ancestor === undefined ? undefined : (ancestor as unknown as Record<string, unknown>)[key];
104
+ let picked: unknown;
105
+ if (key === 'id') {
106
+ picked = id;
107
+ } else if (key === 'sessionIds') {
108
+ const union = unionSessionIds(
109
+ Array.isArray(lv) ? (lv as string[]) : [],
110
+ Array.isArray(rv) ? (rv as string[]) : [],
111
+ );
112
+ if (!sameValue(union, lv)) changedFields += 1;
113
+ picked = union;
114
+ } else if (sameValue(lv, rv)) {
115
+ picked = lv;
116
+ } else if (ancestor !== undefined && sameValue(lv, av)) {
117
+ picked = rv; // 仅远端改了
118
+ changedFields += 1;
119
+ } else if (ancestor !== undefined && sameValue(rv, av)) {
120
+ picked = lv; // 仅本地改了
121
+ } else {
122
+ // 双侧都改(或无祖先,无从判断谁改)→ 冲突,保留本地值供用户对照,绝不静默取舍
123
+ conflicts.push({
124
+ path: 'workspaces.' + id + '.' + key,
125
+ kind: 'key',
126
+ reason: ancestor === undefined ? 'no-ancestor' : 'both-modified',
127
+ autoMergeAttempted: true,
128
+ local: lv,
129
+ remote: rv,
130
+ ancestor: av,
131
+ });
132
+ picked = lv;
133
+ }
134
+ if (picked !== undefined) out[key] = picked;
135
+ }
136
+ return { rec: out as unknown as WorkspaceRecord, changedFields };
137
+ }
138
+
139
+ /** workspaces 分区记录级合并(`merge.ts` 的分区钩子)。 */
140
+ export const mergeWorkspacesSection: GranularMerger = (local, remote, ancestor) => {
141
+ if (!isWorkspaces(local) || !isWorkspaces(remote)) return undefined;
142
+ const a = isWorkspaces(ancestor) ? ancestor : undefined;
143
+ const lMap = recordsById(local.workspaces);
144
+ const rMap = recordsById(remote.workspaces);
145
+ const aMap = a === undefined ? new Map<string, WorkspaceRecord>() : recordsById(a.workspaces);
146
+
147
+ // 记录顺序:本地既有顺序(用户看得见的稳定顺序)→ 远端新增 → 仅祖先有(等删除判定)
148
+ const ids: string[] = [...lMap.keys()];
149
+ for (const id of rMap.keys()) if (!lMap.has(id)) ids.push(id);
150
+ for (const id of aMap.keys()) if (!lMap.has(id) && !rMap.has(id)) ids.push(id);
151
+
152
+ const conflicts: MergeConflict[] = [];
153
+ const mergedRecords: WorkspaceRecord[] = [];
154
+ let mergePoints = 0;
155
+ for (const id of ids) {
156
+ const l = lMap.get(id);
157
+ const r = rMap.get(id);
158
+ const anc = aMap.get(id);
159
+ if (l !== undefined && r !== undefined) {
160
+ const { rec, changedFields } = mergeRecord(id, l, r, anc, conflicts);
161
+ mergedRecords.push(rec);
162
+ mergePoints += changedFields;
163
+ continue;
164
+ }
165
+ if (l !== undefined) {
166
+ if (anc !== undefined && sameValue(l, anc)) continue; // 远端删了、本地未改 → 跟随删除
167
+ if (anc === undefined) { mergedRecords.push(l); continue; }
168
+ conflicts.push({ path: 'workspaces.' + id, kind: 'key', reason: 'modify-delete', autoMergeAttempted: false, local: l, remote: undefined, ancestor: anc });
169
+ mergedRecords.push(l);
170
+ continue;
171
+ }
172
+ if (r !== undefined) {
173
+ if (anc !== undefined && sameValue(r, anc)) continue; // 本地删了、远端未改 → 跟随删除
174
+ mergedRecords.push(r);
175
+ mergePoints += 1; // 远端新增(或本地已删、远端改过:保留远端记录并记并入)
176
+ continue;
177
+ }
178
+ }
179
+ return { merged: { version: 1, workspaces: mergedRecords }, conflicts, mergePoints };
180
+ };
@@ -201,6 +201,11 @@ test('issue #43:已知 skipReason token 各自映射(running / conflict / lo
201
201
  ['running', 'running'],
202
202
  ['conflict', 'conflict'],
203
203
  ['mutation-locked', 'locked'],
204
+ // 锁相关四类分档(宿主 lockSkipToken):此前全部落成 'mutation-locked',
205
+ // 于是 locks 目录为空时界面也说「环境锁被占用」,把排查方向带偏(真机 issue)。
206
+ ['mutation-lock-stale', 'lock-stale'],
207
+ ['mutation-lock-unavailable', 'lock-unavailable'],
208
+ ['mutation-safe-mode', 'safe-mode'],
204
209
  ]
205
210
  for (const [token, expected] of cases) {
206
211
  assert.deepEqual(
@@ -167,8 +167,24 @@ export function backupRunSummary(run: BackupRunResult): {
167
167
 
168
168
  /* ---------------- issue #43:立即备份结果的提示语义(不得假报成功) ---------------- */
169
169
 
170
- /** 宿主 BackupRunResult.skipReason 的结构化投影;未知 token 落 'other'(不静默当成功)。 */
171
- export type BackupSkipReason = 'disabled' | 'running' | 'conflict' | 'locked' | 'other'
170
+ /**
171
+ * 宿主 BackupRunResult.skipReason 的结构化投影;未知 token 落 'other'(不静默当成功)。
172
+ *
173
+ * 锁相关四种分开:宿主按 lockSkipToken() 分档发 token(issue:locks 目录为空也说「锁被占用」)。
174
+ * 'locked' 只表示「真被另一项活任务持有」,残留锁与 SAFE MODE 各有自己的处置方向。
175
+ */
176
+ export type BackupSkipReason =
177
+ | 'disabled'
178
+ | 'running'
179
+ | 'conflict'
180
+ | 'locked'
181
+ /** 残留锁(含心跳降级):重试/重启都不会自愈,必须去事故恢复回收 */
182
+ | 'lock-stale'
183
+ /** 锁不可用(目录 IO/权限/未知状态):稍后重试 */
184
+ | 'lock-unavailable'
185
+ /** SAFE MODE 阻断写入:锁目录通常是空的,处置入口是事故恢复 */
186
+ | 'safe-mode'
187
+ | 'other'
172
188
 
173
189
  /** 立即备份结果 → 客户端提示通道(壳据 kind 选 toast,据 reason 选文案键)。 */
174
190
  export type BackupRunOutcome =
@@ -197,6 +213,9 @@ export function backupRunOutcome(run: BackupRunResult): BackupRunOutcome {
197
213
  case 'running': return { kind: 'skipped', reason: 'running' }
198
214
  case 'conflict': return { kind: 'skipped', reason: 'conflict' }
199
215
  case 'mutation-locked': return { kind: 'skipped', reason: 'locked' }
216
+ case 'mutation-lock-stale': return { kind: 'skipped', reason: 'lock-stale' }
217
+ case 'mutation-lock-unavailable': return { kind: 'skipped', reason: 'lock-unavailable' }
218
+ case 'mutation-safe-mode': return { kind: 'skipped', reason: 'safe-mode' }
200
219
  default: return { kind: 'skipped', reason: 'other' }
201
220
  }
202
221
  }
@@ -4,7 +4,7 @@
4
4
  * 为什么需要它:体检列表此前把内部机器码直接拼上屏(location-mismatch / duplicate-id /
5
5
  * missing-message-id / format-newer …),中英用户看到的都是英文枚举 —— 既违反
6
6
  * AGENTS.md「禁止硬编码用户可见字符串」,也让用户无法判断这一行到底出了什么问题
7
- * (已知缺口登记:docs/maintenance/known-gaps.md 的 G-24 剩余未做项 ③)。
7
+ * (已知缺口登记:docs/known-issues/known-gaps.md 的 G-24 剩余未做项 ③)。
8
8
  *
9
9
  * 口径与既有的 sessionLayoutReasonKey / 同步页的 cloudIssueKey 完全一致:
10
10
  * **未知码回落 sessions.issue.unknown,绝不裸渲染机器码**。
@@ -22,6 +22,8 @@ import {
22
22
  midEllipsis,
23
23
  planHasExecutableActions,
24
24
  scheduleIntervalFact,
25
+ snapshotOriginOf,
26
+ snapshotOriginState,
25
27
  snapshotStatusBadgeKind,
26
28
  snapshotStatusLabelKey,
27
29
  snapshotsPanelStateFromStore,
@@ -226,3 +228,33 @@ test('snapshotsPanelStateFromStore:恢复 store 镜像字段,transient 字
226
228
  assert.equal(state.planning, false)
227
229
  assert.equal(INITIAL_SNAPSHOTS_PANEL_STATE.report, null)
228
230
  })
231
+
232
+ /* ---------------- 来源档案(originProfile):筛选与徽章状态 ---------------- */
233
+
234
+ const metaOf = (id: string, originProfile?: string): SnapshotMeta => ({
235
+ id,
236
+ createdAt: '2026-08-14T12:00:00.000Z',
237
+ sourceZip: `${id}.zip`,
238
+ entryCount: 1,
239
+ hostFileBackupCount: 0,
240
+ beforePluginCount: 0,
241
+ ...(originProfile !== undefined ? { originProfile } : {}),
242
+ })
243
+
244
+
245
+ test('snapshotOriginState:只有「已知当前档案且不同」才敢说来自他人档案', () => {
246
+ assert.equal(snapshotOriginState(metaOf('a')), 'unlabeled')
247
+ assert.equal(snapshotOriginState(metaOf('a', ' ')), 'unlabeled', '空白来源 = 未标注,不是「未知档案」')
248
+ assert.equal(snapshotOriginState(metaOf('a', 'web'), 'web'), 'local')
249
+ assert.equal(snapshotOriginState(metaOf('a', 'Test1'), 'web'), 'foreign')
250
+ // 宿主没给当前档案(老宿主 / 独立 CLI)⇒ 不能声称「来自他人档案」
251
+ assert.equal(snapshotOriginState(metaOf('a', 'Test1')), 'unknownCurrent')
252
+ assert.equal(snapshotOriginState(metaOf('a', 'Test1'), ' '), 'unknownCurrent', '空白当前档案不等于已知')
253
+ })
254
+
255
+
256
+ test('snapshotOriginOf:trim 后转交,空白视为没有', () => {
257
+ assert.equal(snapshotOriginOf({ originProfile: ' web ' }), 'web')
258
+ assert.equal(snapshotOriginOf({ originProfile: '' }), undefined)
259
+ assert.equal(snapshotOriginOf({}), undefined)
260
+ })
@@ -231,3 +231,37 @@ export function isUnreadableNote(note: string): boolean {
231
231
  export function planHasExecutableActions(plan: RestorePlan | null): boolean {
232
232
  return plan !== null && plan.actions.some((a) => a.kind !== 'skip')
233
233
  }
234
+
235
+ /* ------------------------------------------------------------ 来源档案(originProfile) */
236
+
237
+ /* 这里只判「怎么显示」:快照库里混着别的档案拍的条目(插件数据目录被所有 DSH profile 共用),
238
+ * 徽章要能指出它是谁的。**不做筛选** —— 顶部来源筛选已按用户要求移除(2026-11-08),
239
+ * 筛掉哪些快照不改变任何决定,只是在同一屏多一个控件。 */
240
+
241
+ /** 取来源档案名:非空字符串(去首尾空白)才算「能证明的来源」;缺失/空 → undefined(按「未标注」处理)。 */
242
+ export function snapshotOriginOf(meta: { originProfile?: string }): string | undefined {
243
+ const value = meta.originProfile
244
+ if (typeof value !== 'string') return undefined
245
+ const trimmed = value.trim()
246
+ return trimmed === '' ? undefined : trimmed
247
+ }
248
+
249
+ /**
250
+ * 行首来源徽章的呈现状态:
251
+ * - `unlabeled`:没有来源(旧快照)→ **不显示徽章**(绝不拿占位值凑一个「未知档案」);
252
+ * - `local`:与当前档案相同 → 只显示档案名,中性;
253
+ * - `foreign`:与当前档案不同 → 显示档案名 + 强调「来自他人档案」;
254
+ * - `unknownCurrent`:宿主没给当前档案 → 只显示档案名 —— 不知道自己在哪个档案时
255
+ * 声称「来自他人档案」是无法证明的结论。
256
+ */
257
+ export type SnapshotOriginState = 'unlabeled' | 'local' | 'foreign' | 'unknownCurrent'
258
+
259
+ export function snapshotOriginState(meta: { originProfile?: string }, currentProfile?: string): SnapshotOriginState {
260
+ const profile = snapshotOriginOf(meta)
261
+ if (profile === undefined) return 'unlabeled'
262
+ const current = typeof currentProfile === 'string' ? currentProfile.trim() : ''
263
+ if (current === '') return 'unknownCurrent'
264
+ return current === profile ? 'local' : 'foreign'
265
+ }
266
+
267
+