dsh-config-manager 0.4.1 → 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 (122) 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 +0 -5
  5. package/lib/client.js +26116 -25801
  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/model-tools.js +2 -6
  14. package/lib/core/restore.d.ts +0 -2
  15. package/lib/core/restore.js +16 -18
  16. package/lib/core/verify-recovery.js +4 -7
  17. package/lib/index.d.ts +3 -22
  18. package/lib/index.js +69 -325
  19. package/lib/profiles/dsh-profile-manager.d.ts +23 -1
  20. package/lib/profiles/dsh-profile-manager.js +70 -2
  21. package/lib/routes/kit.d.ts +21 -0
  22. package/lib/routes/kit.js +29 -0
  23. package/lib/routes/prefs.js +6 -6
  24. package/lib/routes/recovery.js +25 -41
  25. package/lib/routes/route-support.d.ts +23 -1
  26. package/lib/routes/route-support.js +185 -0
  27. package/lib/routes/snapshots.js +4 -11
  28. package/lib/routes/sync.js +5 -7
  29. package/lib/security/redaction.d.ts +5 -1
  30. package/lib/security/redaction.js +26 -23
  31. package/lib/sync/backup-scheduler.js +2 -6
  32. package/lib/ui/backup-inspect.d.ts +1 -1
  33. package/lib/ui/dsh-profiles-view.d.ts +0 -10
  34. package/lib/ui/dsh-profiles-view.js +3 -7
  35. package/lib/ui/snapshots-view.d.ts +0 -14
  36. package/lib/ui/snapshots-view.js +16 -2
  37. package/lib/utils/paths.d.ts +20 -4
  38. package/lib/utils/paths.js +22 -6
  39. package/lib/utils/time.d.ts +31 -0
  40. package/lib/utils/time.js +54 -0
  41. package/package.json +1 -1
  42. package/src/cli/actions.ts +2 -3
  43. package/src/cli/import-source.ts +2 -7
  44. package/src/cli/index.ts +2 -3
  45. package/src/client/about/AboutPanel.tsx +1 -1
  46. package/src/client/about/ReleaseBody.tsx +22 -52
  47. package/src/client/about/ReleaseNotesDialog.tsx +15 -69
  48. package/src/client/about/release-notes-view.ts +4 -11
  49. package/src/client/common/info-hint-guard.test.ts +11 -5
  50. package/src/client/common/ui.tsx +23 -0
  51. package/src/client/config-manager.module.css +201 -32
  52. package/src/client/css-token-guard.test.ts +135 -1
  53. package/src/client/import/ConflictList.tsx +3 -3
  54. package/src/client/import/ImportWizardView.tsx +1 -1
  55. package/src/client/library/ArtifactRow.tsx +2 -2
  56. package/src/client/library/RestorePlanView.tsx +21 -9
  57. package/src/client/library/report-dismiss.test.ts +5 -3
  58. package/src/client/locales/about.ts +97 -0
  59. package/src/client/locales/backup.ts +141 -0
  60. package/src/client/locales/common.ts +113 -0
  61. package/src/client/locales/export.ts +184 -0
  62. package/src/client/locales/foreign.ts +184 -0
  63. package/src/client/locales/import-compat.ts +32 -0
  64. package/src/client/locales/import.ts +192 -0
  65. package/src/client/locales/next-steps.ts +25 -0
  66. package/src/client/locales/overview-control.ts +32 -0
  67. package/src/client/locales/overview.ts +145 -0
  68. package/src/client/locales/profiles.ts +263 -0
  69. package/src/client/locales/report.ts +17 -0
  70. package/src/client/locales/restore.ts +132 -0
  71. package/src/client/locales/sessions.ts +257 -0
  72. package/src/client/locales/shell.ts +149 -0
  73. package/src/client/locales.ts +49 -1783
  74. package/src/client/market/MarketImportReview.tsx +2 -2
  75. package/src/client/market/MarketPanel.tsx +1 -1
  76. package/src/client/market/market-view.ts +3 -5
  77. package/src/client/recovery/RecoveryPanel.tsx +62 -1054
  78. package/src/client/recovery/SessionHealthCard.tsx +134 -0
  79. package/src/client/recovery/SessionHealthDialog.tsx +665 -0
  80. package/src/client/recovery/SessionLayoutSection.tsx +284 -0
  81. package/src/client/recovery/recovery-api.ts +10 -1
  82. package/src/client/recovery/recovery-panel-layout.test.ts +20 -5
  83. package/src/client/recovery/session-dialog-mount.test.ts +16 -9
  84. package/src/client/recovery/use-recovery-write.test.ts +90 -0
  85. package/src/client/recovery/use-recovery-write.ts +53 -0
  86. package/src/client/run-store.ts +57 -2
  87. package/src/client/sync/PushPreviewCard.tsx +2 -2
  88. package/src/client/sync/SyncConfirmView.tsx +5 -5
  89. package/src/client/sync/SyncLogList.tsx +2 -2
  90. package/src/client/sync/history-model.ts +4 -5
  91. package/src/client/sync/sync-view.ts +3 -4
  92. package/src/core/exporter.ts +2 -4
  93. package/src/core/host-schedulers/cache-cleanup.test.ts +84 -0
  94. package/src/core/host-schedulers/cache-cleanup.ts +74 -0
  95. package/src/core/host-schedulers/lifecycle-hooks.test.ts +111 -0
  96. package/src/core/host-schedulers/lifecycle-hooks.ts +118 -0
  97. package/src/core/host-schedulers/market-cache.test.ts +93 -0
  98. package/src/core/host-schedulers/market-cache.ts +116 -0
  99. package/src/core/model-tools.ts +2 -7
  100. package/src/core/restore-failure-state.test.ts +210 -0
  101. package/src/core/restore.ts +16 -18
  102. package/src/core/verify-recovery.ts +4 -7
  103. package/src/index.ts +76 -330
  104. package/src/profiles/dsh-profile-copy-rollback.test.ts +156 -0
  105. package/src/profiles/dsh-profile-manager.ts +71 -3
  106. package/src/routes/kit.ts +37 -0
  107. package/src/routes/prefs.ts +6 -6
  108. package/src/routes/recovery.ts +25 -42
  109. package/src/routes/route-support.ts +208 -1
  110. package/src/routes/snapshots.ts +4 -9
  111. package/src/routes/sync.ts +4 -7
  112. package/src/security/redaction.ts +29 -23
  113. package/src/sync/backup-scheduler.ts +3 -6
  114. package/src/sync/sync-config.test.ts +24 -13
  115. package/src/ui/backup-inspect.ts +1 -1
  116. package/src/ui/dsh-profiles-view.ts +3 -5
  117. package/src/ui/i18n.test.ts +8 -3
  118. package/src/ui/snapshots-view.ts +2 -2
  119. package/src/utils/paths.test.ts +36 -1
  120. package/src/utils/paths.ts +30 -6
  121. package/src/utils/time.test.ts +46 -0
  122. package/src/utils/time.ts +55 -0
package/src/index.ts CHANGED
@@ -55,13 +55,24 @@ import { dshHomePath, resolveDshHome } from '@deepseek-ai/dsh-home-paths'
55
55
  import type { WebRoute, WebServer } from '@deepseek-ai/dsh-host-webserver'
56
56
  import type { WorkspaceId } from '@deepseek-ai/dsh-workspace'
57
57
 
58
- import { endpoint, registerRoutes, requireJsonObject, writeJson, readJsonBody, errorMessage } from './routes/kit.ts'
58
+ import { endpoint, registerRoutes, requireJsonObject, writeJson, readJsonBody, errorMessage, writeMutationError } from './routes/kit.ts'
59
59
  import { buildRoutes } from './routes/index.ts'
60
60
  import type { RecoveryOrchestrator } from './core/recovery-orchestrator.ts'
61
61
  import type { Portability } from './core/types.ts'
62
62
  import { Exporter, FileSnapshotStore, Importer, verifySnapshot } from './core/index.ts'
63
63
  import { DshProfileLauncher, DshProfileManager, DshProfileRuntimeRegistry } from './profiles/index.ts'
64
64
  import { cleanupCaches } from './core/cache-cleaner.ts'
65
+ // tech-debt #23:宿主调度器下沉(纯调度语义可单测,index.ts 只留一次装配)。
66
+ import { createCacheCleanupScheduler } from './core/host-schedulers/cache-cleanup.ts'
67
+ import { createHostLifecycle } from './core/host-schedulers/lifecycle-hooks.ts'
68
+ import {
69
+ createMarketCacheLayout,
70
+ marketItemCached,
71
+ pruneStagedMarketZips as pruneMarketStagedZips,
72
+ readMarketCacheIndexText,
73
+ writeMarketItemCache,
74
+ } from './core/host-schedulers/market-cache.ts'
75
+ import type { HostLifecycle, StartupVerdict } from './core/host-schedulers/lifecycle-hooks.ts'
65
76
  import { isValidSnapshotId, planRestore } from './core/restore.ts'
66
77
  import { rollback as performRollback } from './core/rollback.ts'
67
78
  // Phase 1 P0-1/P0-2:配置生命周期(自动快照 / 撤销 / 重做)与 P0-5 崩溃归因。
@@ -106,10 +117,10 @@ import { probeSessionFormats, resolveSessionFormatVersion } from './utils/sessio
106
117
  import { describePatchYamlError, dumpPatchDocument, loadPatchDocument } from './utils/patch-yaml.ts'
107
118
  import { atomicCopyFile, atomicWriteFile } from './utils/atomic-write.ts'
108
119
  import { isENOENT } from './utils/guards.ts'
109
- import { EnvironmentLockManager, runWithMutationLock, EnvironmentLockUnavailableError, type MutationLockContext } from './utils/env-lock.ts'
120
+ import { EnvironmentLockManager, runWithMutationLock, type MutationLockContext } from './utils/env-lock.ts'
110
121
  import { activeProxySummary } from './utils/proxy.ts'
111
122
  import { listRecursiveFollowingLinks } from './utils/recursive-walk.ts'
112
- import { Phase3Recovery, TransactionRecoveryRequiredError, mapLockStateForStartup } from './core/phase3-host.ts'
123
+ import { Phase3Recovery, mapLockStateForStartup } from './core/phase3-host.ts'
113
124
  import type { JournalRunContext } from './core/phase3-host.ts'
114
125
  import { classifyStartup, FAIL_CLOSED_STARTUP, resolveStartupSafeMode } from './core/startup-barrier.ts'
115
126
  import type { MutationLockPort } from './utils/env-lock.ts'
@@ -134,7 +145,7 @@ import { selectPruneCandidates } from './core/backup.ts'
134
145
  import { appendAutosyncEntry } from './sync/sync-history.ts'
135
146
  import { MigrationStore, type MigrationKind, type MigrationResult, historyResultFromAutosyncStatus, MIGRATION_HISTORY_DIR } from './core/migration-history.ts'
136
147
  import { createHistoryPruner } from './core/history-prune.ts'
137
- import { validateRepoUrl, validateWebDavUrl, isWebDavConfig, isS3Config, isGistConfig, channelOf, parseSyncChannel, SYNC_CHANNELS, GIST_PROVIDER, isS3CompatProvider, validateCloudChannelInput, cloudSecretRef } from './sync/sync-config.ts'
148
+ import { isWebDavConfig, isS3Config, isGistConfig, channelOf, SYNC_CHANNELS, GIST_PROVIDER, cloudSecretRef } from './sync/sync-config.ts'
138
149
  import {
139
150
  resolveSessionFormatDisposition,
140
151
  sessionFormatAbortResponse,
@@ -158,19 +169,19 @@ import { StarCache } from './market/star-cache.ts'
158
169
  import { createConfiguredSecretScanner } from './security/secret-scanner.ts'
159
170
  import type { ConfiguredSecretPatterns } from './security/secret-scanner.ts'
160
171
  import type { SecretScanner } from './core/types.ts'
161
- import { sha256Hex } from './utils/hashing.ts'
162
172
  import { createTtlAsyncCache } from './utils/ttl-cache.ts'
163
173
  import { isFileSection, SECTION_IDS } from './schema/config.ts'
164
174
  import { stringifyJsonSafe } from './utils/json.ts'
165
175
  import type { SectionId, WorkspaceRecord } from './schema/types.ts'
166
176
  import { isSameOrChild } from './utils/paths.ts'
177
+ import { formatDateOnly } from './utils/time.ts'
167
178
  import { isRecord } from './utils/guards.ts'
168
179
  import { createLogger, parseLogLevel, type Logger } from './utils/logger.ts'
169
180
  // 与 HTTP 路径**同一份**「运行中对话」判据(命令入口绝不能各写一套)
170
181
  import { sessionActiveDenied, sessionActiveGateApplies } from './routes/recovery.ts'
171
182
 
172
183
  // P4:路由组共享的纯工具已下沉到 routes/route-support.ts —— 组文件不再反向 import 本文件。
173
- import { ROUTE_TIMEOUT_MS, SYNC_CREDENTIAL_REF, SYNC_WEBDAV_CREDENTIAL_REF, SyncRouteError, credentialRef, decryptErrorText, executeRestorePlan, isControlledPath, makeRestoreExecutor, safeCredentialRef, syncPasswordRef, tryDecryptCredentials, withTimeout } from './routes/route-support.ts'
184
+ import { ROUTE_TIMEOUT_MS, SYNC_CREDENTIAL_REF, SYNC_WEBDAV_CREDENTIAL_REF, credentialRef, decryptErrorText, executeRestorePlan, isControlledPath, makeRestoreExecutor, safeCredentialRef, syncPasswordRef, tryDecryptCredentials, withTimeout } from './routes/route-support.ts'
174
185
  export { ROUTE_TIMEOUT_MS, REVIEW_KINDS, SYNC_CREDENTIAL_REF, SYNC_ENCRYPT_PASSWORD_REF_PREFIX, SYNC_DECRYPT_PASSWORD_REF_PREFIX, SYNC_WEBDAV_CREDENTIAL_REF, SyncRouteError, buildAutosyncStatus, buildAutosyncStatusByChannel, buildFileDiffBody, buildRestoreBody, credentialRef, decryptErrorText, executeRestorePlan, extractSyncSections, extractSyncSessions, isAutosyncInterval, isControlledPath, isGitHubAuthMissing, isToolchainChangeItem, makeRestoreExecutor, parseMeForm, planToConfirmItems, safeCredentialRef, sessionHealthNextSteps, syncPasswordRef, tryDecryptCredentials, withTimeout, writeProfileError, writeRequestBodyToFile, writeSyncRouteError } from './routes/route-support.ts'
175
186
  export type { AutosyncStatusResponse, BuildFileDiffBodyResult, BuildRestoreBodyResult, RestoreExecutor, SyncConfirmItem } from './routes/route-support.ts'
176
187
 
@@ -183,7 +194,7 @@ export const name = 'config-manager'
183
194
  export const inject = ['settings', 'credentials']
184
195
 
185
196
  /** Plugin version, kept in sync with package.json ("version"). */
186
- export const PLUGIN_VERSION = '0.4.1'
197
+ export const PLUGIN_VERSION = '0.4.2'
187
198
 
188
199
  /** Plugin own package name — excluded from its own exported plugins list. */
189
200
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -2136,13 +2147,6 @@ export class ConfigManagerHostContext implements HostContext {
2136
2147
  /* ---------------------------------------------------------------- routes */
2137
2148
 
2138
2149
 
2139
- function dateStamp(d: Date = new Date()): string {
2140
- const y = d.getFullYear()
2141
- const m = String(d.getMonth() + 1).padStart(2, '0')
2142
- const day = String(d.getDate()).padStart(2, '0')
2143
- return `${y}-${m}-${day}`
2144
- }
2145
-
2146
2150
  /** Minimal real dependency check (MCP §15): `which`/`where` probe. */
2147
2151
  async function dependencyAvailable(command: string): Promise<boolean> {
2148
2152
  const probe = process.platform === 'win32' ? 'where' : 'which'
@@ -2219,202 +2223,12 @@ interface RoutesDeps {
2219
2223
  /* -------------------------------------------------- sync 路由(m-sync-ui) */
2220
2224
 
2221
2225
 
2222
- /** parseSyncBody 的凭据写入依赖(只用到 set;测试可注入内存 mock)。 */
2223
- export interface ParseSyncBodyDeps {
2224
- credentials: Pick<CredentialProvider, 'set'>
2225
- }
2226
-
2227
- /**
2228
- * 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
2229
- * 请求体形状(flat,M4 契约):
2230
- * - git: { transport:'git', repoUrl, token? } —— token 非空写 SYNC_CREDENTIAL_REF;
2231
- * git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
2232
- * - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
2233
- * 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
2234
- */
2235
- export async function parseSyncBody(
2236
- body: Record<string, unknown>,
2237
- deps: ParseSyncBodyDeps,
2238
- ): Promise<SyncConfig> {
2239
- const rawTransport = body['transport']
2240
- // 通道值解析:接受通道名(s3/gist);也接受**具体兼容商**(oss/cos/minio/kodo)直接落到 s3 通道
2241
- const transport = parseSyncChannel(rawTransport) ?? (isS3CompatProvider(rawTransport) ? 's3' : 'git')
2242
- if (transport === 's3') return parseCloudS3Body(body, rawTransport, deps)
2243
- if (transport === 'gist') return parseCloudGistBody(body, deps)
2244
- if (transport === 'webdav') {
2245
- const url = typeof body['url'] === 'string' ? body['url'].trim() : ''
2246
- if (url === '') throw new SyncRouteError('url is required for webdav')
2247
- const urlError = validateWebDavUrl(url)
2248
- if (urlError !== null) throw new SyncRouteError(urlError)
2249
- const username = typeof body['username'] === 'string' && body['username'] !== '' ? body['username'] : undefined
2250
- const password = typeof body['password'] === 'string' && body['password'] !== '' ? body['password'] : undefined
2251
- if (password !== undefined) {
2252
- try {
2253
- await deps.credentials.set(credentialRef(SYNC_WEBDAV_CREDENTIAL_REF), password)
2254
- } catch (error) {
2255
- const reason = error instanceof Error ? error.message : String(error)
2256
- throw new SyncRouteError(
2257
- engineMsg('host.syncWebdavPasswordWriteFailed', { reason, ref: SYNC_WEBDAV_CREDENTIAL_REF }),
2258
- )
2259
- }
2260
- }
2261
- return {
2262
- schemaVersion: 2,
2263
- transport: 'webdav',
2264
- webdav: { url, ...(username !== undefined ? { username } : {}) },
2265
- }
2266
- }
2267
- // git 通道(沿用现有逻辑)
2268
- const repoUrl = typeof body['repoUrl'] === 'string' ? body['repoUrl'].trim() : ''
2269
- if (repoUrl === '') throw new SyncRouteError('repoUrl is required')
2270
- const urlError = validateRepoUrl(repoUrl)
2271
- if (urlError !== null) throw new SyncRouteError(urlError)
2272
- const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined
2273
- if (token !== undefined) {
2274
- try {
2275
- await deps.credentials.set(credentialRef(SYNC_CREDENTIAL_REF), token)
2276
- } catch (error) {
2277
- const reason = error instanceof Error ? error.message : String(error)
2278
- throw new SyncRouteError(
2279
- engineMsg('host.syncTokenWriteFailed', { reason, ref: SYNC_CREDENTIAL_REF }),
2280
- )
2281
- }
2282
- }
2283
- return {
2284
- schemaVersion: 2,
2285
- transport: 'git',
2286
- git: { repoUrl },
2287
- }
2288
- }
2289
-
2290
- /** 请求体字段 → 去空白字符串(非字符串 = 空)。 */
2291
- function syncStr(value: unknown): string {
2292
- return typeof value === 'string' ? value.trim() : ''
2293
- }
2294
-
2295
- /** 云端点密钥写入失败 → 可操作错误(**含 ref 名、绝不含密钥值**)。 */
2296
- function cloudCredentialWriteError(ref: string, kind: string, error: unknown): SyncRouteError {
2297
- const reason = error instanceof Error ? error.message : String(error)
2298
- return new SyncRouteError(
2299
- engineMsg('host.syncCredentialWriteFailed', { kind, reason, ref }),
2300
- 400,
2301
- 'cloud.credentialsWriteFailed',
2302
- )
2303
- }
2226
+ // 请求体解析下沉到 routes/route-support.ts(tech-debt #23:组合根只留装配)。
2227
+ // 组合根继续导出这些符号,`src/index.sync.test.ts` 与既有调用方口径不变。
2228
+ import { mergePersistedWebDavUsername, parseSyncBody, webdavBaseUrl } from './routes/route-support.ts'
2304
2229
 
2305
- /**
2306
- * s3 通道请求体 → SyncConfig(provider 必填或由 transport 直接给出)。
2307
- * 非密字段按 validateCloudChannelInput 校验(错误码 = HTTP body.code,由 UI 映射字典);
2308
- * 密钥**只写**进 DSH credentials 的 cloudSecretRef(provider) 槽位,绝不进返回值 / 文件 / 日志。
2309
- */
2310
- async function parseCloudS3Body(
2311
- body: Record<string, unknown>,
2312
- rawTransport: unknown,
2313
- deps: ParseSyncBodyDeps,
2314
- ): Promise<SyncConfig> {
2315
- const provider = isS3CompatProvider(body['provider'])
2316
- ? body['provider']
2317
- : (isS3CompatProvider(rawTransport) ? rawTransport : null)
2318
- if (provider === null) {
2319
- throw new SyncRouteError('provider is required for s3 (s3/oss/cos/minio/kodo)', 400, 'cloud.providerUnknown')
2320
- }
2321
- const endpoint = syncStr(body['endpoint']).replace(/\/+$/, '')
2322
- const region = syncStr(body['region'])
2323
- const bucket = syncStr(body['bucket'])
2324
- const accessKeyId = syncStr(body['accessKeyId'])
2325
- const prefix = syncStr(body['prefix'])
2326
- const pathStyle = typeof body['pathStyle'] === 'boolean' ? body['pathStyle'] : undefined
2327
- const dialectId = body['dialectId'] === 'aws4' || body['dialectId'] === 'oss4' ? body['dialectId'] : undefined
2328
- const issue = validateCloudChannelInput(provider, {
2329
- endpoint,
2330
- region,
2331
- bucket,
2332
- accessKeyId,
2333
- ...(prefix === '' ? {} : { prefix }),
2334
- ...(pathStyle === undefined ? {} : { pathStyle }),
2335
- ...(dialectId === undefined ? {} : { dialectId }),
2336
- })
2337
- if (issue !== null) throw new SyncRouteError(issue, 400, issue)
2338
- const secret = typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined
2339
- if (secret !== undefined) {
2340
- const ref = cloudSecretRef(provider)
2341
- try {
2342
- await deps.credentials.set(credentialRef(ref), secret)
2343
- } catch (error) {
2344
- throw cloudCredentialWriteError(ref, engineMsg('host.syncKindS3Secret'), error)
2345
- }
2346
- }
2347
- return {
2348
- schemaVersion: 2,
2349
- transport: 's3',
2350
- s3: {
2351
- provider,
2352
- endpoint,
2353
- region,
2354
- bucket,
2355
- accessKeyId,
2356
- ...(prefix === '' ? {} : { prefix }),
2357
- ...(pathStyle === undefined ? {} : { pathStyle }),
2358
- ...(dialectId === undefined ? {} : { dialectId }),
2359
- },
2360
- }
2361
- }
2362
-
2363
- /**
2364
- * gist 通道请求体 → SyncConfig。token 只写进 cloudSecretRef('gist') 槽位
2365
- * (请求体字段名 token 或 secret 都接受;值绝不进返回值 / 文件 / 日志)。
2366
- */
2367
- async function parseCloudGistBody(body: Record<string, unknown>, deps: ParseSyncBodyDeps): Promise<SyncConfig> {
2368
- const gistId = syncStr(body['gistId'])
2369
- const apiBaseUrl = syncStr(body['apiBaseUrl'])
2370
- const filePrefix = syncStr(body['filePrefix'])
2371
- const issue = validateCloudChannelInput(GIST_PROVIDER, {
2372
- gistId,
2373
- ...(apiBaseUrl === '' ? {} : { apiBaseUrl }),
2374
- ...(filePrefix === '' ? {} : { filePrefix }),
2375
- })
2376
- if (issue !== null) throw new SyncRouteError(issue, 400, issue)
2377
- const token = typeof body['token'] === 'string' && body['token'] !== ''
2378
- ? body['token']
2379
- : (typeof body['secret'] === 'string' && body['secret'] !== '' ? body['secret'] : undefined)
2380
- if (token !== undefined) {
2381
- const ref = cloudSecretRef(GIST_PROVIDER)
2382
- try {
2383
- await deps.credentials.set(credentialRef(ref), token)
2384
- } catch (error) {
2385
- throw cloudCredentialWriteError(ref, 'Gist token', error)
2386
- }
2387
- }
2388
- return {
2389
- schemaVersion: 2,
2390
- transport: 'gist',
2391
- gist: {
2392
- gistId,
2393
- ...(apiBaseUrl === '' ? {} : { apiBaseUrl }),
2394
- ...(filePrefix === '' ? {} : { filePrefix }),
2395
- },
2396
- }
2397
- }
2398
-
2399
- /** 由 SyncConfig 合成 WebDAV 通道 baseUrl(webdav.url,尾部规范化带 '/';git 通道返回 '')。 */
2400
- export function webdavBaseUrl(cfg: SyncConfig): string {
2401
- if (!isWebDavConfig(cfg)) return ''
2402
- return cfg.webdav.url.replace(/\/+$/, '') + '/'
2403
- }
2404
-
2405
- /**
2406
- * 补全 webdav 配置缺失的 username(从持久化配置回填;纯函数,不修改入参)。
2407
- * 语义与 password 一致:请求未带 username(表单留空/挂载自动加载)→ 沿用已保存的值;
2408
- * 请求显式带 username → 原样保留(用户新输入优先)。非 webdav / 无持久化 → 原样返回。
2409
- */
2410
- export function mergePersistedWebDavUsername(cfg: SyncConfig, persisted: SyncConfig | null): SyncConfig {
2411
- if (!isWebDavConfig(cfg) || (cfg.webdav.username !== undefined && cfg.webdav.username !== '')) return cfg
2412
- if (persisted !== null && isWebDavConfig(persisted)
2413
- && typeof persisted.webdav.username === 'string' && persisted.webdav.username !== '') {
2414
- return { ...cfg, webdav: { ...cfg.webdav, username: persisted.webdav.username } }
2415
- }
2416
- return cfg
2417
- }
2230
+ export { mergePersistedWebDavUsername, parseSyncBody, webdavBaseUrl } from './routes/route-support.ts'
2231
+ export type { ParseSyncBodyDeps } from './routes/route-support.ts'
2418
2232
 
2419
2233
  /** /status 的插件诊断位(issue #28)。仅回非敏感元信息:目录、profile 名、计数。 */
2420
2234
  export interface PluginDiagnostics {
@@ -2759,18 +2573,9 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
2759
2573
  }
2760
2574
  })
2761
2575
  } catch (error) {
2762
- if (error instanceof EnvironmentLockUnavailableError) {
2763
- // 内部诊断(op/reason)进日志;用户只看到友好文案(error.message 恒为中文友好版,
2764
- // 不暴露环境锁/op/路径等技术细节)。
2765
- host.log.warn(`mutation lock blocked: op=${error.op} reason=${error.reason}${error.detail !== undefined ? ` detail=${error.detail}` : ''}`)
2766
- writeJson(res, 423, { error: error.message, code: 'mutation-locked' })
2767
- return
2768
- }
2769
- // 非 423:若已由 runJournaled 置 SAFE MODE/失败,保持既有错误语义(400/500)
2770
- if (error instanceof TransactionRecoveryRequiredError) {
2771
- writeJson(res, 423, { error: error.message, code: 'transaction-recovery-required' })
2772
- return
2773
- }
2576
+ // 423 家族(SAFE MODE / 环境锁 / 未收敛事务)的唯一映射在 routes/kit.ts 的 writeMutationError;
2577
+ // 其余错误**必须 rethrow** —— endpoint() 的出口与救急台的 errorRenderer 都依赖这条抛出。
2578
+ if (writeMutationError(res, host, error)) return
2774
2579
  throw error
2775
2580
  }
2776
2581
  }
@@ -3023,12 +2828,11 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
3023
2828
  // ------------------------------------------------ market 辅助(m-market)
3024
2829
  // 目录:<marketDir>/cache/<url-hash>/(index/条目缓存)
3025
2830
  // + <marketDir>/work/<url-hash>/(git 只读工作副本,--depth 1)。无任何凭据。
3026
- const marketCacheRoot = join(marketDir, 'cache')
3027
- const marketWorkRoot = join(marketDir, 'work')
3028
- const urlHash = (url: string) => sha256Hex(url).slice(0, 32)
3029
- const marketCacheIndex = (url: string) => join(marketCacheRoot, urlHash(url), 'index.json')
3030
- const marketCacheItemDir = (url: string) => join(marketCacheRoot, urlHash(url), 'items')
3031
- const marketWorkDir = (url: string) => join(marketWorkRoot, urlHash(url))
2831
+ // 布局与暂存 GC 的下沉实现见 core/host-schedulers/market-cache.ts(可单测)。
2832
+ const marketCache = createMarketCacheLayout(marketDir)
2833
+ const marketCacheIndex = marketCache.cacheIndex
2834
+ const marketCacheItemDir = marketCache.itemDir
2835
+ const marketWorkDir = marketCache.workDir
3032
2836
 
3033
2837
  /**
3034
2838
  * 进程生命周期标记:本次 dsh 启动后市场是否已成功刷新过一次(内存态,dsh 重启后自动归零)。
@@ -3056,13 +2860,10 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
3056
2860
 
3057
2861
  /** 读缓存的 index.json(结构校验通过才返回,否则 null)。 */
3058
2862
  async function readCachedIndexObj(url: string): Promise<MarketIndex | null> {
3059
- try {
3060
- const raw = await fs.readFile(marketCacheIndex(url), 'utf8')
3061
- const res = parseMarketIndex(raw)
3062
- return res.ok ? res.index : null
3063
- } catch {
3064
- return null
3065
- }
2863
+ const raw = await readMarketCacheIndexText(marketCache, url)
2864
+ if (raw === null) return null
2865
+ const res = parseMarketIndex(raw)
2866
+ return res.ok ? res.index : null
3066
2867
  }
3067
2868
 
3068
2869
  /** 由配置条目构建市场摘要(name/itemCount/lastFetchedAt 来自缓存 index,可空)。 */
@@ -3081,50 +2882,17 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
3081
2882
  }
3082
2883
 
3083
2884
  /** 条目是否已有完整缓存(manifest + config.zip)。 */
3084
- async function itemCached(url: string, itemId: string): Promise<boolean> {
3085
- try {
3086
- await fs.access(join(marketCacheItemDir(url), itemId, 'config.zip'))
3087
- await fs.access(join(marketCacheItemDir(url), itemId, 'manifest.json'))
3088
- return true
3089
- } catch {
3090
- return false
3091
- }
3092
- }
2885
+ const itemCached = (url: string, itemId: string): Promise<boolean> => marketItemCached(marketCache, url, itemId)
3093
2886
 
3094
2887
  /** 写条目缓存(manifest + config.zip)供离线重复查看。内容始终视为不可信。 */
3095
- async function writeItemCache(url: string, itemId: string, manifestRaw: string, zipBytes: Uint8Array): Promise<void> {
3096
- const dir = join(marketCacheItemDir(url), itemId)
3097
- await fs.mkdir(dir, { recursive: true })
3098
- await fs.writeFile(join(dir, 'manifest.json'), manifestRaw, 'utf8')
3099
- await fs.writeFile(join(dir, 'config.zip'), zipBytes)
3100
- }
2888
+ const writeItemCache = (url: string, itemId: string, manifestRaw: string, zipBytes: Uint8Array): Promise<void> =>
2889
+ writeMarketItemCache(marketCache, url, itemId, manifestRaw, zipBytes)
3101
2890
 
3102
2891
  /**
3103
- * 清理滞留在 tmpDir 的过期市场暂存 zip(market-*.zip)。
3104
- * market/download 每次暂存新 zip 前调用(懒 GC):保留最近 RETENTION_MS 内的(供刚下载
3105
- * 后立即执行的 /execute 消费),清理更旧的 —— 防止未确认导入的暂存文件无限堆积。
3106
- * 一次性尽力而为:任何读取/删除失败不影响主流程。
2892
+ * 清理滞留在 tmpDir 的过期市场暂存 zip(market-*.zip / publish-*.zip)。
2893
+ * market/download 每次暂存新 zip 前调用(懒 GC);保留期与尽力而为语义见 market-cache.ts。
3107
2894
  */
3108
- const MARKET_TMP_RETENTION_MS = 10 * 60 * 1000
3109
- async function pruneStagedMarketZips(): Promise<void> {
3110
- try {
3111
- const names = await fs.readdir(tmpDir)
3112
- const now = Date.now()
3113
- for (const name of names) {
3114
- // market-*.zip(未确认导入的暂存)与 publish-*.zip(发布向导产物)都纳入保留策略
3115
- if ((!name.startsWith('market-') && !name.startsWith('publish-')) || !name.endsWith('.zip')) continue
3116
- const p = join(tmpDir, name)
3117
- try {
3118
- const st = await fs.stat(p)
3119
- if (now - st.mtimeMs > MARKET_TMP_RETENTION_MS) await fs.rm(p, { force: true, recursive: true })
3120
- } catch {
3121
- // 单文件 stat/删除失败 → 跳过(尽力而为)
3122
- }
3123
- }
3124
- } catch {
3125
- // tmpDir 读取失败 → 跳过(尽力而为)
3126
- }
3127
- }
2895
+ const pruneStagedMarketZips = async (): Promise<void> => { await pruneMarketStagedZips(tmpDir) }
3128
2896
 
3129
2897
  // -------------------------------------------------- me 装配(m-my-configs)
3130
2898
  // 「一键上传 / 我的配置」:GitHub REST 客户端 + 上传编排。
@@ -3427,7 +3195,7 @@ function makeRoutes(deps: RoutesDeps): { routes: WebRoute[]; scheduler: AutoSync
3427
3195
  }
3428
3196
  const desiredName = customFileName !== null
3429
3197
  ? customFileName
3430
- : `dsh-config-${dateStamp()}-${randomBytes(3).toString('hex')}.zip`
3198
+ : `dsh-config-${formatDateOnly(new Date())}-${randomBytes(3).toString('hex')}.zip`
3431
3199
  const finalFileName = resolveNonCollidingExportName(desiredName, existingExportNames)
3432
3200
  const outPath = join(exportsDir, finalFileName)
3433
3201
  // m1:执行开始注册 run(同 kind 已有进行中任务 → 409 拒绝,防止重复导出)
@@ -3928,11 +3696,11 @@ export function apply(ctx: Context, config?: Config): void {
3928
3696
  host.log.warn('Phase 3 SAFE MODE 激活:存在未恢复的 transaction,destructive 操作被阻断(如需恢复请先显式处理)')
3929
3697
  }
3930
3698
  // P1-B:启动 recovery 分类 barrier。调度器(AutoSync/Backup)只在分类完成且 state=NORMAL 时启动。
3931
- // schedulerGate.start 由 makeRoutes 返回 scheduler + apply 构造 backupScheduler 后赋值;apply 为同步,
3932
- // 故在该异步分类块 await 完成前,schedulerGate.start 通常已就绪。fail-closed:分类抛错 → 不启动调度器。
3933
- const schedulerGate = { start: null as (() => void) | null }
3934
- let startupStateResolved = false
3935
- let shouldStartSchedulers = false
3699
+ // 启停 / 退出兜底释放锁 / 实例心跳的装配下沉到 core/host-schedulers/lifecycle-hooks.ts:
3700
+ // 这里只把分类结论投给它,arm 与 classify 谁先到都收敛到同一结果。
3701
+ // fail-closed:分类抛错 → 结论 BLOCKED(终态)→ 调度器不启动。
3702
+ const lifecycleRef: { current: HostLifecycle | null } = { current: null }
3703
+ const startupVerdictRef: { value: StartupVerdict | null } = { value: null }
3936
3704
  void (async () => {
3937
3705
  try {
3938
3706
  await phase3Recovery.initFingerprint()
@@ -3953,7 +3721,6 @@ export function apply(ctx: Context, config?: Config): void {
3953
3721
  lockState: mapLockStateForStartup(lockInsp.state),
3954
3722
  })
3955
3723
  const { state } = await startupState.classify()
3956
- startupStateResolved = true
3957
3724
  // 残留锁自愈(可证 stale 回收 + 孤儿心跳清理),判定与理由见 core/env-lock-lifecycle.ts。
3958
3725
  const effectiveLockState = await reclaimStaleLockAtStartup({ kind: state.kind, inspected: lockInsp.state, lock: envLockManager, log: host.log })
3959
3726
  // issue #87:分类结论才是本轮权威。NORMAL 且没有活锁者 ⇒ 上一轮留下的 durable SAFE MODE 是**陈旧标记**
@@ -3969,12 +3736,12 @@ export function apply(ctx: Context, config?: Config): void {
3969
3736
  await phase3Recovery.clearSafeMode().catch(() => undefined)
3970
3737
  host.log.info('Phase 3 启动分类 NORMAL:上一轮遗留的 SAFE MODE 标记已复位(无未决事务、无活锁者)')
3971
3738
  }
3972
- shouldStartSchedulers = (state.kind === 'NORMAL')
3739
+ const verdict: StartupVerdict = state.kind === 'NORMAL' ? 'NORMAL' : 'BLOCKED'
3740
+ startupVerdictRef.value = verdict
3973
3741
  if (state.kind === 'RECOVERY_REQUIRED' || state.kind === 'NEEDS_ATTENTION') {
3974
3742
  host.log.warn(`Phase 3 ${state.kind}:上次 destructive operation 崩溃残留,需显式恢复;destructive 调度器未启动(read-only host 存活)`)
3975
- } else if (shouldStartSchedulers && schedulerGate.start !== null) {
3976
- schedulerGate.start()
3977
3743
  }
3744
+ lifecycleRef.current?.onStartupClassified(verdict)
3978
3745
  // Phase 1 P0-5:启动分类已得出结论 → 本次启动判定为成功(推进 lastGoodAt)。
3979
3746
  // 灾备总开关关闭时不写 boot-state。
3980
3747
  try {
@@ -3987,8 +3754,8 @@ export function apply(ctx: Context, config?: Config): void {
3987
3754
  // fail-open —— 此刻无法证明环境干净,destructive 路由必须一并被阻断:置内存 SAFE MODE
3988
3755
  // (isBlocked 谓词立即生效)+ 写 durable 标记(下次启动不判 NORMAL),与 phase3-host.ts
3989
3756
  // runJournaled 异常分支的姿态一致。清理通道仍是用户显式 recovery(clearSafeMode)。
3990
- startupStateResolved = true
3991
- shouldStartSchedulers = FAIL_CLOSED_STARTUP.startSchedulers
3757
+ // 分类抛错时保留 null:接线期若仍无结论,lifecycle 不会启动调度器(fail-closed 的第一道)。
3758
+ startupVerdictRef.value = FAIL_CLOSED_STARTUP.startSchedulers ? 'NORMAL' : 'BLOCKED'
3992
3759
  if (FAIL_CLOSED_STARTUP.safeModeRequired) {
3993
3760
  phase3Recovery.safeModeActive = true
3994
3761
  await phase3Recovery.store.writeSafeMode(true).catch(() => undefined)
@@ -4002,12 +3769,11 @@ export function apply(ctx: Context, config?: Config): void {
4002
3769
  })
4003
3770
  }
4004
3771
  })()
4005
- // 缓存自动清理:启动即清一次 + 每 24h 定时清一次。
3772
+ // 缓存自动清理:启动即清一次 + 每 24h 定时清一次(调度语义见 core/host-schedulers/cache-cleanup.ts)。
4006
3773
  // 只清「可重建/一次性」缓存与临时文件(tmp 暂存、exports 导出副本、market cache/work),
4007
3774
  // 保留期内的文件不删(供刷新恢复导入/下载等窗口继续消费);snapshots 与 sync 属用户数据/安全网不动。
4008
- // 尽力而为:任何失败仅记日志,不影响插件挂载与其他功能。
4009
- const runCacheCleanup = (): void => {
4010
- void cleanupCaches({
3775
+ const cacheCleanup = createCacheCleanupScheduler({
3776
+ cleanup: () => cleanupCaches({
4011
3777
  tmpDir,
4012
3778
  exportsDir,
4013
3779
  // 定时备份产物(dsh-config-auto-*)豁免按天回收:保留策略归 BackupScheduler
@@ -4015,20 +3781,12 @@ export function apply(ctx: Context, config?: Config): void {
4015
3781
  exportsExemptPrefix: AUTO_BACKUP_PREFIX,
4016
3782
  marketCacheRoot: join(marketDir, 'cache'),
4017
3783
  marketWorkRoot: join(marketDir, 'work'),
4018
- })
4019
- .then((report) => {
4020
- if (report.removed > 0) {
4021
- host.log.info('缓存自动清理完成', { removed: report.removed, freedBytes: report.freedBytes })
4022
- }
4023
- })
4024
- .catch((error) => {
4025
- host.log.warn('缓存自动清理失败', { error: error instanceof Error ? error.message : String(error) })
4026
- })
4027
- }
4028
- runCacheCleanup()
4029
- const cacheCleanupTimer = setInterval(runCacheCleanup, CACHE_CLEANUP_INTERVAL_MS)
4030
- ctx.effect(() => () => clearInterval(cacheCleanupTimer), 'config-manager: cache cleanup scheduler')
4031
- // self 分区目录(相对 ~/.dsh 根):dataDir 在 homeDir 下 → 用相对路径挂载 self adapter;
3784
+ }),
3785
+ intervalMs: CACHE_CLEANUP_INTERVAL_MS,
3786
+ log: host.log,
3787
+ })
3788
+ cacheCleanup.start()
3789
+ ctx.effect(() => () => cacheCleanup.dispose(), 'config-manager: cache cleanup scheduler')
4032
3790
  // 自定义 dataDir 位于 ~/.dsh 之外时 Host fs 门面无法覆盖(confined to home root),
4033
3791
  // 不挂 self 分区并告警(其余分区不受影响)。
4034
3792
  const selfRel = relative(homeDir, dataDir)
@@ -4133,33 +3891,21 @@ export function apply(ctx: Context, config?: Config): void {
4133
3891
  // M1:与 HTTP 导出路由同一个 scanner(G-09 文件类分区凭据告警在两条路径上一致)。
4134
3892
  scanner: secretScanner,
4135
3893
  })
4136
- // P1-B:backupScheduler 不再同步 start —— 由启动 recovery 分类完成后(仅 NORMAL)启动。
4137
- schedulerGate.start = () => {
4138
- scheduler.start();
4139
- backupScheduler.start();
4140
- }
4141
- // 若启动分类已在此构造完成前解析为 NORMAL(罕见竞态),立即补启动。
4142
- if (startupStateResolved && shouldStartSchedulers && schedulerGate.start !== null) { schedulerGate.start(); }
4143
- ctx.effect(() => () => backupScheduler.stop(), 'config-manager: backup scheduler')
4144
- // 自动同步调度器随插件生命周期停止:插件重载/卸载时清理定时器,
4145
- // 避免旧调度器残留导致重复后台同步。
4146
- ctx.effect(() => () => scheduler.stop(), 'config-manager: autosync scheduler')
4147
- // 退出兜底释放环境锁:关窗时若后台同步正在跑,各入口的 finally 等不到 ⇒ 锁留盘(见 core/env-lock-lifecycle.ts)。
4148
- // 强杀 / 崩溃 / 断电仍靠下次启动的自动回收兜底。
4149
- const releaseLockOnExit = createExitLockReleaser(envLockManager)
4150
- process.once('exit', releaseLockOnExit)
4151
- ctx.effect(() => () => {
4152
- process.removeListener('exit', releaseLockOnExit)
4153
- releaseLockOnExit()
4154
- }, 'config-manager: environment lock exit release')
4155
- // m-profiles:实例心跳(自报 + 定期刷新);dispose 时撤回自己的心跳文件,别让别人把死实例当成活的。
4156
- ctx.effect(() => {
4157
- const stopHeartbeat = profileRuntime.startHeartbeat()
4158
- return () => {
4159
- stopHeartbeat()
4160
- profileRuntime.withdraw()
4161
- }
4162
- }, 'config-manager: profile runtime heartbeat')
3894
+ // P1-B:backupScheduler 与 autosync scheduler 都不在构造期启动 —— 由启动分类结论驱动(仅 NORMAL)。
3895
+ // 启停顺序、卸载清理、退出兜底释放环境锁、实例心跳统一在 lifecycle-hooks 里装配(可单测)。
3896
+ const lifecycle = createHostLifecycle({
3897
+ scheduler,
3898
+ backupScheduler,
3899
+ releaseLockOnExit: createExitLockReleaser(envLockManager),
3900
+ profileRuntime,
3901
+ effect: (label, setup) => { ctx.effect(setup, label) },
3902
+ })
3903
+ lifecycle.mount()
3904
+ lifecycleRef.current = lifecycle
3905
+ lifecycle.arm()
3906
+ // 分类结论若已先到(异步 barrier 抢在接线前跑完),补投一次;重复投递无副作用。
3907
+ const pendingVerdict = startupVerdictRef.value
3908
+ if (pendingVerdict !== null) lifecycle.onStartupClassified(pendingVerdict)
4163
3909
  // ------------------------------------------- S1:回合自动留点(宿主真接线)
4164
3910
  //
4165
3911
  // 订阅 `session/event`(@deepseek-ai/dsh-session 的 post-commit fire-and-forget feed)。