dsh-config-manager 0.10.0 → 0.12.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 (233) hide show
  1. package/lib/adapters/attachment-index-cache.d.ts +33 -0
  2. package/lib/adapters/attachment-index-cache.js +114 -0
  3. package/lib/adapters/attachments.d.ts +97 -0
  4. package/lib/adapters/attachments.js +448 -0
  5. package/lib/adapters/index.d.ts +1 -0
  6. package/lib/adapters/index.js +7 -1
  7. package/lib/adapters/self.d.ts +2 -2
  8. package/lib/adapters/self.js +4 -0
  9. package/lib/adapters/sessions.d.ts +18 -1
  10. package/lib/adapters/sessions.js +193 -0
  11. package/lib/adapters/test-helpers.d.ts +7 -0
  12. package/lib/adapters/test-helpers.js +8 -1
  13. package/lib/adapters/workspaces.d.ts +0 -1
  14. package/lib/adapters/workspaces.js +244 -5
  15. package/lib/client.d.ts +170 -1
  16. package/lib/client.js +2067 -889
  17. package/lib/core/analyzer.d.ts +1 -14
  18. package/lib/core/analyzer.js +25 -67
  19. package/lib/core/backup-plan.js +4 -0
  20. package/lib/core/backup.d.ts +7 -0
  21. package/lib/core/backup.js +3 -0
  22. package/lib/core/external-failure.d.ts +18 -2
  23. package/lib/core/external-failure.js +63 -19
  24. package/lib/core/host-service.d.ts +12 -0
  25. package/lib/core/host-service.js +12 -0
  26. package/lib/core/host-session-shapes.d.ts +209 -0
  27. package/lib/core/host-session-shapes.js +134 -0
  28. package/lib/core/host-workspace-facade.d.ts +57 -0
  29. package/lib/core/host-workspace-facade.js +127 -0
  30. package/lib/core/import-planning.d.ts +15 -0
  31. package/lib/core/import-planning.js +44 -0
  32. package/lib/core/messages.d.ts +20 -0
  33. package/lib/core/messages.js +40 -0
  34. package/lib/core/phase3-host.js +2 -2
  35. package/lib/core/session-analyze.d.ts +52 -0
  36. package/lib/core/session-analyze.js +135 -0
  37. package/lib/core/session-compare.d.ts +54 -0
  38. package/lib/core/session-compare.js +154 -0
  39. package/lib/core/session-meta.d.ts +32 -0
  40. package/lib/core/session-meta.js +49 -0
  41. package/lib/core/session-verdict-plan.d.ts +2 -0
  42. package/lib/core/session-verdict-plan.js +33 -0
  43. package/lib/core/types.d.ts +153 -0
  44. package/lib/core/unit-enrichment.d.ts +19 -0
  45. package/lib/core/unit-enrichment.js +39 -0
  46. package/lib/core/workspace-root.d.ts +46 -0
  47. package/lib/core/workspace-root.js +121 -0
  48. package/lib/index.d.ts +2 -112
  49. package/lib/index.js +17 -222
  50. package/lib/profiles/dsh-profile-runtime.d.ts +54 -2
  51. package/lib/profiles/dsh-profile-runtime.js +124 -9
  52. package/lib/routes/route-support.d.ts +3 -0
  53. package/lib/routes/route-support.js +6 -0
  54. package/lib/schema/section-registry.js +15 -0
  55. package/lib/schema/types.d.ts +17 -1
  56. package/lib/sync/autosync-backoff.d.ts +40 -0
  57. package/lib/sync/autosync-backoff.js +74 -0
  58. package/lib/sync/autosync-config.d.ts +26 -41
  59. package/lib/sync/autosync-config.js +25 -26
  60. package/lib/sync/autosync-scheduler.d.ts +22 -10
  61. package/lib/sync/autosync-scheduler.js +509 -331
  62. package/lib/sync/backup-files.d.ts +3 -1
  63. package/lib/sync/backup-files.js +5 -3
  64. package/lib/sync/baseline-record.d.ts +10 -1
  65. package/lib/sync/baseline-record.js +2 -2
  66. package/lib/sync/credential-plan.d.ts +8 -0
  67. package/lib/sync/credential-plan.js +65 -0
  68. package/lib/sync/local-changes.d.ts +2 -1
  69. package/lib/sync/local-changes.js +4 -2
  70. package/lib/sync/partial-conflict-push.d.ts +39 -0
  71. package/lib/sync/partial-conflict-push.js +70 -0
  72. package/lib/sync/retention-policy.d.ts +23 -6
  73. package/lib/sync/retention-policy.js +51 -10
  74. package/lib/sync/round-export-cache.d.ts +22 -0
  75. package/lib/sync/round-export-cache.js +36 -0
  76. package/lib/sync/snapshot-zip.d.ts +9 -0
  77. package/lib/sync/snapshot-zip.js +62 -0
  78. package/lib/sync/sync-engine.d.ts +24 -30
  79. package/lib/sync/sync-engine.js +145 -157
  80. package/lib/sync/sync-history.d.ts +4 -0
  81. package/lib/sync/sync-watcher.d.ts +27 -0
  82. package/lib/sync/sync-watcher.js +80 -3
  83. package/lib/sync/transport.js +11 -2
  84. package/lib/sync/watch-scope.js +2 -1
  85. package/lib/ui/backup-schedule.d.ts +5 -1
  86. package/lib/ui/backup-schedule.js +5 -3
  87. package/lib/ui/export-flow.js +1 -0
  88. package/lib/ui/i18n.d.ts +3 -0
  89. package/lib/ui/i18n.js +6 -0
  90. package/lib/ui/import-wizard.d.ts +8 -0
  91. package/lib/ui/import-wizard.js +10 -0
  92. package/lib/ui/overview-view.d.ts +20 -7
  93. package/lib/ui/overview-view.js +31 -12
  94. package/lib/ui/selection-model.d.ts +60 -0
  95. package/lib/ui/selection-model.js +258 -2
  96. package/lib/ui/session-compare-facts.d.ts +51 -0
  97. package/lib/ui/session-compare-facts.js +82 -0
  98. package/lib/ui/sync-settings-view.d.ts +25 -0
  99. package/lib/ui/sync-settings-view.js +9 -0
  100. package/lib/ui/test-helpers.js +2 -2
  101. package/lib/utils/attachment-refs.d.ts +49 -0
  102. package/lib/utils/attachment-refs.js +169 -0
  103. package/lib/utils/shared-constants.d.ts +16 -0
  104. package/lib/utils/shared-constants.js +13 -0
  105. package/package.json +1 -1
  106. package/src/adapters/attachment-index-cache.test.ts +122 -0
  107. package/src/adapters/attachment-index-cache.ts +129 -0
  108. package/src/adapters/attachments.test.ts +358 -0
  109. package/src/adapters/attachments.ts +472 -0
  110. package/src/adapters/index.ts +8 -1
  111. package/src/adapters/self.ts +5 -1
  112. package/src/adapters/sessions.test.ts +140 -0
  113. package/src/adapters/sessions.ts +184 -1
  114. package/src/adapters/test-helpers.ts +8 -1
  115. package/src/adapters/workspaces.test.ts +254 -0
  116. package/src/adapters/workspaces.ts +234 -5
  117. package/src/client/common/ContentPicker.tsx +235 -15
  118. package/src/client/common/section-labels.test.ts +1 -1
  119. package/src/client/common/section-labels.ts +1 -0
  120. package/src/client/common/ui.tsx +17 -1
  121. package/src/client/config-manager.module.css +117 -0
  122. package/src/client/export/ExportView.tsx +15 -2
  123. package/src/client/home/BackupScheduleCard.tsx +13 -9
  124. package/src/client/home/HomePanel.tsx +28 -8
  125. package/src/client/import/ImportWizardView.tsx +8 -0
  126. package/src/client/import/PathMappingForm.tsx +49 -10
  127. package/src/client/import/import-wizard-steps.tsx +80 -3
  128. package/src/client/import/use-import-wizard-controller.ts +3 -0
  129. package/src/client/locales/backup.ts +6 -0
  130. package/src/client/locales/common.ts +2 -0
  131. package/src/client/locales/export.ts +5 -0
  132. package/src/client/locales/import.ts +6 -0
  133. package/src/client/locales/overview.ts +14 -0
  134. package/src/client/locales/sessions.ts +26 -0
  135. package/src/client/run-store-redact.ts +122 -0
  136. package/src/client/run-store.ts +13 -115
  137. package/src/client/sync/AutosyncCard.tsx +19 -8
  138. package/src/client/sync/SyncChannelEntryCard.tsx +21 -2
  139. package/src/client/sync/SyncChannelSection.tsx +23 -0
  140. package/src/client/sync/SyncChannelSkeleton.tsx +116 -0
  141. package/src/client/sync/SyncLogList.tsx +22 -2
  142. package/src/client/sync/SyncPanel.tsx +24 -25
  143. package/src/client/sync/SyncSecuritySection.tsx +7 -1
  144. package/src/client/sync/SyncSettingsDialog.tsx +22 -6
  145. package/src/client/sync/SyncSettingsView.test.ts +15 -0
  146. package/src/client/sync/history-model.test.ts +19 -1
  147. package/src/client/sync/history-model.ts +15 -0
  148. package/src/client/sync/sync-api.ts +14 -0
  149. package/src/client/sync/sync-locales.ts +28 -0
  150. package/src/client/sync/sync-view-v2.test.ts +14 -3
  151. package/src/client/sync/sync-view.test.ts +106 -4
  152. package/src/client/sync/sync-view.ts +159 -16
  153. package/src/core/analyzer.ts +38 -79
  154. package/src/core/backup-plan.ts +4 -0
  155. package/src/core/backup.ts +10 -0
  156. package/src/core/external-failure.test.ts +31 -0
  157. package/src/core/external-failure.ts +71 -21
  158. package/src/core/host-service.ts +17 -0
  159. package/src/core/host-session-shapes.ts +270 -0
  160. package/src/core/host-workspace-facade.ts +153 -0
  161. package/src/core/import-planning.ts +48 -0
  162. package/src/core/messages.ts +40 -0
  163. package/src/core/native-path-picker.test.ts +3 -2
  164. package/src/core/phase3-host.ts +2 -2
  165. package/src/core/phase3-production-integration.test.ts +73 -1
  166. package/src/core/session-analyze.ts +159 -0
  167. package/src/core/session-compare-wiring.test.ts +207 -0
  168. package/src/core/session-compare.test.ts +119 -0
  169. package/src/core/session-compare.ts +185 -0
  170. package/src/core/session-meta.test.ts +25 -2
  171. package/src/core/session-meta.ts +54 -0
  172. package/src/core/session-verdict-plan.test.ts +70 -0
  173. package/src/core/session-verdict-plan.ts +32 -0
  174. package/src/core/types.ts +161 -0
  175. package/src/core/unit-enrichment.ts +46 -0
  176. package/src/core/workspace-root.test.ts +152 -0
  177. package/src/core/workspace-root.ts +146 -0
  178. package/src/foreign/trae-sqlcipher.test.ts +13 -4
  179. package/src/index.ts +27 -355
  180. package/src/profiles/dsh-profile-runtime.test.ts +77 -3
  181. package/src/profiles/dsh-profile-runtime.ts +125 -9
  182. package/src/routes/route-support.test.ts +49 -0
  183. package/src/routes/route-support.ts +9 -0
  184. package/src/schema/manifest-schema.test.ts +1 -1
  185. package/src/schema/registry.test.ts +7 -2
  186. package/src/schema/section-registry.ts +15 -0
  187. package/src/schema/types.ts +23 -2
  188. package/src/sync/autosync-backoff.test.ts +64 -0
  189. package/src/sync/autosync-backoff.ts +88 -0
  190. package/src/sync/autosync-config.test.ts +38 -0
  191. package/src/sync/autosync-config.ts +66 -52
  192. package/src/sync/autosync-risk-tier.test.ts +5 -1
  193. package/src/sync/autosync-scheduler.test.ts +537 -4
  194. package/src/sync/autosync-scheduler.ts +252 -68
  195. package/src/sync/backup-files.ts +4 -1
  196. package/src/sync/backup-scheduler.test.ts +5 -4
  197. package/src/sync/baseline-record.ts +12 -3
  198. package/src/sync/credential-plan.ts +70 -0
  199. package/src/sync/local-changes.ts +10 -4
  200. package/src/sync/partial-conflict-push.test.ts +237 -0
  201. package/src/sync/partial-conflict-push.ts +105 -0
  202. package/src/sync/retention-age-tier.test.ts +79 -0
  203. package/src/sync/retention-policy.test.ts +101 -10
  204. package/src/sync/retention-policy.ts +57 -8
  205. package/src/sync/round-export-cache.test.ts +83 -0
  206. package/src/sync/round-export-cache.ts +53 -0
  207. package/src/sync/snapshot-zip.ts +70 -0
  208. package/src/sync/sync-engine.test.ts +35 -1
  209. package/src/sync/sync-engine.ts +145 -155
  210. package/src/sync/sync-history.ts +4 -0
  211. package/src/sync/sync-watcher.test.ts +76 -4
  212. package/src/sync/sync-watcher.ts +82 -3
  213. package/src/sync/transport.test.ts +1 -1
  214. package/src/sync/transport.ts +10 -2
  215. package/src/sync/watch-scope.test.ts +8 -0
  216. package/src/sync/watch-scope.ts +2 -1
  217. package/src/ui/backup-schedule.test.ts +13 -6
  218. package/src/ui/backup-schedule.ts +4 -2
  219. package/src/ui/export-flow.ts +1 -0
  220. package/src/ui/i18n.ts +6 -0
  221. package/src/ui/import-wizard.ts +11 -0
  222. package/src/ui/overview-view.test.ts +48 -0
  223. package/src/ui/overview-view.ts +47 -13
  224. package/src/ui/selection-model.test.ts +265 -3
  225. package/src/ui/selection-model.ts +256 -2
  226. package/src/ui/session-compare-facts.test.ts +67 -0
  227. package/src/ui/session-compare-facts.ts +122 -0
  228. package/src/ui/sync-settings-view.test.ts +60 -1
  229. package/src/ui/sync-settings-view.ts +36 -0
  230. package/src/ui/test-helpers.ts +2 -2
  231. package/src/utils/attachment-refs.test.ts +98 -0
  232. package/src/utils/attachment-refs.ts +177 -0
  233. package/src/utils/shared-constants.ts +22 -0
@@ -0,0 +1,134 @@
1
+ import { isRecord } from '../utils/guards.js';
2
+ /** 按 API 形状探测会话存储基线:有 `open` → handle;只有 `readFrom`/`append` → legacy;都没有 → unknown。 */
3
+ export function sessionPersistenceShapeOf(service) {
4
+ if (!isRecord(service))
5
+ return 'unknown';
6
+ if (typeof service['open'] === 'function')
7
+ return 'handle';
8
+ if (typeof service['readFrom'] === 'function' || typeof service['append'] === 'function')
9
+ return 'legacy';
10
+ return 'unknown';
11
+ }
12
+ /**
13
+ * 把一个列举元素归一成 header 视图(**两种基线形状都认**)。
14
+ *
15
+ * 认不出 id → undefined:这是「读侧兼容失败」的唯一信号,调用方必须**响亮处理**
16
+ * (记日志 / 抛错),绝不当成「本机没有会话」。
17
+ */
18
+ export function normalizeListedSession(element) {
19
+ if (!isRecord(element))
20
+ return undefined;
21
+ const nested = isRecord(element['header']) ? element['header'] : undefined;
22
+ // handle 形态 = header 在 element.header;legacy 形态 = header 字段平铺在元素上。
23
+ // header 存在但取不出 id 时回落元素自身(两种都取不到才算解析失败 —— 不猜)。
24
+ const source = nested !== undefined && typeof nested['id'] === 'string' && nested['id'] !== '' ? nested : element;
25
+ const id = source['id'];
26
+ if (typeof id !== 'string' || id === '')
27
+ return undefined;
28
+ const rawParent = source['parentSession'] ?? source['parentSessionId'];
29
+ const parent = typeof rawParent === 'string' && rawParent !== '' ? rawParent : undefined;
30
+ return { id, origin: source['origin'], raw: source, ...(parent !== undefined ? { parent } : {}) };
31
+ }
32
+ /** 用途 → 字典键(本仓纪律:文案只做「原因 → 字典键」映射,禁止渲染裸枚举)。 */
33
+ export const SESSION_STORE_PURPOSE_KEY = {
34
+ reindexSessionHeader: 'host.sessionStorePurposeReindex',
35
+ parentRelations: 'host.sessionStorePurposeParentRelations',
36
+ rewindWorkspaceAttach: 'host.sessionStorePurposeRewindAttach',
37
+ };
38
+ /**
39
+ * 父子关系缓存的 TTL(毫秒)。
40
+ *
41
+ * 取值依据:`sessionPersistence.list()` 在真机上约 **0.7 s**,而 `/export-preview` 每次都要它;
42
+ * 父子关系只在「有新子代理会话」时变化,几秒陈旧对选择器的「勾父带子 / 勾子带父」联动毫无影响。
43
+ * 取 5 s:连续打开/刷新选择器都在同一窗口内命中,同时保证新会话最多 5 s 后就能被联动识别。
44
+ *
45
+ * F-1:缓存里只放**成功结果** —— 列举失败/形状识别失败走 `parentRelations()` 的抛错路径,
46
+ * 由 ttl-cache 的「失败不缓存」语义保证下一次调用立刻重试;
47
+ * 不再把失败吞成空 Map(那会被缓存整整 5 s,正是「静默失效」的放大器)。
48
+ */
49
+ export const PARENT_RELATIONS_CACHE_TTL_MS = 5_000;
50
+ /**
51
+ * `ancestorSessionIds` 的上溯深度上限。
52
+ *
53
+ * 取 8:DSH 的子代理树实际深度是个位数(`delegationDepth`),8 层足够覆盖「子代理的子代理」;
54
+ * 上限 + 环保护一道,保证异常数据(自指 / 环)不会把回退路径卡死。
55
+ */
56
+ export const ANCESTOR_LOOKUP_MAX_DEPTH = 8;
57
+ /** 归位失败时给调用方的 warning 串(稳定前缀 + 具体理由码)。 */
58
+ export const WORKSPACE_ATTACH_FAILED_PREFIX = 'workspace-attach-failed';
59
+ /**
60
+ * 归位失败后的重试次数与间隔(毫秒)。
61
+ *
62
+ * 为什么需要(真机 2026-10-17/10-12):fork 返回时子会话刚由 `agents.create` 建好,
63
+ * DSH 侧的会话索引 / 持久化列举可能还没就绪 —— 与「目录根本不存在」这类终结性失败不同,
64
+ * 这是**时序性**失败。归位本身幂等(`attachSession` 自查成员名单、`mutate` 空操作即不改写),
65
+ * 因此重试零副作用;不重试则子会话永久停在侧栏「未分组」。
66
+ */
67
+ export const WORKSPACE_ATTACH_ATTEMPTS = 2;
68
+ export const WORKSPACE_ATTACH_RETRY_DELAY_MS = 200;
69
+ /** 归位诊断文件的相对路径(相对插件数据根;只在**失败**时追加一行 JSON)。 */
70
+ export const WORKSPACE_ATTACH_DIAGNOSTIC_REL = 'logs/rewind-workspace-attach.jsonl';
71
+ /**
72
+ * DSH 官方 fork 在「子会话已创建、但 `workspace.attachSession` 失败」时抛的错误码。
73
+ *
74
+ * 依据 DSH 源码:`dsh-api-session-controller/lib/index.js` L829-836 抛
75
+ * `new RemoteError('session/workspace-attach-failed', …, { sessionId: childId, workspaceId })`。
76
+ */
77
+ export const WORKSPACE_ATTACH_FAILED_ERROR_CODE = 'session/workspace-attach-failed';
78
+ /**
79
+ * 从官方 fork 的 `session/workspace-attach-failed` 错误里取回**已经创建好的子会话 id**。
80
+ *
81
+ * 字段名**不是猜的** —— DSH 自己的客户端就是这么取的(同款姿势):
82
+ * `dsh-api-session-controller/lib/client.js` L3013-3015 的 `workspaceAttachSessionId(error)`:
83
+ * `error.code === 'session/workspace-attach-failed' ? error.details.sessionId : undefined`
84
+ * 错误类是 `dsh-typert-protocol/lib/index.js` L11-28 的 `RemoteError`(`code` + `details`;
85
+ * DSH 明文规定「判别只按 code,never by instanceof」,故这里也只按 `code`,不 import 那门包)。
86
+ *
87
+ * 形状不符(不是对象 / code 不是这个 / 没有 details.sessionId / 空串)一律 undefined ——
88
+ * 调用方据此**保持现状**报 fork-failed,绝不假装成功、也绝不猜别的字段名。
89
+ */
90
+ export function workspaceAttachFailureChildId(error) {
91
+ if (error === null || typeof error !== 'object')
92
+ return undefined;
93
+ const code = error.code;
94
+ if (code !== WORKSPACE_ATTACH_FAILED_ERROR_CODE)
95
+ return undefined;
96
+ const details = error.details;
97
+ if (details === null || typeof details !== 'object')
98
+ return undefined;
99
+ const sessionId = details.sessionId;
100
+ return typeof sessionId === 'string' && sessionId !== '' ? sessionId : undefined;
101
+ }
102
+ /**
103
+ * 归位失败 → warning 串;成功 → undefined。
104
+ *
105
+ * 为什么是「前缀:理由码」而不是新字段:`RollbackForkSeam`(core/types.ts,本任务 scope 外)的返回
106
+ * 形状只有 `{ childSessionId, warning? }`,warning 是**唯一**能把具体理由带到调用方的通道;
107
+ * core 只判「非空」并落成 `rollback.guidance.sessionNotAttached`(界面如实上屏),
108
+ * 前缀保持稳定以便既有 grep / 诊断脚本继续命中。
109
+ */
110
+ export function workspaceAttachWarningOf(outcome) {
111
+ return outcome.ok ? undefined : WORKSPACE_ATTACH_FAILED_PREFIX + ':' + outcome.reason;
112
+ }
113
+ /**
114
+ * 目录同一性比较用的折叠(**只在 `resolveByPath` 拿不到时的回落档**使用)。
115
+ *
116
+ * 分隔符统一为 `/`;win32 大小写不敏感(Windows 路径大小写等价)。
117
+ * 注意:本函数只比较**两侧都经 realpath 规范化**过的路径 —— 绝不拿「原样 cwd」与「规范 path」直接比,
118
+ * 那正是真机 2026-10-12 的根因(工作区 path 经 `realpathNormalize`、会话头 cwd 是原样字符串)。
119
+ */
120
+ export function foldWorkspacePath(value) {
121
+ const unified = value.replace(/\\/g, '/');
122
+ return process.platform === 'win32' ? unified.toLowerCase() : unified;
123
+ }
124
+ /** 工作区记录的稳定 id(形状不符 → undefined;只作诊断/日志,不参与判定)。 */
125
+ export function workspaceRecordIdOf(record) {
126
+ const id = record['id'];
127
+ return typeof id === 'string' && id !== '' ? id : undefined;
128
+ }
129
+ /** 该记录是否把某会话算作成员(`sessionIds` 非数组 = 形状不符,不算成员)。 */
130
+ export function recordHasMember(record, sessionId) {
131
+ const sessionIds = record['sessionIds'];
132
+ return Array.isArray(sessionIds) && sessionIds.includes(sessionId);
133
+ }
134
+ //# sourceMappingURL=host-session-shapes.js.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * DshWorkspaceFacade —— DSH `workspaceRegistry` → 引擎 `WorkspaceFacade` 的适配。
3
+ *
4
+ * 从 src/index.ts 下沉(体量棘轮):本类只做「服务读取 + 形状转换」,不含任何路由或
5
+ * 生命周期逻辑。边界同上:core 不 import `@deepseek-ai/*`,宿主入口传入真 ctx。
6
+ */
7
+ import type { MsgFunc } from './messages.ts';
8
+ import { type ServiceGetter } from './host-service.ts';
9
+ import type { WorkspaceFacade } from './types.ts';
10
+ import type { WorkspaceRecord } from '../schema/types.ts';
11
+ export declare class DshWorkspaceFacade implements WorkspaceFacade {
12
+ private readonly ctx;
13
+ private readonly msg;
14
+ constructor(ctx: ServiceGetter, msg?: MsgFunc);
15
+ private registry;
16
+ listRecords(): Promise<WorkspaceRecord[]>;
17
+ writeRecord(record: WorkspaceRecord): Promise<void>;
18
+ removeRecord(id: string): Promise<void>;
19
+ /**
20
+ * 把一个已存储会话登记进工作区(issue #45 会话归位)。
21
+ *
22
+ * 走 DSH `workspaceRegistry` 的实体方法 `attachSession`:
23
+ * - DSH 自己读会话 header 并用 realpath 校验 cwd 必须等于该工作区 path(不匹配直接拒绝);
24
+ * - 写入走 storage domain 的原子 update(内存权威与磁盘同时更新),并按 cwd 剪掉不属于
25
+ * 本工作区的候选 —— 因此**不需要**插件做「注册表合并 / 去重 / 备份回滚」,
26
+ * 更**不得**旁路直写 storages/workspace.json。
27
+ */
28
+ attachSession(workspaceId: string, sessionId: string): Promise<void>;
29
+ /**
30
+ * P2:读注册表级归档集。
31
+ *
32
+ * 「宿主没这个能力」与「归档集为空」必须分开:前者返回空数组但不会让导出侧写
33
+ * `archivedSessionIds: []`(导出侧只看能力是否存在决定带不带这个字段)。
34
+ */
35
+ listArchivedSessionIds(): Promise<string[] | undefined>;
36
+ /** P2:归档一个会话;宿主未暴露该能力时显式报错(由调用方降级为告警,绝不静默当成功)。 */
37
+ archiveSession(sessionId: string): Promise<void>;
38
+ /**
39
+ * P2-pin:读注册表级置顶集(最近置顶在前)。
40
+ *
41
+ * 与归档集同款边界:`undefined` = 宿主没暴露(导出侧不带字段),**不是**空数组
42
+ * —— 返回 [] 会让导出侧写出 `pinnedSessionIds: []`,等于声称「这台机器没有置顶会话」。
43
+ * 能力在 DSH 0.2.2-rc.5 的 `workspaceRegistry` 上(`pinnedSessionIds` / `pinSession`)。
44
+ */
45
+ listPinnedSessionIds(): Promise<string[] | undefined>;
46
+ /** P2-pin:置顶一个会话;宿主未暴露该能力时显式报错(调用方降级为告警,绝不静默当成功)。 */
47
+ pinSession(sessionId: string): Promise<void>;
48
+ /**
49
+ * P2:按目标顺序重排工作区显示顺序。
50
+ *
51
+ * 宿主只给 `insertBefore(id, beforeId)`(DOM 语义),所以「变成目标顺序」由这里推出:
52
+ * 从倒数第二个开始,把每个 id 挪到它后一个 id 前面,逐次收敛即为目标相对顺序。
53
+ * 未知 id 直接过滤(别人删掉的工作区不该让整轮导入报错);宿主没有该原语时静默跳过 ——
54
+ * 顺序不是数据,丢了不影响可用性。
55
+ */
56
+ reorderWorkspaces(orderedIds: readonly string[]): Promise<void>;
57
+ }
@@ -0,0 +1,127 @@
1
+ import { zhMsg } from './messages.js';
2
+ import { readService } from './host-service.js';
3
+ export class DshWorkspaceFacade {
4
+ ctx;
5
+ msg;
6
+ constructor(ctx, msg = zhMsg) {
7
+ this.ctx = ctx;
8
+ this.msg = msg;
9
+ }
10
+ registry() {
11
+ return readService(this.ctx, 'workspaceRegistry');
12
+ }
13
+ async listRecords() {
14
+ const registry = this.registry();
15
+ if (!registry)
16
+ return [];
17
+ return registry.list().map((w) => ({
18
+ id: String(w.id),
19
+ path: w.path,
20
+ title: w.title,
21
+ sessionIds: [...w.sessionIds].map(String),
22
+ createdAt: w.createdAt,
23
+ updatedAt: w.updatedAt,
24
+ }));
25
+ }
26
+ async writeRecord(record) {
27
+ const registry = this.registry();
28
+ if (!registry)
29
+ throw new Error(this.msg('host.workspaceUnavailable'));
30
+ const existing = registry.get(record.id);
31
+ if (existing) {
32
+ // DSH API 没有「整体覆盖」写通道:标题可更新;path/会话由 registry 依真实目录维护
33
+ if (record.title !== undefined && existing.title !== record.title)
34
+ await existing.setTitle(record.title);
35
+ return;
36
+ }
37
+ await registry.create(record.path, record.title);
38
+ }
39
+ async removeRecord(id) {
40
+ const registry = this.registry();
41
+ if (!registry)
42
+ return;
43
+ await registry.delete(id);
44
+ }
45
+ /**
46
+ * 把一个已存储会话登记进工作区(issue #45 会话归位)。
47
+ *
48
+ * 走 DSH `workspaceRegistry` 的实体方法 `attachSession`:
49
+ * - DSH 自己读会话 header 并用 realpath 校验 cwd 必须等于该工作区 path(不匹配直接拒绝);
50
+ * - 写入走 storage domain 的原子 update(内存权威与磁盘同时更新),并按 cwd 剪掉不属于
51
+ * 本工作区的候选 —— 因此**不需要**插件做「注册表合并 / 去重 / 备份回滚」,
52
+ * 更**不得**旁路直写 storages/workspace.json。
53
+ */
54
+ async attachSession(workspaceId, sessionId) {
55
+ const registry = this.registry();
56
+ if (!registry)
57
+ throw new Error(this.msg('host.workspaceUnavailable'));
58
+ const existing = registry.get(workspaceId);
59
+ if (!existing)
60
+ throw new Error(this.msg('host.workspaceMissingTarget', { id: workspaceId }));
61
+ await existing.attachSession(sessionId);
62
+ }
63
+ /**
64
+ * P2:读注册表级归档集。
65
+ *
66
+ * 「宿主没这个能力」与「归档集为空」必须分开:前者返回空数组但不会让导出侧写
67
+ * `archivedSessionIds: []`(导出侧只看能力是否存在决定带不带这个字段)。
68
+ */
69
+ async listArchivedSessionIds() {
70
+ const registry = this.registry();
71
+ // 宿主没暴露 getter ⇒ undefined(「读不到」),**不是**空数组(「确实为空」):
72
+ // 返回 [] 会让导出侧写出 `archivedSessionIds: []`,等于对用户声称「这台机器没有归档会话」。
73
+ if (registry === undefined || registry.archivedSessionIds === undefined)
74
+ return undefined;
75
+ const ids = registry.archivedSessionIds;
76
+ return Array.isArray(ids) ? ids.map(String) : undefined;
77
+ }
78
+ /** P2:归档一个会话;宿主未暴露该能力时显式报错(由调用方降级为告警,绝不静默当成功)。 */
79
+ async archiveSession(sessionId) {
80
+ const registry = this.registry();
81
+ if (!registry || typeof registry.archiveSession !== 'function') {
82
+ throw new Error(this.msg('host.workspaceArchiveUnavailable'));
83
+ }
84
+ await registry.archiveSession(sessionId);
85
+ }
86
+ /**
87
+ * P2-pin:读注册表级置顶集(最近置顶在前)。
88
+ *
89
+ * 与归档集同款边界:`undefined` = 宿主没暴露(导出侧不带字段),**不是**空数组
90
+ * —— 返回 [] 会让导出侧写出 `pinnedSessionIds: []`,等于声称「这台机器没有置顶会话」。
91
+ * 能力在 DSH 0.2.2-rc.5 的 `workspaceRegistry` 上(`pinnedSessionIds` / `pinSession`)。
92
+ */
93
+ async listPinnedSessionIds() {
94
+ const registry = this.registry();
95
+ if (registry === undefined || registry.pinnedSessionIds === undefined)
96
+ return undefined;
97
+ const ids = registry.pinnedSessionIds;
98
+ return Array.isArray(ids) ? ids.map(String) : undefined;
99
+ }
100
+ /** P2-pin:置顶一个会话;宿主未暴露该能力时显式报错(调用方降级为告警,绝不静默当成功)。 */
101
+ async pinSession(sessionId) {
102
+ const registry = this.registry();
103
+ if (!registry || typeof registry.pinSession !== 'function') {
104
+ throw new Error(this.msg('host.workspacePinUnavailable'));
105
+ }
106
+ await registry.pinSession(sessionId);
107
+ }
108
+ /**
109
+ * P2:按目标顺序重排工作区显示顺序。
110
+ *
111
+ * 宿主只给 `insertBefore(id, beforeId)`(DOM 语义),所以「变成目标顺序」由这里推出:
112
+ * 从倒数第二个开始,把每个 id 挪到它后一个 id 前面,逐次收敛即为目标相对顺序。
113
+ * 未知 id 直接过滤(别人删掉的工作区不该让整轮导入报错);宿主没有该原语时静默跳过 ——
114
+ * 顺序不是数据,丢了不影响可用性。
115
+ */
116
+ async reorderWorkspaces(orderedIds) {
117
+ const registry = this.registry();
118
+ if (!registry || typeof registry.insertBefore !== 'function')
119
+ return;
120
+ const known = new Set(registry.list().map((w) => String(w.id)));
121
+ const ids = orderedIds.filter((id) => known.has(id));
122
+ for (let i = ids.length - 2; i >= 0; i -= 1) {
123
+ await registry.insertBefore(ids[i], ids[i + 1]);
124
+ }
125
+ }
126
+ }
127
+ //# sourceMappingURL=host-workspace-facade.js.map
@@ -49,6 +49,11 @@ export declare function rebaseMapping(sourceHome: string | undefined, localHome:
49
49
  * 哪个适配器在消费它(core 也不得 import 会话字节工具)。键空间对齐因此落在计划生成期。
50
50
  */
51
51
  export declare function sessionUnitVersion(byUnit: ReadonlyMap<string, number>, unitId: string): number | undefined;
52
+ /**
53
+ * 同一键空间对齐的泛化版(P3 的逐条比对行、格式探针都用它)。
54
+ * 返回 undefined 表示「两个形态都没命中」——调用方必须把这种情况与「命中但值为空」分开。
55
+ */
56
+ export declare function sessionUnitLookup<T>(byUnit: ReadonlyMap<string, T>, unitId: string): T | undefined;
52
57
  /** 路径映射合并:只保留「已解析」(newPrefix 非空)的映射用于执行期数据改写;
53
58
  * 未解决项(newPrefix 空)保留在 plan.items 里供 UI 提示,但不参与数据映射。 */
54
59
  export declare function mergePathMappings(items: PlanItem[], userMappings: PathMapping[]): PathMapping[];
@@ -61,6 +66,16 @@ export declare function mergePathMappings(items: PlanItem[], userMappings: PathM
61
66
  * 映射在这些分区上**没有任何合法作用**:文件内容存的是字节(`Uint8Array` 叶子),不会被改。
62
67
  */
63
68
  export declare function applyMappingsToSections(sections: Map<SectionId, unknown>, mappings: PathMapping[], fileCollectionIds?: ReadonlySet<string>): void;
69
+ /**
70
+ * P4:由「导入到 <目录>」推导出工作区路径映射(`workspaceRoot` → `PathMapping[]`)。
71
+ *
72
+ * 只产出**已解析**(newPrefix 非空)的映射,且只作用于 workspaces;没有绝对源路径、没有根目录、
73
+ * 或该源路径已被用户手填映射命中时,一律不产出(显式映射优先,不重复给规则)。
74
+ *
75
+ * 为什么放在计划期纯函数里:它只读分析产物(sections 里的 workspaces 载荷)+ 目标平台,
76
+ * 不碰文件系统,因此 Dry Run 与真导入看到的是同一份推导结果。
77
+ */
78
+ export declare function workspaceRootMappings(sections: ReadonlyMap<SectionId, unknown>, rootDir: string | undefined, targetPlatform: string, userMappings: readonly PathMapping[]): PathMapping[];
64
79
  /** 路径形态判定:跨平台盘符/UNIX 冲突 → platformMismatch;其余绝对路径 → missing(需映射) */
65
80
  export declare function detectPathIssues(sourcePlatform: string, targetPlatform: string, sections: Map<SectionId, unknown>): PathIssue[];
66
81
  export declare function judgePath(p: string, sourcePlatform: string, targetPlatform: string): PathIssue;
@@ -14,6 +14,8 @@ import { isFileSection } from '../schema/config.js';
14
14
  import { validateManifest } from '../schema/manifest.js';
15
15
  import { migrateToCurrent } from '../migrations/index.js';
16
16
  import { isTombstoned } from '../schema/tombstones.js';
17
+ import { applyPathMapping } from './path-mapping.js';
18
+ import { deriveWorkspaceMappings } from './workspace-root.js';
17
19
  export async function reportRollbackToJournal(binding, report) {
18
20
  const reporter = binding;
19
21
  await reporter?.recordRollback?.(report);
@@ -90,6 +92,13 @@ export function rebaseMapping(sourceHome, localHome) {
90
92
  * 哪个适配器在消费它(core 也不得 import 会话字节工具)。键空间对齐因此落在计划生成期。
91
93
  */
92
94
  export function sessionUnitVersion(byUnit, unitId) {
95
+ return sessionUnitLookup(byUnit, unitId);
96
+ }
97
+ /**
98
+ * 同一键空间对齐的泛化版(P3 的逐条比对行、格式探针都用它)。
99
+ * 返回 undefined 表示「两个形态都没命中」——调用方必须把这种情况与「命中但值为空」分开。
100
+ */
101
+ export function sessionUnitLookup(byUnit, unitId) {
93
102
  const direct = byUnit.get(unitId);
94
103
  if (direct !== undefined)
95
104
  return direct;
@@ -132,6 +141,41 @@ export function applyMappingsToSections(sections, mappings, fileCollectionIds =
132
141
  sections.set(sectionId, applyPrefixMappings(data, relevant));
133
142
  }
134
143
  }
144
+ /**
145
+ * P4:由「导入到 <目录>」推导出工作区路径映射(`workspaceRoot` → `PathMapping[]`)。
146
+ *
147
+ * 只产出**已解析**(newPrefix 非空)的映射,且只作用于 workspaces;没有绝对源路径、没有根目录、
148
+ * 或该源路径已被用户手填映射命中时,一律不产出(显式映射优先,不重复给规则)。
149
+ *
150
+ * 为什么放在计划期纯函数里:它只读分析产物(sections 里的 workspaces 载荷)+ 目标平台,
151
+ * 不碰文件系统,因此 Dry Run 与真导入看到的是同一份推导结果。
152
+ */
153
+ export function workspaceRootMappings(sections, rootDir, targetPlatform, userMappings) {
154
+ if (rootDir === undefined || rootDir.trim() === '')
155
+ return [];
156
+ const data = sections.get('workspaces');
157
+ if (data === null || typeof data !== 'object')
158
+ return [];
159
+ const records = data.workspaces;
160
+ if (!Array.isArray(records))
161
+ return [];
162
+ const inputs = [];
163
+ for (const raw of records) {
164
+ if (raw === null || typeof raw !== 'object')
165
+ continue;
166
+ const path = raw.path;
167
+ const title = raw.title;
168
+ if (typeof path !== 'string')
169
+ continue;
170
+ inputs.push({ path, title: typeof title === 'string' ? title : undefined });
171
+ }
172
+ // 用户手填映射优先:只把「作用于 workspaces(或未限定分区)」的规则算作已认领
173
+ const claimed = userMappings.filter((m) => m.newPrefix !== '' && (m.appliesTo.length === 0 || m.appliesTo.includes('workspaces')));
174
+ return deriveWorkspaceMappings(inputs, rootDir, {
175
+ platform: targetPlatform,
176
+ isClaimed: (source) => applyPathMapping(source, claimed) !== null,
177
+ });
178
+ }
135
179
  /** 路径形态判定:跨平台盘符/UNIX 冲突 → platformMismatch;其余绝对路径 → missing(需映射) */
136
180
  export function detectPathIssues(sourcePlatform, targetPlatform, sections) {
137
181
  const issues = [];
@@ -26,6 +26,12 @@ export declare const zh: {
26
26
  readonly 'export.vaultRefreshFailed': 'vault 镜像刷新失败(不影响导出): {reason}';
27
27
  readonly 'export.sessionsLimited': '会话按数量筛选:只带最新 {count} 个(共 {total} 个;单位 = 会话目录,同一会话的日志一起走)';
28
28
  readonly 'export.sessionsNone': '会话按数量筛选:本次一个都不带(sessions.limit = 0)';
29
+ readonly 'export.attachmentsReferenced': '附件只带被会话引用过的 {count} 个(本机库共 {total} 个,另有 {missing} 个被引用但已不在本机)';
30
+ readonly 'export.attachmentsNoSessions': '附件分区依赖会话:本次未选中任何会话,故一条附件都不带';
31
+ readonly 'export.attachmentsLimitIgnored': '附件按全部会话的引用收集,未按「最新 N 个」收窄(宁可多带,不静默丢图)';
32
+ readonly 'export.attachmentsScanUnreadable': '读不到会话目录,无法判定哪些附件被引用:本次按整个附件库收集';
33
+ readonly 'export.attachmentsScanFailed': '{count} 个会话日志读不出或解不开,无法判定附件引用:本次按整个附件库收集';
34
+ readonly 'export.attachmentsNoZstd': '当前运行环境没有 zstd 解压能力,无法读取会话日志判定附件引用:本次按整个附件库收集';
29
35
  readonly 'export.sessionsWorkspacesCoupled': '已连带导出 {count} 条与会话相关的工作区记录(会话要在目标机显示出来,必须有工作区指向它的 cwd)';
30
36
  readonly 'export.sessionsDeclaredInWorkspaces': '已把本次导出的 {count} 次会话声明进 {workspaces} 条工作区记录(DSH 工作区 sessionIds 覆盖率很低,漏了这一步目标机就看不见这些对话)';
31
37
  readonly 'export.sessionsWorkspacesCarriedAll': '选中的会话没有登记在任何工作区记录里:已连带导出全部 {count} 条工作区记录(漏带工作区 = 目标机上这些对话看不见)';
@@ -52,6 +58,9 @@ export declare const zh: {
52
58
  readonly 'import.sessionsFormatSampled': '会话格式体检为抽查:本次检查了 {sampled} 条,另有 {skipped} 条未检查';
53
59
  readonly 'import.sessionsFormatAborted': '包内有 {count} 条会话是 v{newer} 格式,高于本机 DSH 支持的 v{target}:按当前处置「中止」,本次导入在计划阶段已停止(未写入任何内容)。请改选「跳过这些会话」或「仅提示引导」,或先把本机 DSH 升级到相同/更新版本';
54
60
  readonly 'import.sessionsNeedRestart': '已写入 {count} 个会话文件:DSH 的会话列表在启动时读取,需要重启 DSH(桌面端:退出应用重开)后这些对话才会出现在工作区列表里';
61
+ readonly 'import.sessionOverwrite': '导入会覆盖掉本机 {units} 条会话里的新消息(共 {events} 条;本次比对 {total} 条会话):这些内容只存在于本机、备份包里没有,恢复后按包为准会被替换 —— 需要留下本机这份请先导出当前状态';
62
+ readonly 'import.sessionAttachmentsMissing': '包内有 {count} 个被对话引用的附件没有随包({ids} …):恢复后这些图片/文件会显示为缺失(多半是导出时未勾选「会话附件」分区)';
63
+ readonly 'import.sessionCompareSampled': '会话逐条比对为抽查:本次比对了 {sampled} 条,另有 {skipped} 条未比对(未比对不代表一致)';
55
64
  readonly 'export.sessionParentsCoupled': '已连带导出 {count} 个父对话(DSH 工作区只在父对话之下显示子代理会话;不带父对话时导入后在工作区里看不到)';
56
65
  readonly 'export.sessionParentsUncoupled': '有 {count} 个子代理会话未能连带其父对话:{detail} —— 只带子会话时,导入后 DSH 工作区里不会显示它们';
57
66
  readonly 'export.sessionChildrenCoupled': '已连带导出 {count} 个子代理会话(DSH 把子对话显示在父对话的树状图下面;只带父对话时那棵树是空的)';
@@ -182,6 +191,17 @@ export declare const zh: {
182
191
  readonly 'host.syncStatusTimeout': '同步状态读取超时(10 秒):DSH 凭据服务或工作副本自检没有在预算内返回,请重试';
183
192
  readonly 'host.workspaceUnavailable': 'workspaceRegistry 服务不可用,无法写入工作区';
184
193
  readonly 'host.workspaceMissingTarget': '目标机不存在工作区 {id}(无法登记会话)';
194
+ readonly 'host.workspaceArchiveUnavailable': '宿主未暴露会话归档能力,归档状态未恢复';
195
+ readonly 'adapter.workspaceArchiveUnreadable': '未能读取会话归档集(本次备份不含归档状态):{msg}';
196
+ readonly 'adapter.workspaceArchiveRestored': '已恢复 {count} 个归档会话';
197
+ readonly 'adapter.workspaceArchiveFailed': '{count} 个归档会话未恢复({ids}):{msg}';
198
+ readonly 'host.workspacePinUnavailable': '宿主未暴露会话置顶能力,置顶状态未恢复';
199
+ readonly 'adapter.workspacePinUnreadable': '未能读取会话置顶集(本次备份不含置顶状态):{msg}';
200
+ readonly 'adapter.workspacePinRestored': '已恢复 {count} 个置顶会话';
201
+ readonly 'adapter.workspacePinFailed': '{count} 个置顶会话未恢复({ids}):{msg}';
202
+ readonly 'adapter.workspaceReorderSkipped': '工作区显示顺序未恢复:包内 {count} 条工作区没能与新机记录对应上(路径与标题都变过?)';
203
+ readonly 'adapter.workspaceReorderFailed': '工作区显示顺序未恢复:{msg}';
204
+ readonly 'export.attachmentsAllSessions': '附件按全部会话计算引用面(未指定会话范围):本机库共 {total} 个对象,其中 {count} 个被引用,{missing} 个已被引用但不在本机';
185
205
  readonly 'host.sessionStoreShapeUnknown': '宿主会话存储列举(sessionPersistence.list())的元素形状无法解析(探测形状 {shape},{count} 个元素全部认不出):父子关系判定放弃,绝不当作「本机没有父子关系」(请升级 DSH,或把该形状反馈给插件)';
186
206
  readonly 'host.sessionStorePurposeReindex': '会话 header 重新索引';
187
207
  readonly 'host.sessionStorePurposeParentRelations': '父子关系判定';
@@ -10,6 +10,12 @@ export const zh = {
10
10
  'export.vaultRefreshFailed': 'vault 镜像刷新失败(不影响导出): {reason}',
11
11
  'export.sessionsLimited': '会话按数量筛选:只带最新 {count} 个(共 {total} 个;单位 = 会话目录,同一会话的日志一起走)',
12
12
  'export.sessionsNone': '会话按数量筛选:本次一个都不带(sessions.limit = 0)',
13
+ 'export.attachmentsReferenced': '附件只带被会话引用过的 {count} 个(本机库共 {total} 个,另有 {missing} 个被引用但已不在本机)',
14
+ 'export.attachmentsNoSessions': '附件分区依赖会话:本次未选中任何会话,故一条附件都不带',
15
+ 'export.attachmentsLimitIgnored': '附件按全部会话的引用收集,未按「最新 N 个」收窄(宁可多带,不静默丢图)',
16
+ 'export.attachmentsScanUnreadable': '读不到会话目录,无法判定哪些附件被引用:本次按整个附件库收集',
17
+ 'export.attachmentsScanFailed': '{count} 个会话日志读不出或解不开,无法判定附件引用:本次按整个附件库收集',
18
+ 'export.attachmentsNoZstd': '当前运行环境没有 zstd 解压能力,无法读取会话日志判定附件引用:本次按整个附件库收集',
13
19
  'export.sessionsWorkspacesCoupled': '已连带导出 {count} 条与会话相关的工作区记录(会话要在目标机显示出来,必须有工作区指向它的 cwd)',
14
20
  'export.sessionsDeclaredInWorkspaces': '已把本次导出的 {count} 次会话声明进 {workspaces} 条工作区记录(DSH 工作区 sessionIds 覆盖率很低,漏了这一步目标机就看不见这些对话)',
15
21
  'export.sessionsWorkspacesCarriedAll': '选中的会话没有登记在任何工作区记录里:已连带导出全部 {count} 条工作区记录(漏带工作区 = 目标机上这些对话看不见)',
@@ -37,6 +43,9 @@ export const zh = {
37
43
  'import.sessionsFormatSampled': '会话格式体检为抽查:本次检查了 {sampled} 条,另有 {skipped} 条未检查',
38
44
  'import.sessionsFormatAborted': '包内有 {count} 条会话是 v{newer} 格式,高于本机 DSH 支持的 v{target}:按当前处置「中止」,本次导入在计划阶段已停止(未写入任何内容)。请改选「跳过这些会话」或「仅提示引导」,或先把本机 DSH 升级到相同/更新版本',
39
45
  'import.sessionsNeedRestart': '已写入 {count} 个会话文件:DSH 的会话列表在启动时读取,需要重启 DSH(桌面端:退出应用重开)后这些对话才会出现在工作区列表里',
46
+ 'import.sessionOverwrite': '导入会覆盖掉本机 {units} 条会话里的新消息(共 {events} 条;本次比对 {total} 条会话):这些内容只存在于本机、备份包里没有,恢复后按包为准会被替换 —— 需要留下本机这份请先导出当前状态',
47
+ 'import.sessionAttachmentsMissing': '包内有 {count} 个被对话引用的附件没有随包({ids} …):恢复后这些图片/文件会显示为缺失(多半是导出时未勾选「会话附件」分区)',
48
+ 'import.sessionCompareSampled': '会话逐条比对为抽查:本次比对了 {sampled} 条,另有 {skipped} 条未比对(未比对不代表一致)',
40
49
  'export.sessionParentsCoupled': '已连带导出 {count} 个父对话(DSH 工作区只在父对话之下显示子代理会话;不带父对话时导入后在工作区里看不到)',
41
50
  'export.sessionParentsUncoupled': '有 {count} 个子代理会话未能连带其父对话:{detail} —— 只带子会话时,导入后 DSH 工作区里不会显示它们',
42
51
  'export.sessionChildrenCoupled': '已连带导出 {count} 个子代理会话(DSH 把子对话显示在父对话的树状图下面;只带父对话时那棵树是空的)',
@@ -171,6 +180,17 @@ export const zh = {
171
180
  'host.syncStatusTimeout': '同步状态读取超时(10 秒):DSH 凭据服务或工作副本自检没有在预算内返回,请重试',
172
181
  'host.workspaceUnavailable': 'workspaceRegistry 服务不可用,无法写入工作区',
173
182
  'host.workspaceMissingTarget': '目标机不存在工作区 {id}(无法登记会话)',
183
+ 'host.workspaceArchiveUnavailable': '宿主未暴露会话归档能力,归档状态未恢复',
184
+ 'adapter.workspaceArchiveUnreadable': '未能读取会话归档集(本次备份不含归档状态):{msg}',
185
+ 'adapter.workspaceArchiveRestored': '已恢复 {count} 个归档会话',
186
+ 'adapter.workspaceArchiveFailed': '{count} 个归档会话未恢复({ids}):{msg}',
187
+ 'host.workspacePinUnavailable': '宿主未暴露会话置顶能力,置顶状态未恢复',
188
+ 'adapter.workspacePinUnreadable': '未能读取会话置顶集(本次备份不含置顶状态):{msg}',
189
+ 'adapter.workspacePinRestored': '已恢复 {count} 个置顶会话',
190
+ 'adapter.workspacePinFailed': '{count} 个置顶会话未恢复({ids}):{msg}',
191
+ 'adapter.workspaceReorderSkipped': '工作区显示顺序未恢复:包内 {count} 条工作区没能与新机记录对应上(路径与标题都变过?)',
192
+ 'adapter.workspaceReorderFailed': '工作区显示顺序未恢复:{msg}',
193
+ 'export.attachmentsAllSessions': '附件按全部会话计算引用面(未指定会话范围):本机库共 {total} 个对象,其中 {count} 个被引用,{missing} 个已被引用但不在本机',
174
194
  'host.sessionStoreShapeUnknown': '宿主会话存储列举(sessionPersistence.list())的元素形状无法解析(探测形状 {shape},{count} 个元素全部认不出):父子关系判定放弃,绝不当作「本机没有父子关系」(请升级 DSH,或把该形状反馈给插件)',
175
195
  'host.sessionStorePurposeReindex': '会话 header 重新索引',
176
196
  'host.sessionStorePurposeParentRelations': '父子关系判定',
@@ -542,6 +562,12 @@ export const en = {
542
562
  'export.vaultRefreshFailed': 'Vault mirror refresh failed (export unaffected): {reason}',
543
563
  'export.sessionsLimited': 'Sessions filtered by count: only the latest {count} are included ({total} total; the unit is a session directory, so all logs of one session travel together)',
544
564
  'export.sessionsNone': 'Sessions filtered by count: none are included this time (sessions.limit = 0)',
565
+ 'export.attachmentsReferenced': 'Attachments: only {count} referenced by sessions are included ({total} in the local store, {missing} referenced ones are already gone from this machine)',
566
+ 'export.attachmentsNoSessions': 'The attachments section depends on sessions: no session was selected, so no attachment is included',
567
+ 'export.attachmentsLimitIgnored': 'Attachments are collected from every session reference, not narrowed by "latest N" (prefer extra bytes over silently losing images)',
568
+ 'export.attachmentsScanUnreadable': 'The sessions directory is unreadable, so referenced attachments cannot be determined: the whole attachment store is collected this time',
569
+ 'export.attachmentsScanFailed': '{count} session logs could not be read or decoded, so attachment references cannot be determined: the whole attachment store is collected this time',
570
+ 'export.attachmentsNoZstd': 'This runtime has no zstd decompression, so session logs cannot be read to determine attachment references: the whole attachment store is collected this time',
545
571
  'export.sessionsWorkspacesCoupled': 'Also exported {count} workspace record(s) that own the selected sessions (a session only shows up when a workspace points at its cwd)',
546
572
  'export.sessionsDeclaredInWorkspaces': 'Declared the {count} exported session(s) in {workspaces} workspace record(s) (DSH workspace sessionIds coverage is very low; without this step those conversations stay invisible on the target machine)',
547
573
  'export.sessionsWorkspacesCarriedAll': 'None of the selected sessions is registered in any workspace record: all {count} workspace record(s) were exported as well (without a workspace those sessions stay invisible on the target machine)',
@@ -569,6 +595,9 @@ export const en = {
569
595
  'import.sessionsFormatSampled': 'Session format check was sampled: {sampled} checked, {skipped} not checked',
570
596
  'import.sessionsFormatAborted': 'This backup carries {count} session log(s) in format v{newer}, newer than this DSH build supports (v{target}): with the current "abort" disposition the import stopped at the planning stage (nothing was written). Choose "skip these sessions" or "guidance only", or upgrade this DSH build to the same or a newer version first',
571
597
  'import.sessionsNeedRestart': 'Wrote {count} session file(s): DSH reads its session list at startup, so those conversations only appear in the workspace list after restarting DSH (Desktop: quit and reopen the app)',
598
+ 'import.sessionOverwrite': 'Import replaces newer messages that exist only on this machine: {units} conversation(s), {events} message(s), compared against {total} conversation(s). Those messages are not in the backup, so restoring makes the bundle authoritative -- export the current state first if you need to keep them',
599
+ 'import.sessionAttachmentsMissing': 'The backup references {count} attachment(s) that are not in the bundle ({ids} ...): those images/files will show as missing after restore (the session attachments section was probably not selected when exporting)',
600
+ 'import.sessionCompareSampled': 'Per-conversation comparison was sampled: {sampled} compared, {skipped} not compared (not compared does not mean identical)',
572
601
  'export.sessionParentsCoupled': 'Carried {count} parent conversation(s) along (DSH only shows subagent sessions underneath their parent; without the parent they stay invisible in the workspace after import)',
573
602
  'export.sessionParentsUncoupled': '{count} subagent session(s) could not carry their parent conversation: {detail} -- the imported child alone never shows up in a DSH workspace',
574
603
  'export.sessionChildrenCoupled': 'Carried {count} subagent conversation(s) along (DSH renders child conversations underneath their parent; the parent alone arrives with an empty tree)',
@@ -703,6 +732,17 @@ export const en = {
703
732
  'host.syncStatusTimeout': 'Sync status timed out (10 s): the DSH credential service or work-copy self-check did not return within budget; please retry',
704
733
  'host.workspaceUnavailable': 'workspaceRegistry service unavailable; cannot write the workspace',
705
734
  'host.workspaceMissingTarget': 'Workspace {id} does not exist on this machine (cannot attach the session)',
735
+ 'host.workspaceArchiveUnavailable': 'This host exposes no session-archive capability; archive state was not restored',
736
+ 'adapter.workspaceArchiveUnreadable': 'Could not read the session archive set (this backup carries no archive state): {msg}',
737
+ 'adapter.workspaceArchiveRestored': 'Restored {count} archived session(s)',
738
+ 'adapter.workspaceArchiveFailed': '{count} archived session(s) were not restored ({ids}): {msg}',
739
+ 'host.workspacePinUnavailable': 'This host exposes no session-pin capability; pin state was not restored',
740
+ 'adapter.workspacePinUnreadable': 'Could not read the session pin set (this backup carries no pin state): {msg}',
741
+ 'adapter.workspacePinRestored': 'Restored {count} pinned session(s)',
742
+ 'adapter.workspacePinFailed': '{count} pinned session(s) were not restored ({ids}): {msg}',
743
+ 'adapter.workspaceReorderSkipped': 'Workspace display order was not restored: {count} workspace(s) in the bundle could not be matched to a record on this machine (path and title both changed?)',
744
+ 'adapter.workspaceReorderFailed': 'Workspace display order was not restored: {msg}',
745
+ 'export.attachmentsAllSessions': 'Attachments are collected against every session (no session scope was given): {count} of {total} objects on this machine are referenced, and {missing} referenced object(s) are no longer present',
706
746
  'host.sessionStoreShapeUnknown': 'Cannot parse the elements returned by the host session store (sessionPersistence.list(); probed shape {shape}, none of the {count} elements is recognizable): parent/child detection is abandoned rather than treated as "no parent relations on this machine" (please upgrade DSH or report this shape to the plugin)',
707
747
  'host.sessionStorePurposeReindex': 'session header re-index',
708
748
  'host.sessionStorePurposeParentRelations': 'parent/child detection',
@@ -17,7 +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
+ import { isNonBlockingExternalFailure } from './external-failure.js';
21
21
  /** 存在未收敛的 active transaction → 拒绝创建第二个(active≤1)。 */
22
22
  export class TransactionRecoveryRequiredError extends Error {
23
23
  constructor(opId) {
@@ -572,7 +572,7 @@ export class Phase3Recovery {
572
572
  // 放大成「全部写入 423,直到手动解除阻断」,而界面还说是「环境锁被占用」——
573
573
  // 真机 issue 的链路就是这样(locks 目录为空却报锁,见 core/external-failure.ts)。
574
574
  // 除该判据之外的一切失败保持 fail-closed(照旧 durable SAFE MODE,跨重启生效)。
575
- if (!isLocalOnlyExternalFailure(err)) {
575
+ if (!isNonBlockingExternalFailure(err)) {
576
576
  this.safeModeActive = true;
577
577
  await this.store.writeSafeMode(true).catch(() => undefined);
578
578
  }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * 分析期的会话体检:格式版本探针、逐条比对、解析结果告警 —— 从 analyzer.ts 下沉。
3
+ * (计划项标记不在这里:它只写展示字段、属于计划期,见 core/session-verdict-plan.ts。)
4
+ *
5
+ * 为什么独立成模块:analyzer 越过体量棘轮(tests/file-size-ratchet.test.ts),而这些函数的
6
+ * 依赖全部由入参给出(探针、适配器表、文案函数、本机支持版本),搬出来不改变任何调用点的
7
+ * 语义,也不新增对外契约。**判定口径仍只有一处**:纯比对算法在 core/session-compare.ts。
8
+ */
9
+ import type { SectionId } from '../schema/types.ts';
10
+ import type { MsgFunc } from './messages.ts';
11
+ import type { ConfigAdapter, HostContext, SessionCompareSummary, SessionFormatProbeResult } from './types.ts';
12
+ /** 会话格式体检的「已落定」结果(探针 + 本机支持版本;不可判定时整体缺省)。 */
13
+ export interface ResolvedSessionFormats {
14
+ target: number;
15
+ unreadable: {
16
+ unitId: string;
17
+ version: number;
18
+ }[];
19
+ /** 本次体检真正看过的会话条数(解出 header 的 + 解不出的) */
20
+ examined: number;
21
+ /** 因抽样上限未检查的会话条数 */
22
+ skipped: number;
23
+ }
24
+ /**
25
+ * 会话格式体检(探针注入:core 不解析会话格式)。
26
+ *
27
+ * 「包里的版本 > 本机支持的版本」告警;本机版本解析不到时**不猜**(宁可不报,也不谎报兼容)。
28
+ * 不可判定(无探针 / 无 sessions / 本机版本解析不到 / 探针抛错)一律返回 null。
29
+ */
30
+ export declare function resolveSessionFormats(sections: Map<SectionId, unknown>, probe: ((files: readonly {
31
+ relativePath: string;
32
+ data: Uint8Array;
33
+ }[]) => SessionFormatProbeResult) | undefined, target: number | undefined): ResolvedSessionFormats | null;
34
+ export declare function sessionFormatWarnings(result: ResolvedSessionFormats | null, msg: MsgFunc): string[];
35
+ /**
36
+ * 会话逐条比对(包内同名会话 vs **本机**)—— 与格式体检一样**每份归档只跑一次**。
37
+ *
38
+ * 为什么由 sessions adapter 执行而不是这里:解会话日志要用 zstd 帧与首帧能力,那是会话字节
39
+ * 工具(core 不 import 它);纯比对算法在 core/session-compare.ts。此处只负责「找到适配器、
40
+ * 调一次、再补上附件缺口」。
41
+ *
42
+ * 附件缺口是**纯包内判定**(包内会话引用到的 id ∩ 包内实际带上的附件对象),因此不读本机、
43
+ * 也不会因为本机文件被用户删了而误报:它回答的是「按这个包恢复,哪些图会缺」。
44
+ */
45
+ export declare function resolveSessionCompare(sections: Map<SectionId, unknown>, adapters: readonly ConfigAdapter[], ctx: HostContext): Promise<SessionCompareSummary | null>;
46
+ /**
47
+ * 逐条比对的告警(只在**真会丢东西**时说话):
48
+ * - 本机比包内多内容 → 「导入会覆盖掉本机 N 条消息」(这是本功能存在的理由);
49
+ * - 引用了包内没有的附件 → 恢复后图会缺;
50
+ * - 预算截断 → 「另有 N 条未比对」(绝不让用户以为全都比过了)。
51
+ */
52
+ export declare function sessionCompareWarnings(result: SessionCompareSummary | null, msg: MsgFunc): string[];