dsh-config-manager 0.5.0 → 0.7.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.
- package/lib/client.d.ts +8 -0
- package/lib/client.js +748 -602
- package/lib/core/local-plugin-host.d.ts +9 -0
- package/lib/core/local-plugin-host.js +174 -1
- package/lib/core/messages.d.ts +7 -0
- package/lib/core/messages.js +16 -0
- package/lib/core/migration-history.d.ts +40 -0
- package/lib/core/migration-history.js +55 -0
- package/lib/core/plugin-cli.d.ts +5 -0
- package/lib/core/plugin-cli.js +11 -3
- package/lib/core/run-registry.d.ts +10 -0
- package/lib/core/run-registry.js +17 -0
- package/lib/index.d.ts +7 -2
- package/lib/index.js +20 -19
- package/lib/profiles/dsh-profile-manager.d.ts +1 -1
- package/lib/profiles/dsh-profile-manager.js +26 -7
- package/lib/profiles/dsh-profile-shared.d.ts +3 -1
- package/lib/routes/import.js +6 -1
- package/lib/routes/route-support.d.ts +2 -1
- package/lib/routes/route-support.js +8 -3
- package/lib/routes/sync.js +5 -2
- package/lib/sync/autosync-config.d.ts +9 -1
- package/lib/sync/autosync-config.js +10 -2
- package/lib/sync/autosync-scheduler.js +18 -6
- package/lib/sync/git/git-transport.d.ts +31 -1
- package/lib/sync/git/git-transport.js +119 -23
- package/lib/sync/sync-config.d.ts +34 -3
- package/lib/sync/sync-config.js +38 -5
- package/lib/ui/sync-repository-picker.d.ts +21 -0
- package/lib/ui/sync-repository-picker.js +18 -0
- package/lib/ui/sync-settings-view.d.ts +4 -0
- package/lib/ui/sync-settings-view.js +3 -0
- package/lib/utils/remove-tree.d.ts +7 -0
- package/lib/utils/remove-tree.js +265 -0
- package/package.json +1 -1
- package/src/client/config-manager.module.css +21 -1
- package/src/client/environment/EnvironmentPanel.tsx +2 -2
- package/src/client/locales/profiles.ts +2 -0
- package/src/client/run-store.test.ts +1 -1
- package/src/client/run-store.ts +5 -0
- package/src/client/sync/ChannelConfigDialog.tsx +47 -2
- package/src/client/sync/SyncPanel.tsx +17 -30
- package/src/client/sync/SyncRepositoryPicker.tsx +34 -13
- package/src/client/sync/SyncSettingsView.test.ts +32 -0
- package/src/client/sync/config-save-state.test.ts +99 -0
- package/src/client/sync/config-save-state.ts +69 -0
- package/src/client/sync/sync-api.ts +2 -0
- package/src/client/sync/sync-locales.ts +10 -0
- package/src/core/engine-locale.test.ts +4 -0
- package/src/core/local-plugin-host.test.ts +31 -2
- package/src/core/local-plugin-host.ts +175 -2
- package/src/core/messages.ts +16 -0
- package/src/core/migration-history.test.ts +65 -0
- package/src/core/migration-history.ts +70 -0
- package/src/core/plugin-cli.fs.test.ts +30 -3
- package/src/core/plugin-cli.ts +11 -3
- package/src/core/run-registry-runs.test.ts +26 -1
- package/src/core/run-registry.ts +18 -0
- package/src/index.sync.test.ts +27 -0
- package/src/index.ts +21 -21
- package/src/profiles/dsh-profile-manager.test.ts +20 -0
- package/src/profiles/dsh-profile-manager.ts +25 -7
- package/src/profiles/dsh-profile-shared.ts +2 -0
- package/src/routes/import.ts +6 -1
- package/src/routes/route-support.ts +7 -3
- package/src/routes/sync.ts +5 -2
- package/src/sync/autosync-config.ts +10 -2
- package/src/sync/autosync-scheduler.test.ts +61 -1
- package/src/sync/autosync-scheduler.ts +17 -5
- package/src/sync/git/git-transport.test.ts +117 -0
- package/src/sync/git/git-transport.ts +131 -23
- package/src/sync/sync-config.test.ts +59 -1
- package/src/sync/sync-config.ts +51 -5
- package/src/ui/sync-repository-picker.test.ts +34 -1
- package/src/ui/sync-repository-picker.ts +24 -0
- package/src/ui/sync-settings-view.test.ts +1 -0
- package/src/ui/sync-settings-view.ts +7 -0
- package/src/utils/remove-tree.test.ts +120 -0
- package/src/utils/remove-tree.ts +239 -0
package/src/index.ts
CHANGED
|
@@ -107,6 +107,7 @@ import { PROJECT_KEY_RE, readLogCwdFromBytes, rewriteSessionLogDir } from './uti
|
|
|
107
107
|
import { probeSessionFormats, resolveSessionFormatVersion } from './utils/session-format.ts'
|
|
108
108
|
import { describePatchYamlError, dumpPatchDocument, loadPatchDocument } from './utils/patch-yaml.ts'
|
|
109
109
|
import { atomicCopyFile, atomicWriteFile } from './utils/atomic-write.ts'
|
|
110
|
+
import { removeTree } from './utils/remove-tree.ts'
|
|
110
111
|
import { isENOENT } from './utils/guards.ts'
|
|
111
112
|
import { EnvironmentLockManager, runWithMutationLock, type MutationLockContext, type MutationLockPort } from './utils/env-lock.ts'
|
|
112
113
|
import { activeProxySummary } from './utils/proxy.ts'
|
|
@@ -131,7 +132,7 @@ import type { RetentionPolicy } from './sync/retention-policy.ts'
|
|
|
131
132
|
import type { PruneSelector } from './core/backup.ts'
|
|
132
133
|
import { selectPruneCandidates } from './core/backup.ts'
|
|
133
134
|
import { appendAutosyncEntry } from './sync/sync-history.ts'
|
|
134
|
-
import { MigrationStore, type MigrationKind, type MigrationResult,
|
|
135
|
+
import { MigrationStore, type MigrationKind, type MigrationResult, autosyncUnifiedHistoryInput, MIGRATION_HISTORY_DIR } from './core/migration-history.ts'
|
|
135
136
|
import { createHistoryPruner } from './core/history-prune.ts'
|
|
136
137
|
import { isWebDavConfig, isS3Config, isGistConfig, channelOf, SYNC_CHANNELS, GIST_PROVIDER, cloudSecretRef } from './sync/sync-config.ts'
|
|
137
138
|
import {
|
|
@@ -182,7 +183,7 @@ export const name = 'config-manager'
|
|
|
182
183
|
export const inject = ['settings', 'credentials']
|
|
183
184
|
|
|
184
185
|
/** Plugin version, kept in sync with package.json ("version"). */
|
|
185
|
-
export const PLUGIN_VERSION = '0.
|
|
186
|
+
export const PLUGIN_VERSION = '0.7.0'
|
|
186
187
|
|
|
187
188
|
/** Plugin own package name — excluded from its own exported plugins list. */
|
|
188
189
|
const PLUGIN_NAME = 'dsh-config-manager'
|
|
@@ -1831,8 +1832,12 @@ export class DshFileSystemFacade implements FileSystemFacade {
|
|
|
1831
1832
|
await atomicCopyFile(this.abs(from), this.abs(to))
|
|
1832
1833
|
}
|
|
1833
1834
|
|
|
1835
|
+
/**
|
|
1836
|
+
* 递归删除(home 内,缺失目标视为成功)。**不用 fs.rm(recursive)**:目录里有悬空链接时它静默
|
|
1837
|
+
* 空转(报告写「已还原」而磁盘原样在)。removeTree 逐条删、只删链接本身、删不净就抛错。
|
|
1838
|
+
*/
|
|
1834
1839
|
async remove(relPath: string): Promise<void> {
|
|
1835
|
-
await
|
|
1840
|
+
await removeTree(this.abs(relPath))
|
|
1836
1841
|
}
|
|
1837
1842
|
|
|
1838
1843
|
/** 仅路径列表(既有契约):委托 listRecursiveDetailed,丢弃诊断。 */
|
|
@@ -2171,7 +2176,7 @@ const WEBDAV_TIMEOUT_MS = 120_000
|
|
|
2171
2176
|
* (见 W1 报告的重测配方),把结果落到这里;makeRoutes 里的 const routeEnv: RouteEnvInferred =
|
|
2172
2177
|
* 注解保证两侧不漂移(新增依赖漏登记会在构造点报错)。
|
|
2173
2178
|
*/
|
|
2174
|
-
export type RouteEnvInferred = { sessionExportFetch: ((input: string, init: RequestInit) => Promise<Response>) | undefined; sessionExportPort: number | undefined; adapters: ConfigAdapter<unknown>[]; sessionHealth: { homeDir: string; targetFormatVersion: () => number | undefined; workspaceKeys: () => Promise<ReadonlySet<string>>; knownSessionIds: () => Promise<ReadonlySet<string>>; sessionMeta: (ids: readonly string[]) => Promise<SessionMetaIndex>; }; backupScheduler: BackupScheduler; bootSafetyAudit: () => Promise<BootSafetyReport>; cancelDecisionTimeoutMs: number; buildMarketSummary: (e: { url: string; addedAt: string; }) => Promise<MarketSummary>; credentials: CredentialProvider; dataDir: string; exportsDir: string; syncRootDir: string; syncScope: SyncScope; githubAuth: GitHubAuthClient; githubClientId: string | undefined; githubClientSecret: string | undefined; githubFlows: DeviceFlowStore; history: MigrationStore; host: ConfigManagerHostContext; itemCached: (url: string, itemId: string) => Promise<boolean>; knownSyncSectionIds: Set<SectionId>; makeImporter: () => Importer; makeMarketReader: () => GitMarketReader; makeRecoveryExecutors: (runId: string) => RecoveryExecutorFns; makeSyncEngine: (cfg: SyncConfig, engineOpts?: { optInSections?: readonly SectionId[]; }) => SyncEngine; marketBootAutoRefreshed: { value: boolean; }; marketCacheIndex: (url: string) => string; marketDir: string; marketCacheItemDir: (url: string) => string; marketStarCache: StarCache; marketWorkDir: (url: string) => string; meGitHubRest: GitHubAuthRest; meService: MyRepoService; meTokenProvider: () => Promise<string>; msg: MsgFunc; prepareSync: (body: Record<string, unknown>) => Promise<SyncConfig>; pluginVersion: string; profileLauncher: DshProfileLauncher; profileRuntime: DshProfileRuntimeRegistry; profiles: DshProfileManager; pruneStagedMarketZips: () => Promise<void>; readCachedIndexObj: (url: string) => Promise<MarketIndex | null>; recoveryOrchestrator: RecoveryOrchestrator; resolveSyncPassword: (ref: string) => Promise<string | undefined>; roots: string[]; runAbortControllers: Map<string, AbortController>; runCancels: Map<string, { signal: AbortController; settle: (d: 'rollback' | 'keep') => void; decided: boolean }>; runs: RunRegistry; scheduler: AutoSyncScheduler; selectionCache: Partial<Record<SyncTransportType, SyncSelection>>; selectionOptInSections: (channel: SyncTransportType, onlyAuto?: boolean) => SectionId[]; selectionView: (channel: SyncTransportType) => Promise<SelectionView>; selectionViewByChannel: () => Promise<Record<SyncTransportType, SelectionView>>; snapshotEntrySections: (snapshotDir: string) => Promise<string[]>; snapshotsDir: string; starPromptRepoUrl: string; syncCredentialsByChannelView: () => Promise<Record<SyncTransportType, { encryptPasswordConfigured: boolean; decryptPasswordConfigured: boolean; }>>; syncDir: string; syncPasswordConfigured: (ref: string) => Promise<boolean>; syncWorkDir: { inspect: (repoUrl: string, opts?: { detail?: boolean; }) => Promise<{ facts: GitWorkDirFacts; } | { error: string; }>; rebuild: (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone') => Promise<GitWorkDirFacts>; }; syncSectionCatalog: { id: SectionId; displayName: string; portability: Portability; defaultIncluded: boolean; }[]; syncSessions: SyncSessionStore; tmpDir: string; tryAppendHistory: (raw: { kind: MigrationKind; result: MigrationResult; sections: string[]; operationId?: string; snapshotId?: string; runId?: string; source: 'api' | 'autosync' | 'backup-scheduler' | 'recovery' | 'cli' | 'internal'; summary: string; error?: string; }) => Promise<string | undefined>; withMutationGate: (op: string, handler: (req: IncomingMessage, res: ServerResponse, lockCtx?: MutationLockContext, journalCtx?: JournalRunContext) => Promise<void>, opts?: { journaled?: boolean; deferredSnapshot?: boolean; }) => ((req: IncomingMessage, res: ServerResponse) => Promise<void>); selfUpdate: (targetVersion: string) => Promise<SelfUpdateOutcome>; writeItemCache: (url: string, itemId: string, manifestRaw: string, zipBytes: Uint8Array) => Promise<void>; }
|
|
2179
|
+
export type RouteEnvInferred = { sessionExportFetch: ((input: string, init: RequestInit) => Promise<Response>) | undefined; sessionExportPort: number | undefined; adapters: ConfigAdapter<unknown>[]; sessionHealth: { homeDir: string; targetFormatVersion: () => number | undefined; workspaceKeys: () => Promise<ReadonlySet<string>>; knownSessionIds: () => Promise<ReadonlySet<string>>; sessionMeta: (ids: readonly string[]) => Promise<SessionMetaIndex>; }; backupScheduler: BackupScheduler; bootSafetyAudit: () => Promise<BootSafetyReport>; cancelDecisionTimeoutMs: number; buildMarketSummary: (e: { url: string; addedAt: string; }) => Promise<MarketSummary>; credentials: CredentialProvider; dataDir: string; exportsDir: string; syncRootDir: string; syncScope: SyncScope; githubAuth: GitHubAuthClient; githubClientId: string | undefined; githubClientSecret: string | undefined; githubFlows: DeviceFlowStore; history: MigrationStore; host: ConfigManagerHostContext; itemCached: (url: string, itemId: string) => Promise<boolean>; knownSyncSectionIds: Set<SectionId>; makeImporter: () => Importer; makeMarketReader: () => GitMarketReader; makeRecoveryExecutors: (runId: string) => RecoveryExecutorFns; makeSyncEngine: (cfg: SyncConfig, engineOpts?: { optInSections?: readonly SectionId[]; }) => SyncEngine; marketBootAutoRefreshed: { value: boolean; }; marketCacheIndex: (url: string) => string; marketDir: string; marketCacheItemDir: (url: string) => string; marketStarCache: StarCache; marketWorkDir: (url: string) => string; meGitHubRest: GitHubAuthRest; meService: MyRepoService; meTokenProvider: () => Promise<string>; msg: MsgFunc; prepareSync: (body: Record<string, unknown>) => Promise<SyncConfig>; pluginVersion: string; profileLauncher: DshProfileLauncher; profileRuntime: DshProfileRuntimeRegistry; profiles: DshProfileManager; pruneStagedMarketZips: () => Promise<void>; readCachedIndexObj: (url: string) => Promise<MarketIndex | null>; recoveryOrchestrator: RecoveryOrchestrator; resolveSyncPassword: (ref: string) => Promise<string | undefined>; roots: string[]; runAbortControllers: Map<string, AbortController>; runCancels: Map<string, { signal: AbortController; settle: (d: 'rollback' | 'keep') => void; decided: boolean }>; runs: RunRegistry; scheduler: AutoSyncScheduler; selectionCache: Partial<Record<SyncTransportType, SyncSelection>>; selectionOptInSections: (channel: SyncTransportType, onlyAuto?: boolean) => SectionId[]; selectionView: (channel: SyncTransportType) => Promise<SelectionView>; selectionViewByChannel: () => Promise<Record<SyncTransportType, SelectionView>>; snapshotEntrySections: (snapshotDir: string) => Promise<string[]>; snapshotsDir: string; starPromptRepoUrl: string; syncCredentialsByChannelView: () => Promise<Record<SyncTransportType, { encryptPasswordConfigured: boolean; decryptPasswordConfigured: boolean; }>>; syncDir: string; syncPasswordConfigured: (ref: string) => Promise<boolean>; syncWorkDir: { inspect: (repoUrl: string, opts?: { detail?: boolean; subdir?: string; }) => Promise<{ facts: GitWorkDirFacts; } | { error: string; }>; rebuild: (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone', subdir?: string) => Promise<GitWorkDirFacts>; }; syncSectionCatalog: { id: SectionId; displayName: string; portability: Portability; defaultIncluded: boolean; }[]; syncSessions: SyncSessionStore; tmpDir: string; tryAppendHistory: (raw: { kind: MigrationKind; result: MigrationResult; sections: string[]; operationId?: string; snapshotId?: string; runId?: string; source: 'api' | 'autosync' | 'backup-scheduler' | 'recovery' | 'cli' | 'internal'; summary: string; error?: string; }) => Promise<string | undefined>; withMutationGate: (op: string, handler: (req: IncomingMessage, res: ServerResponse, lockCtx?: MutationLockContext, journalCtx?: JournalRunContext) => Promise<void>, opts?: { journaled?: boolean; deferredSnapshot?: boolean; }) => ((req: IncomingMessage, res: ServerResponse) => Promise<void>); selfUpdate: (targetVersion: string) => Promise<SelfUpdateOutcome>; writeItemCache: (url: string, itemId: string, manifestRaw: string, zipBytes: Uint8Array) => Promise<void>; }
|
|
2175
2180
|
|
|
2176
2181
|
|
|
2177
2182
|
interface RoutesDeps {
|
|
@@ -2683,8 +2688,10 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2683
2688
|
* 构造 git 通道实例(同步引擎与 issue #79 的工作副本自检/重建共用同一份地址与凭据口径)。
|
|
2684
2689
|
* token 只经 credentials 端口现取(值永不落盘/日志/回传)。
|
|
2685
2690
|
*/
|
|
2686
|
-
const makeGitTransport = (repoUrl: string): GitTransport => new GitTransport({
|
|
2691
|
+
const makeGitTransport = (repoUrl: string, subdir?: string): GitTransport => new GitTransport({
|
|
2687
2692
|
repoUrl,
|
|
2693
|
+
// issue #131:子目录前缀与 repoUrl 同源(配置 → 传输层),空串 = 仓库根
|
|
2694
|
+
...(subdir === undefined ? {} : { subdir }),
|
|
2688
2695
|
workDir: gitWorkDir,
|
|
2689
2696
|
credentials: {
|
|
2690
2697
|
getToken: async () => {
|
|
@@ -2747,7 +2754,7 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2747
2754
|
msg,
|
|
2748
2755
|
})
|
|
2749
2756
|
} else {
|
|
2750
|
-
transport = makeGitTransport(cfg.git.repoUrl)
|
|
2757
|
+
transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir)
|
|
2751
2758
|
}
|
|
2752
2759
|
const channel: SyncTransportType = channelOf(cfg)
|
|
2753
2760
|
const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection())
|
|
@@ -2792,17 +2799,10 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2792
2799
|
// Phase 6:autosync 既写 sync-history.json(既有语义),也写统一迁移历史(COMPLETE 不变量)。
|
|
2793
2800
|
appendHistoryFn: async (entry) => {
|
|
2794
2801
|
await appendAutosyncEntry(syncDir, entry).catch(() => undefined)
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
source: 'autosync',
|
|
2800
|
-
summary: engineMsg('host.autosyncSummary', {
|
|
2801
|
-
direction: entry.direction,
|
|
2802
|
-
transportSuffix: entry.transport !== undefined ? engineMsg('host.autosyncTransportSuffix', { transport: entry.transport }) : '',
|
|
2803
|
-
}),
|
|
2804
|
-
error: entry.status === 'failed' ? (entry.error ?? entry.skipReason) : undefined,
|
|
2805
|
-
}).catch(() => undefined)
|
|
2802
|
+
// 空检查轮(每 60s 一次的远端探测,什么都没传)不进统一历史;payload 组装与判据见 core。
|
|
2803
|
+
const input = autosyncUnifiedHistoryInput(entry, engineMsg)
|
|
2804
|
+
if (input === null) return
|
|
2805
|
+
await history.append({ kind: 'autosync', ...input }).catch(() => undefined)
|
|
2806
2806
|
},
|
|
2807
2807
|
})
|
|
2808
2808
|
// P1-B:调度器不再在 makeRoutes 内同步 start —— 由 apply() 在「启动 recovery 分类完成后、仅 NORMAL」时启动。
|
|
@@ -3056,20 +3056,20 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
3056
3056
|
syncWorkDir: {
|
|
3057
3057
|
// 自检失败(git 不可用 / 工作副本异常)→ 返回 { error },**不让整个状态接口 500**,
|
|
3058
3058
|
// 也不伪装成「工作副本不存在」。
|
|
3059
|
-
inspect: async (repoUrl: string, opts: { detail?: boolean } = {}): Promise<{ facts: GitWorkDirFacts } | { error: string }> => {
|
|
3059
|
+
inspect: async (repoUrl: string, opts: { detail?: boolean; subdir?: string } = {}): Promise<{ facts: GitWorkDirFacts } | { error: string }> => {
|
|
3060
3060
|
try {
|
|
3061
3061
|
// issue #104 建议 3:`/sync/status` 要回传「领先远端提交数 / 远端快照数」,
|
|
3062
3062
|
// 用户看不见积压就会在「以为在备份」的状态下一直失败。detail 那几条是本地只读但各起
|
|
3063
3063
|
// 一次 git 进程(Windows 约 80 ms)⇒ 缺省完整(WorkDirCard 要),路由可传 false。
|
|
3064
|
-
return { facts: await makeGitTransport(repoUrl).inspectWorkDir({ detail: opts.detail !== false }) }
|
|
3064
|
+
return { facts: await makeGitTransport(repoUrl, opts.subdir).inspectWorkDir({ detail: opts.detail !== false }) }
|
|
3065
3065
|
} catch (err) {
|
|
3066
3066
|
return { error: err instanceof Error ? err.message : String(err) }
|
|
3067
3067
|
}
|
|
3068
3068
|
},
|
|
3069
3069
|
// 重建:relink 非破坏;adopt 合并远端历史(不改写本地提交,issue #104);
|
|
3070
3070
|
// reclone 删目录重克隆(调用方必须先取得用户确认)
|
|
3071
|
-
rebuild: async (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone'): Promise<GitWorkDirFacts> => {
|
|
3072
|
-
const transport = makeGitTransport(repoUrl)
|
|
3071
|
+
rebuild: async (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone', subdir?: string): Promise<GitWorkDirFacts> => {
|
|
3072
|
+
const transport = makeGitTransport(repoUrl, subdir)
|
|
3073
3073
|
await transport.rebuildWorkDir(mode)
|
|
3074
3074
|
return await transport.inspectWorkDir()
|
|
3075
3075
|
},
|
|
@@ -349,6 +349,26 @@ test('remove:物理删除目录;当前 profile 需显式确认', () => {
|
|
|
349
349
|
}
|
|
350
350
|
})
|
|
351
351
|
|
|
352
|
+
test('remove:含悬空 junction 的档案也能删净(fs.rm 静默失效的回归)', () => {
|
|
353
|
+
const { mgr, home, cleanup } = makeManager()
|
|
354
|
+
try {
|
|
355
|
+
mgr.create('work', 'base')
|
|
356
|
+
const dir = join(home, 'profiles', 'work')
|
|
357
|
+
mkdirSync(join(dir, 'node_modules'), { recursive: true })
|
|
358
|
+
// DSH 的真实形态:node_modules/<pkg> → 已消失的 .dsh-module-fallback/node_modules/<pkg>
|
|
359
|
+
symlinkSync(
|
|
360
|
+
join(dir, '.dsh-module-fallback', 'node_modules', 'immer'),
|
|
361
|
+
join(dir, 'node_modules', 'immer'),
|
|
362
|
+
process.platform === 'win32' ? 'junction' : 'dir',
|
|
363
|
+
)
|
|
364
|
+
mgr.remove('work')
|
|
365
|
+
// 曾经:fs.rmSync 遇到悬空链接「不抛错也不删」,路由回 200 + 台账 success,档案留在磁盘上
|
|
366
|
+
assert.equal(existsSync(dir), false, '悬空 junction 不得让删除静默失败')
|
|
367
|
+
} finally {
|
|
368
|
+
cleanup()
|
|
369
|
+
}
|
|
370
|
+
})
|
|
371
|
+
|
|
352
372
|
test('desktop 保留档案:删除与改名一律拒绝(managedProfile),只读操作照常', async () => {
|
|
353
373
|
const { mgr, home, cleanup } = makeManager()
|
|
354
374
|
try {
|
|
@@ -18,14 +18,17 @@
|
|
|
18
18
|
* 历史上这里还有一个 `<dataDir>/next-profile`「下次启动」标记——DSH 根本没有消费者,
|
|
19
19
|
* 只会误导用户(2026-09 按产品决策整体移除,连同前端按钮)。
|
|
20
20
|
*
|
|
21
|
-
* 物理删除:remove() 走 rmSync(recursive)
|
|
22
|
-
*
|
|
21
|
+
* 物理删除:remove() 走 utils/remove-tree 的 removeTreeSync —— 不能用 fs.rmSync(recursive):
|
|
22
|
+
* 目录里只要有一个**悬空链接**(DSH 的 node_modules/<pkg> → 已消失的 .dsh-module-fallback),
|
|
23
|
+
* rmSync 会不报错也不删任何东西(实测),于是「删除成功」而档案原样留在磁盘上。
|
|
24
|
+
* profile 目录内的 junction(pnpm 链接)只删链接本身,不会跟随进 pnpm store。
|
|
23
25
|
*/
|
|
24
26
|
import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, type Dirent } from 'node:fs'
|
|
25
27
|
// 复制走 async fs(整档案上万个文件,cpSync 会把宿主事件循环卡住二十多秒)
|
|
26
|
-
import { copyFile, cp, mkdir, readdir, readlink,
|
|
28
|
+
import { copyFile, cp, mkdir, readdir, readlink, stat, symlink, unlink } from 'node:fs/promises'
|
|
27
29
|
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
28
30
|
import { atomicWriteFileSync } from '../utils/atomic-write.ts'
|
|
31
|
+
import { removeTree, removeTreeSync } from '../utils/remove-tree.ts'
|
|
29
32
|
import { isRecord } from '../utils/guards.ts'
|
|
30
33
|
import { resolveProfileDir, validateProfileName } from '../core/plugin-cli.ts'
|
|
31
34
|
import { readTextSafe } from './dsh-profile-io.ts'
|
|
@@ -103,9 +106,15 @@ export interface DshProfileIncompleteCopiesScan {
|
|
|
103
106
|
/** t89:profiles 根目录枚举失败的原因码(诊断/日志用)。 */
|
|
104
107
|
export const PROFILES_ROOT_UNREADABLE = 'profiles-root-unreadable'
|
|
105
108
|
|
|
106
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* 回滚复制目标目录的缺省删除实现(不存在不算错)。
|
|
111
|
+
*
|
|
112
|
+
* 必须走 removeTree 而不是 fs.rm(recursive):半截副本里可能已经有指向
|
|
113
|
+
* `.dsh-module-fallback` 的悬空 junction,fs.rm 会「成功」却一个字节都不删,
|
|
114
|
+
* 回滚于是无声失败。
|
|
115
|
+
*/
|
|
107
116
|
const defaultProfileRemove = async (target: string): Promise<void> => {
|
|
108
|
-
await
|
|
117
|
+
await removeTree(target)
|
|
109
118
|
}
|
|
110
119
|
|
|
111
120
|
/**
|
|
@@ -413,7 +422,7 @@ export class DshProfileManager {
|
|
|
413
422
|
}
|
|
414
423
|
|
|
415
424
|
/**
|
|
416
|
-
* 物理删除 profile 目录(
|
|
425
|
+
* 物理删除 profile 目录(removeTreeSync;目录内 junction 只删链接本身,删不干净报 deleteFailed)。
|
|
417
426
|
* 当前运行中的 profile 需要 allowCurrent=true 显式确认(删除会让重启后的实例直接失败)。
|
|
418
427
|
*
|
|
419
428
|
* Desktop 独占档案(desktop)**一律拒绝**(连 allowCurrent 也不行):它由桌面端应用自己
|
|
@@ -428,7 +437,16 @@ export class DshProfileManager {
|
|
|
428
437
|
if (name === this.currentProfile() && opts.allowCurrent !== true) {
|
|
429
438
|
throw new DshProfileError('currentProfile')
|
|
430
439
|
}
|
|
431
|
-
rmSync(
|
|
440
|
+
// 不用 rmSync(recursive):悬空 junction 会让它静默空转(见 utils/remove-tree.ts 头注)。
|
|
441
|
+
// 删不掉必须变成可见错误码,绝不回 200 —— 那正是「点了删除、档案还在」的成因。
|
|
442
|
+
try {
|
|
443
|
+
removeTreeSync(dir)
|
|
444
|
+
} catch (error) {
|
|
445
|
+
throw new DshProfileError('deleteFailed', error instanceof Error ? error.message : String(error))
|
|
446
|
+
}
|
|
447
|
+
if (existsSync(dir)) {
|
|
448
|
+
throw new DshProfileError('deleteFailed', `profile directory still exists after removal: ${dir}`)
|
|
449
|
+
}
|
|
432
450
|
}
|
|
433
451
|
|
|
434
452
|
/**
|
|
@@ -275,6 +275,8 @@ export type DshProfileErrorCode =
|
|
|
275
275
|
| 'copyFailed'
|
|
276
276
|
/** 该档案由 Desktop 应用独占管理(启动 / 删除 / 改名一律拒绝,操作它会让桌面端起不来) */
|
|
277
277
|
| 'managedProfile'
|
|
278
|
+
/** 目录删不干净(被占用 / 权限不足;message 里附底层原因)—— 绝不是「删成功」 */
|
|
279
|
+
| 'deleteFailed'
|
|
278
280
|
|
|
279
281
|
/** 复制档案的非致命告警码(UI 按码映射文案,绝不静默)。 */
|
|
280
282
|
export type DshProfileCopyWarning =
|
package/src/routes/import.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { endpoint, requireJsonObject, readJsonBody, writeJson, queryParam } from
|
|
|
9
9
|
import type { WebRoute } from './kit.ts'
|
|
10
10
|
import type { RoutesEnv } from './context.ts'
|
|
11
11
|
import type { RunState } from '../core/run-registry.ts'
|
|
12
|
+
import { isIdleAutosyncRun } from '../core/run-registry.ts'
|
|
12
13
|
import type { ImportPlan } from '../core/types.ts'
|
|
13
14
|
import { DEFAULT_ROLLBACK_ON_ERROR } from '../core/import-defaults.ts'
|
|
14
15
|
import { decryptErrorText, isControlledPath, tryDecryptCredentials, writeRequestBodyToFile } from './route-support.ts'
|
|
@@ -361,7 +362,11 @@ export function importRoutes(env: RoutesEnv): WebRoute[] {
|
|
|
361
362
|
endpoint({ path: '/api/dsh-config-manager/runs', methods: ['GET'] }, async (req, res) => {
|
|
362
363
|
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
363
364
|
const scope = queryParam(url, 'scope')
|
|
364
|
-
|
|
365
|
+
// 空转的自动同步轮次不进「运行中心」:60s 一次轮询,每轮一张「已完成」卡片与迁移历史同属噪音;
|
|
366
|
+
// running / 真干活的轮次照常列出(判据见 core/run-registry.ts 的 isIdleAutosyncRun)。
|
|
367
|
+
writeJson(res, 200, scope === 'recent'
|
|
368
|
+
? runs.listRecent(50).filter((run) => !isIdleAutosyncRun(run))
|
|
369
|
+
: runs.listActive())
|
|
365
370
|
}),
|
|
366
371
|
// ------------------------------------------------------- runs/cancel
|
|
367
372
|
// 运行中心「终止」:只在**计划项边界**生效的协作式取消(abort run 级信号)。
|
|
@@ -36,7 +36,7 @@ import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restor
|
|
|
36
36
|
import type { RestoreResumeHint } from '../core/restore-resume.ts'
|
|
37
37
|
import type { RestoreJournalPort, RestoreWalHandle, RestoreWalSettleStatus } from '../core/restore-wal.ts'
|
|
38
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'
|
|
39
|
+
import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, normalizeGitSubdir, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.ts'
|
|
40
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'
|
|
41
41
|
import type { AutosyncAutoApplyTier, AutosyncConflictPolicy, AutosyncInterval, AutosyncRunStatus } from '../sync/autosync-config.ts'
|
|
42
42
|
import { SYNC_CHANNELS } from '../sync/sync-config.ts'
|
|
@@ -756,7 +756,8 @@ export interface SyncRefScope {
|
|
|
756
756
|
/**
|
|
757
757
|
* 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
|
|
758
758
|
* 请求体形状(flat,M4 契约):
|
|
759
|
-
* - git: { transport:'git', repoUrl, token? } ——
|
|
759
|
+
* - git: { transport:'git', repoUrl, subdir?, token? } —— subdir = 仓库内子目录前缀(issue #131);
|
|
760
|
+
* token 非空写 SYNC_CREDENTIAL_REF;
|
|
760
761
|
* git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
|
|
761
762
|
* - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
|
|
762
763
|
* 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
|
|
@@ -802,6 +803,9 @@ export async function parseSyncBody(
|
|
|
802
803
|
if (repoUrl === '') throw new SyncRouteError('repoUrl is required')
|
|
803
804
|
const urlError = validateRepoUrl(repoUrl)
|
|
804
805
|
if (urlError !== null) throw new SyncRouteError(urlError)
|
|
806
|
+
// issue #131:仓库内子目录前缀(可选;空 = 仓库根)。非法值在这里就拒,绝不先落盘再交给 git。
|
|
807
|
+
const subdirCheck = normalizeGitSubdir(syncStr(body['subdir']))
|
|
808
|
+
if (!subdirCheck.ok) throw new SyncRouteError(engineMsg('sync.git.subdirInvalid', { subdir: syncStr(body['subdir']) }))
|
|
805
809
|
const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined
|
|
806
810
|
if (token !== undefined) {
|
|
807
811
|
try {
|
|
@@ -816,7 +820,7 @@ export async function parseSyncBody(
|
|
|
816
820
|
return {
|
|
817
821
|
schemaVersion: 2,
|
|
818
822
|
transport: 'git',
|
|
819
|
-
git: { repoUrl },
|
|
823
|
+
git: { repoUrl, ...(subdirCheck.value === '' ? {} : { subdir: subdirCheck.value }) },
|
|
820
824
|
}
|
|
821
825
|
}
|
|
822
826
|
|
package/src/routes/sync.ts
CHANGED
|
@@ -240,13 +240,16 @@ export function syncRoutes(env: RoutesEnv): WebRoute[] {
|
|
|
240
240
|
// 远端快照数」(只读自检;后者是「本地一直没真正备份」的预警依据)。
|
|
241
241
|
// 读不出来时**如实回传错误**(workDirError),不让状态接口静默少一块信息。
|
|
242
242
|
const gitRepoUrl = full?.git?.repoUrl ?? ''
|
|
243
|
+
// issue #131:自检必须按配置的子目录前缀读(远端快照数来自 <subdir>/snapshots)
|
|
244
|
+
const gitSubdir = full?.git?.subdir ?? ''
|
|
243
245
|
let workDir: Awaited<ReturnType<typeof syncWorkDir.inspect>> | null = null
|
|
244
|
-
if (gitRepoUrl !== '') workDir = await syncWorkDir.inspect(gitRepoUrl, { detail: opts.workDirDetail })
|
|
246
|
+
if (gitRepoUrl !== '') workDir = await syncWorkDir.inspect(gitRepoUrl, { detail: opts.workDirDetail, ...(gitSubdir === '' ? {} : { subdir: gitSubdir }) })
|
|
245
247
|
return {
|
|
246
248
|
ok: true,
|
|
247
249
|
configured: full !== null,
|
|
248
250
|
transport,
|
|
249
251
|
repoUrl: full?.git?.repoUrl,
|
|
252
|
+
subdir: full?.git?.subdir,
|
|
250
253
|
// 被丢弃的通道配置成因(默认空数组:字段恒在,客户端不必判 undefined;
|
|
251
254
|
// 合法配置不产生幻影告警)。code 是机读 token,message 可直接展示。
|
|
252
255
|
configIssues,
|
|
@@ -334,7 +337,7 @@ export function syncRoutes(env: RoutesEnv): WebRoute[] {
|
|
|
334
337
|
})
|
|
335
338
|
return
|
|
336
339
|
}
|
|
337
|
-
const rebuilt = await syncWorkDir.rebuild(repoUrl, mode)
|
|
340
|
+
const rebuilt = await syncWorkDir.rebuild(repoUrl, mode, full?.git?.subdir)
|
|
338
341
|
writeJson(res, 200, { ok: true, mode, workDir: { facts: rebuilt } })
|
|
339
342
|
} catch (error) {
|
|
340
343
|
writeSyncRouteError(res, error)
|
|
@@ -37,8 +37,16 @@ export const DEFAULT_STARTUP_MIN_INTERVAL_MS = 5 * 60 * 1000;
|
|
|
37
37
|
/** 缺省开启「本地改动即时触发」(真·自动同步;关闭后退回纯定时器) */
|
|
38
38
|
export const DEFAULT_AUTOSYNC_REALTIME = true;
|
|
39
39
|
|
|
40
|
-
/**
|
|
41
|
-
|
|
40
|
+
/**
|
|
41
|
+
* 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 5 分钟内下行)。
|
|
42
|
+
*
|
|
43
|
+
* 2026-11-09 由 60s 改为 5 分钟(用户拍板):远端探测本身很便宜,但过去每轮还会顺带做一次本地
|
|
44
|
+
* 全量导出判定,plugins 分区要为每个本机源插件跑 npm pack(真机 12 个 ≈12 s、单个 210MB 44.7 s)
|
|
45
|
+
* ⇒ 60 s 一轮等于长期占用一个核。本地改动的即时性由文件监听负责(local-change 触发),
|
|
46
|
+
* 兜底由 interval 负责,远端「有没有新快照」不需要 1 分钟一问。旧配置里已写死的值不在此处迁移
|
|
47
|
+
* (用户显式选过的值优先),需要改的走 POST /sync/autosync 的 remoteCheckMs。
|
|
48
|
+
*/
|
|
49
|
+
export const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS = 5 * 60 * 1000;
|
|
42
50
|
|
|
43
51
|
/** 远端轮询间隔下限(15 s):再短只是空转 fetch,收益为零 */
|
|
44
52
|
export const MIN_AUTOSYNC_REMOTE_CHECK_MS = 15 * 1000;
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
AutoSyncScheduler, intervalToMs, shouldTriggerStartupRun, buildAutoApplyPlan,
|
|
16
16
|
resolveConflictPushPolicy,
|
|
17
17
|
} from './autosync-scheduler.ts';
|
|
18
|
-
import { RunRegistry } from '../core/run-registry.ts';
|
|
18
|
+
import { RunRegistry, isIdleAutosyncRun } from '../core/run-registry.ts';
|
|
19
19
|
import { nullLogger, createLogger } from '../utils/logger.ts';
|
|
20
20
|
import type { LogSink } from '../utils/logger.ts';
|
|
21
21
|
import type { MutationLockPort, MutationLockToken } from '../utils/env-lock.ts';
|
|
@@ -1318,3 +1318,63 @@ test('runOnce: 稳态(两端无变化)不取环境锁;有活干才取(20
|
|
|
1318
1318
|
assert.equal(blocked.status, 'skipped');
|
|
1319
1319
|
assert.equal(blocked.skipReason, 'mutation-locked');
|
|
1320
1320
|
});
|
|
1321
|
+
|
|
1322
|
+
/**
|
|
1323
|
+
* 2026-11-09(CPU 优化):远端轮询轮不得跑本地全量导出。
|
|
1324
|
+
*
|
|
1325
|
+
* 现场:realtime 开着时每 60s 一轮 remote-poll,而每轮预检都会导出所有分区 —— plugins 分区要为每个
|
|
1326
|
+
* 本机源插件跑一次 npm pack(真机单插件 44.7s/轮)。轮询只需要回答「远端有没有新快照」,
|
|
1327
|
+
* 本地改动由 realtime 监听(local-change)与 30 分钟兜底 interval 负责。
|
|
1328
|
+
*/
|
|
1329
|
+
test('runOnce: reason=remote-poll 且远端无新快照 → 跳过本地导出(不白跑 npm pack)', async () => {
|
|
1330
|
+
const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
|
|
1331
|
+
let localCalls = 0;
|
|
1332
|
+
const { scheduler, runs } = makeScheduler({
|
|
1333
|
+
cfg,
|
|
1334
|
+
engine: { listSnapshots: async () => [] } as never,
|
|
1335
|
+
history: [],
|
|
1336
|
+
detectRemoteNew: async () => false,
|
|
1337
|
+
detectLocalChange: async () => { localCalls += 1; return false; },
|
|
1338
|
+
});
|
|
1339
|
+
|
|
1340
|
+
const result = await scheduler.runOnce('git', { reason: 'remote-poll' });
|
|
1341
|
+
assert.equal(result.skipReason, 'upToDate');
|
|
1342
|
+
assert.equal(localCalls, 0, '远端轮询轮不得触发本地全量导出');
|
|
1343
|
+
|
|
1344
|
+
const [only] = runs.listRecent(50);
|
|
1345
|
+
assert.ok(only !== undefined);
|
|
1346
|
+
assert.equal(isIdleAutosyncRun(only), true, '空转轮跑完后应是 idle run(运行中心据此过滤卡片)');
|
|
1347
|
+
});
|
|
1348
|
+
|
|
1349
|
+
test('runOnce: 非远端轮询触发仍要跑本地检测(不能把优化扩成「永不检查本地」)', async () => {
|
|
1350
|
+
const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
|
|
1351
|
+
let localCalls = 0;
|
|
1352
|
+
const { scheduler, runs } = makeScheduler({
|
|
1353
|
+
cfg,
|
|
1354
|
+
engine: { listSnapshots: async () => [] } as never,
|
|
1355
|
+
history: [],
|
|
1356
|
+
detectRemoteNew: async () => false,
|
|
1357
|
+
detectLocalChange: async () => { localCalls += 1; return false; },
|
|
1358
|
+
});
|
|
1359
|
+
|
|
1360
|
+
const result = await scheduler.runOnce('git', { reason: 'local-change' });
|
|
1361
|
+
assert.equal(result.skipReason, 'upToDate');
|
|
1362
|
+
assert.equal(localCalls, 1, '本地改动触发必须真的比对一次');
|
|
1363
|
+
const [only] = runs.listRecent(50);
|
|
1364
|
+
assert.equal(isIdleAutosyncRun(only!), true);
|
|
1365
|
+
});
|
|
1366
|
+
|
|
1367
|
+
test('runOnce: 真有改动时不带 idle(卡片必须留下,它解释刚才发生了什么)', async () => {
|
|
1368
|
+
const cfg: AutosyncConfig = { enabled: true, interval: '30m', startupMinIntervalMs: 300000, consecutiveFailures: 0 };
|
|
1369
|
+
const { scheduler, runs } = makeScheduler({
|
|
1370
|
+
cfg,
|
|
1371
|
+
engine: { listSnapshots: async () => [] } as never,
|
|
1372
|
+
history: [],
|
|
1373
|
+
detectRemoteNew: async () => false,
|
|
1374
|
+
detectLocalChange: async () => true,
|
|
1375
|
+
});
|
|
1376
|
+
await scheduler.runOnce('git', { reason: 'local-change' }).catch(() => undefined);
|
|
1377
|
+
const recent = runs.listRecent(50);
|
|
1378
|
+
assert.ok(recent.length > 0, '有活干必然留下 run 记录');
|
|
1379
|
+
assert.equal(isIdleAutosyncRun(recent[0]!), false, '有改动的轮次不得被当成空转过滤掉');
|
|
1380
|
+
});
|
|
@@ -567,10 +567,10 @@ export class AutoSyncScheduler {
|
|
|
567
567
|
* 仍 updatedAt == createdAt;此后每次 autosync 都 `register('autosync')` → RunConflictError
|
|
568
568
|
* → 后台同步静默停摆(正是下面 finally 注释警告的后果),运行中心里那张卡片也「一直在加载」。
|
|
569
569
|
*/
|
|
570
|
-
const finishRun = (): void => {
|
|
570
|
+
const finishRun = (extra: { idle?: true } = {}): void => {
|
|
571
571
|
if (runId === null) return;
|
|
572
572
|
try {
|
|
573
|
-
this.runs.finish(runId, { kind: 'autosync' });
|
|
573
|
+
this.runs.finish(runId, { kind: 'autosync', ...extra });
|
|
574
574
|
} catch {
|
|
575
575
|
/* 尽力而为:收尾失败不影响同步结果 */
|
|
576
576
|
}
|
|
@@ -583,11 +583,17 @@ export class AutoSyncScheduler {
|
|
|
583
583
|
// (实测单个 210MB 插件 44.7s/次、每轮重算)。旧实现把这段整个放进 GLOBAL mutation 锁内,60s 一轮的
|
|
584
584
|
// 轮询于是让锁几乎全程被占(45s/60s),用户任何 destructive 操作(删除档案…)都撞 423「另一个任务正在运行」。
|
|
585
585
|
// 现在稳态(upToDate)根本不取锁;命中「有活干」才取,并在锁内重跑检测再写。
|
|
586
|
-
|
|
586
|
+
// 远端轮询轮跳过本地导出(reason='remote-poll'):本地改动由 realtime 监听(local-change 触发)
|
|
587
|
+
// 与 30 分钟兜底 interval 负责;这里每 60s 再跑一次全量导出 = 白跑 plugins 的 npm pack
|
|
588
|
+
// (真机单插件 44.7s/轮)。判定口径不变 —— 真要比对时比的仍是载荷字节,不做任何近似。
|
|
589
|
+
const preflight = await this.detectPhase(channel, cfg, nowIso, historyId, {
|
|
590
|
+
localCheck: opts.reason !== 'remote-poll',
|
|
591
|
+
});
|
|
587
592
|
if (preflight.kind === 'skip') {
|
|
588
593
|
this.running = false;
|
|
589
594
|
this.watcher?.resume();
|
|
590
|
-
|
|
595
|
+
// 空转轮(什么都没传)打上 idle:运行中心据此不为它留卡片(见 core/run-registry 的 isIdleAutosyncRun)。
|
|
596
|
+
finishRun(preflight.result.skipReason === 'upToDate' ? { idle: true } : {});
|
|
591
597
|
return preflight.result;
|
|
592
598
|
}
|
|
593
599
|
|
|
@@ -947,6 +953,11 @@ export class AutoSyncScheduler {
|
|
|
947
953
|
cfg: AutosyncConfig,
|
|
948
954
|
nowIso: string,
|
|
949
955
|
historyId: string,
|
|
956
|
+
/**
|
|
957
|
+
* localCheck=false = 本轮只回答「远端有没有新快照」,不跑本地导出(60s 远端轮询专用)。
|
|
958
|
+
* 本地是否改动由 realtime 监听与兜底 interval 负责;这不是近似判定 —— 需要比对时比的仍是载荷字节。
|
|
959
|
+
*/
|
|
960
|
+
opts: { localCheck?: boolean } = {},
|
|
950
961
|
): Promise<AutosyncDetectOutcome> {
|
|
951
962
|
// 读该通道 sync-config:按通道判定「已配置」——git 看 git.repoUrl、webdav 看 webdav.url。
|
|
952
963
|
// SEC-03:「未配置」有两种成因 —— 真的没配,或存过的地址被白名单拒掉(读侧丢弃)。
|
|
@@ -1011,7 +1022,8 @@ export class AutoSyncScheduler {
|
|
|
1011
1022
|
// 定时器只是兜底轮询;真正驱动是这两个「变化」信号。
|
|
1012
1023
|
// 列表拿不到(网络失败)时 remoteMetas 为 null → 检测自己再 list 一次,行为与改造前一致
|
|
1013
1024
|
const remoteNew = await this.detectRemoteNew(engine, remoteMetas ?? undefined);
|
|
1014
|
-
|
|
1025
|
+
// 关掉本地检测时 localDirty 恒 false:远端也没变 → 立刻 upToDate,一次导出都不跑。
|
|
1026
|
+
const localDirty = opts.localCheck === false ? false : await this.detectLocalChange(engine);
|
|
1015
1027
|
// SYN-05:首轮(从未跑过)与「远端有新快照」是覆盖风险最高的两个时刻 —— 由
|
|
1016
1028
|
// resolveConflictPushPolicy 统一把这两处的 ask 标成 forced。
|
|
1017
1029
|
const firstRun = cfg.lastRunAt === undefined || cfg.lastRunAt === '';
|
|
@@ -1939,3 +1939,120 @@ test('已有工作副本缺提交身份 → 进入工作副本时自动补写仓
|
|
|
1939
1939
|
await new GitTransport(makeOptions({ workDir: dir2, exec: exec2 })).list();
|
|
1940
1940
|
assert.deepEqual(writes2, [], '已有身份不得被覆盖: ' + writes2.join(' | '));
|
|
1941
1941
|
});
|
|
1942
|
+
|
|
1943
|
+
/* ---------------- issue #131:仓库内子目录前缀 ---------------- */
|
|
1944
|
+
|
|
1945
|
+
test('issue #131 集成:子目录前缀 —— 上传/列表/下载/删除都落在前缀下,仓库根不被污染', async (t) => {
|
|
1946
|
+
const bare = await makeBareRepo(t);
|
|
1947
|
+
const workDir = await makeTempDir(t);
|
|
1948
|
+
const subdir = 'DSH备份';
|
|
1949
|
+
const transport = new GitTransport({ repoUrl: bare, workDir, credentials: { getToken: async () => TEST_TOKEN }, subdir });
|
|
1950
|
+
|
|
1951
|
+
const snap = sampleSnapshot();
|
|
1952
|
+
await transport.upload(snap);
|
|
1953
|
+
|
|
1954
|
+
// 远端根只有前缀目录(多工具共用一个私有仓库:根上不放任何同步内容)
|
|
1955
|
+
const root = await runRealGit(['-c', 'core.quotePath=false', 'ls-tree', '--name-only', 'HEAD'], bare);
|
|
1956
|
+
assert.equal(root.code, 0, 'ls-tree 失败: ' + root.stderr);
|
|
1957
|
+
assert.deepEqual(root.stdout.split('\n').filter(Boolean), [subdir], '仓库根必须只有子目录前缀');
|
|
1958
|
+
|
|
1959
|
+
// 前缀下的同步目录(无外置 blob 时只建 snapshots)
|
|
1960
|
+
const inner = await runRealGit(['-c', 'core.quotePath=false', 'ls-tree', '--name-only', 'HEAD:' + subdir], bare);
|
|
1961
|
+
assert.equal(inner.code, 0, 'ls-tree 子目录失败: ' + inner.stderr);
|
|
1962
|
+
assert.deepEqual(inner.stdout.split('\n').filter(Boolean), ['snapshots'], '子目录下必须是同步目录');
|
|
1963
|
+
|
|
1964
|
+
// 工作副本同样落在前缀下
|
|
1965
|
+
assert.ok(await fs.stat(path.join(workDir, subdir, 'snapshots', 'snap-001', 'manifest.json')));
|
|
1966
|
+
await assert.rejects(fs.stat(path.join(workDir, 'snapshots')), /ENOENT/, '工作副本根不得出现 snapshots/');
|
|
1967
|
+
|
|
1968
|
+
// list / download 从前缀位置读
|
|
1969
|
+
const listed = await transport.list();
|
|
1970
|
+
assert.equal(listed.length, 1);
|
|
1971
|
+
assert.equal(listed[0]!.id, 'snap-001');
|
|
1972
|
+
assert.deepEqual(await transport.download('snap-001'), snap);
|
|
1973
|
+
|
|
1974
|
+
// delete 也只动前缀下的内容
|
|
1975
|
+
await transport.delete('snap-001');
|
|
1976
|
+
assert.equal((await transport.list()).length, 0);
|
|
1977
|
+
const after = await runRealGit(['ls-tree', '-r', '--name-only', 'HEAD'], bare);
|
|
1978
|
+
assert.equal(after.code, 0, 'ls-tree 失败: ' + after.stderr);
|
|
1979
|
+
assert.ok(!after.stdout.includes('snap-001'), '远端不得残留已删除的快照: ' + after.stdout);
|
|
1980
|
+
});
|
|
1981
|
+
|
|
1982
|
+
test('issue #131:同一工作副本换前缀 → 明确「同步布局已变」并指向重建,绝不静默表现为远端没有快照', async (t) => {
|
|
1983
|
+
const bare = await makeBareRepo(t);
|
|
1984
|
+
const workDir = await makeTempDir(t);
|
|
1985
|
+
const creds = { getToken: async () => TEST_TOKEN };
|
|
1986
|
+
await new GitTransport({ repoUrl: bare, workDir, credentials: creds }).upload(sampleSnapshot());
|
|
1987
|
+
|
|
1988
|
+
// 旧工作副本(根布局)换成子目录前缀:sparse-checkout 只在首次 clone 生效,旧副本里没有新前缀的树
|
|
1989
|
+
const moved = new GitTransport({ repoUrl: bare, workDir, credentials: creds, subdir: 'tools/dsh' });
|
|
1990
|
+
await assert.rejects(moved.list(), (err: unknown) => {
|
|
1991
|
+
assert.ok(err instanceof SyncTransportError);
|
|
1992
|
+
assert.match(err.message, /同步布局/, '必须说清是布局不一致');
|
|
1993
|
+
assert.match(err.message, /仓库根/, '必须点出当前工作副本的真实布局');
|
|
1994
|
+
assert.match(err.message, /重建工作副本/, '必须给出出口');
|
|
1995
|
+
return true;
|
|
1996
|
+
});
|
|
1997
|
+
|
|
1998
|
+
// 重建后可正常使用新前缀(同一远端、同一历史,布局换到子目录)
|
|
1999
|
+
await moved.rebuildWorkDir('reclone');
|
|
2000
|
+
await moved.upload(sampleSnapshot({ id: 'snap-002' }));
|
|
2001
|
+
const tools = await runRealGit(['ls-tree', '--name-only', 'HEAD:tools'], bare);
|
|
2002
|
+
assert.equal(tools.code, 0, 'ls-tree 失败: ' + tools.stderr);
|
|
2003
|
+
assert.deepEqual(tools.stdout.split('\n').filter(Boolean), ['dsh'], '重建后内容落进 tools/dsh');
|
|
2004
|
+
// 工作副本按新前缀布局:根上没有 snapshots/,新快照落在 tools/dsh/snapshots 下
|
|
2005
|
+
await assert.rejects(fs.stat(path.join(workDir, 'snapshots')), /ENOENT/, '重建后的工作副本根不得有旧布局目录');
|
|
2006
|
+
assert.ok(await fs.stat(path.join(workDir, 'tools', 'dsh', 'snapshots', 'snap-002', 'manifest.json')));
|
|
2007
|
+
assert.equal((await moved.list())[0]!.id, 'snap-002');
|
|
2008
|
+
});
|
|
2009
|
+
|
|
2010
|
+
test('issue #131:adopt 只看 <subdir>/ 子树 —— 仓库根有其他工具目录可采纳,子树内陌生条目仍拒', async (t) => {
|
|
2011
|
+
const creds = { getToken: async () => TEST_TOKEN };
|
|
2012
|
+
const subdir = 'DSH备份';
|
|
2013
|
+
|
|
2014
|
+
/**
|
|
2015
|
+
* 造一个「多工具共用」远端:先用本插件正常上传一条快照(子目录布局由被测代码自己写),
|
|
2016
|
+
* 再在仓库根塞一个别的工具目录(可再在子目录里塞一个陌生条目)。
|
|
2017
|
+
*/
|
|
2018
|
+
const seedRemote = async (extraInSubdir: string | null): Promise<string> => {
|
|
2019
|
+
const bare = await makeBareRepo(t);
|
|
2020
|
+
const work = await makeTempDir(t);
|
|
2021
|
+
await new GitTransport({ repoUrl: bare, workDir: work, credentials: creds, subdir }).upload(sampleSnapshot({ id: 'snap-009' }));
|
|
2022
|
+
const seed = await makeTempDir(t);
|
|
2023
|
+
const cloned = await runRealGit(['clone', bare, '.'], seed);
|
|
2024
|
+
assert.equal(cloned.code, 0, 'clone 失败: ' + cloned.stderr);
|
|
2025
|
+
await runRealGit(['config', 'user.name', 'test'], seed);
|
|
2026
|
+
await runRealGit(['config', 'user.email', 'test@local'], seed);
|
|
2027
|
+
await fs.mkdir(path.join(seed, 'other-tool', 'data'), { recursive: true });
|
|
2028
|
+
await fs.writeFile(path.join(seed, 'other-tool', 'data', 'x.json'), '{}');
|
|
2029
|
+
if (extraInSubdir !== null) await fs.writeFile(path.join(seed, subdir, extraInSubdir), 'oops');
|
|
2030
|
+
await runRealGit(['add', '-A'], seed);
|
|
2031
|
+
await runRealGit(['commit', '-m', 'seed'], seed);
|
|
2032
|
+
const pushed = await runRealGit(['push', 'origin', 'HEAD'], seed);
|
|
2033
|
+
assert.equal(pushed.code, 0, 'push 失败: ' + pushed.stderr);
|
|
2034
|
+
return bare;
|
|
2035
|
+
};
|
|
2036
|
+
|
|
2037
|
+
// 仓库根有别的工具目录 → 仍可采纳(子目录模式只认子树)
|
|
2038
|
+
const okBare = await seedRemote(null);
|
|
2039
|
+
const workA = await makeTempDir(t);
|
|
2040
|
+
const tA = new GitTransport({ repoUrl: okBare, workDir: workA, credentials: creds, subdir });
|
|
2041
|
+
await tA.rebuildWorkDir('reclone'); // 先建出工作副本(adopt 要求 .git 已存在)
|
|
2042
|
+
await tA.rebuildWorkDir('adopt');
|
|
2043
|
+
assert.equal((await tA.inspectWorkDir()).exists, true);
|
|
2044
|
+
const ids = (await tA.list()).map((m) => m.id);
|
|
2045
|
+
assert.ok(ids.includes('snap-009'), '采纳后必须能读到子目录里的快照: ' + ids.join(','));
|
|
2046
|
+
|
|
2047
|
+
// 子树内出现陌生条目 → 仍拒绝(不放宽成「顶层随便」)
|
|
2048
|
+
const badBare = await seedRemote('random.txt');
|
|
2049
|
+
const workB = await makeTempDir(t);
|
|
2050
|
+
const tB = new GitTransport({ repoUrl: badBare, workDir: workB, credentials: creds, subdir });
|
|
2051
|
+
await tB.rebuildWorkDir('reclone');
|
|
2052
|
+
await assert.rejects(tB.rebuildWorkDir('adopt'), (err: unknown) => {
|
|
2053
|
+
assert.ok(err instanceof SyncTransportError);
|
|
2054
|
+
assert.match(err.message, /random\.txt/, '必须点名陌生条目');
|
|
2055
|
+
return true;
|
|
2056
|
+
});
|
|
2057
|
+
});
|
|
2058
|
+
|