dsh-config-manager 0.6.0 → 0.8.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/adapters/test-helpers.d.ts +7 -0
- package/lib/adapters/test-helpers.js +11 -0
- package/lib/cli/actions.js +1 -1
- package/lib/client.d.ts +14 -2
- package/lib/client.js +722 -647
- package/lib/core/backup.d.ts +9 -1
- package/lib/core/backup.js +21 -0
- package/lib/core/local-plugin-host.d.ts +9 -0
- package/lib/core/local-plugin-host.js +174 -1
- package/lib/core/messages-core.d.ts +3 -0
- package/lib/core/messages-core.js +6 -0
- package/lib/core/messages.d.ts +8 -0
- package/lib/core/messages.js +18 -0
- package/lib/core/model-tools.js +2 -0
- package/lib/core/phase4-crash-child.js +1 -1
- package/lib/core/plugin-cli.d.ts +11 -0
- package/lib/core/plugin-cli.js +30 -0
- package/lib/core/restore-wal.d.ts +2 -0
- package/lib/core/restore-wal.js +11 -6
- package/lib/core/restore.d.ts +15 -2
- package/lib/core/restore.js +65 -3
- package/lib/core/run-registry.d.ts +10 -0
- package/lib/core/run-registry.js +17 -0
- package/lib/core/snapshot-diff.js +2 -1
- package/lib/core/types.d.ts +32 -0
- package/lib/index.d.ts +8 -2
- package/lib/index.js +24 -21
- package/lib/routes/import.js +6 -1
- package/lib/routes/route-support.d.ts +7 -1
- package/lib/routes/route-support.js +36 -5
- package/lib/routes/sync.js +8 -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/merge-preview-view.d.ts +78 -0
- package/lib/sync/merge-preview-view.js +46 -0
- package/lib/sync/merge.d.ts +2 -1
- package/lib/sync/merge.js +9 -4
- package/lib/sync/plugin-removal-apply.d.ts +95 -0
- package/lib/sync/plugin-removal-apply.js +158 -0
- package/lib/sync/plugin-removals.d.ts +90 -0
- package/lib/sync/plugin-removals.js +167 -0
- package/lib/sync/sync-config.d.ts +34 -3
- package/lib/sync/sync-config.js +38 -5
- package/lib/sync/sync-engine.d.ts +34 -43
- package/lib/sync/sync-engine.js +50 -42
- package/lib/sync/sync-selection.d.ts +8 -0
- package/lib/sync/sync-selection.js +6 -0
- package/lib/sync/workspace-merge.d.ts +8 -1
- package/lib/ui/restore-plan-view.js +1 -0
- package/lib/ui/sync-settings-view.d.ts +14 -0
- package/lib/ui/sync-settings-view.js +5 -0
- package/package.json +1 -1
- package/src/adapters/test-helpers.ts +10 -0
- package/src/cli/actions.ts +1 -1
- package/src/client/common/info-hint-guard.test.ts +2 -1
- package/src/client/run-store.test.ts +8 -6
- package/src/client/run-store.ts +9 -5
- package/src/client/sync/ChannelConfigDialog.tsx +15 -1
- package/src/client/sync/SyncPanel.tsx +16 -0
- package/src/client/sync/SyncSectionPickerDialog.tsx +17 -1
- package/src/client/sync/sync-api.ts +2 -0
- package/src/client/sync/sync-locales.ts +10 -0
- package/src/client/sync/sync-view.ts +6 -0
- package/src/core/backup.ts +21 -1
- package/src/core/local-plugin-host.test.ts +31 -2
- package/src/core/local-plugin-host.ts +175 -2
- package/src/core/messages-core.ts +6 -0
- package/src/core/messages.ts +18 -0
- package/src/core/model-tools.ts +2 -0
- package/src/core/phase4-crash-child.ts +1 -1
- package/src/core/plugin-cli.ts +37 -0
- package/src/core/restore-plugin-install.test.ts +116 -0
- package/src/core/restore-wal.ts +12 -6
- package/src/core/restore.ts +79 -4
- package/src/core/run-registry-runs.test.ts +26 -1
- package/src/core/run-registry.ts +18 -0
- package/src/core/smoke.test.ts +5 -0
- package/src/core/snapshot-diff.test.ts +1 -1
- package/src/core/snapshot-diff.ts +2 -1
- package/src/core/types.ts +31 -0
- package/src/index.sync.test.ts +27 -0
- package/src/index.ts +30 -28
- package/src/routes/import.ts +6 -1
- package/src/routes/route-support.ts +34 -5
- package/src/routes/sync.ts +8 -2
- package/src/security/security.test.ts +1 -0
- 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/merge-preview-view.ts +97 -0
- package/src/sync/merge.test.ts +17 -15
- package/src/sync/merge.ts +10 -3
- package/src/sync/plugin-removal-apply.ts +198 -0
- package/src/sync/plugin-removals.test.ts +221 -0
- package/src/sync/plugin-removals.ts +208 -0
- package/src/sync/sync-config.test.ts +59 -1
- package/src/sync/sync-config.ts +51 -5
- package/src/sync/sync-engine.test.ts +251 -1
- package/src/sync/sync-engine.ts +84 -83
- package/src/sync/sync-selection.test.ts +29 -7
- package/src/sync/sync-selection.ts +13 -0
- package/src/sync/workspace-merge.ts +9 -0
- package/src/ui/restore-plan-view.test.ts +1 -1
- package/src/ui/restore-plan-view.ts +1 -0
- package/src/ui/snapshots-view.test.ts +1 -1
- package/src/ui/sync-settings-view.test.ts +21 -0
- package/src/ui/sync-settings-view.ts +19 -0
package/src/index.ts
CHANGED
|
@@ -92,7 +92,7 @@ import { ROLLBACK_ACTIVITY_FILE_NAME, RollbackSessionActivity } from './core/rol
|
|
|
92
92
|
import { isRollbackEnabled, onRollbackEnabledChange, setRollbackEnabled } from './core/rollback-gate.ts'
|
|
93
93
|
// t3:宿主斜杠命令 /rollback(与 HTTP 路由同一道写入门;命令服务惰取,未组合时安静跳过)。
|
|
94
94
|
import { agentSessionFactsOf, registerRollbackCommand, type CommandServiceLike, type RollbackCommandHost } from './core/command-rollback.ts'
|
|
95
|
-
import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.ts'
|
|
95
|
+
import { cleanupAbortedInstall, hasDshBundlePatch, installAnchorFromProfileContext, installErrorFor, uninstallViaCli, readInstalledVersion, reconcileBundlesAfterInstall, listInstalledPlugins, profileNameFromProfileContext, resolveProcessProfileName, resolveProfileDir, readProfileManifest, runDshPlugin, validateProfileName } from './core/plugin-cli.ts'
|
|
96
96
|
import { ImportUserSkippedError, type ConfigAdapter, type CredentialsFacade, type ExportUnit, type FileSystemFacade, type HostContext, type ImportDecisions, type ImportPlan, type NamedNamespaceInfo, type NamespaceInfo, type PatchFileFacade, type PluginInfo, type PluginsFacade, type Portability, type SecretScanner, type SessionFormatDisposition, type SessionMoveResult, type SessionParentRelation, type SessionRewriteResult, type SessionStoreFacade, type SettingsFacade, type SkillDefinitionView, type SkillStoreFacade, type SkillSummaryView, type WorkspaceFacade } from './core/types.ts'
|
|
97
97
|
import { PLUGIN_NPM_PACKAGE } from './core/update-check.ts'
|
|
98
98
|
import { planSelfUpdate, runSelfUpdate, type SelfUpdateOutcome } from './core/self-update.ts'
|
|
@@ -183,7 +183,7 @@ export const name = 'config-manager'
|
|
|
183
183
|
export const inject = ['settings', 'credentials']
|
|
184
184
|
|
|
185
185
|
/** Plugin version, kept in sync with package.json ("version"). */
|
|
186
|
-
export const PLUGIN_VERSION = '0.
|
|
186
|
+
export const PLUGIN_VERSION = '0.8.0'
|
|
187
187
|
|
|
188
188
|
/** Plugin own package name — excluded from its own exported plugins list. */
|
|
189
189
|
const PLUGIN_NAME = 'dsh-config-manager'
|
|
@@ -597,6 +597,11 @@ export class DshPluginsFacade implements PluginsFacade {
|
|
|
597
597
|
// 回读实际落盘版本:调用方据此校验升级是否真的生效(issue #101),而不是只看子进程退出码。
|
|
598
598
|
return { needsRestart: true, installedVersion: readInstalledVersion(profileDir, pkg) }
|
|
599
599
|
}
|
|
600
|
+
|
|
601
|
+
/** 卸载插件(issue #132):走官方 CLI `dsh plugin remove`,不自己改 package.json、也不补对账。 */
|
|
602
|
+
uninstall(pkg: string, signal?: AbortSignal): Promise<{ needsRestart: boolean }> {
|
|
603
|
+
return uninstallViaCli(this.homeDir, this.profile, pkg, this.runner, signal)
|
|
604
|
+
}
|
|
600
605
|
}
|
|
601
606
|
|
|
602
607
|
/** Workspace facade over the real ctx.workspaceRegistry. */
|
|
@@ -2176,7 +2181,7 @@ const WEBDAV_TIMEOUT_MS = 120_000
|
|
|
2176
2181
|
* (见 W1 报告的重测配方),把结果落到这里;makeRoutes 里的 const routeEnv: RouteEnvInferred =
|
|
2177
2182
|
* 注解保证两侧不漂移(新增依赖漏登记会在构造点报错)。
|
|
2178
2183
|
*/
|
|
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; }) => 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>; }
|
|
2184
|
+
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>; }
|
|
2180
2185
|
|
|
2181
2186
|
|
|
2182
2187
|
interface RoutesDeps {
|
|
@@ -2240,7 +2245,7 @@ export interface PluginDiagnostics {
|
|
|
2240
2245
|
bundles: string[]
|
|
2241
2246
|
}
|
|
2242
2247
|
|
|
2243
|
-
type SelectionView = { mode: SyncSelectionMode; sections: SectionId[]; sessionsLimit: number; sessionsInclude: string[]; encrypt: boolean; includeSecrets: boolean }
|
|
2248
|
+
type SelectionView = { mode: SyncSelectionMode; sections: SectionId[]; sessionsLimit: number; sessionsInclude: string[]; encrypt: boolean; includeSecrets: boolean; deletePlugins: boolean }
|
|
2244
2249
|
|
|
2245
2250
|
|
|
2246
2251
|
/**
|
|
@@ -2641,21 +2646,17 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2641
2646
|
|
|
2642
2647
|
/** 全部通道的分区选择视图(status 路由一次返回;UI 按当前 tab 取对应通道)。 */
|
|
2643
2648
|
/** 指定通道的分区选择视图。 */
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2649
|
+
/** SyncSelection → SelectionView(字段白名单;密码值永不进视图)。 */
|
|
2650
|
+
const toSelectionView = (sel: SyncSelection): SelectionView =>
|
|
2651
|
+
({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets, deletePlugins: sel.deletePlugins })
|
|
2652
|
+
|
|
2653
|
+
const selectionView = async (channel: SyncTransportType): Promise<SelectionView> => toSelectionView(await ensureSelectionLoaded(channel))
|
|
2648
2654
|
|
|
2649
2655
|
const selectionViewByChannel = async (): Promise<Record<SyncTransportType, SelectionView>> => {
|
|
2650
2656
|
const all = await readAllSyncSelections(syncDir)
|
|
2651
|
-
const view = (sel: SyncSelection): SelectionView =>
|
|
2652
|
-
({ mode: sel.mode, sections: sel.sections, sessionsLimit: sel.sessionsLimit, sessionsInclude: sel.sessionsInclude, encrypt: sel.encrypt, includeSecrets: sel.includeSecrets })
|
|
2653
2657
|
// 通道集合来自唯一枚举(SYNC_CHANNELS);不得穷举字面量(漏一处即该通道状态静默缺失)
|
|
2654
2658
|
const out = {} as Record<SyncTransportType, SelectionView>
|
|
2655
|
-
for (const channel of SYNC_CHANNELS) {
|
|
2656
|
-
selectionCache[channel] = all[channel]
|
|
2657
|
-
out[channel] = view(all[channel])
|
|
2658
|
-
}
|
|
2659
|
+
for (const channel of SYNC_CHANNELS) { selectionCache[channel] = all[channel]; out[channel] = toSelectionView(all[channel]) }
|
|
2659
2660
|
return out
|
|
2660
2661
|
}
|
|
2661
2662
|
|
|
@@ -2688,8 +2689,10 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2688
2689
|
* 构造 git 通道实例(同步引擎与 issue #79 的工作副本自检/重建共用同一份地址与凭据口径)。
|
|
2689
2690
|
* token 只经 credentials 端口现取(值永不落盘/日志/回传)。
|
|
2690
2691
|
*/
|
|
2691
|
-
const makeGitTransport = (repoUrl: string): GitTransport => new GitTransport({
|
|
2692
|
+
const makeGitTransport = (repoUrl: string, subdir?: string): GitTransport => new GitTransport({
|
|
2692
2693
|
repoUrl,
|
|
2694
|
+
// issue #131:子目录前缀与 repoUrl 同源(配置 → 传输层),空串 = 仓库根
|
|
2695
|
+
...(subdir === undefined ? {} : { subdir }),
|
|
2693
2696
|
workDir: gitWorkDir,
|
|
2694
2697
|
credentials: {
|
|
2695
2698
|
getToken: async () => {
|
|
@@ -2752,10 +2755,11 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2752
2755
|
msg,
|
|
2753
2756
|
})
|
|
2754
2757
|
} else {
|
|
2755
|
-
transport = makeGitTransport(cfg.git.repoUrl)
|
|
2758
|
+
transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir)
|
|
2756
2759
|
}
|
|
2757
2760
|
const channel: SyncTransportType = channelOf(cfg)
|
|
2758
|
-
const
|
|
2761
|
+
const selection = selectionCache[channel] ?? defaultSyncSelection()
|
|
2762
|
+
const sections = effectiveSections(selection)
|
|
2759
2763
|
return new SyncEngine({
|
|
2760
2764
|
ctx: host,
|
|
2761
2765
|
transport,
|
|
@@ -2766,11 +2770,10 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
2766
2770
|
zipDir: tmpDir,
|
|
2767
2771
|
msg,
|
|
2768
2772
|
...(sections === undefined ? {} : { sections }),
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
// m-retention
|
|
2773
|
-
// 与改造前逐字等价);用户改完策略即时生效(每次 prune 都重读)。
|
|
2773
|
+
// issue #132:开关开 = 授权(手动/自动同判据);self 守卫防同步把自己删掉
|
|
2774
|
+
deletePlugins: selection.deletePlugins, selfPluginName: PLUGIN_NPM_PACKAGE,
|
|
2775
|
+
...(engineOpts.optInSections?.length ? { optInSections: engineOpts.optInSections } : {}),
|
|
2776
|
+
// m-retention:远端裁剪与本地备份共用 GFS 策略(缺省最近 10 个,每次 prune 重读 ⇒ 改完即时生效)。
|
|
2774
2777
|
retentionPolicy: () => retentionPolicyProvider(),
|
|
2775
2778
|
})
|
|
2776
2779
|
}
|
|
@@ -3054,20 +3057,20 @@ function makeRoutes(deps: RoutesDeps): {
|
|
|
3054
3057
|
syncWorkDir: {
|
|
3055
3058
|
// 自检失败(git 不可用 / 工作副本异常)→ 返回 { error },**不让整个状态接口 500**,
|
|
3056
3059
|
// 也不伪装成「工作副本不存在」。
|
|
3057
|
-
inspect: async (repoUrl: string, opts: { detail?: boolean } = {}): Promise<{ facts: GitWorkDirFacts } | { error: string }> => {
|
|
3060
|
+
inspect: async (repoUrl: string, opts: { detail?: boolean; subdir?: string } = {}): Promise<{ facts: GitWorkDirFacts } | { error: string }> => {
|
|
3058
3061
|
try {
|
|
3059
3062
|
// issue #104 建议 3:`/sync/status` 要回传「领先远端提交数 / 远端快照数」,
|
|
3060
3063
|
// 用户看不见积压就会在「以为在备份」的状态下一直失败。detail 那几条是本地只读但各起
|
|
3061
3064
|
// 一次 git 进程(Windows 约 80 ms)⇒ 缺省完整(WorkDirCard 要),路由可传 false。
|
|
3062
|
-
return { facts: await makeGitTransport(repoUrl).inspectWorkDir({ detail: opts.detail !== false }) }
|
|
3065
|
+
return { facts: await makeGitTransport(repoUrl, opts.subdir).inspectWorkDir({ detail: opts.detail !== false }) }
|
|
3063
3066
|
} catch (err) {
|
|
3064
3067
|
return { error: err instanceof Error ? err.message : String(err) }
|
|
3065
3068
|
}
|
|
3066
3069
|
},
|
|
3067
3070
|
// 重建:relink 非破坏;adopt 合并远端历史(不改写本地提交,issue #104);
|
|
3068
3071
|
// reclone 删目录重克隆(调用方必须先取得用户确认)
|
|
3069
|
-
rebuild: async (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone'): Promise<GitWorkDirFacts> => {
|
|
3070
|
-
const transport = makeGitTransport(repoUrl)
|
|
3072
|
+
rebuild: async (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone', subdir?: string): Promise<GitWorkDirFacts> => {
|
|
3073
|
+
const transport = makeGitTransport(repoUrl, subdir)
|
|
3071
3074
|
await transport.rebuildWorkDir(mode)
|
|
3072
3075
|
return await transport.inspectWorkDir()
|
|
3073
3076
|
},
|
|
@@ -3793,8 +3796,7 @@ export function apply(ctx: Context, config?: Config): void {
|
|
|
3793
3796
|
namespaces: async () => (await ctx.settings.describe({ redactSecrets: true })).map((d) => String(d.ns)),
|
|
3794
3797
|
// Sessions 分区默认关(含敏感内容):挂载 adapter 供 Custom Export 显式勾选(§3.3/§15)。
|
|
3795
3798
|
includeSessions: true,
|
|
3796
|
-
// 导出 plugins
|
|
3797
|
-
selfPluginName: PLUGIN_NAME,
|
|
3799
|
+
selfPluginName: PLUGIN_NAME, // 导出 plugins 分区时不列本插件自身,避免备份里的自引用条目
|
|
3798
3800
|
// pluginFiles 扩展:额外白名单文件 + 约定配置目录(都相对 ~/.dsh 根),支持导出更多插件配置。
|
|
3799
3801
|
pluginFiles: config?.pluginFiles,
|
|
3800
3802
|
pluginFilesDir: config?.pluginFilesDir,
|
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 级信号)。
|
|
@@ -32,11 +32,11 @@ import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'
|
|
|
32
32
|
import { engineMsg } from '../core/engine-locale.ts'
|
|
33
33
|
import { createPreRestoreAttemptDir } from '../core/restore.ts'
|
|
34
34
|
import type { RestoreActionKind, RestorePlan, RestoreReport } from '../core/restore.ts'
|
|
35
|
-
import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
|
|
35
|
+
import { collectRestoreWalEntries, createRestoreWal, isExternalPluginKind, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.ts'
|
|
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'
|
|
@@ -554,6 +554,8 @@ export interface RestoreExecutor {
|
|
|
554
554
|
removeHome(relPath: string): Promise<void>
|
|
555
555
|
/** 卸载插件(官方通道);失败返回 { ok:false, message } */
|
|
556
556
|
uninstallPlugin(name: string): Promise<{ ok: boolean; message?: string }>
|
|
557
|
+
/** 装回跟远端删掉的插件(官方通道,issue 132 的反向);失败返回 { ok:false, message } */
|
|
558
|
+
installPlugin(name: string, target: string): Promise<{ ok: boolean; message?: string }>
|
|
557
559
|
/**
|
|
558
560
|
* home 相对路径 → 磁盘绝对路径(逐动作 WAL 用:journal 的 ref 必须是绝对路径,
|
|
559
561
|
* reconcile 的 verifyStepFingerprint 直接拿它读盘算指纹)。缺省 = 不登记 WAL。
|
|
@@ -578,6 +580,7 @@ export async function executeRestorePlan(
|
|
|
578
580
|
snapshotId: plan.snapshotId,
|
|
579
581
|
restored: [],
|
|
580
582
|
removedPlugins: [],
|
|
583
|
+
installedPlugins: [],
|
|
581
584
|
manualHints: [],
|
|
582
585
|
failed: [],
|
|
583
586
|
skipped: [],
|
|
@@ -589,7 +592,7 @@ export async function executeRestorePlan(
|
|
|
589
592
|
const walByAction = new Map<(typeof plan.actions)[number], RestoreWalHandle | undefined>()
|
|
590
593
|
const resume = resumeHint
|
|
591
594
|
const absOf = (action: (typeof plan.actions)[number]): string | null =>
|
|
592
|
-
action.kind
|
|
595
|
+
isExternalPluginKind(action.kind) || action.target === undefined || exec.absPath === undefined
|
|
593
596
|
? null
|
|
594
597
|
: exec.absPath(action.target)
|
|
595
598
|
if (wal !== null && exec.absPath !== undefined) {
|
|
@@ -656,6 +659,21 @@ export async function executeRestorePlan(
|
|
|
656
659
|
}
|
|
657
660
|
break
|
|
658
661
|
}
|
|
662
|
+
case 'pluginInstall': {
|
|
663
|
+
const name = action.pluginName
|
|
664
|
+
const target = action.pluginTarget ?? name
|
|
665
|
+
if (name === undefined || target === undefined) throw new Error(engineMsg('restore.missingPluginName'))
|
|
666
|
+
const result = await exec.installPlugin(name, target)
|
|
667
|
+
if (result.ok) {
|
|
668
|
+
report.installedPlugins.push(target)
|
|
669
|
+
} else {
|
|
670
|
+
const reason = result.message ?? engineMsg('restore.pluginInstallFailed')
|
|
671
|
+
report.failed.push({ item: `plugin:${name}`, reason })
|
|
672
|
+
settleStatus = 'attention'
|
|
673
|
+
settleMessage = reason
|
|
674
|
+
}
|
|
675
|
+
break
|
|
676
|
+
}
|
|
659
677
|
case 'credentialHint':
|
|
660
678
|
report.manualHints.push(action.manualHint ?? action.description)
|
|
661
679
|
break
|
|
@@ -720,6 +738,13 @@ export function makeRestoreExecutor(snapshotDir: string, host: HostContext, prof
|
|
|
720
738
|
const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput')
|
|
721
739
|
return { ok: false, message: msgOf(host)('host.restoreUninstallFailed', { name, code: String(result.exitCode), tail }) }
|
|
722
740
|
},
|
|
741
|
+
installPlugin: async (name, target) => {
|
|
742
|
+
const result = await runDshPlugin(profileDir, profile, ['add', target])
|
|
743
|
+
if (result.exitCode === 0) return { ok: true }
|
|
744
|
+
const output = `${result.stderr}\n${result.stdout}`.trim()
|
|
745
|
+
const tail = output.split('\n').slice(-8).join('\n') || msgOf(host)('host.restoreNoOutput')
|
|
746
|
+
return { ok: false, message: engineMsg('restore.installFailedExit', { name, code: String(result.exitCode), tail }) }
|
|
747
|
+
},
|
|
723
748
|
}
|
|
724
749
|
}
|
|
725
750
|
|
|
@@ -756,7 +781,8 @@ export interface SyncRefScope {
|
|
|
756
781
|
/**
|
|
757
782
|
* 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
|
|
758
783
|
* 请求体形状(flat,M4 契约):
|
|
759
|
-
* - git: { transport:'git', repoUrl, token? } ——
|
|
784
|
+
* - git: { transport:'git', repoUrl, subdir?, token? } —— subdir = 仓库内子目录前缀(issue #131);
|
|
785
|
+
* token 非空写 SYNC_CREDENTIAL_REF;
|
|
760
786
|
* git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
|
|
761
787
|
* - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
|
|
762
788
|
* 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
|
|
@@ -802,6 +828,9 @@ export async function parseSyncBody(
|
|
|
802
828
|
if (repoUrl === '') throw new SyncRouteError('repoUrl is required')
|
|
803
829
|
const urlError = validateRepoUrl(repoUrl)
|
|
804
830
|
if (urlError !== null) throw new SyncRouteError(urlError)
|
|
831
|
+
// issue #131:仓库内子目录前缀(可选;空 = 仓库根)。非法值在这里就拒,绝不先落盘再交给 git。
|
|
832
|
+
const subdirCheck = normalizeGitSubdir(syncStr(body['subdir']))
|
|
833
|
+
if (!subdirCheck.ok) throw new SyncRouteError(engineMsg('sync.git.subdirInvalid', { subdir: syncStr(body['subdir']) }))
|
|
805
834
|
const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined
|
|
806
835
|
if (token !== undefined) {
|
|
807
836
|
try {
|
|
@@ -816,7 +845,7 @@ export async function parseSyncBody(
|
|
|
816
845
|
return {
|
|
817
846
|
schemaVersion: 2,
|
|
818
847
|
transport: 'git',
|
|
819
|
-
git: { repoUrl },
|
|
848
|
+
git: { repoUrl, ...(subdirCheck.value === '' ? {} : { subdir: subdirCheck.value }) },
|
|
820
849
|
}
|
|
821
850
|
}
|
|
822
851
|
|
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)
|
|
@@ -1217,6 +1220,9 @@ export function syncRoutes(env: RoutesEnv): WebRoute[] {
|
|
|
1217
1220
|
encrypt: body['encrypt'] === true,
|
|
1218
1221
|
// 安全兜底:includeSecrets 必须同时 encrypt(密钥绝不明文进同步通道)
|
|
1219
1222
|
includeSecrets: body['includeSecrets'] === true && body['encrypt'] === true,
|
|
1223
|
+
// issue #132:跟随远端删除插件。缺省关;请求体非 true 一律按关处理
|
|
1224
|
+
// (重新保存表单时收起开关 = 明确关掉,不留上一次的 true)
|
|
1225
|
+
deletePlugins: body['deletePlugins'] === true,
|
|
1220
1226
|
}
|
|
1221
1227
|
// 加密/解密密码持久化(用户要求:勾选即记住,取消勾选或主动删除才清)。
|
|
1222
1228
|
// 值只写进 DSH credentials(绝不进 sync-selection.json / 日志 / 响应);
|
|
@@ -200,6 +200,7 @@ class MemCredentials implements CredentialsFacade {
|
|
|
200
200
|
class MemPlugins implements PluginsFacade {
|
|
201
201
|
async listInstalled() { return []; }
|
|
202
202
|
async install(_pkg: string, _spec?: string) { return { needsRestart: true }; }
|
|
203
|
+
async uninstall(_pkg: string) { return { needsRestart: true }; }
|
|
203
204
|
}
|
|
204
205
|
|
|
205
206
|
class MemWorkspace implements WorkspaceFacade {
|
|
@@ -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
|
+
|