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
@@ -709,18 +709,126 @@ test('#146(follow-up):引擎回 skipped:all-conflicted → 台账不得记
709
709
  assert.equal(skipped.status, 'skipped', '一个分区都没上行 = 成功但跳过(不是 failed,也不是 success)');
710
710
  assert.equal(skipped.skipReason, 'all-conflicted');
711
711
  });
712
- test('runOnce: startup 变体 → 只做 pull 合并,不上传', async () => {
712
+ test('runOnce: startup 变体(本地无改动)→ 只做 pull 合并,不上传', async () => {
713
713
  const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
714
714
  const pushCalls: string[] = [];
715
715
  const engine = {
716
+ hasLocalChanges: async () => false,
716
717
  merge: async (): Promise<MergePlan> => makeMergePlan([['settings', 'useRemote']]),
717
718
  applyMergePlan: async () => ({ ok: true, applied: ['settings'], restoreId: 'r1', rolledBack: false, review: [], warnings: [] }),
718
719
  push: async () => { pushCalls.push('push'); return { ok: true, snapshotId: 'x', sections: [] as never, warnings: [] }; },
719
720
  };
720
721
  const { scheduler } = makeScheduler({ cfg, engine, history: [] });
721
722
  const result = await scheduler.runOnce('git', { startup: true });
722
- assert.equal(result.direction, 'pull', 'startup 不上传');
723
- assert.equal(pushCalls.length, 0, 'startup 变体不调用 push');
723
+ assert.equal(result.direction, 'pull', '本地无改动时不上传');
724
+ assert.equal(pushCalls.length, 0, '本地无改动不调用 push');
725
+ });
726
+
727
+ test('Group B(a): remote-poll upToDate 只刷 lastRunAt 不刷 lastSuccessAt;重启仍跑启动轮', async () => {
728
+ const MIN = 60_000;
729
+ let nowMs = Date.parse('2026-11-18T12:00:00.000Z');
730
+ let gitCfg: AutosyncConfig = {
731
+ enabled: true, interval: '30m', startupMinIntervalMs: 5 * MIN, consecutiveFailures: 0, realtime: false,
732
+ lastSuccessAt: new Date(nowMs - 10 * MIN).toISOString(),
733
+ };
734
+ let mergeCount = 0;
735
+ const engine = {
736
+ hasNewRemoteSnapshot: async () => false,
737
+ hasLocalChanges: async () => false,
738
+ merge: async (): Promise<MergePlan> => { mergeCount += 1; return makeMergePlan([]); },
739
+ };
740
+ const s1 = new AutoSyncScheduler({
741
+ syncDir: '/tmp/b-a1',
742
+ host: { log: nullLogger() },
743
+ makeSyncEngine: () => engine as unknown as SyncEngine,
744
+ msg: (k: string) => k,
745
+ runs: new RunRegistry(),
746
+ now: () => new Date(nowMs),
747
+ readConfig: async (ch) => (ch === 'git' ? gitCfg : { enabled: false, interval: '30m', startupMinIntervalMs: 5 * MIN, consecutiveFailures: 0, realtime: false }),
748
+ writeConfig: async (ch, c) => { if (ch === 'git') gitCfg = c; },
749
+ readSyncConfigFn: async () => ({ schemaVersion: 2, transport: 'git', git: { repoUrl: 'git@github.com:foo/bar.git' } }),
750
+ readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: [], updatedAt: '' }),
751
+ appendHistoryFn: async () => {},
752
+ });
753
+ const emptyPoll = await s1.runOnce('git', { reason: 'remote-poll' });
754
+ assert.equal(emptyPoll.skipReason, 'upToDate');
755
+ assert.equal(gitCfg.lastRunAt, new Date(nowMs).toISOString(), 'lastRunAt 必须记录上次检查时间');
756
+ assert.equal(gitCfg.lastSuccessAt, new Date(nowMs - 10 * MIN).toISOString(), 'upToDate 空轮不得刷新 lastSuccessAt');
757
+
758
+ // 1 分钟后重启宿主(远低于 5 分钟 startupMinIntervalMs,但距 lastSuccessAt 已超 11 分钟)
759
+ nowMs += 60_000;
760
+ let startupRan = false;
761
+ const s2 = new AutoSyncScheduler({
762
+ syncDir: '/tmp/b-a2',
763
+ host: { log: nullLogger() },
764
+ makeSyncEngine: () => ({
765
+ hasNewRemoteSnapshot: async () => { startupRan = true; return false; },
766
+ hasLocalChanges: async () => false,
767
+ merge: async (): Promise<MergePlan> => { mergeCount += 1; return makeMergePlan([]); },
768
+ }) as unknown as SyncEngine,
769
+ msg: (k: string) => k,
770
+ runs: new RunRegistry(),
771
+ now: () => new Date(nowMs),
772
+ readConfig: async (ch) => (ch === 'git' ? gitCfg : { enabled: false, interval: '30m', startupMinIntervalMs: 5 * MIN, consecutiveFailures: 0, realtime: false }),
773
+ writeConfig: async (ch, c) => { if (ch === 'git') gitCfg = c; },
774
+ readSyncConfigFn: async () => ({ schemaVersion: 2, transport: 'git', git: { repoUrl: 'git@github.com:foo/bar.git' } }),
775
+ readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: [], updatedAt: '' }),
776
+ appendHistoryFn: async () => {},
777
+ setTimer: () => 0 as unknown as ReturnType<typeof setTimeout>,
778
+ clearTimer: () => {},
779
+ });
780
+ s2.start();
781
+ await new Promise((r) => setTimeout(r, 20));
782
+ s2.stop();
783
+ assert.equal(startupRan, true, '空轮后 1 分钟重启必须仍执行启动检查(按 lastSuccessAt 节流)');
784
+ assert.equal(mergeCount, 0);
785
+ });
786
+
787
+ test('Group B(b): 启动轮 localDirty 时真的 push,且遇冲突仍受 SYN-05 降级 ask(绝不隐式 force)', async () => {
788
+ // 1) 无冲突:启动轮应合并远端后立即上行离线本地改动,并刷新 lastSuccessAt
789
+ const cfgClean: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
790
+ const pushCalls1: Array<{ force?: boolean } | undefined> = [];
791
+ const engine1 = {
792
+ hasNewRemoteSnapshot: async () => true,
793
+ hasLocalChanges: async () => true,
794
+ merge: async (): Promise<MergePlan> => makeMergePlan([['settings', 'useRemote']]),
795
+ applyMergePlan: async () => ({ ok: true, applied: ['settings'] as never, restoreId: 'r1', rolledBack: false, review: [], warnings: [] }),
796
+ push: async (opts?: { force?: boolean }) => {
797
+ pushCalls1.push(opts);
798
+ return { ok: true, snapshotId: 'snap-startup-up', sections: ['settings', 'skills'] as never, warnings: [] };
799
+ },
800
+ };
801
+ const h1 = makeScheduler({ cfg: cfgClean, engine: engine1, history: [] });
802
+ const r1 = await h1.scheduler.runOnce('git', { startup: true, reason: 'startup' });
803
+ assert.equal(r1.status, 'success');
804
+ assert.equal(r1.direction, 'both');
805
+ assert.equal(r1.pushedSnapshotId, 'snap-startup-up');
806
+ assert.equal(pushCalls1.length, 1, '启动轮离线改动必须触发 push');
807
+ assert.equal(pushCalls1[0]?.force, undefined, '绝不隐式 force');
808
+ assert.ok(h1.getConfig().lastSuccessAt, '真实同步成功后必须记录 lastSuccessAt');
809
+
810
+ // 2) 冲突 + 显式 local:启动轮仍强制降级 ask(SYN-05 forcedAsk)
811
+ const cfgLocal: AutosyncConfig = {
812
+ enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0,
813
+ conflictPolicy: 'local', lastSuccessAt: '2026-11-01T10:00:00.000Z',
814
+ };
815
+ const pushCalls2: Array<{ force?: boolean } | undefined> = [];
816
+ const engine2 = {
817
+ hasNewRemoteSnapshot: async () => true,
818
+ hasLocalChanges: async () => true,
819
+ merge: async (): Promise<MergePlan> => makeMergePlan([['settings', 'conflict']]),
820
+ push: async (opts?: { force?: boolean }) => {
821
+ pushCalls2.push(opts);
822
+ return { ok: false, snapshotId: '', sections: [] as never, warnings: [], conflict: true, message: '远端已推进' };
823
+ },
824
+ };
825
+ const h2 = makeScheduler({ cfg: cfgLocal, engine: engine2, history: [] });
826
+ const r2 = await h2.scheduler.runOnce('git', { startup: true, reason: 'startup' });
827
+ assert.equal(pushCalls2.length, 1);
828
+ assert.equal(pushCalls2[0]?.force, undefined, '启动轮遇冲突+remoteNew 时绝不绕过 SYN-05');
829
+ assert.equal(r2.forced, true, '必须记录 forced=true');
830
+ assert.equal(r2.skipReason, 'conflict');
831
+ assert.equal(h2.getConfig().lastSuccessAt, '2026-11-01T10:00:00.000Z', '冲突跳过不得刷新 lastSuccessAt');
724
832
  });
725
833
 
726
834
  test('runOnce: 连续两次执行不再 skip(conflict)(run 完成收尾)', async () => {
@@ -1046,7 +1154,9 @@ test('双通道:git/webdav 同时 enabled → 各自独立排期;runOnce 写
1046
1154
  const result = await scheduler.runOnce('webdav');
1047
1155
  assert.equal(result.status, 'success', 'webdav 通道照常执行');
1048
1156
  assert.deepEqual(configs.git, gitBefore, 'git 通道配置未被 webdav 运行改变');
1049
- assert.equal(configs.webdav.lastRunStatus, 'success', 'webdav 通道写入自己的运行状态');
1157
+ assert.equal(configs.webdav.lastCheckStatus, 'upToDate', 'webdav 通道记录本次检查状态为 upToDate');
1158
+ assert.ok(configs.webdav.lastRunAt, 'webdav 通道写入自己的检查时间');
1159
+ assert.equal(configs.webdav.lastRunStatus, undefined, 'upToDate 空轮不得写入真实同步结论');
1050
1160
  });
1051
1161
  test('审计 P5-2:一条通道到点只重排它自己,不得连带清掉另一条通道的定时器', async () => {
1052
1162
  const configs = {} as Record<SyncTransportType, AutosyncConfig>;
@@ -1892,4 +2002,427 @@ test('P2 反向控制:干净的成功轮不写待裁决(不能凭空挂一
1892
2002
  assert.deepEqual(recorded, []);
1893
2003
  });
1894
2004
 
2005
+ test('Group C(a): autoApplyTier=low 纯下行扣下中风险分区 → pendingMerge 落盘 + partial(conflict) + 历史 conflictedSections 含该分区', async () => {
2006
+ const cfg: AutosyncConfig = {
2007
+ enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0,
2008
+ autoApplyTier: 'low',
2009
+ };
2010
+ const recorded: string[][] = [];
2011
+ const applied: string[][] = [];
2012
+ const engine = {
2013
+ hasNewRemoteSnapshot: async () => true,
2014
+ hasLocalChanges: async () => false,
2015
+ merge: async (): Promise<MergePlan> => makeMergePlan([['settings', 'useRemote'], ['plugins', 'useRemote']]),
2016
+ applyMergePlan: async (plan: { autoApply: MergeSectionResult[] }) => {
2017
+ const ids = plan.autoApply.map((s) => s.id);
2018
+ applied.push(ids);
2019
+ return { ok: true, applied: ids, restoreId: 'r1', rolledBack: false, review: [], warnings: [] };
2020
+ },
2021
+ push: async () => { throw new Error('纯下行轮不应 push'); },
2022
+ recordPendingMerge: async (sections: readonly string[]) => { recorded.push([...sections]); return null; },
2023
+ };
2024
+ const { scheduler, getEntries } = makeScheduler({ cfg, engine: engine as unknown as SyncEngine, history: [] });
2025
+ const result = await scheduler.runOnce('git');
2026
+ assert.deepEqual(applied, [['settings']]);
2027
+ assert.equal(result.status, 'partial', 'deferredSections 非空时纯下行轮绝不能报 success');
2028
+ assert.equal(result.skipReason, 'conflict');
2029
+ assert.deepEqual(result.conflictedSections, ['plugins']);
2030
+ assert.deepEqual(recorded, [['plugins']], '纯下行扣下的 deferredSections 必须写入 pendingMerge');
2031
+ const hist = getEntries().find((e) => e.status === 'partial');
2032
+ assert.deepEqual(hist?.conflictedSections, ['plugins']);
2033
+ assert.equal(hist?.skipReason, 'conflict');
2034
+ });
2035
+
2036
+ test('Group C(b): 启动轮纯下行扣下叶级冲突(heldLeafSections)→ pendingMerge 必有记录', async () => {
2037
+ const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
2038
+ const recorded: string[][] = [];
2039
+ const engine = {
2040
+ hasNewRemoteSnapshot: async () => true,
2041
+ hasLocalChanges: async () => false,
2042
+ merge: async (): Promise<MergePlan> => makeMergePlan([['settings', 'useRemote'], ['plugins', 'useRemote']]),
2043
+ applyMergePlan: async () => ({
2044
+ ok: true,
2045
+ applied: ['settings'] as never,
2046
+ restoreId: 'r1',
2047
+ rolledBack: false,
2048
+ review: [{ id: 'patch:line-a', sectionId: 'plugins' as never, kind: 'key' as const, description: '叶级冲突' }],
2049
+ warnings: ['有 1 个叶级冲突未裁决(分区:plugins)'],
2050
+ }),
2051
+ recordPendingMerge: async (sections: readonly string[]) => { recorded.push([...sections]); return null; },
2052
+ };
2053
+ const { scheduler } = makeScheduler({ cfg, engine: engine as unknown as SyncEngine, history: [] });
2054
+ const result = await scheduler.runOnce('git', { startup: true, reason: 'startup' });
2055
+ assert.equal(result.status, 'partial');
2056
+ assert.equal(result.skipReason, 'conflict');
2057
+ assert.deepEqual(recorded, [['plugins']], '启动轮扣下的叶级冲突必须进 pendingMerge');
2058
+ });
2059
+
2060
+ test('Group D(P0-2):upToDate 空轮不洗白 failed 状态与连续失败计数;3 连败告警照常触发;真实成功后才清零', async () => {
2061
+ let nowMs = Date.parse('2026-11-18T10:00:00.000Z');
2062
+ const warnings: string[] = [];
2063
+ let shouldFail = true;
2064
+ let dirty = true;
2065
+ const cfg: AutosyncConfig = {
2066
+ enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0, realtime: true,
2067
+ };
2068
+ let saved = cfg;
2069
+ const engine = {
2070
+ hasNewRemoteSnapshot: async () => false,
2071
+ hasLocalChanges: async () => dirty,
2072
+ push: async () => {
2073
+ if (shouldFail) throw new Error('502 Bad Gateway');
2074
+ return { ok: true, snapshotId: 'snap-ok', sections: [] as never, warnings: [] };
2075
+ },
2076
+ };
2077
+ const logger = {
2078
+ level: 'info' as const,
2079
+ debug: () => {},
2080
+ info: () => {},
2081
+ warn: (m: string) => { warnings.push(m); },
2082
+ error: () => {},
2083
+ };
2084
+ const scheduler = new AutoSyncScheduler({
2085
+ syncDir: '/tmp',
2086
+ host: { log: logger },
2087
+ makeSyncEngine: () => engine as unknown as SyncEngine,
2088
+ msg: (k: string) => k,
2089
+ runs: new RunRegistry(),
2090
+ now: () => new Date(nowMs),
2091
+ readConfig: async () => saved,
2092
+ writeConfig: async (_ch, c) => { saved = c; },
2093
+ readSyncConfigFn: async () => ({ schemaVersion: 2, transport: 'git', git: { repoUrl: 'git@github.com:foo/bar.git' } }),
2094
+ readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: [], updatedAt: '' }),
2095
+ appendHistoryFn: async () => {},
2096
+ });
2097
+
2098
+ // 第 1 次真实失败(T0)
2099
+ const r1 = await scheduler.runOnce('git', { reason: 'local-change' });
2100
+ assert.equal(r1.status, 'failed');
2101
+ assert.equal(saved.lastRunStatus, 'failed');
2102
+ assert.equal(saved.consecutiveFailures, 1);
2103
+ assert.equal(saved.lastRunMessage, '502 Bad Gateway');
2104
+ assert.equal(saved.lastSyncAt, '2026-11-18T10:00:00.000Z');
2105
+
2106
+ // 第 1 次 remote-poll 空轮(T0 + 5m):localCheck=false → upToDate
2107
+ nowMs += 5 * 60_000;
2108
+ const poll1 = await scheduler.runOnce('git', { reason: 'remote-poll' });
2109
+ assert.equal(poll1.skipReason, 'upToDate');
2110
+ assert.equal(poll1.consecutiveFailures, 1);
2111
+ assert.equal(saved.lastRunAt, '2026-11-18T10:05:00.000Z', '检查时间刷新');
2112
+ assert.equal(saved.lastCheckStatus, 'upToDate');
2113
+ assert.equal(saved.lastSyncAt, '2026-11-18T10:00:00.000Z', '真实结论时间保持失败那一刻');
2114
+ assert.equal(saved.lastRunStatus, 'failed', 'upToDate 空轮不得洗白 failed');
2115
+ assert.equal(saved.lastRunMessage, '502 Bad Gateway', '错误原文必须保留');
2116
+ assert.equal(saved.consecutiveFailures, 1, '连续失败计数不得归零');
2117
+
2118
+ // 第 2 次失败(T0 + 10m)+ 第 2 次 remote-poll(T0 + 15m)
2119
+ nowMs += 5 * 60_000;
2120
+ await scheduler.runOnce('git', { reason: 'local-change' });
2121
+ assert.equal(saved.consecutiveFailures, 2);
2122
+ nowMs += 5 * 60_000;
2123
+ await scheduler.runOnce('git', { reason: 'remote-poll' });
2124
+ assert.equal(saved.consecutiveFailures, 2);
2125
+ assert.equal(saved.lastRunStatus, 'failed');
2126
+ assert.equal(warnings.length, 0, '2 连败尚未达告警阈值');
2127
+
2128
+ // 第 3 次失败(T0 + 20m)→ 跨过空轮后仍顺利累计到 3 并触发告警
2129
+ nowMs += 5 * 60_000;
2130
+ await scheduler.runOnce('git', { reason: 'local-change' });
2131
+ assert.equal(saved.consecutiveFailures, 3);
2132
+ assert.ok(warnings.some((w) => w.includes('连续失败 3 次')), '跨空轮 3 连败必须触发告警: ' + JSON.stringify(warnings));
2133
+
2134
+ // 第 4 次:网络恢复且真实 push 成功(T0 + 25m)→ 清零失败计数、恢复 success
2135
+ nowMs += 5 * 60_000;
2136
+ shouldFail = false;
2137
+ dirty = true;
2138
+ const okRun = await scheduler.runOnce('git', { reason: 'local-change' });
2139
+ assert.equal(okRun.status, 'success');
2140
+ assert.equal(okRun.consecutiveFailures, 0);
2141
+ assert.equal(saved.lastRunStatus, 'success');
2142
+ assert.equal(saved.consecutiveFailures, 0);
2143
+ assert.equal(saved.lastRunMessage, '');
2144
+ assert.equal(saved.lastSyncAt, '2026-11-18T10:25:00.000Z');
2145
+ assert.equal(saved.lastSuccessAt, '2026-11-18T10:25:00.000Z');
2146
+ });
2147
+
2148
+ test('I 项:单轮自动同步(远端有新快照 + 本地有改动)复用本地导出,未改动分区最多 export 一次且写盘分区按需失效', async () => {
2149
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-autosync-round-cache-'));
2150
+ try {
2151
+ const devA = makeContext('win32', 'C:\\Users\\alice');
2152
+ devA.settings.ns.set('general', { value: { theme: 'light' }, revision: 1, secrets: [] });
2153
+ await devA.fs.writeFile('AGENTS.md', new TextEncoder().encode('# base rules\n'));
2154
+ // devB 初始注册同 namespace(供 settings importer 写入)但取不同值,拉取 initPlan 后建立同一祖先基线
2155
+ const devB = makeContext('win32', 'C:\\Users\\alice');
2156
+ devB.settings.ns.set('general', { value: { theme: 'init' }, revision: 0, secrets: [] });
2157
+
2158
+ const adaptersA = createAdapters({ namespaces: ['general'] });
2159
+ const adaptersB = createAdapters({ namespaces: ['general'] });
2160
+ const transport = new E2eTransport();
2161
+ const stateB = path.join(tmp, 'state-b');
2162
+ await fs.mkdir(stateB, { recursive: true });
2163
+
2164
+ const engineA = new SyncEngine({
2165
+ ctx: devA,
2166
+ transport,
2167
+ stateDir: path.join(tmp, 'state-a'),
2168
+ adapters: adaptersA,
2169
+ sections: ['settings', 'agentInstructions', 'plugins'],
2170
+ importer: new Importer({ ctx: devA, adapters: adaptersA, snapshotStore: new MemSnapshotStore() }),
2171
+ now: () => new Date('2026-11-18T12:00:00.000Z'),
2172
+ });
2173
+ await engineA.push({ force: true });
2174
+
2175
+ // 计数包装 adaptersB 各个 adapter.export(直接覆写实例属性,保留适配器类原型方法供 Importer 使用)
2176
+ const exportCounts = new Map<string, number>();
2177
+ for (const adapter of adaptersB) {
2178
+ const origExport = adapter.export.bind(adapter);
2179
+ adapter.export = async (...args: Parameters<typeof adapter.export>) => {
2180
+ exportCounts.set(adapter.id, (exportCounts.get(adapter.id) ?? 0) + 1);
2181
+ return origExport(...args);
2182
+ };
2183
+ }
2184
+
2185
+ const engineB = new SyncEngine({
2186
+ ctx: devB,
2187
+ transport,
2188
+ stateDir: stateB,
2189
+ localSnapshotsDir: path.join(tmp, 'local-snaps-b'),
2190
+ adapters: adaptersB,
2191
+ sections: ['settings', 'agentInstructions', 'plugins'],
2192
+ importer: new Importer({ ctx: devB, adapters: adaptersB, snapshotStore: new MemSnapshotStore() }),
2193
+ now: () => new Date('2026-11-18T12:05:00.000Z'),
2194
+ });
2195
+ // devB 先拉一次并以 useRemote 建好同一起点基线
2196
+ const initPlan = await engineB.merge();
2197
+ const initReport = await engineB.applyMergeResolutions(
2198
+ initPlan.sections
2199
+ .filter((s) => s.decision === 'conflict')
2200
+ .map((s) => ({ id: s.id, action: 'useRemote' as const })),
2201
+ );
2202
+ assert.equal(initReport.ok, true, 'initReport: ' + JSON.stringify(initReport));
2203
+ assert.deepEqual(initReport.pendingConflicts, [], 'init pending: ' + JSON.stringify(initReport));
2204
+
2205
+ // devA 改 settings 并推送远端新快照;devB 本机只改 agentInstructions;plugins 两端均未写 →
2206
+ // 触发「远端有新 + 本地有改」一轮完整双向同步
2207
+ devA.settings.ns.set('general', { value: { theme: 'dark' }, revision: 2, secrets: [] });
2208
+ await engineA.push({ force: true });
2209
+ await devB.fs.writeFile('AGENTS.md', new TextEncoder().encode('# local updated rules\n'));
2210
+
2211
+ exportCounts.clear();
2212
+ let cfg: AutosyncConfig = {
2213
+ enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0, realtime: true,
2214
+ };
2215
+ const scheduler = new AutoSyncScheduler({
2216
+ syncDir: stateB,
2217
+ host: { log: nullLogger() },
2218
+ makeSyncEngine: () => engineB,
2219
+ msg: (k: string) => k,
2220
+ runs: new RunRegistry(),
2221
+ now: () => new Date('2026-11-18T12:10:00.000Z'),
2222
+ readConfig: async (_channel: SyncTransportType) => cfg,
2223
+ writeConfig: async (_channel: SyncTransportType, next: AutosyncConfig) => { cfg = next; },
2224
+ readSyncConfigFn: async (_channel: SyncTransportType) =>
2225
+ ({ schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://example.com/repo.git' } }) as SyncConfig,
2226
+ readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: [], updatedAt: '' }),
2227
+ appendHistoryFn: async () => {},
2228
+ setTimer: () => 0 as unknown as ReturnType<typeof setTimeout>,
2229
+ clearTimer: () => {},
2230
+ minTriggerGapMs: 0,
2231
+ });
2232
+
2233
+ const res = await scheduler.runOnce('git', { reason: 'local-change' });
2234
+ assert.equal(res.direction, 'both', 'unexpected direction: ' + JSON.stringify(res));
2235
+ assert.ok(Boolean(res.pushedSnapshotId), '本地改动必须推上远端: ' + JSON.stringify(res));
2236
+ assert.equal((devB.settings.ns.get('general')?.value as { theme?: string } | undefined)?.theme, 'dark', '远端 settings 改动必须正常写盘');
2237
+ assert.equal(
2238
+ exportCounts.get('plugins'),
2239
+ 1,
2240
+ `未被 applyMergePlan 写入的 plugins 整轮(hasLocalChanges + merge + push)只允许 export 1 次,实测=${exportCounts.get('plugins')}`,
2241
+ );
2242
+ assert.equal(
2243
+ exportCounts.get('settings'),
2244
+ 3,
2245
+ `被 applyMergePlan 写入的 settings 仅在写入前 1 次 + exportAppliedSections 1 次 + 失效后 push 1 次,实测=${exportCounts.get('settings')}`,
2246
+ );
2247
+ } finally {
2248
+ await fs.rm(tmp, { recursive: true, force: true });
2249
+ }
2250
+ });
2251
+
2252
+ test('J 项:连续失败按指数退避拉长定时器与 lastRunNextRetryAt(1h 封顶),恢复成功后清零退避', async () => {
2253
+ let nowMs = Date.parse('2026-11-18T12:00:00.000Z');
2254
+ let shouldFail = true;
2255
+ let pushCalls = 0;
2256
+ const scheduledDelays: number[] = [];
2257
+ const timerCallbacks: Array<{ fn: () => void; ms: number; cleared: boolean }> = [];
2258
+
2259
+ let cfg: AutosyncConfig = {
2260
+ enabled: true,
2261
+ interval: '30m',
2262
+ startupMinIntervalMs: 300_000,
2263
+ consecutiveFailures: 0,
2264
+ realtime: true,
2265
+ remoteCheckMs: 5 * 60_000,
2266
+ // 跳过启动轮以便精确观察定时器和失败退避演变
2267
+ lastSuccessAt: '2026-11-18T11:59:00.000Z',
2268
+ };
2269
+ const scheduler = new AutoSyncScheduler({
2270
+ syncDir: '/tmp',
2271
+ host: { log: nullLogger() },
2272
+ makeSyncEngine: () => ({
2273
+ listSnapshots: async () => [],
2274
+ hasNewRemoteSnapshot: async () => false,
2275
+ hasLocalChanges: async () => true,
2276
+ async push() {
2277
+ pushCalls += 1;
2278
+ if (shouldFail) throw new Error('connect ETIMEDOUT');
2279
+ return { ok: true, snapshotId: 'snap-recovered', sections: ['settings'], warnings: [] };
2280
+ },
2281
+ } as unknown as SyncEngine),
2282
+ msg: (k: string) => k,
2283
+ runs: new RunRegistry(),
2284
+ now: () => new Date(nowMs),
2285
+ readConfig: async () => cfg,
2286
+ writeConfig: async (_ch, next) => { cfg = next; },
2287
+ readSyncConfigFn: async () => ({ schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://example.com/repo.git' } }) as SyncConfig,
2288
+ readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: [], updatedAt: '' }),
2289
+ appendHistoryFn: async () => {},
2290
+ setTimer: (fn, ms) => {
2291
+ const entry = { fn, ms, cleared: false };
2292
+ timerCallbacks.push(entry);
2293
+ scheduledDelays.push(ms);
2294
+ return entry as unknown as ReturnType<typeof setTimeout>;
2295
+ },
2296
+ clearTimer: (handle) => {
2297
+ (handle as unknown as { cleared: boolean }).cleared = true;
2298
+ },
2299
+ minTriggerGapMs: 0,
2300
+ });
2301
+
2302
+ scheduler.start();
2303
+ await tick();
2304
+ await tick();
2305
+ assert.ok(scheduledDelays.includes(5 * 60_000), '初始 remote-poll 为 5m: ' + JSON.stringify(scheduledDelays));
2306
+
2307
+ // 第 1 次失败(T0)→ 5m * 2 = 10m
2308
+ await scheduler.runOnce('git', { reason: 'local-change' });
2309
+ await tick();
2310
+ assert.equal(cfg.consecutiveFailures, 1);
2311
+ assert.equal(cfg.lastRunNextRetryAt, new Date(nowMs + 10 * 60_000).toISOString());
2312
+ const activePollDelay1 = timerCallbacks.filter((t) => !t.cleared).map((t) => t.ms);
2313
+ assert.ok(activePollDelay1.includes(10 * 60_000), '1 连败后定时器重排为 10m: ' + JSON.stringify(activePollDelay1));
2314
+
2315
+ // 退避窗口内 trigger('remote-poll') 必须被节流,而 manual 照常执行
2316
+ const beforePollCalls = pushCalls;
2317
+ nowMs += 5 * 60_000;
2318
+ scheduler.trigger('git', 'remote-poll');
2319
+ await tick();
2320
+ assert.equal(pushCalls, beforePollCalls, '退避期内不得再跑 remote-poll 形成失败风暴');
2321
+
2322
+ // 推进到第 1 次退避窗口之后再败 3 次:20m → 40m → 60m(1h 封顶)
2323
+ nowMs += 6 * 60_000; // T0 + 11m
2324
+ await scheduler.runOnce('git', { reason: 'manual' });
2325
+ assert.equal(cfg.consecutiveFailures, 2);
2326
+ assert.equal(cfg.lastRunNextRetryAt, new Date(nowMs + 20 * 60_000).toISOString());
2327
+
2328
+ nowMs += 25 * 60_000;
2329
+ await scheduler.runOnce('git', { reason: 'manual' });
2330
+ assert.equal(cfg.consecutiveFailures, 3);
2331
+ assert.equal(cfg.lastRunNextRetryAt, new Date(nowMs + 40 * 60_000).toISOString());
2332
+
2333
+ nowMs += 45 * 60_000;
2334
+ await scheduler.runOnce('git', { reason: 'manual' });
2335
+ assert.equal(cfg.consecutiveFailures, 4);
2336
+ assert.equal(cfg.lastRunNextRetryAt, new Date(nowMs + 60 * 60_000).toISOString(), '连续失败 >=4 次退避封顶 1h');
2337
+
2338
+ // 恢复成功后必须清除退避时间,定时恢复为 5m
2339
+ shouldFail = false;
2340
+ nowMs += 65 * 60_000;
2341
+ const recovered = await scheduler.runOnce('git', { reason: 'manual' });
2342
+ assert.equal(recovered.status, 'success');
2343
+ assert.equal(cfg.consecutiveFailures, 0);
2344
+ assert.equal(cfg.lastRunNextRetryAt, undefined);
2345
+ scheduler.stop();
2346
+ });
2347
+
2348
+ test('J 项:local-change 撞短暂 mutation-locked 时安排补偿重试并丢不掉脏标志;stale 残留锁不空转', async () => {
2349
+ let lockState: 'LOCKED' | 'ACQUIRED' | 'STALE_LOCK_DETECTED' = 'LOCKED';
2350
+ let localDirty = true;
2351
+ let pushCalls = 0;
2352
+ const retryTimers: Array<{ fn: () => void; ms: number; cleared: boolean }> = [];
2353
+
2354
+ let cfg: AutosyncConfig = {
2355
+ enabled: true, interval: '30m', startupMinIntervalMs: 300_000, consecutiveFailures: 0, realtime: true,
2356
+ };
2357
+ const lockPort = {
2358
+ async acquire() {
2359
+ if (lockState === 'ACQUIRED') {
2360
+ return { state: 'ACQUIRED' as const, token: { ownershipPath: '/tmp/lock', instanceId: 'i1', acquiredAt: 1 } };
2361
+ }
2362
+ if (lockState === 'STALE_LOCK_DETECTED') {
2363
+ return { state: 'STALE_LOCK_DETECTED' as const, token: null };
2364
+ }
2365
+ return { state: 'LOCKED' as const, token: null };
2366
+ },
2367
+ async release() {},
2368
+ validate() { return true; },
2369
+ } as unknown as import('../utils/env-lock.ts').MutationLockPort;
2370
+
2371
+ const scheduler = new AutoSyncScheduler({
2372
+ syncDir: '/tmp',
2373
+ host: { log: nullLogger() },
2374
+ mutationLock: lockPort,
2375
+ makeSyncEngine: () => ({
2376
+ listSnapshots: async () => [],
2377
+ hasNewRemoteSnapshot: async () => false,
2378
+ hasLocalChanges: async () => localDirty,
2379
+ async push() {
2380
+ pushCalls += 1;
2381
+ localDirty = false;
2382
+ return { ok: true, snapshotId: 'snap-after-lock', sections: ['settings'], warnings: [] };
2383
+ },
2384
+ } as unknown as SyncEngine),
2385
+ msg: (k: string) => k,
2386
+ runs: new RunRegistry(),
2387
+ now: () => new Date('2026-11-18T12:00:00.000Z'),
2388
+ readConfig: async () => cfg,
2389
+ writeConfig: async (_ch, next) => { cfg = next; },
2390
+ readSyncConfigFn: async () => ({ schemaVersion: 2, transport: 'git', git: { repoUrl: 'https://example.com/repo.git' } }) as SyncConfig,
2391
+ readHistoryFn: async () => ({ schemaVersion: 1, autosyncEntries: [], updatedAt: '' }),
2392
+ appendHistoryFn: async () => {},
2393
+ setTimer: (fn, ms) => {
2394
+ const rec = { fn, ms, cleared: false };
2395
+ retryTimers.push(rec);
2396
+ return rec as unknown as ReturnType<typeof setTimeout>;
2397
+ },
2398
+ clearTimer: (h) => {
2399
+ (h as unknown as { cleared: boolean }).cleared = true;
2400
+ },
2401
+ minTriggerGapMs: 0,
2402
+ lockRetryDelayMs: 1200,
2403
+ });
2404
+
2405
+ // 1) local-change 撞短暂活跃锁 → skipped(mutation-locked) 且排队 1200ms 补偿重试
2406
+ const lockedRes = await scheduler.runOnce('git', { reason: 'local-change' });
2407
+ assert.equal(lockedRes.skipReason, 'mutation-locked');
2408
+ assert.equal(pushCalls, 0);
2409
+ const firstRetry = retryTimers.find((t) => !t.cleared);
2410
+ assert.ok(firstRetry !== undefined && firstRetry.ms === 1200, '撞活跃锁后必须排 1200ms 补偿定时器');
2411
+
2412
+ // 2) 若远端轮询先到期,也因待补推标志自动升级查本地;此时锁释放 → 一举推上远端并清空补偿标记
2413
+ lockState = 'ACQUIRED';
2414
+ await scheduler.runOnce('git', { reason: 'remote-poll' });
2415
+ assert.equal(pushCalls, 1, 'pendingDirty 存在时即使 remote-poll 也要检查并补推本地改动');
2416
+ assert.equal(retryTimers.every((t) => t.cleared), true, '成功推送后残留锁重试定时器必须清理');
2417
+
2418
+ // 3) stale 残留锁不会空转排补偿定时器
2419
+ retryTimers.length = 0;
2420
+ localDirty = true;
2421
+ lockState = 'STALE_LOCK_DETECTED';
2422
+ const staleRes = await scheduler.runOnce('git', { reason: 'local-change' });
2423
+ assert.equal(staleRes.skipReason, 'mutation-lock-stale');
2424
+ assert.equal(retryTimers.length, 0, 'stale 残留锁不能自愈,绝不空转重试');
2425
+ scheduler.stop();
2426
+ });
2427
+
1895
2428