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
@@ -24,7 +24,12 @@ import type { AutosyncHistoryEntry } from './sync-history.ts';
24
24
  import type { MergePlan, MergeSectionResult } from './merge.ts';
25
25
  import type { SyncSnapshotMeta } from './transport.ts';
26
26
  import type { SectionId } from '../schema/types.ts';
27
- import type { SyncEngine } from './sync-engine.ts';
27
+ import { SyncEngine } from './sync-engine.ts';
28
+ import { createAdapters } from '../adapters/index.ts';
29
+ import { makeContext, MemSnapshotStore } from '../adapters/test-helpers.ts';
30
+ import { Importer } from '../core/importer.ts';
31
+ import { computeSnapshotMeta } from './transport.ts';
32
+ import type { SyncSnapshot, SyncTransport } from './transport.ts';
28
33
  import type { SyncConfig, SyncTransportType } from './sync-config.ts';
29
34
  import { SYNC_CONFIG_FILE } from './sync-config.ts';
30
35
  import { SYNC_CHANNELS } from './sync-config.ts';
@@ -61,6 +66,9 @@ function makeScheduler(opts: {
61
66
  mutationLock?: MutationLockPort;
62
67
  /** issue #31:捕获日志行(断言 stale 指引确实写给用户) */
63
68
  logSink?: LogSink;
69
+ /** 2026-11-07 事故护栏:注入检测结论(缺省走真实检测,需要真引擎) */
70
+ detectRemoteNew?: (engine: SyncEngine, listed?: readonly SyncSnapshotMeta[]) => Promise<boolean>;
71
+ detectLocalChange?: (engine: SyncEngine) => Promise<boolean>;
64
72
  }) {
65
73
  const runs = new RunRegistry();
66
74
  const entries: AutosyncHistoryEntry[] = [...opts.history];
@@ -78,6 +86,8 @@ function makeScheduler(opts: {
78
86
  readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: entries, updatedAt: '' }),
79
87
  appendHistoryFn: async (e) => { entries.push(e); },
80
88
  ...(opts.mutationLock !== undefined ? { mutationLock: opts.mutationLock } : {}),
89
+ ...(opts.detectRemoteNew !== undefined ? { detectRemoteNew: opts.detectRemoteNew } : {}),
90
+ ...(opts.detectLocalChange !== undefined ? { detectLocalChange: opts.detectLocalChange } : {}),
81
91
  // 测试不用真实定时器:不调 start()
82
92
  });
83
93
  return { scheduler, runs, getConfig: () => config, getEntries: () => entries };
@@ -160,11 +170,12 @@ test('runOnce: 残留锁挡住 → skipped(mutation-locked) 且**写历史**(i
160
170
  });
161
171
  const result = await scheduler.runOnce('git');
162
172
  assert.equal(result.status, 'skipped');
163
- assert.equal(result.skipReason, 'mutation-locked');
173
+ // 分档(lockSkipToken):注入的是 STALE_LOCK_DETECTED → 残留锁 token,客户端据此给「去事故恢复回收」
174
+ assert.equal(result.skipReason, 'mutation-lock-stale');
164
175
  const entries = getEntries();
165
176
  assert.equal(entries.length, 1, '被锁挡下必须留一条历史(否则用户只看得到「自动同步不再更新」)');
166
177
  assert.equal(entries[0]!.status, 'skipped');
167
- assert.equal(entries[0]!.skipReason, 'mutation-locked');
178
+ assert.equal(entries[0]!.skipReason, 'mutation-lock-stale');
168
179
  assert.equal(entries[0]!.transport, 'git');
169
180
  assert.equal(getConfig().consecutiveFailures, 0, '被锁挡下不计入连续失败');
170
181
  });
@@ -182,7 +193,7 @@ test('runOnce: 被锁挡下(stale)不得泄漏 running run —— 否则后
182
193
  assert.deepEqual(runs.listActive(), [], '被锁挡下后不得留下 running run(泄漏会挡住后续每一次 autosync)');
183
194
  // 反向控制:泄漏时这个断言必须变红(run 仍在 running)
184
195
  const again = await scheduler.runOnce('git');
185
- assert.equal(again.skipReason, 'mutation-locked', '第二次仍是被锁挡下,而不是 conflict');
196
+ assert.equal(again.skipReason, 'mutation-lock-stale', '第二次仍是被锁挡下(残留锁),而不是 conflict');
186
197
  });
187
198
 
188
199
  test('runOnce: acquire 抛错(锁目录 IO)同样不得泄漏 running run', async () => {
@@ -225,9 +236,11 @@ test('issue #31 D:acquire 本身抛错(锁目录 IO)同样必须写历史
225
236
  });
226
237
  const result = await scheduler.runOnce('git');
227
238
  assert.equal(result.status, 'skipped');
228
- assert.equal(result.skipReason, 'mutation-locked');
239
+ // 分档(lockSkipToken):acquire 抛错 = 锁不可用,既不是「被另一任务占用」也不是「残留锁」——
240
+ // 此前三种都落成 'mutation-locked',界面只能写「被占用或残留」,真机 locks 为空时把排查方向带偏。
241
+ assert.equal(result.skipReason, 'mutation-lock-unavailable');
229
242
  assert.equal(getEntries().length, 1, 'acquire 抛错也是「被挡」,同样要留历史');
230
- assert.equal(getEntries()[0]!.skipReason, 'mutation-locked');
243
+ assert.equal(getEntries()[0]!.skipReason, 'mutation-lock-unavailable');
231
244
  assert.equal(getConfig().consecutiveFailures, 0, '不计入连续失败');
232
245
  });
233
246
 
@@ -1144,3 +1157,164 @@ test('SEC-03:真的没配 → 不带 configIssue(不产生幻影告警)',
1144
1157
  const entry = getEntries()[0] as AutosyncHistoryEntry & { configIssue?: string } | undefined;
1145
1158
  assert.equal(entry?.configIssue, undefined);
1146
1159
  });
1160
+
1161
+ /* ---------------- 端到端:勾选 mcp 后「仅连接器存储改动」必须真的上行 ---------------- */
1162
+
1163
+ /**
1164
+ * 修复前必失败(复现):自动同步只放行 'auto' 档可选分区(当前 = mcp,src/index.ts:2796-2810),
1165
+ * 而 hasLocalChanges 只比 portable ⇒ 用户勾了 mcp 后「只改连接器存储」被判成无改动 ⇒
1166
+ * Phase C 不 push(autosync-scheduler.ts:800-819),改动永不单独上行。
1167
+ *
1168
+ * 这里用**真实 SyncEngine + 真实调度器**跑完整一轮(不做 hasLocalChanges 的 mock):
1169
+ * 1) 仅改 storages/mcp_connector.json → 必须真的上传一轮,且新载荷带新 args;
1170
+ * 2) 紧接着无改动再跑一轮 → upToDate,且**不得**再多一次上传(判定字节 == 载荷字节,不空推)。
1171
+ */
1172
+ class E2eTransport implements SyncTransport {
1173
+ readonly type = 'memory';
1174
+ snapshots: SyncSnapshot[] = [];
1175
+ calls: string[] = [];
1176
+ async list(): Promise<SyncSnapshotMeta[]> {
1177
+ this.calls.push('list');
1178
+ return this.snapshots.map((s) => computeSnapshotMeta(s));
1179
+ }
1180
+ async upload(snapshot: SyncSnapshot): Promise<SyncSnapshotMeta> {
1181
+ this.calls.push('upload');
1182
+ this.snapshots.push(snapshot);
1183
+ return computeSnapshotMeta(snapshot);
1184
+ }
1185
+ async download(id: string): Promise<SyncSnapshot> {
1186
+ const found = this.snapshots.find((s) => s.id === id);
1187
+ if (found === undefined) throw new Error('快照不存在: ' + id);
1188
+ return found;
1189
+ }
1190
+ async delete(id: string): Promise<void> {
1191
+ this.calls.push('delete');
1192
+ this.snapshots = this.snapshots.filter((s) => s.id !== id);
1193
+ }
1194
+ }
1195
+
1196
+ /** 连接器存储形态取自 core/mcp-connector-store.ts:361-378(tables.connections 表,按 key 索引)。 */
1197
+ function writeConnectorStore(ctx: ReturnType<typeof makeContext>, args: string[]): void {
1198
+ const store = {
1199
+ tables: {
1200
+ connections: {
1201
+ citra: {
1202
+ key: 'citra', connectorId: 'citra', kind: 'manual', name: 'Citra',
1203
+ serverName: 'citra', transport: 'stdio', command: 'npx', args, enabled: true,
1204
+ },
1205
+ },
1206
+ },
1207
+ };
1208
+ void ctx.fs.writeFile('storages/mcp_connector.json', new TextEncoder().encode(JSON.stringify(store)));
1209
+ }
1210
+
1211
+ test('端到端:勾选 mcp 后仅改连接器存储 → 自动同步一轮真的上传;无改动的一轮不空推', async () => {
1212
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-autosync-mcp-e2e-'));
1213
+ try {
1214
+ const ctx = makeContext('win32', 'C:\\Users\\alice');
1215
+ ctx.settings.ns.set('general', { value: { theme: 'dark' }, revision: 1, secrets: [] });
1216
+ writeConnectorStore(ctx, ['-y', '@sylphx/citra']);
1217
+
1218
+ const adapters = createAdapters({ namespaces: ['general'] });
1219
+ const transport = new E2eTransport();
1220
+ const engine = new SyncEngine({
1221
+ ctx,
1222
+ transport,
1223
+ stateDir: tmp,
1224
+ adapters,
1225
+ importer: new Importer({ ctx, adapters, snapshotStore: new MemSnapshotStore() }),
1226
+ now: () => new Date('2026-11-06T12:00:00.000Z'),
1227
+ optInSections: ['mcp'],
1228
+ } as ConstructorParameters<typeof SyncEngine>[0]);
1229
+
1230
+ // 基线:先推一轮(此时 mcp 已被放行并记入 sync-state 基线)
1231
+ await engine.push({});
1232
+ const uploadsAfterBaseline = transport.calls.filter((c) => c === 'upload').length;
1233
+ assert.equal(uploadsAfterBaseline, 1, '基线轮只上传一次');
1234
+
1235
+ // 只改连接器存储:portable 分区(settings)与 patch 行一律不动
1236
+ writeConnectorStore(ctx, ['-y', '@sylphx/citra@2']);
1237
+
1238
+ const cfg: AutosyncConfig = {
1239
+ enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0, realtime: true,
1240
+ };
1241
+ const scheduler = new AutoSyncScheduler({
1242
+ syncDir: tmp,
1243
+ host: { log: nullLogger() },
1244
+ makeSyncEngine: () => engine,
1245
+ msg: (k: string) => k,
1246
+ runs: new RunRegistry(),
1247
+ now: () => new Date(1_000_000_000_000),
1248
+ readConfig: async (_channel: SyncTransportType) => cfg,
1249
+ writeConfig: async () => {},
1250
+ readSyncConfigFn: async (_channel: SyncTransportType) =>
1251
+ ({ schemaVersion: 2, transport: 'git', git: { repoUrl: 'git@github.com:foo/bar.git' } }) as SyncConfig,
1252
+ readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: [], updatedAt: '' }),
1253
+ appendHistoryFn: async () => {},
1254
+ setTimer: () => 0 as unknown as ReturnType<typeof setTimeout>,
1255
+ clearTimer: () => {},
1256
+ minTriggerGapMs: 0,
1257
+ });
1258
+
1259
+ const pushed = await scheduler.runOnce('git');
1260
+ assert.equal(pushed.status, 'success', '仅改 mcp 的自动同步轮必须成功: ' + JSON.stringify(pushed));
1261
+ const uploadsAfterChange = transport.calls.filter((c) => c === 'upload').length;
1262
+ assert.equal(uploadsAfterChange, 2, '仅改 mcp 也必须真的上传一轮(修复前这里是 1 = 静默丢失)');
1263
+ const latest = transport.snapshots[transport.snapshots.length - 1]!;
1264
+ assert.ok(
1265
+ JSON.stringify(latest.sections).includes('@sylphx/citra@2'),
1266
+ '新快照必须带改后的连接器 args',
1267
+ );
1268
+
1269
+ // 无改动的一轮:判定字节与载荷同源 ⇒ upToDate,绝不再上传(否则每轮轮询都空推一次)
1270
+ const idle = await scheduler.runOnce('git');
1271
+ assert.equal(idle.skipReason, 'upToDate', '无改动 → upToDate: ' + JSON.stringify(idle));
1272
+ assert.equal(
1273
+ transport.calls.filter((c) => c === 'upload').length, 2,
1274
+ '无改动不得产生空推(判定集合必须与载荷同一份字节)',
1275
+ );
1276
+ } finally {
1277
+ await fs.rm(tmp, { recursive: true, force: true });
1278
+ }
1279
+ });
1280
+
1281
+ // ---------- 2026-11-07 真机事故:稳态一轮不得占 GLOBAL mutation 锁 ----------
1282
+ // 现场(实测):autosync 每 60s 触发一轮,每轮在 GLOBAL 锁内为本地源插件跑 npm pack(单个 210MB 插件 44.7s),
1283
+ // 锁几乎全程被占 → 用户删除档案/导入配置恒 423「另一个任务正在运行」。
1284
+ // 现在只读检测放在锁外:稳态(两端无变化)直接收工,不 acquire。
1285
+ test('runOnce: 稳态(两端无变化)不取环境锁;有活干才取(2026-11-07 档案删除 423 护栏)', async () => {
1286
+ const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
1287
+ const engine = { listSnapshots: async () => [] } as unknown as Partial<SyncEngine>;
1288
+
1289
+ // 锁端口:LOCKED(真机上「另一任务正在跑」的形态)。稳态里它绝不该被调用。
1290
+ let acquireCalls = 0;
1291
+ const lockedPort: MutationLockPort = {
1292
+ acquire: async () => {
1293
+ acquireCalls += 1;
1294
+ return { state: 'LOCKED', token: null, detail: 'injected: another task' };
1295
+ },
1296
+ validate: (tok: unknown): tok is MutationLockToken => false,
1297
+ release: async () => undefined,
1298
+ };
1299
+
1300
+ const steady = makeScheduler({
1301
+ cfg, engine, history: [], mutationLock: lockedPort,
1302
+ detectRemoteNew: async () => false,
1303
+ detectLocalChange: async () => false,
1304
+ });
1305
+ const idle = await steady.scheduler.runOnce('git');
1306
+ assert.equal(idle.status, 'success');
1307
+ assert.equal(idle.skipReason, 'upToDate');
1308
+ assert.equal(acquireCalls, 0, '稳态一轮不得占用写锁(否则用户 destructive 操作被 423 挡住)');
1309
+
1310
+ // 反向控制:真有活干时才取锁 —— 取不到就按「被占用」跳过(此时 acquire 必须被调用到)
1311
+ const busy = makeScheduler({
1312
+ cfg, engine, history: [], mutationLock: lockedPort,
1313
+ detectRemoteNew: async () => false,
1314
+ detectLocalChange: async () => true,
1315
+ });
1316
+ const blocked = await busy.scheduler.runOnce('git');
1317
+ assert.equal(acquireCalls, 1, '有活干才取锁(且只取一次)');
1318
+ assert.equal(blocked.status, 'skipped');
1319
+ assert.equal(blocked.skipReason, 'mutation-locked');
1320
+ });
@@ -54,7 +54,7 @@ import type { JournalRunContext } from '../core/phase3-host.ts';
54
54
  import type { SyncEngine } from './sync-engine.ts';
55
55
  import type { SyncSnapshotMeta } from './transport.ts';
56
56
  import type { MutationLockPort, MutationLockContext } from '../utils/env-lock.ts';
57
- import { withMutationLock, LOCK_BLOCK_MESSAGE } from '../utils/env-lock.ts';
57
+ import { withMutationLock, LOCK_BLOCK_MESSAGE, lockSkipToken } from '../utils/env-lock.ts';
58
58
  import { engineMsg } from './messages.ts';
59
59
  import {
60
60
  readAutosyncConfig, writeAutosyncConfig, clampRemoteCheckMs,
@@ -172,6 +172,11 @@ export interface WatcherFactoryOptions {
172
172
  onFlush: (changed: readonly string[]) => void;
173
173
  }
174
174
 
175
+ /** Phase 1(只读预检)的产出:要么本轮无事可做(skip),要么带回给 Phase A/B/C 的检测结论。 */
176
+ type AutosyncDetectOutcome =
177
+ | { kind: 'skip'; result: AutosyncRunResult }
178
+ | { kind: 'work'; engine: SyncEngine; remoteNew: boolean; localDirty: boolean; firstRun: boolean };
179
+
175
180
  export interface AutoSyncSchedulerOptions {
176
181
  syncDir: string;
177
182
  host: { log: Logger };
@@ -571,9 +576,21 @@ export class AutoSyncScheduler {
571
576
  }
572
577
  };
573
578
 
574
- // Phase 2 锁:autosync 的 apply(写本地配置)与 push(写远端+本地散文件)属 GLOBAL mutation。
575
- // 获取失败(另一项 DSH 任务进行中)→ skipped(mutation-locked);成功则在整个 runOnce 持锁并在 finally 释放。
576
- // 无锁环境(测试未注入 mutationLock)→ 不锁定,直接执行(与旧行为一致)。
579
+
580
+ // Phase 1:无锁预检(只读:读配置 + 列远端 + 检测两端变化)。
581
+ //
582
+ // 为什么先检测再取锁(2026-11-07 真机事故):检测里的 plugins 分区导出会为本机源插件跑 npm pack
583
+ // (实测单个 210MB 插件 44.7s/次、每轮重算)。旧实现把这段整个放进 GLOBAL mutation 锁内,60s 一轮的
584
+ // 轮询于是让锁几乎全程被占(45s/60s),用户任何 destructive 操作(删除档案…)都撞 423「另一个任务正在运行」。
585
+ // 现在稳态(upToDate)根本不取锁;命中「有活干」才取,并在锁内重跑检测再写。
586
+ const preflight = await this.detectPhase(channel, cfg, nowIso, historyId);
587
+ if (preflight.kind === 'skip') {
588
+ this.running = false;
589
+ this.watcher?.resume();
590
+ finishRun();
591
+ return preflight.result;
592
+ }
593
+
577
594
  let releaseLock: (() => Promise<void>) | null = null;
578
595
  if (this.mutationLock !== undefined) {
579
596
  try {
@@ -588,8 +605,9 @@ export class AutoSyncScheduler {
588
605
  // issue #31:与 backup-scheduler 对齐——非 stale 分类也留一行(不再只对 stale 说话);
589
606
  // 更重要的是**补写历史**:此前该分支 return 前不写 sync-history,用户看历史面板
590
607
  // 只能发现「自动同步不再更新」,却看不到任何一条「为什么跳过」(实测 9 天 0 条记录)。
591
- if (lk.reason === 'stale') {
592
- this.host.log.warn(`自动同步已跳过(${channel}):${LOCK_BLOCK_MESSAGE.stale}`);
608
+ // stale 与 stale-degraded 同属「重试不会自愈」,都走 warn(都带显式回收指引)。
609
+ if (lk.reason === 'stale' || lk.reason === 'stale-degraded') {
610
+ this.host.log.warn(`自动同步已跳过(${channel}):${LOCK_BLOCK_MESSAGE[lk.reason]}`);
593
611
  } else if (lk.reason !== undefined) {
594
612
  this.host.log.info(`自动同步已跳过(${channel}):${LOCK_BLOCK_MESSAGE[lk.reason]}`);
595
613
  }
@@ -598,13 +616,13 @@ export class AutoSyncScheduler {
598
616
  await this.appendHistory(channel, {
599
617
  direction: 'both',
600
618
  status: 'skipped',
601
- skipReason: 'mutation-locked',
619
+ skipReason: lockSkipToken(lk.reason),
602
620
  createdAt: nowIso,
603
621
  failureCountAtRun: 0,
604
622
  });
605
623
  finishRun();
606
624
  return {
607
- status: 'skipped', direction: 'none', skipReason: 'mutation-locked', historyId,
625
+ status: 'skipped', direction: 'none', skipReason: lockSkipToken(lk.reason), historyId,
608
626
  consecutiveFailures: 0,
609
627
  };
610
628
  }
@@ -617,97 +635,21 @@ export class AutoSyncScheduler {
617
635
  await this.appendHistory(channel, {
618
636
  direction: 'both',
619
637
  status: 'skipped',
620
- skipReason: 'mutation-locked',
638
+ // acquire 本身抛错(锁目录 IO/权限):既不是「被占」也不是「残留」,如实报不可用。
639
+ skipReason: lockSkipToken('unavailable'),
621
640
  createdAt: nowIso,
622
641
  failureCountAtRun: 0,
623
642
  });
624
643
  finishRun();
625
- return { status: 'skipped', direction: 'none', skipReason: 'mutation-locked', historyId, consecutiveFailures: 0 };
644
+ return { status: 'skipped', direction: 'none', skipReason: lockSkipToken('unavailable'), historyId, consecutiveFailures: 0 };
626
645
  }
627
646
  }
628
-
629
647
  try {
630
- // 读该通道 sync-config:按通道判定「已配置」——git 看 git.repoUrl、webdav 看 webdav.url。
631
- // SEC-03:「未配置」有两种成因 —— 真的没配,或存过的地址被白名单拒掉(读侧丢弃)。
632
- // 必须区分:后者如果说成前者的「尚未配置」,用户会一遍遍重填同一个被拒地址。
633
- const configIssues: SyncConfigIssue[] = [];
634
- const syncCfg = await this.readSyncConfigFn(channel, configIssues);
635
- if (!syncIsConfigured(syncCfg)) {
636
- const configIssue = describeConfigIssue(configIssues, channel);
637
- if (configIssue !== undefined) this.reportConfigIssue(channel, configIssue);
638
- const result: AutosyncRunResult = {
639
- status: 'skipped', direction: 'none', skipReason: 'unconfigured', historyId,
640
- consecutiveFailures: 0,
641
- ...(configIssue === undefined ? {} : { configIssue }),
642
- };
643
- await this.appendHistory(channel, {
644
- direction: 'both',
645
- status: 'skipped',
646
- skipReason: 'unconfigured',
647
- createdAt: nowIso,
648
- failureCountAtRun: 0,
649
- ...(configIssue === undefined ? {} : { configIssue }),
650
- });
651
- await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
652
- return result;
653
- }
654
-
655
- const engine = this.makeSyncEngine(syncCfg!);
656
-
657
- // 加密快照检测:远端最新快照为加密 → 自动同步无密码无法解密 → 整体跳过,
658
- // 同步历史记录 skipReason='encrypted'(提示需手动输入密码同步)。
659
- // 加密快照只通过手动推送/拉取产生与消费;自动同步仅处理普通快照。
660
- // list 失败宽容处理:视为无加密快照,继续正常流程(网络问题由后续链路暴露为 failed)。
661
- let encryptedRemote = false;
662
- // 本轮远端列表:加密快照检查与「远端是否有新快照」共用同一次 list。
663
- // 每次 list 都是一次真实网络往返(git = `pull --ff-only`,webdav = PROPFIND/GET),
664
- // 缺省 60s 轮询下多 list 一次 = 一天白跑 1440 次往返。
665
- let remoteMetas: readonly SyncSnapshotMeta[] | null = null;
666
- try {
667
- const metas = await engine.listSnapshots();
668
- remoteMetas = metas;
669
- const latestMeta = metas.length > 0 ? metas[metas.length - 1]! : null;
670
- encryptedRemote = latestMeta !== null && latestMeta.manifest.encrypted === true;
671
- } catch {
672
- encryptedRemote = false;
673
- }
674
- if (encryptedRemote) {
675
- const result: AutosyncRunResult = {
676
- status: 'skipped', direction: 'pull', skipReason: 'encrypted', historyId,
677
- consecutiveFailures: 0,
678
- };
679
- await this.appendHistory(channel, {
680
- direction: 'pull', status: 'skipped', skipReason: 'encrypted',
681
- createdAt: nowIso, failureCountAtRun: 0,
682
- });
683
- await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
684
- return result;
685
- }
686
-
687
- // 事件驱动触发(§3.1/§3.2/§3.3 看变化不看时间):
688
- // - remoteNew:远端是否出现比本地祖先更新的快照 → 决定是否做下载合并(Phase A);
689
- // - localDirty:本地 portable 配置相对基线是否真的变了 → 决定是否上传(Phase C)。
690
- // 定时器只是兜底轮询;真正驱动是这两个「变化」信号。
691
- // 列表拿不到(网络失败)时 remoteMetas 为 null → 检测自己再 list 一次,行为与改造前一致
692
- const remoteNew = await this.detectRemoteNew(engine, remoteMetas ?? undefined);
693
- const localDirty = await this.detectLocalChange(engine);
694
- // SYN-05:首轮(从未跑过)与「远端有新快照」是覆盖风险最高的两个时刻 —— 由
695
- // resolveConflictPushPolicy 统一把这两处的 ask 标成 forced。
696
- const firstRun = cfg.lastRunAt === undefined || cfg.lastRunAt === '';
697
-
698
- // 两端都无变化 → 什么都不做,记为 upToDate(不重复拉取/不空转)。
699
- if (!remoteNew && !localDirty) {
700
- const result: AutosyncRunResult = {
701
- status: 'success', direction: 'none', skipReason: 'upToDate', historyId,
702
- consecutiveFailures: 0,
703
- };
704
- await this.appendHistory(channel, {
705
- direction: 'both', status: 'success', skipReason: 'upToDate',
706
- createdAt: nowIso, failureCountAtRun: 0,
707
- });
708
- await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
709
- return result;
710
- }
648
+ // 锁内重跑一次检测:预检到写入之间可能被别的进程推进(远端新快照 / 本机配置改动),
649
+ // 拿过期结论去写等于覆盖别人的成果。无锁环境(测试)直接用预检结果 —— 同一份数据,没有竞态。
650
+ const phase = releaseLock === null ? preflight : await this.detectPhase(channel, cfg, nowIso, historyId);
651
+ if (phase.kind === 'skip') return phase.result;
652
+ const { engine, remoteNew, localDirty, firstRun } = phase;
711
653
 
712
654
  let appliedSections: SectionId[] = [];
713
655
  // audit-sync sync-F5:被风险分级扣下、需人工确认的分区(medium/high)。在 Phase A 赋值、
@@ -992,6 +934,104 @@ export class AutoSyncScheduler {
992
934
  * 现在:失败写错误原文;跳过写**结构化原因码**(界面按码取字典,语言在渲染那刻解析);
993
935
  * 成功清空两者(空串/undefined 不进文件,见 autosync-config.toChannelPayload)。
994
936
  */
937
+ /**
938
+ * Phase 1:只读预检 —— 读该通道配置、列远端快照、判断「远端有新 / 本地有改动」。
939
+ *
940
+ * 为什么不持锁:这些步骤全是只读,但 plugins 分区的导出会为本机源(link: / file:)插件跑 npm pack
941
+ * (真机实测 210MB 插件 44.7s/次、每轮重算)。放进 GLOBAL mutation 锁内,60s 一轮的轮询就让锁几乎
942
+ * 全程被占,用户任何 destructive 操作都撞 423(2026-11-07 真机事故的根因)。
943
+ * 结论**不具权威性**:调用方取到锁之后必须重跑一次(见 runOnceInternal 的 Phase 2)。
944
+ */
945
+ private async detectPhase(
946
+ channel: SyncTransportType,
947
+ cfg: AutosyncConfig,
948
+ nowIso: string,
949
+ historyId: string,
950
+ ): Promise<AutosyncDetectOutcome> {
951
+ // 读该通道 sync-config:按通道判定「已配置」——git 看 git.repoUrl、webdav 看 webdav.url。
952
+ // SEC-03:「未配置」有两种成因 —— 真的没配,或存过的地址被白名单拒掉(读侧丢弃)。
953
+ // 必须区分:后者如果说成前者的「尚未配置」,用户会一遍遍重填同一个被拒地址。
954
+ const configIssues: SyncConfigIssue[] = [];
955
+ const syncCfg = await this.readSyncConfigFn(channel, configIssues);
956
+ if (!syncIsConfigured(syncCfg)) {
957
+ const configIssue = describeConfigIssue(configIssues, channel);
958
+ if (configIssue !== undefined) this.reportConfigIssue(channel, configIssue);
959
+ const result: AutosyncRunResult = {
960
+ status: 'skipped', direction: 'none', skipReason: 'unconfigured', historyId,
961
+ consecutiveFailures: 0,
962
+ ...(configIssue === undefined ? {} : { configIssue }),
963
+ };
964
+ await this.appendHistory(channel, {
965
+ direction: 'both',
966
+ status: 'skipped',
967
+ skipReason: 'unconfigured',
968
+ createdAt: nowIso,
969
+ failureCountAtRun: 0,
970
+ ...(configIssue === undefined ? {} : { configIssue }),
971
+ });
972
+ await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
973
+ return { kind: 'skip', result };
974
+ }
975
+
976
+ const engine = this.makeSyncEngine(syncCfg!);
977
+
978
+ // 加密快照检测:远端最新快照为加密 → 自动同步无密码无法解密 → 整体跳过,
979
+ // 同步历史记录 skipReason='encrypted'(提示需手动输入密码同步)。
980
+ // 加密快照只通过手动推送/拉取产生与消费;自动同步仅处理普通快照。
981
+ // list 失败宽容处理:视为无加密快照,继续正常流程(网络问题由后续链路暴露为 failed)。
982
+ let encryptedRemote = false;
983
+ // 本轮远端列表:加密快照检查与「远端是否有新快照」共用同一次 list。
984
+ // 每次 list 都是一次真实网络往返(git = `pull --ff-only`,webdav = PROPFIND/GET),
985
+ // 缺省 60s 轮询下多 list 一次 = 一天白跑 1440 次往返。
986
+ let remoteMetas: readonly SyncSnapshotMeta[] | null = null;
987
+ try {
988
+ const metas = await engine.listSnapshots();
989
+ remoteMetas = metas;
990
+ const latestMeta = metas.length > 0 ? metas[metas.length - 1]! : null;
991
+ encryptedRemote = latestMeta !== null && latestMeta.manifest.encrypted === true;
992
+ } catch {
993
+ encryptedRemote = false;
994
+ }
995
+ if (encryptedRemote) {
996
+ const result: AutosyncRunResult = {
997
+ status: 'skipped', direction: 'pull', skipReason: 'encrypted', historyId,
998
+ consecutiveFailures: 0,
999
+ };
1000
+ await this.appendHistory(channel, {
1001
+ direction: 'pull', status: 'skipped', skipReason: 'encrypted',
1002
+ createdAt: nowIso, failureCountAtRun: 0,
1003
+ });
1004
+ await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
1005
+ return { kind: 'skip', result };
1006
+ }
1007
+
1008
+ // 事件驱动触发(§3.1/§3.2/§3.3 看变化不看时间):
1009
+ // - remoteNew:远端是否出现比本地祖先更新的快照 → 决定是否做下载合并(Phase A);
1010
+ // - localDirty:本地 portable 配置相对基线是否真的变了 → 决定是否上传(Phase C)。
1011
+ // 定时器只是兜底轮询;真正驱动是这两个「变化」信号。
1012
+ // 列表拿不到(网络失败)时 remoteMetas 为 null → 检测自己再 list 一次,行为与改造前一致
1013
+ const remoteNew = await this.detectRemoteNew(engine, remoteMetas ?? undefined);
1014
+ const localDirty = await this.detectLocalChange(engine);
1015
+ // SYN-05:首轮(从未跑过)与「远端有新快照」是覆盖风险最高的两个时刻 —— 由
1016
+ // resolveConflictPushPolicy 统一把这两处的 ask 标成 forced。
1017
+ const firstRun = cfg.lastRunAt === undefined || cfg.lastRunAt === '';
1018
+
1019
+ // 两端都无变化 → 什么都不做,记为 upToDate(不重复拉取/不空转)。
1020
+ if (!remoteNew && !localDirty) {
1021
+ const result: AutosyncRunResult = {
1022
+ status: 'success', direction: 'none', skipReason: 'upToDate', historyId,
1023
+ consecutiveFailures: 0,
1024
+ };
1025
+ await this.appendHistory(channel, {
1026
+ direction: 'both', status: 'success', skipReason: 'upToDate',
1027
+ createdAt: nowIso, failureCountAtRun: 0,
1028
+ });
1029
+ await this.writeFinalConfig(cfg, result, nowIso, historyId, channel);
1030
+ return { kind: 'skip', result };
1031
+ }
1032
+ return { kind: 'work', engine, remoteNew, localDirty, firstRun };
1033
+ }
1034
+
995
1035
  private async writeFinalConfig(
996
1036
  base: AutosyncConfig,
997
1037
  result: AutosyncRunResult,
@@ -596,7 +596,9 @@ test('issue #31:残留锁挡住定时备份 → 日志按分类给出 stale
596
596
  const { scheduler } = staleLockScheduler({ cfg, tmp, logSink: (level, message) => { lines.push({ level, message }); } });
597
597
  const result = await scheduler.runOnce();
598
598
  assert.equal(result.status, 'skipped');
599
- assert.equal(result.skipReason, 'mutation-locked');
599
+ // 分档(lockSkipToken):残留锁必须发自己的 token —— 客户端据此给「去事故恢复回收」而不是
600
+ // 「另一个任务正在使用环境锁,稍后重试」(后者对残留锁是错的指引,重试/重启都不会自愈)。
601
+ assert.equal(result.skipReason, 'mutation-lock-stale');
600
602
  assert.equal(result.consecutiveFailures, 0, '被锁挡下不计入连续失败');
601
603
  const staleLine = lines.find((l) => l.message.includes('定时备份跳过'));
602
604
  assert.ok(staleLine !== undefined, `应有跳过日志: ${JSON.stringify(lines)}`);
@@ -675,9 +677,14 @@ test('M1 源码守卫:index.ts 给 BackupScheduler 注入与 makeRoutes/regist
675
677
  const routesStart = source.indexOf('makeRoutes({');
676
678
  const routesBody = source.slice(routesStart, source.indexOf('\n })', routesStart));
677
679
  assert.ok(routesBody.includes(`scanner: ${name},`), `makeRoutes 必须注入同一 scanner(scanner: ${name},)`);
678
- const toolsStart = source.indexOf('registerModelTools(ctx, {');
679
- const toolsBody = source.slice(toolsStart, source.indexOf('\n })', toolsStart));
680
- assert.ok(toolsBody.includes(`scanner: ${name},`), `registerModelTools 必须注入同一 scanner(scanner: ${name},)`);
680
+ // 装配已下沉:index.ts 的 agentToolDeps 取 RoutesDeps 的同一实例,
681
+ // routes/model-tools-deps.ts 再把它交给 ModelToolsDeps.scanner。
682
+ const toolsStart = source.indexOf('agentToolDeps: createAgentToolDeps({');
683
+ assert.ok(toolsStart > 0, '应能找到 agentToolDeps 装配');
684
+ const toolsBody = source.slice(toolsStart, source.indexOf('\n }),', toolsStart));
685
+ assert.ok(toolsBody.includes('scanner: deps.scanner'), 'agentToolDeps 必须注入同一 scanner(scanner: deps.scanner)');
686
+ const wiring = (await fs.readFile(new URL('../routes/model-tools-deps.ts', import.meta.url), 'utf8')).replace(/\r\n/g, '\n');
687
+ assert.ok(wiring.includes('scanner: input.scanner'), 'model-tools-deps.ts 必须把 input.scanner 交给 ModelToolsDeps(注入了却没接上会静默退回默认扫描器)');
681
688
  });
682
689
 
683
690
  /**
@@ -30,7 +30,7 @@ import type { RunRegistry } from '../core/run-registry.ts';
30
30
  import type { ConfigAdapter, HostContext, SecretScanner } from '../core/types.ts';
31
31
  import type { MutationLockPort } from '../utils/env-lock.ts';
32
32
  import type { LockBlockReason } from '../utils/env-lock.ts';
33
- import { runWithMutationLock, EnvironmentLockUnavailableError, LOCK_BLOCK_MESSAGE, LOCK_BLOCK_BRIEF } from '../utils/env-lock.ts';
33
+ import { runWithMutationLock, EnvironmentLockUnavailableError, LOCK_BLOCK_MESSAGE, LOCK_BLOCK_BRIEF, lockSkipToken } from '../utils/env-lock.ts';
34
34
  import { Exporter } from '../core/exporter.ts';
35
35
  import { randomBytes } from 'node:crypto';
36
36
  import { join } from 'node:path';
@@ -341,12 +341,13 @@ export class BackupScheduler {
341
341
  // (LOCK_BLOCK_MESSAGE),避免同一句指引在多条路径上再次漂移(#27 只接了 autosync,
342
342
  // 本路径漏接 → 实测 9 天内 57 次静默跳过,用户无从知道要回收残留锁)。
343
343
  if (err instanceof EnvironmentLockUnavailableError) {
344
- if (err.reason === 'stale') {
345
- this.log.warn(`${trigger}跳过:${LOCK_BLOCK_MESSAGE.stale}`);
344
+ // stale 与 stale-degraded 同属「重试不会自愈」,都走 warn(都带显式回收指引)。
345
+ if (err.reason === 'stale' || err.reason === 'stale-degraded') {
346
+ this.log.warn(`${trigger}跳过:${LOCK_BLOCK_MESSAGE[err.reason]}`);
346
347
  } else {
347
348
  this.log.info(`${trigger}跳过:${LOCK_BLOCK_MESSAGE[err.reason]}`);
348
349
  }
349
- const skipped: BackupRunResult = { status: 'skipped', skipReason: 'mutation-locked', consecutiveFailures: cfg.consecutiveFailures };
350
+ const skipped: BackupRunResult = { status: 'skipped', skipReason: lockSkipToken(err.reason), consecutiveFailures: cfg.consecutiveFailures };
350
351
  // skipReason 保持稳定的机器 token(客户端据此本地化);历史摘要用同源**短**文案,
351
352
  // 不留裸 token(issue #31 ②:中文前缀 + 英文 token 的历史行)。
352
353
  await this.appendHistory(skipped, err.reason, manual);
@@ -9,13 +9,13 @@
9
9
  * (`<section>.blobs.json` / WebDAV 的 JSON 载荷里的 blobRefs)。内容没变 = 同一个哈希 =
10
10
  * 已在仓里 = 不再传输。快照保留策略裁剪快照时,无人引用的 blob 由 GC 回收。
11
11
  *
12
- * 兼容性(**这是对外格式变更**,必须同步 docs/spec):
12
+ * 兼容性(**这是对外格式变更**,必须同步 docs/contracts/):
13
13
  * - 外置只发生在**通道侧**:只有 transport 传了 BlobSink 才启用;引擎/导出/导入看到的
14
14
  * 仍是普通 FilesSection(含 data)。本地散文件副本、加密快照、加密载荷一律不外置。
15
15
  * - 旧版插件读新格式:`<section>.blobs.json` 不是 FilesSection,旧版 layout 会当成
16
16
  * 「文件分区目录缺失」—— git 通道 missingFileDir='empty' 会降级为空分区(丢内容但不崩),
17
17
  * WebDAV 通道 blobRefs 也认不出。因此 /sync/status 不下发版本协商,**跨版本混用不被支持**:
18
- * 两端插件版本应当一致(与既有「同步通道不做协议协商」的定位一致,见 docs/spec)。
18
+ * 两端插件版本应当一致(与既有「同步通道不做协议协商」的定位一致,见 docs/contracts/)。
19
19
  */
20
20
  import type { FilesSection, SectionId } from '../schema/types.ts';
21
21
  import { sha256Hex } from '../utils/hashing.ts';