dsh-config-manager 0.4.0 → 0.4.2

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 (152) hide show
  1. package/lib/cli/actions.js +2 -3
  2. package/lib/cli/import-source.js +2 -6
  3. package/lib/cli/index.js +2 -3
  4. package/lib/client.d.ts +21 -7
  5. package/lib/client.js +26122 -25799
  6. package/lib/core/exporter.js +2 -4
  7. package/lib/core/host-schedulers/cache-cleanup.d.ts +41 -0
  8. package/lib/core/host-schedulers/cache-cleanup.js +45 -0
  9. package/lib/core/host-schedulers/lifecycle-hooks.d.ts +51 -0
  10. package/lib/core/host-schedulers/lifecycle-hooks.js +78 -0
  11. package/lib/core/host-schedulers/market-cache.d.ts +40 -0
  12. package/lib/core/host-schedulers/market-cache.js +92 -0
  13. package/lib/core/messages-core.d.ts +1 -0
  14. package/lib/core/messages-core.js +2 -0
  15. package/lib/core/migration-history.d.ts +18 -2
  16. package/lib/core/migration-history.js +19 -3
  17. package/lib/core/model-tools.js +2 -6
  18. package/lib/core/restore.d.ts +0 -2
  19. package/lib/core/restore.js +16 -18
  20. package/lib/core/verify-recovery.js +4 -7
  21. package/lib/index.d.ts +3 -22
  22. package/lib/index.js +71 -327
  23. package/lib/profiles/dsh-profile-manager.d.ts +23 -1
  24. package/lib/profiles/dsh-profile-manager.js +70 -2
  25. package/lib/routes/kit.d.ts +21 -0
  26. package/lib/routes/kit.js +29 -0
  27. package/lib/routes/prefs.js +6 -6
  28. package/lib/routes/recovery.js +25 -41
  29. package/lib/routes/route-support.d.ts +23 -1
  30. package/lib/routes/route-support.js +185 -0
  31. package/lib/routes/snapshots.js +4 -11
  32. package/lib/routes/sync.js +5 -7
  33. package/lib/security/redaction.d.ts +5 -1
  34. package/lib/security/redaction.js +26 -23
  35. package/lib/sync/autosync-scheduler.js +6 -2
  36. package/lib/sync/backup-scheduler.js +2 -6
  37. package/lib/sync/baseline-heal.d.ts +35 -0
  38. package/lib/sync/baseline-heal.js +39 -0
  39. package/lib/sync/push-precheck.d.ts +35 -0
  40. package/lib/sync/push-precheck.js +58 -0
  41. package/lib/sync/sync-engine.d.ts +9 -12
  42. package/lib/sync/sync-engine.js +24 -43
  43. package/lib/ui/backup-inspect.d.ts +1 -1
  44. package/lib/ui/dsh-profiles-view.d.ts +0 -10
  45. package/lib/ui/dsh-profiles-view.js +3 -7
  46. package/lib/ui/history-model.js +3 -2
  47. package/lib/ui/overview-view.d.ts +3 -3
  48. package/lib/ui/overview-view.js +9 -1
  49. package/lib/ui/snapshots-view.d.ts +0 -14
  50. package/lib/ui/snapshots-view.js +16 -2
  51. package/lib/utils/paths.d.ts +20 -4
  52. package/lib/utils/paths.js +22 -6
  53. package/lib/utils/time.d.ts +31 -0
  54. package/lib/utils/time.js +54 -0
  55. package/package.json +1 -1
  56. package/src/cli/actions.ts +2 -3
  57. package/src/cli/import-source.ts +2 -7
  58. package/src/cli/index.ts +2 -3
  59. package/src/client/about/AboutPanel.tsx +1 -1
  60. package/src/client/about/ReleaseBody.tsx +22 -52
  61. package/src/client/about/ReleaseNotesDialog.tsx +15 -69
  62. package/src/client/about/release-notes-view.ts +4 -11
  63. package/src/client/common/info-hint-guard.test.ts +11 -5
  64. package/src/client/common/ui.tsx +23 -0
  65. package/src/client/config-manager.module.css +201 -32
  66. package/src/client/css-token-guard.test.ts +135 -1
  67. package/src/client/history/history-locales.ts +2 -0
  68. package/src/client/home/HomePanel.tsx +9 -3
  69. package/src/client/import/ConflictList.tsx +3 -3
  70. package/src/client/import/ImportWizardView.tsx +1 -1
  71. package/src/client/library/ArtifactRow.tsx +2 -2
  72. package/src/client/library/RestorePlanView.tsx +21 -9
  73. package/src/client/library/report-dismiss.test.ts +5 -3
  74. package/src/client/locales/about.ts +97 -0
  75. package/src/client/locales/backup.ts +141 -0
  76. package/src/client/locales/common.ts +113 -0
  77. package/src/client/locales/export.ts +184 -0
  78. package/src/client/locales/foreign.ts +184 -0
  79. package/src/client/locales/import-compat.ts +32 -0
  80. package/src/client/locales/import.ts +192 -0
  81. package/src/client/locales/next-steps.ts +25 -0
  82. package/src/client/locales/overview-control.ts +32 -0
  83. package/src/client/locales/overview.ts +145 -0
  84. package/src/client/locales/profiles.ts +263 -0
  85. package/src/client/locales/report.ts +17 -0
  86. package/src/client/locales/restore.ts +132 -0
  87. package/src/client/locales/sessions.ts +257 -0
  88. package/src/client/locales/shell.ts +149 -0
  89. package/src/client/locales.ts +49 -1781
  90. package/src/client/market/MarketImportReview.tsx +2 -2
  91. package/src/client/market/MarketPanel.tsx +1 -1
  92. package/src/client/market/market-view.ts +3 -5
  93. package/src/client/recovery/RecoveryPanel.tsx +62 -1054
  94. package/src/client/recovery/SessionHealthCard.tsx +134 -0
  95. package/src/client/recovery/SessionHealthDialog.tsx +665 -0
  96. package/src/client/recovery/SessionLayoutSection.tsx +284 -0
  97. package/src/client/recovery/recovery-api.ts +10 -1
  98. package/src/client/recovery/recovery-panel-layout.test.ts +20 -5
  99. package/src/client/recovery/session-dialog-mount.test.ts +16 -9
  100. package/src/client/recovery/use-recovery-write.test.ts +90 -0
  101. package/src/client/recovery/use-recovery-write.ts +53 -0
  102. package/src/client/run-store.ts +57 -2
  103. package/src/client/sync/PushPreviewCard.tsx +2 -2
  104. package/src/client/sync/SyncConfirmView.tsx +5 -5
  105. package/src/client/sync/SyncLogList.tsx +2 -2
  106. package/src/client/sync/history-model.ts +7 -5
  107. package/src/client/sync/sync-locales.ts +2 -0
  108. package/src/client/sync/sync-view.ts +3 -4
  109. package/src/core/exporter.ts +2 -4
  110. package/src/core/host-schedulers/cache-cleanup.test.ts +84 -0
  111. package/src/core/host-schedulers/cache-cleanup.ts +74 -0
  112. package/src/core/host-schedulers/lifecycle-hooks.test.ts +111 -0
  113. package/src/core/host-schedulers/lifecycle-hooks.ts +118 -0
  114. package/src/core/host-schedulers/market-cache.test.ts +93 -0
  115. package/src/core/host-schedulers/market-cache.ts +116 -0
  116. package/src/core/messages-core.ts +2 -0
  117. package/src/core/migration-history.test.ts +19 -0
  118. package/src/core/migration-history.ts +28 -5
  119. package/src/core/model-tools.ts +2 -7
  120. package/src/core/restore-failure-state.test.ts +210 -0
  121. package/src/core/restore.ts +16 -18
  122. package/src/core/verify-recovery.ts +4 -7
  123. package/src/index.ts +78 -332
  124. package/src/profiles/dsh-profile-copy-rollback.test.ts +156 -0
  125. package/src/profiles/dsh-profile-manager.ts +71 -3
  126. package/src/routes/kit.ts +37 -0
  127. package/src/routes/prefs.ts +6 -6
  128. package/src/routes/recovery.ts +25 -42
  129. package/src/routes/route-support.ts +208 -1
  130. package/src/routes/snapshots.ts +4 -9
  131. package/src/routes/sync.ts +4 -7
  132. package/src/security/redaction.ts +29 -23
  133. package/src/sync/autosync-scheduler.test.ts +23 -0
  134. package/src/sync/autosync-scheduler.ts +6 -2
  135. package/src/sync/backup-scheduler.ts +3 -6
  136. package/src/sync/baseline-heal.ts +74 -0
  137. package/src/sync/push-precheck.ts +75 -0
  138. package/src/sync/sync-config.test.ts +24 -13
  139. package/src/sync/sync-engine.test.ts +88 -0
  140. package/src/sync/sync-engine.ts +33 -43
  141. package/src/ui/backup-inspect.ts +1 -1
  142. package/src/ui/dsh-profiles-view.ts +3 -5
  143. package/src/ui/history-model.test.ts +2 -1
  144. package/src/ui/history-model.ts +3 -2
  145. package/src/ui/i18n.test.ts +8 -3
  146. package/src/ui/overview-view.test.ts +12 -0
  147. package/src/ui/overview-view.ts +12 -4
  148. package/src/ui/snapshots-view.ts +2 -2
  149. package/src/utils/paths.test.ts +36 -1
  150. package/src/utils/paths.ts +30 -6
  151. package/src/utils/time.test.ts +46 -0
  152. package/src/utils/time.ts +55 -0
@@ -28,13 +28,15 @@ import { collectCredentialRefs } from '../security/credentials-yaml.ts'
28
28
  import { decryptCredentials, SecurityError } from '../security/index.ts'
29
29
  import type { Manifest, SectionId } from '../schema/types.ts'
30
30
  import type { HostContext, ImportPlan, PlanItemKind } from '../core/types.ts'
31
+ import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'
31
32
  import { engineMsg } from '../core/engine-locale.ts'
32
33
  import { createPreRestoreAttemptDir } from '../core/restore.ts'
33
34
  import type { RestoreActionKind, RestorePlan, RestoreReport } from '../core/restore.ts'
34
35
  import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
35
36
  import type { RestoreResumeHint } from '../core/restore-resume.ts'
36
37
  import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from '../core/restore-wal.ts'
37
- import type { SyncTransportType } from '../sync/sync-config.ts'
38
+ import type { SyncConfig, SyncTransportType } from '../sync/sync-config.ts'
39
+ import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.ts'
38
40
  import { DEFAULT_AUTOSYNC_AUTO_APPLY_TIER, DEFAULT_AUTOSYNC_CONFLICT_POLICY, DEFAULT_AUTOSYNC_REALTIME, DEFAULT_AUTOSYNC_REMOTE_CHECK_MS, lastRunFailureMessage, readAllAutosyncConfigs, readAutosyncConfig } from '../sync/autosync-config.ts'
39
41
  import type { AutosyncAutoApplyTier, AutosyncConflictPolicy, AutosyncInterval, AutosyncRunStatus } from '../sync/autosync-config.ts'
40
42
  import { SYNC_CHANNELS } from '../sync/sync-config.ts'
@@ -733,3 +735,208 @@ export function makeRestoreExecutor(snapshotDir: string, host: HostContext, prof
733
735
  },
734
736
  }
735
737
  }
738
+
739
+
740
+ /* ------------------------------------------- 同步通道请求体解析(tech-debt #23 下沉)
741
+ *
742
+ * 原在 src/index.ts 的宿主组合根里,但它们是**不依赖组合根状态**的纯解析:
743
+ * body → 归一化 SyncConfig(可辨识联合)+ 密钥只写 DSH credentials 槽位。
744
+ * 下沉后 `src/index.sync.test.ts` 仍经组合根的再导出取用(符号名不变)。
745
+ */
746
+
747
+ /** parseSyncBody 的凭据写入依赖(只用到 set;测试可注入内存 mock)。 */
748
+ export interface ParseSyncBodyDeps {
749
+ credentials: Pick<CredentialProvider, 'set'>
750
+ }
751
+
752
+ /**
753
+ * 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
754
+ * 请求体形状(flat,M4 契约):
755
+ * - git: { transport:'git', repoUrl, token? } —— token 非空写 SYNC_CREDENTIAL_REF;
756
+ * git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
757
+ * - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
758
+ * 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
759
+ */
760
+ export async function parseSyncBody(
761
+ body: Record<string, unknown>,
762
+ deps: ParseSyncBodyDeps,
763
+ ): Promise<SyncConfig> {
764
+ const rawTransport = body['transport']
765
+ // 通道值解析:接受通道名(s3/gist);也接受**具体兼容商**(oss/cos/minio/kodo)直接落到 s3 通道
766
+ const transport = parseSyncChannel(rawTransport) ?? (isS3CompatProvider(rawTransport) ? 's3' : 'git')
767
+ if (transport === 's3') return parseCloudS3Body(body, rawTransport, deps)
768
+ if (transport === 'gist') return parseCloudGistBody(body, deps)
769
+ if (transport === 'webdav') {
770
+ const url = typeof body['url'] === 'string' ? body['url'].trim() : ''
771
+ if (url === '') throw new SyncRouteError('url is required for webdav')
772
+ const urlError = validateWebDavUrl(url)
773
+ if (urlError !== null) throw new SyncRouteError(urlError)
774
+ const username = typeof body['username'] === 'string' && body['username'] !== '' ? body['username'] : undefined
775
+ const password = typeof body['password'] === 'string' && body['password'] !== '' ? body['password'] : undefined
776
+ if (password !== undefined) {
777
+ try {
778
+ await deps.credentials.set(credentialRef(SYNC_WEBDAV_CREDENTIAL_REF), password)
779
+ } catch (error) {
780
+ const reason = error instanceof Error ? error.message : String(error)
781
+ throw new SyncRouteError(
782
+ engineMsg('host.syncWebdavPasswordWriteFailed', { reason, ref: SYNC_WEBDAV_CREDENTIAL_REF }),
783
+ )
784
+ }
785
+ }
786
+ return {
787
+ schemaVersion: 2,
788
+ transport: 'webdav',
789
+ webdav: { url, ...(username !== undefined ? { username } : {}) },
790
+ }
791
+ }
792
+ // git 通道(沿用现有逻辑)
793
+ const repoUrl = typeof body['repoUrl'] === 'string' ? body['repoUrl'].trim() : ''
794
+ if (repoUrl === '') throw new SyncRouteError('repoUrl is required')
795
+ const urlError = validateRepoUrl(repoUrl)
796
+ if (urlError !== null) throw new SyncRouteError(urlError)
797
+ const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined
798
+ if (token !== undefined) {
799
+ try {
800
+ await deps.credentials.set(credentialRef(SYNC_CREDENTIAL_REF), token)
801
+ } catch (error) {
802
+ const reason = error instanceof Error ? error.message : String(error)
803
+ throw new SyncRouteError(
804
+ engineMsg('host.syncTokenWriteFailed', { reason, ref: SYNC_CREDENTIAL_REF }),
805
+ )
806
+ }
807
+ }
808
+ return {
809
+ schemaVersion: 2,
810
+ transport: 'git',
811
+ git: { repoUrl },
812
+ }
813
+ }
814
+
815
+ /** 请求体字段 → 去空白字符串(非字符串 = 空)。 */
816
+ function syncStr(value: unknown): string {
817
+ return typeof value === 'string' ? value.trim() : ''
818
+ }
819
+
820
+ /** 云端点密钥写入失败 → 可操作错误(**含 ref 名、绝不含密钥值**)。 */
821
+ function cloudCredentialWriteError(ref: string, kind: string, error: unknown): SyncRouteError {
822
+ const reason = error instanceof Error ? error.message : String(error)
823
+ return new SyncRouteError(
824
+ engineMsg('host.syncCredentialWriteFailed', { kind, reason, ref }),
825
+ 400,
826
+ 'cloud.credentialsWriteFailed',
827
+ )
828
+ }
829
+
830
+ /**
831
+ * s3 通道请求体 → SyncConfig(provider 必填或由 transport 直接给出)。
832
+ * 非密字段按 validateCloudChannelInput 校验(错误码 = HTTP body.code,由 UI 映射字典);
833
+ * 密钥**只写**进 DSH credentials 的 cloudSecretRef(provider) 槽位,绝不进返回值 / 文件 / 日志。
834
+ */
835
+ async function parseCloudS3Body(
836
+ body: Record<string, unknown>,
837
+ rawTransport: unknown,
838
+ deps: ParseSyncBodyDeps,
839
+ ): Promise<SyncConfig> {
840
+ const provider = isS3CompatProvider(body['provider'])
841
+ ? body['provider']
842
+ : (isS3CompatProvider(rawTransport) ? rawTransport : null)
843
+ if (provider === null) {
844
+ throw new SyncRouteError('provider is required for s3 (s3/oss/cos/minio/kodo)', 400, 'cloud.providerUnknown')
845
+ }
846
+ const endpoint = syncStr(body['endpoint']).replace(/\/+$/, '')
847
+ const region = syncStr(body['region'])
848
+ const bucket = syncStr(body['bucket'])
849
+ const accessKeyId = syncStr(body['accessKeyId'])
850
+ const prefix = syncStr(body['prefix'])
851
+ const pathStyle = typeof body['pathStyle'] === 'boolean' ? body['pathStyle'] : undefined
852
+ const dialectId = body['dialectId'] === 'aws4' || body['dialectId'] === 'oss4' ? body['dialectId'] : undefined
853
+ const issue = validateCloudChannelInput(provider, {
854
+ endpoint,
855
+ region,
856
+ bucket,
857
+ accessKeyId,
858
+ ...(prefix === '' ? {} : { prefix }),
859
+ ...(pathStyle === undefined ? {} : { pathStyle }),
860
+ ...(dialectId === undefined ? {} : { dialectId }),
861
+ })
862
+ if (issue !== null) throw new SyncRouteError(issue, 400, issue)
863
+ const secret = typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined
864
+ if (secret !== undefined) {
865
+ const ref = cloudSecretRef(provider)
866
+ try {
867
+ await deps.credentials.set(credentialRef(ref), secret)
868
+ } catch (error) {
869
+ throw cloudCredentialWriteError(ref, engineMsg('host.syncKindS3Secret'), error)
870
+ }
871
+ }
872
+ return {
873
+ schemaVersion: 2,
874
+ transport: 's3',
875
+ s3: {
876
+ provider,
877
+ endpoint,
878
+ region,
879
+ bucket,
880
+ accessKeyId,
881
+ ...(prefix === '' ? {} : { prefix }),
882
+ ...(pathStyle === undefined ? {} : { pathStyle }),
883
+ ...(dialectId === undefined ? {} : { dialectId }),
884
+ },
885
+ }
886
+ }
887
+
888
+ /**
889
+ * gist 通道请求体 → SyncConfig。token 只写进 cloudSecretRef('gist') 槽位
890
+ * (请求体字段名 token 或 secret 都接受;值绝不进返回值 / 文件 / 日志)。
891
+ */
892
+ async function parseCloudGistBody(body: Record<string, unknown>, deps: ParseSyncBodyDeps): Promise<SyncConfig> {
893
+ const gistId = syncStr(body['gistId'])
894
+ const apiBaseUrl = syncStr(body['apiBaseUrl'])
895
+ const filePrefix = syncStr(body['filePrefix'])
896
+ const issue = validateCloudChannelInput(GIST_PROVIDER, {
897
+ gistId,
898
+ ...(apiBaseUrl === '' ? {} : { apiBaseUrl }),
899
+ ...(filePrefix === '' ? {} : { filePrefix }),
900
+ })
901
+ if (issue !== null) throw new SyncRouteError(issue, 400, issue)
902
+ const token = typeof body['token'] === 'string' && body['token'] !== ''
903
+ ? body['token']
904
+ : (typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined)
905
+ if (token !== undefined) {
906
+ const ref = cloudSecretRef(GIST_PROVIDER)
907
+ try {
908
+ await deps.credentials.set(credentialRef(ref), token)
909
+ } catch (error) {
910
+ throw cloudCredentialWriteError(ref, 'Gist token', error)
911
+ }
912
+ }
913
+ return {
914
+ schemaVersion: 2,
915
+ transport: 'gist',
916
+ gist: {
917
+ gistId,
918
+ ...(apiBaseUrl === '' ? {} : { apiBaseUrl }),
919
+ ...(filePrefix === '' ? {} : { filePrefix }),
920
+ },
921
+ }
922
+ }
923
+
924
+ /** 由 SyncConfig 合成 WebDAV 通道 baseUrl(webdav.url,尾部规范化带 '/';git 通道返回 '')。 */
925
+ export function webdavBaseUrl(cfg: SyncConfig): string {
926
+ if (!isWebDavConfig(cfg)) return ''
927
+ return cfg.webdav.url.replace(/\/+$/, '') + '/'
928
+ }
929
+
930
+ /**
931
+ * 补全 webdav 配置缺失的 username(从持久化配置回填;纯函数,不修改入参)。
932
+ * 语义与 password 一致:请求未带 username(表单留空/挂载自动加载)→ 沿用已保存的值;
933
+ * 请求显式带 username → 原样保留(用户新输入优先)。非 webdav / 无持久化 → 原样返回。
934
+ */
935
+ export function mergePersistedWebDavUsername(cfg: SyncConfig, persisted: SyncConfig | null): SyncConfig {
936
+ if (!isWebDavConfig(cfg) || (cfg.webdav.username !== undefined && cfg.webdav.username !== '')) return cfg
937
+ if (persisted !== null && isWebDavConfig(persisted)
938
+ && typeof persisted.webdav.username === 'string' && persisted.webdav.username !== '') {
939
+ return { ...cfg, webdav: { ...cfg.webdav, username: persisted.webdav.username } }
940
+ }
941
+ return cfg
942
+ }
@@ -5,10 +5,9 @@
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
7
 
8
- import { endpoint, readJsonBody, writeJson } from './kit.ts'
8
+ import { endpoint, readJsonBody, writeJson, writeMutationError } from './kit.ts'
9
9
  import type { WebRoute } from './kit.ts'
10
10
  import type { RoutesEnv } from './context.ts'
11
- import { TransactionRecoveryRequiredError } from '../core/phase3-host.ts'
12
11
  import { deleteSnapshot, isValidSnapshotId, listSnapshots, planRestore, setSnapshotPinned } from '../core/restore.ts'
13
12
  import type { RunState } from '../core/run-registry.ts'
14
13
  import { snapshotFileDiff, summarizeRestoreChanges } from '../core/snapshot-diff.ts'
@@ -16,7 +15,7 @@ import { buildFileDiffBody, buildRestoreBody, executeRestorePlan, makeRestoreExe
16
15
  import type { RestoreJournalPort } from '../core/restore-wal.ts'
17
16
  import { probeRestoreResume, runRestoreWithResume } from '../core/restore-resume.ts'
18
17
  import type { RestoreResumeHint } from '../core/restore-resume.ts'
19
- import { EnvironmentLockUnavailableError, runWithMutationLock } from '../utils/env-lock.ts'
18
+ import { runWithMutationLock } from '../utils/env-lock.ts'
20
19
  import { isENOENT } from '../utils/guards.ts'
21
20
  import { join } from 'node:path'
22
21
  import { createHash } from 'node:crypto'
@@ -205,12 +204,8 @@ export function snapshotRoutes(env: RoutesEnv): WebRoute[] {
205
204
  }
206
205
  })
207
206
  } catch (error) {
208
- if (error instanceof EnvironmentLockUnavailableError) {
209
- host.log.warn(`mutation lock blocked: op=${error.op} reason=${error.reason}${error.detail !== undefined ? ` detail=${error.detail}` : ''}`)
210
- writeJson(res, 423, { error: error.message, code: 'mutation-locked' })
211
- } else if (error instanceof TransactionRecoveryRequiredError) {
212
- writeJson(res, 423, { error: error.message, code: 'transaction-recovery-required' })
213
- } else {
207
+ // 423 家族(SAFE MODE / 环境锁 / 未收敛事务)的唯一映射在 kit;本路由其余错误沿用 400 口径。
208
+ if (!writeMutationError(res, host, error)) {
214
209
  writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
215
210
  }
216
211
  }
@@ -5,8 +5,8 @@
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
7
 
8
- import { endpoint, queryParam, requireJsonObject, readJsonBody, writeJson } from './kit.ts'
9
- import { EnvironmentLockUnavailableError, runWithMutationLock } from '../utils/env-lock.ts'
8
+ import { endpoint, queryParam, requireJsonObject, readJsonBody, writeJson, writeMutationError } from './kit.ts'
9
+ import { runWithMutationLock } from '../utils/env-lock.ts'
10
10
  import type { WebRoute } from './kit.ts'
11
11
  import type { RoutesEnv } from './context.ts'
12
12
  import { FileSnapshotStore } from '../core/index.ts'
@@ -426,11 +426,8 @@ export function syncRoutes(env: RoutesEnv): WebRoute[] {
426
426
  )
427
427
  writeJson(res, 200, { ok: true, lastSyncChannel: channel })
428
428
  } catch (error) {
429
- if (error instanceof EnvironmentLockUnavailableError) {
430
- writeJson(res, 423, { error: error.message, code: 'mutation-locked' })
431
- return
432
- }
433
- writeSyncRouteError(res, error)
429
+ // 423 家族(SAFE MODE / 环境锁)的唯一映射在 kit;其余沿用本组既有 SyncRouteError 口径。
430
+ if (!writeMutationError(res, host, error)) writeSyncRouteError(res, error)
434
431
  }
435
432
  }),
436
433
  // ------------------------------------------------------ sync/push
@@ -116,23 +116,34 @@ function replaceSensitiveField(text: string, re: RegExp, blacklist: readonly str
116
116
  }
117
117
 
118
118
  /**
119
- * 文本脱敏(幂等)。blacklist 为**附加**规范化字段名(小写无分隔符,如 'clientsecret')。
120
- * 输出仍保留结构化形态(JSON 行合法)。
119
+ * 脱敏流水线(**唯一实现**,redact 与 createRedactor 共用一套顺序与语义)。
120
+ *
121
+ * 曾经这里与 createRedactor 各写一遍完全相同的 6 步(结构化 3 步 + 值形状 + URL query + userinfo),
122
+ * 两份代码只在「正则实例从哪来」上不同 —— 任何一步调整都要记得改两处,漏一次就是两条脱敏口径。
123
+ * 现在只由调用方决定正则实例的生命周期(模块级常量 / 每次预编译),流水线本身不再有副本。
121
124
  */
122
- export function redact(text: string, blacklist: readonly string[] = []): string {
123
- let out = text;
125
+ function redactPipeline(
126
+ text: string, blacklist: readonly string[], json: RegExp, kv: RegExp, colon: RegExp,
127
+ ): string {
124
128
  // 1. 结构化字段形态(顺序:JSON → kv → colon;JSON 键不会被后续形态二次命中)
125
- out = replaceSensitiveField(out, JSON_FIELD_RE, blacklist);
126
- out = replaceSensitiveField(out, KV_FIELD_RE, blacklist);
127
- out = replaceSensitiveField(out, COLON_FIELD_RE, blacklist);
129
+ let out = replaceSensitiveField(text, json, blacklist);
130
+ out = replaceSensitiveField(out, kv, blacklist);
131
+ out = replaceSensitiveField(out, colon, blacklist);
128
132
  // 2. 值形状模式(字段名无关,包含式)
129
133
  for (const { re } of VALUE_PATTERNS) {
130
134
  re.lastIndex = 0;
131
135
  out = out.replace(re, REDACTED);
132
136
  }
133
137
  out = out.replace(URL_QUERY_RE, `$1${REDACTED}`);
134
- out = out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
135
- return out;
138
+ return out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
139
+ }
140
+
141
+ /**
142
+ * 文本脱敏(幂等)。blacklist 为**附加**规范化字段名(小写无分隔符,如 'clientsecret')。
143
+ * 输出仍保留结构化形态(JSON 行合法)。
144
+ */
145
+ export function redact(text: string, blacklist: readonly string[] = []): string {
146
+ return redactPipeline(text, blacklist, JSON_FIELD_RE, KV_FIELD_RE, COLON_FIELD_RE);
136
147
  }
137
148
 
138
149
  /** 对象级掩码:字段名命中敏感名单 → 整值替换(返回新对象,不改原对象;结构与类型保留) */
@@ -147,21 +158,16 @@ export function redactValue(value: unknown, blacklist: readonly string[] = []):
147
158
  return out;
148
159
  }
149
160
 
150
- /** 预编译脱敏器(多次调用复用;blacklist 为附加规范化字段名) */
161
+ /**
162
+ * 预编译脱敏器(多次调用复用;blacklist 为附加规范化字段名)。
163
+ * 正则实例**在创建时**各复制一份:模块级常量若与本函数共享,多线程无害但会让「谁动了 lastIndex」
164
+ * 不可追溯;复制成本只有一次,换来每个脱敏器实例自持状态。
165
+ */
151
166
  export function createRedactor(blacklist: readonly string[] = []): (text: string) => string {
152
- const compiled = { json: JSON_FIELD_RE, kv: KV_FIELD_RE, colon: COLON_FIELD_RE };
153
- return (text: string): string => {
154
- let out = replaceSensitiveField(text, new RegExp(compiled.json.source, 'g'), blacklist);
155
- out = replaceSensitiveField(out, new RegExp(compiled.kv.source, 'g'), blacklist);
156
- out = replaceSensitiveField(out, new RegExp(compiled.colon.source, 'g'), blacklist);
157
- for (const { re } of VALUE_PATTERNS) {
158
- re.lastIndex = 0;
159
- out = out.replace(re, REDACTED);
160
- }
161
- out = out.replace(URL_QUERY_RE, `$1${REDACTED}`);
162
- out = out.replace(URL_USERINFO_RE, `$1${REDACTED}$3`);
163
- return out;
164
- };
167
+ const json = new RegExp(JSON_FIELD_RE.source, 'g');
168
+ const kv = new RegExp(KV_FIELD_RE.source, 'g');
169
+ const colon = new RegExp(COLON_FIELD_RE.source, 'g');
170
+ return (text: string): string => redactPipeline(text, blacklist, json, kv, colon);
165
171
  }
166
172
 
167
173
  /** 默认名单(文档用;redact 的默认附加名单为空,内置判定已含 DEFAULT_SECRET_FIELD_NAMES) */
@@ -544,6 +544,29 @@ test('push 被远端推进检测拒绝(conflict)→ skipped(conflict) 而非
544
544
  );
545
545
  });
546
546
 
547
+ test('0.4.1 自愈:push 收养了本机残留基线(adoptedBase)→ success + 跳过码 baseline-adopted(面板能看见基线自己动过)', async () => {
548
+ const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 3 };
549
+ const engine = {
550
+ hasNewRemoteSnapshot: async () => false,
551
+ hasLocalChanges: async () => true,
552
+ push: async () => ({
553
+ ok: true, snapshotId: 'snap-healed', sections: [] as never,
554
+ warnings: ['远端最新快照 sync-001 是本机上次推送的:已收养为基线'],
555
+ adoptedBase: 'sync-001',
556
+ }),
557
+ };
558
+ const { scheduler, getConfig, getEntries } = makeScheduler({ cfg, engine, history: [] });
559
+ const result = await scheduler.runOnce('git');
560
+ assert.equal(result.status, 'success', '收养后照常推送 = 成功,不是跳过也不是失败');
561
+ assert.equal(result.skipReason, 'baseline-adopted', '要有独立跳过码,否则既有的「跳过」看不出为什么');
562
+ assert.equal(result.consecutiveFailures, 0, '自愈成功即归零连续失败');
563
+ assert.equal(getConfig().lastRunSkipReason, 'baseline-adopted');
564
+ assert.ok(
565
+ getEntries().some((e) => e.status === 'success' && e.skipReason === 'baseline-adopted'),
566
+ '历史必须留痕:不然用户看到基线跳变却查不到原因',
567
+ );
568
+ });
569
+
547
570
  test('runOnce: 无冲突且无变化 → success(pull,unchanged),不上传(本地也无改动)', async () => {
548
571
  const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
549
572
  const engine = {
@@ -883,11 +883,15 @@ export class AutoSyncScheduler {
883
883
  : partial
884
884
  ? conflictedSections
885
885
  : deferredSections;
886
+ // 0.4.1:推送前收养了「本机自己推上去的」远端快照(上次推送在写基线前被打断)→
887
+ // 如实记一条 skipReason,让历史与首页能说清「这次推上去之前先修好了基线」,
888
+ // 而不是让用户以为又发生了一次莫名冲突。冲突原因优先(真有冲突时更该被看见)。
889
+ const adoptedReason = pushReport.adoptedBase !== undefined ? ('baseline-adopted' as const) : undefined;
886
890
  const result: AutosyncRunResult = {
887
891
  status: partial ? 'partial' : 'success',
888
892
  direction: appliedSections.length ? 'both' : 'push',
889
893
  appliedSections, pushedSnapshotId: pushReport.snapshotId, historyId,
890
- ...(skipReason !== undefined ? { skipReason } : {}),
894
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
891
895
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
892
896
  consecutiveFailures: 0,
893
897
  ...forcedMark,
@@ -896,7 +900,7 @@ export class AutoSyncScheduler {
896
900
  direction: appliedSections.length ? 'both' : 'push',
897
901
  status: partial ? 'partial' : 'success',
898
902
  appliedSections, pushedSnapshotId: pushReport.snapshotId,
899
- ...(skipReason !== undefined ? { skipReason } : {}),
903
+ ...(skipReason !== undefined || adoptedReason !== undefined ? { skipReason: skipReason ?? adoptedReason } : {}),
900
904
  ...(reportedConflicted.length > 0 ? { conflictedSections: reportedConflicted } : {}),
901
905
  createdAt: nowIso, failureCountAtRun: 0,
902
906
  ...forcedMark,
@@ -40,6 +40,7 @@ import { shouldTriggerStartupRun } from './autosync-scheduler.ts';
40
40
  import { AUTO_BACKUP_PREFIX, pruneAutoBackupsByPolicy } from './backup-files.ts';
41
41
  import { DEFAULT_RETENTION_POLICY } from './retention-policy.ts';
42
42
  import type { RetentionPolicy } from './retention-policy.ts';
43
+ import { formatDateStamp } from '../utils/time.ts';
43
44
 
44
45
  export interface BackupRunResult {
45
46
  status: BackupRunStatus;
@@ -280,7 +281,7 @@ export class BackupScheduler {
280
281
  });
281
282
  // 显式落 exportsDir(与 host 路由同构;Exporter 缺省 outPath 是相对文件名,不落目录)
282
283
  // auto 前缀 = 定时备份产物标识:列表来源 Badge + cache-cleaner 豁免 + 保留策略清理依据
283
- const outPath = join(this.exportsDir, `${AUTO_BACKUP_PREFIX}${dateStamp(this.now())}-${randomBytes(3).toString('hex')}.zip`);
284
+ const outPath = join(this.exportsDir, `${AUTO_BACKUP_PREFIX}${formatDateStamp(this.now())}-${randomBytes(3).toString('hex')}.zip`);
284
285
  const { report } = await exporter.export({
285
286
  includeSecrets: false, // 恒不含 secret(与自动同步同语义)
286
287
  outPath,
@@ -404,8 +405,4 @@ export class BackupScheduler {
404
405
  }
405
406
  }
406
407
 
407
- /** 导出文件时间戳(YYYYMMDD-HHmmss),与 host 路由 dateStamp 同构。 */
408
- function dateStamp(d: Date): string {
409
- const p = (n: number): string => String(n).padStart(2, '0');
410
- return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
411
- }
408
+
@@ -0,0 +1,74 @@
1
+ /**
2
+ * m-sync-flow:推送基线自愈(0.4.1)。
3
+ *
4
+ * 为什么单独成模块:这段逻辑是「事故形态 → 判据 → 只写 sync-state」的完整决策,
5
+ * 塞在 SyncEngine.push 里会让本就偏大的引擎再涨几十行(体量棘轮),而它本身不需要引擎的
6
+ * 任何其他状态 —— 只吃 (sync-state 目录, 快照元信息, 本机身份)。
7
+ *
8
+ * 事故形态(0.3.0 真机):push 在「transport.upload 成功」与「recordBaseline 写 sync-state」
9
+ * 之间被打断(退出/崩溃/断电/进程被杀)。远端已经前进、本机基线仍停在上一版,于是后续每一轮
10
+ * 前置推进检测都判定「远端被别的设备推进了」并拒绝推送 —— 用户被**自己推上去的快照**永久锁死,
11
+ * 只能手改 sync-state.json 才能解开。
12
+ *
13
+ * 判据只有一条:远端最新那份快照的 manifest.deviceId == 本机 deviceId。别的设备推进过、
14
+ * 或旧快照没记 deviceId(可能是任何机器)一律不收养,调用方仍按冲突返回 —— 绝不越过别人的改动。
15
+ */
16
+ import type { SectionId } from '../schema/types.ts';
17
+ import type { MsgFunc } from '../core/messages.ts';
18
+ import { joinFs } from './fs.ts';
19
+ import type { SnapshotFs } from './fs.ts';
20
+ import { loadSyncState, resolveDeviceIdentity, saveSyncState } from './sync-state.ts';
21
+ import type { SyncSnapshotMeta } from './transport.ts';
22
+
23
+ export interface AdoptOwnRemoteHeadOptions {
24
+ /** sync-state.json 所在目录。 */
25
+ stateDir: string;
26
+ fsx: SnapshotFs;
27
+ /** 本地快照副本目录(祖先来源);缺省 = 本机没有副本可指。 */
28
+ localSnapshotsDir?: string;
29
+ /** 远端快照列表(已按 createdAt 升序)。 */
30
+ metas: readonly SyncSnapshotMeta[];
31
+ /** 判定为「比基线新」的那份远端快照 id。 */
32
+ remoteId: string;
33
+ /** 本机当前基线(仅用于告警文案)。 */
34
+ base: string;
35
+ /** 本次通道身份(写回 sync-state.transport)。 */
36
+ transport: { type: string; ref: string };
37
+ hostname: string;
38
+ msg: MsgFunc;
39
+ /** 出参:收养说明追加到这里(调用方原样带给用户)。 */
40
+ warnings: string[];
41
+ }
42
+
43
+ /**
44
+ * 把「本机自己推上去、但基线没跟上」的远端最新快照收养为基线。
45
+ *
46
+ * 只写 sync-state:lastSnapshotId / 每分区 hash(取**被收养快照自己**的 sectionHashes,
47
+ * 不是本次导出结果)/ 祖先目录名(本机真有该副本才指过去,没有就保持原祖先 —— 三方合并仍成立,
48
+ * 也不会被写成一个不存在的目录名)。
49
+ *
50
+ * @returns 被收养的快照 id;null = 不满足收养条件(调用方按冲突返回)
51
+ */
52
+ export async function adoptOwnRemoteHead(opts: AdoptOwnRemoteHeadOptions): Promise<string | null> {
53
+ const meta = opts.metas.find((m) => m.id === opts.remoteId);
54
+ if (meta === undefined) return null;
55
+ const device = await resolveDeviceIdentity(opts.stateDir, opts.hostname, opts.fsx, opts.msg);
56
+ const remoteDevice = meta.manifest.deviceId;
57
+ if (typeof remoteDevice !== 'string' || remoteDevice === '' || remoteDevice !== device.id) return null;
58
+ const ancestorKnown = opts.localSnapshotsDir !== undefined
59
+ && await opts.fsx.isDir(joinFs(opts.localSnapshotsDir, opts.remoteId));
60
+ const state = await loadSyncState(opts.stateDir, opts.fsx, opts.msg);
61
+ state.lastSnapshotId = opts.remoteId;
62
+ if (ancestorKnown) state.ancestorId = opts.remoteId;
63
+ for (const [sid, hash] of Object.entries(meta.sections)) {
64
+ if (typeof hash !== 'string' || hash === '') continue;
65
+ state.sections[sid as SectionId] = { hash, updatedAt: meta.createdAt };
66
+ }
67
+ state.transport = opts.transport;
68
+ await saveSyncState(opts.stateDir, state, opts.fsx);
69
+ opts.warnings.push(opts.msg(ancestorKnown ? 'sync.pushBaselineAdopted' : 'sync.pushBaselineAdoptedNoAncestor', {
70
+ remote: opts.remoteId,
71
+ base: opts.base,
72
+ }));
73
+ return opts.remoteId;
74
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * push 前置:远端是否已被别的设备推进,以及「是本机自己推的」时收养基线(0.4.1)。
3
+ *
4
+ * 为什么单独成模块:这段判据是「推不推得上去」的唯一闸门,逻辑上只有三条出口
5
+ * (放行 / 告警放行 / 冲突拒绝),却要在 push 里挤掉二十多行 —— 抽出来后
6
+ * `sync-engine.push` 只剩「问一次闸门,拿到基线或冲突文案」。
7
+ *
8
+ * 事故形态(0.3.0 真机):transport.upload 已成功、recordBaseline 未执行 ⇒ 远端最新快照
9
+ * 就是本机自己那份,而基线还停在旧 id ⇒ 之后每轮都被判「远端被别的设备推进」永久拒绝,
10
+ * 每 60 s 一条失败,用户只能手改 sync-state。判据见 baseline-heal.ts:只有 deviceId 对得上
11
+ * 本机才收养,别的设备(或没有 deviceId 的旧快照)一律照旧拒绝。
12
+ */
13
+ import os from 'node:os';
14
+ import { adoptOwnRemoteHead } from './baseline-heal.ts';
15
+ import type { SnapshotFs } from './fs.ts';
16
+ import type { RemoteSnapshotIndex } from './session-tombstones.ts';
17
+ import { loadSyncState } from './sync-state.ts';
18
+ import type { SyncTransport } from './transport.ts';
19
+ import type { MsgFunc } from '../core/messages.ts';
20
+
21
+ export interface PushBaseOptions {
22
+ stateDir: string;
23
+ fsx: SnapshotFs;
24
+ localSnapshotsDir?: string;
25
+ /** SYN-02:本轮已列过的远端 index(推进检测与墓碑继承共用同一份)。 */
26
+ index: RemoteSnapshotIndex;
27
+ transport: Pick<SyncTransport, 'type'> & { ref: string };
28
+ hostname?: string;
29
+ msg: MsgFunc;
30
+ warnings: string[];
31
+ }
32
+
33
+ export type PushBaseOutcome =
34
+ | { ok: true; base: string; adopted?: string }
35
+ | { ok: false; message: string };
36
+
37
+ /**
38
+ * 判定本机能否继续推送,返回可用的基线。
39
+ *
40
+ * - 首次同步(没有基线)→ 放行;远端为空 → 放行(没有可比对的快照)。
41
+ * - 读不到远端列表 → **告警放行**(上传本身会再暴露通道问题),绝不把「读不到」当「没变」。
42
+ * - 远端最新快照就是当前基线 → 放行。
43
+ * - 远端最新快照是本机自己推的 → 收养为基线后放行(`adopted` 回传,调用方写进报告)。
44
+ * - 其余(别的设备的改动 / 没有 deviceId 的旧快照)→ 冲突拒绝,给 force 出口。
45
+ */
46
+ export async function resolvePushBase(opts: PushBaseOptions): Promise<PushBaseOutcome> {
47
+ const state = await loadSyncState(opts.stateDir, opts.fsx, opts.msg);
48
+ const base = state.lastSnapshotId;
49
+ if (base === '') return { ok: true, base };
50
+ if (opts.index.reason !== undefined) {
51
+ opts.warnings.push(opts.msg('sync.pushAdvanceCheckFailed', { reason: opts.index.reason }));
52
+ return { ok: true, base };
53
+ }
54
+ const metas = opts.index.metas;
55
+ if (metas.length === 0) return { ok: true, base };
56
+ const latest = metas[metas.length - 1]!.id; // list 按 createdAt 升序 → 最新在末
57
+ if (latest === base) return { ok: true, base };
58
+ const adopted = await adoptOwnRemoteHead({
59
+ stateDir: opts.stateDir,
60
+ fsx: opts.fsx,
61
+ localSnapshotsDir: opts.localSnapshotsDir,
62
+ metas,
63
+ remoteId: latest,
64
+ base,
65
+ transport: opts.transport,
66
+ hostname: opts.hostname ?? os.hostname(),
67
+ msg: opts.msg,
68
+ warnings: opts.warnings,
69
+ });
70
+ if (adopted === null) {
71
+ // 无法安全断言「远端没变」时的保守拒绝:不 upload、不记基线、不改 sync-state。
72
+ return { ok: false, message: opts.msg('sync.pushRemoteAdvanced', { remote: latest, base }) };
73
+ }
74
+ return { ok: true, base: adopted, adopted };
75
+ }