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.
Files changed (79) hide show
  1. package/lib/client.d.ts +8 -0
  2. package/lib/client.js +748 -602
  3. package/lib/core/local-plugin-host.d.ts +9 -0
  4. package/lib/core/local-plugin-host.js +174 -1
  5. package/lib/core/messages.d.ts +7 -0
  6. package/lib/core/messages.js +16 -0
  7. package/lib/core/migration-history.d.ts +40 -0
  8. package/lib/core/migration-history.js +55 -0
  9. package/lib/core/plugin-cli.d.ts +5 -0
  10. package/lib/core/plugin-cli.js +11 -3
  11. package/lib/core/run-registry.d.ts +10 -0
  12. package/lib/core/run-registry.js +17 -0
  13. package/lib/index.d.ts +7 -2
  14. package/lib/index.js +20 -19
  15. package/lib/profiles/dsh-profile-manager.d.ts +1 -1
  16. package/lib/profiles/dsh-profile-manager.js +26 -7
  17. package/lib/profiles/dsh-profile-shared.d.ts +3 -1
  18. package/lib/routes/import.js +6 -1
  19. package/lib/routes/route-support.d.ts +2 -1
  20. package/lib/routes/route-support.js +8 -3
  21. package/lib/routes/sync.js +5 -2
  22. package/lib/sync/autosync-config.d.ts +9 -1
  23. package/lib/sync/autosync-config.js +10 -2
  24. package/lib/sync/autosync-scheduler.js +18 -6
  25. package/lib/sync/git/git-transport.d.ts +31 -1
  26. package/lib/sync/git/git-transport.js +119 -23
  27. package/lib/sync/sync-config.d.ts +34 -3
  28. package/lib/sync/sync-config.js +38 -5
  29. package/lib/ui/sync-repository-picker.d.ts +21 -0
  30. package/lib/ui/sync-repository-picker.js +18 -0
  31. package/lib/ui/sync-settings-view.d.ts +4 -0
  32. package/lib/ui/sync-settings-view.js +3 -0
  33. package/lib/utils/remove-tree.d.ts +7 -0
  34. package/lib/utils/remove-tree.js +265 -0
  35. package/package.json +1 -1
  36. package/src/client/config-manager.module.css +21 -1
  37. package/src/client/environment/EnvironmentPanel.tsx +2 -2
  38. package/src/client/locales/profiles.ts +2 -0
  39. package/src/client/run-store.test.ts +1 -1
  40. package/src/client/run-store.ts +5 -0
  41. package/src/client/sync/ChannelConfigDialog.tsx +47 -2
  42. package/src/client/sync/SyncPanel.tsx +17 -30
  43. package/src/client/sync/SyncRepositoryPicker.tsx +34 -13
  44. package/src/client/sync/SyncSettingsView.test.ts +32 -0
  45. package/src/client/sync/config-save-state.test.ts +99 -0
  46. package/src/client/sync/config-save-state.ts +69 -0
  47. package/src/client/sync/sync-api.ts +2 -0
  48. package/src/client/sync/sync-locales.ts +10 -0
  49. package/src/core/engine-locale.test.ts +4 -0
  50. package/src/core/local-plugin-host.test.ts +31 -2
  51. package/src/core/local-plugin-host.ts +175 -2
  52. package/src/core/messages.ts +16 -0
  53. package/src/core/migration-history.test.ts +65 -0
  54. package/src/core/migration-history.ts +70 -0
  55. package/src/core/plugin-cli.fs.test.ts +30 -3
  56. package/src/core/plugin-cli.ts +11 -3
  57. package/src/core/run-registry-runs.test.ts +26 -1
  58. package/src/core/run-registry.ts +18 -0
  59. package/src/index.sync.test.ts +27 -0
  60. package/src/index.ts +21 -21
  61. package/src/profiles/dsh-profile-manager.test.ts +20 -0
  62. package/src/profiles/dsh-profile-manager.ts +25 -7
  63. package/src/profiles/dsh-profile-shared.ts +2 -0
  64. package/src/routes/import.ts +6 -1
  65. package/src/routes/route-support.ts +7 -3
  66. package/src/routes/sync.ts +5 -2
  67. package/src/sync/autosync-config.ts +10 -2
  68. package/src/sync/autosync-scheduler.test.ts +61 -1
  69. package/src/sync/autosync-scheduler.ts +17 -5
  70. package/src/sync/git/git-transport.test.ts +117 -0
  71. package/src/sync/git/git-transport.ts +131 -23
  72. package/src/sync/sync-config.test.ts +59 -1
  73. package/src/sync/sync-config.ts +51 -5
  74. package/src/ui/sync-repository-picker.test.ts +34 -1
  75. package/src/ui/sync-repository-picker.ts +24 -0
  76. package/src/ui/sync-settings-view.test.ts +1 -0
  77. package/src/ui/sync-settings-view.ts +7 -0
  78. package/src/utils/remove-tree.test.ts +120 -0
  79. package/src/utils/remove-tree.ts +239 -0
package/lib/index.js CHANGED
@@ -90,6 +90,7 @@ import { PROJECT_KEY_RE, readLogCwdFromBytes, rewriteSessionLogDir } from './uti
90
90
  import { probeSessionFormats, resolveSessionFormatVersion } from './utils/session-format.js';
91
91
  import { describePatchYamlError, dumpPatchDocument, loadPatchDocument } from './utils/patch-yaml.js';
92
92
  import { atomicCopyFile, atomicWriteFile } from './utils/atomic-write.js';
93
+ import { removeTree } from './utils/remove-tree.js';
93
94
  import { isENOENT } from './utils/guards.js';
94
95
  import { EnvironmentLockManager, runWithMutationLock } from './utils/env-lock.js';
95
96
  import { activeProxySummary } from './utils/proxy.js';
@@ -111,7 +112,7 @@ import { AUTO_BACKUP_PREFIX, isValidExportFileName, resolveNonCollidingExportNam
111
112
  import { DEFAULT_RETENTION_POLICY, selectPruneCandidatesByPolicy } from './sync/retention-policy.js';
112
113
  import { selectPruneCandidates } from './core/backup.js';
113
114
  import { appendAutosyncEntry } from './sync/sync-history.js';
114
- import { MigrationStore, historyResultFromAutosyncStatus, MIGRATION_HISTORY_DIR } from './core/migration-history.js';
115
+ import { MigrationStore, autosyncUnifiedHistoryInput, MIGRATION_HISTORY_DIR } from './core/migration-history.js';
115
116
  import { createHistoryPruner } from './core/history-prune.js';
116
117
  import { isWebDavConfig, isS3Config, isGistConfig, channelOf, SYNC_CHANNELS, GIST_PROVIDER, cloudSecretRef } from './sync/sync-config.js';
117
118
  import { resolveSessionFormatDisposition, sessionFormatAbortResponse, } from './routes/session-format.js';
@@ -147,7 +148,7 @@ export const name = 'config-manager';
147
148
  /** Services required before the engine can mount (present in every profile). */
148
149
  export const inject = ['settings', 'credentials'];
149
150
  /** Plugin version, kept in sync with package.json ("version"). */
150
- export const PLUGIN_VERSION = '0.5.0';
151
+ export const PLUGIN_VERSION = '0.7.0';
151
152
  /** Plugin own package name — excluded from its own exported plugins list. */
152
153
  const PLUGIN_NAME = 'dsh-config-manager';
153
154
  /**
@@ -1605,8 +1606,12 @@ export class DshFileSystemFacade {
1605
1606
  async copy(from, to) {
1606
1607
  await atomicCopyFile(this.abs(from), this.abs(to));
1607
1608
  }
1609
+ /**
1610
+ * 递归删除(home 内,缺失目标视为成功)。**不用 fs.rm(recursive)**:目录里有悬空链接时它静默
1611
+ * 空转(报告写「已还原」而磁盘原样在)。removeTree 逐条删、只删链接本身、删不净就抛错。
1612
+ */
1608
1613
  async remove(relPath) {
1609
- await fs.rm(this.abs(relPath), { recursive: true, force: true });
1614
+ await removeTree(this.abs(relPath));
1610
1615
  }
1611
1616
  /** 仅路径列表(既有契约):委托 listRecursiveDetailed,丢弃诊断。 */
1612
1617
  async listRecursive(dir) {
@@ -2367,8 +2372,10 @@ function makeRoutes(deps) {
2367
2372
  * 构造 git 通道实例(同步引擎与 issue #79 的工作副本自检/重建共用同一份地址与凭据口径)。
2368
2373
  * token 只经 credentials 端口现取(值永不落盘/日志/回传)。
2369
2374
  */
2370
- const makeGitTransport = (repoUrl) => new GitTransport({
2375
+ const makeGitTransport = (repoUrl, subdir) => new GitTransport({
2371
2376
  repoUrl,
2377
+ // issue #131:子目录前缀与 repoUrl 同源(配置 → 传输层),空串 = 仓库根
2378
+ ...(subdir === undefined ? {} : { subdir }),
2372
2379
  workDir: gitWorkDir,
2373
2380
  credentials: {
2374
2381
  getToken: async () => {
@@ -2433,7 +2440,7 @@ function makeRoutes(deps) {
2433
2440
  });
2434
2441
  }
2435
2442
  else {
2436
- transport = makeGitTransport(cfg.git.repoUrl);
2443
+ transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir);
2437
2444
  }
2438
2445
  const channel = channelOf(cfg);
2439
2446
  const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection());
@@ -2476,17 +2483,11 @@ function makeRoutes(deps) {
2476
2483
  // Phase 6:autosync 既写 sync-history.json(既有语义),也写统一迁移历史(COMPLETE 不变量)。
2477
2484
  appendHistoryFn: async (entry) => {
2478
2485
  await appendAutosyncEntry(syncDir, entry).catch(() => undefined);
2479
- await history.append({
2480
- kind: 'autosync',
2481
- result: historyResultFromAutosyncStatus(entry.status),
2482
- sections: entry.appliedSections ?? [],
2483
- source: 'autosync',
2484
- summary: engineMsg('host.autosyncSummary', {
2485
- direction: entry.direction,
2486
- transportSuffix: entry.transport !== undefined ? engineMsg('host.autosyncTransportSuffix', { transport: entry.transport }) : '',
2487
- }),
2488
- error: entry.status === 'failed' ? (entry.error ?? entry.skipReason) : undefined,
2489
- }).catch(() => undefined);
2486
+ // 空检查轮(每 60s 一次的远端探测,什么都没传)不进统一历史;payload 组装与判据见 core。
2487
+ const input = autosyncUnifiedHistoryInput(entry, engineMsg);
2488
+ if (input === null)
2489
+ return;
2490
+ await history.append({ kind: 'autosync', ...input }).catch(() => undefined);
2490
2491
  },
2491
2492
  });
2492
2493
  // P1-B:调度器不再在 makeRoutes 内同步 start —— 由 apply() 在「启动 recovery 分类完成后、仅 NORMAL」时启动。
@@ -2740,7 +2741,7 @@ function makeRoutes(deps) {
2740
2741
  // issue #104 建议 3:`/sync/status` 要回传「领先远端提交数 / 远端快照数」,
2741
2742
  // 用户看不见积压就会在「以为在备份」的状态下一直失败。detail 那几条是本地只读但各起
2742
2743
  // 一次 git 进程(Windows 约 80 ms)⇒ 缺省完整(WorkDirCard 要),路由可传 false。
2743
- return { facts: await makeGitTransport(repoUrl).inspectWorkDir({ detail: opts.detail !== false }) };
2744
+ return { facts: await makeGitTransport(repoUrl, opts.subdir).inspectWorkDir({ detail: opts.detail !== false }) };
2744
2745
  }
2745
2746
  catch (err) {
2746
2747
  return { error: err instanceof Error ? err.message : String(err) };
@@ -2748,8 +2749,8 @@ function makeRoutes(deps) {
2748
2749
  },
2749
2750
  // 重建:relink 非破坏;adopt 合并远端历史(不改写本地提交,issue #104);
2750
2751
  // reclone 删目录重克隆(调用方必须先取得用户确认)
2751
- rebuild: async (repoUrl, mode) => {
2752
- const transport = makeGitTransport(repoUrl);
2752
+ rebuild: async (repoUrl, mode, subdir) => {
2753
+ const transport = makeGitTransport(repoUrl, subdir);
2753
2754
  await transport.rebuildWorkDir(mode);
2754
2755
  return await transport.inspectWorkDir();
2755
2756
  },
@@ -109,7 +109,7 @@ export declare class DshProfileManager {
109
109
  /** 单个链接的重指向(失败保持原样:源档案还在时仍旧可用,不让整次复制失败)。 */
110
110
  private relinkCopiedEntry;
111
111
  /**
112
- * 物理删除 profile 目录(rmSync recursive;目录内 junction 只删链接本身)。
112
+ * 物理删除 profile 目录(removeTreeSync;目录内 junction 只删链接本身,删不干净报 deleteFailed)。
113
113
  * 当前运行中的 profile 需要 allowCurrent=true 显式确认(删除会让重启后的实例直接失败)。
114
114
  *
115
115
  * Desktop 独占档案(desktop)**一律拒绝**(连 allowCurrent 也不行):它由桌面端应用自己
@@ -18,14 +18,17 @@
18
18
  * 历史上这里还有一个 `<dataDir>/next-profile`「下次启动」标记——DSH 根本没有消费者,
19
19
  * 只会误导用户(2026-09 按产品决策整体移除,连同前端按钮)。
20
20
  *
21
- * 物理删除:remove() 走 rmSync(recursive),profile 目录内的 junction(pnpm 链接)
22
- * 只删链接本身,不会跟随进 pnpm store。
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 } from 'node:fs';
25
27
  // 复制走 async fs(整档案上万个文件,cpSync 会把宿主事件循环卡住二十多秒)
26
- import { copyFile, cp, mkdir, readdir, readlink, rm, stat, symlink, unlink } from 'node:fs/promises';
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.js';
31
+ import { removeTree, removeTreeSync } from '../utils/remove-tree.js';
29
32
  import { isRecord } from '../utils/guards.js';
30
33
  import { resolveProfileDir, validateProfileName } from '../core/plugin-cli.js';
31
34
  import { readTextSafe } from './dsh-profile-io.js';
@@ -74,9 +77,15 @@ function isInsideDir(root, candidate) {
74
77
  }
75
78
  /** t89:profiles 根目录枚举失败的原因码(诊断/日志用)。 */
76
79
  export const PROFILES_ROOT_UNREADABLE = 'profiles-root-unreadable';
77
- /** 回滚复制目标目录的缺省删除实现(递归强制;不存在不算错)。 */
80
+ /**
81
+ * 回滚复制目标目录的缺省删除实现(不存在不算错)。
82
+ *
83
+ * 必须走 removeTree 而不是 fs.rm(recursive):半截副本里可能已经有指向
84
+ * `.dsh-module-fallback` 的悬空 junction,fs.rm 会「成功」却一个字节都不删,
85
+ * 回滚于是无声失败。
86
+ */
78
87
  const defaultProfileRemove = async (target) => {
79
- await rm(target, { recursive: true, force: true });
88
+ await removeTree(target);
80
89
  };
81
90
  /**
82
91
  * 复制失败时回滚目标目录(cross-F3 收尾 / tech-debt #5)。
@@ -398,7 +407,7 @@ export class DshProfileManager {
398
407
  }
399
408
  }
400
409
  /**
401
- * 物理删除 profile 目录(rmSync recursive;目录内 junction 只删链接本身)。
410
+ * 物理删除 profile 目录(removeTreeSync;目录内 junction 只删链接本身,删不干净报 deleteFailed)。
402
411
  * 当前运行中的 profile 需要 allowCurrent=true 显式确认(删除会让重启后的实例直接失败)。
403
412
  *
404
413
  * Desktop 独占档案(desktop)**一律拒绝**(连 allowCurrent 也不行):它由桌面端应用自己
@@ -414,7 +423,17 @@ export class DshProfileManager {
414
423
  if (name === this.currentProfile() && opts.allowCurrent !== true) {
415
424
  throw new DshProfileError('currentProfile');
416
425
  }
417
- rmSync(dir, { recursive: true, force: true });
426
+ // 不用 rmSync(recursive):悬空 junction 会让它静默空转(见 utils/remove-tree.ts 头注)。
427
+ // 删不掉必须变成可见错误码,绝不回 200 —— 那正是「点了删除、档案还在」的成因。
428
+ try {
429
+ removeTreeSync(dir);
430
+ }
431
+ catch (error) {
432
+ throw new DshProfileError('deleteFailed', error instanceof Error ? error.message : String(error));
433
+ }
434
+ if (existsSync(dir)) {
435
+ throw new DshProfileError('deleteFailed', `profile directory still exists after removal: ${dir}`);
436
+ }
418
437
  }
419
438
  /**
420
439
  * cross-F3:目标目录 = **正常 profile(有 package.json)** 或 **中断的复制残留(有进行中标记)**;
@@ -241,7 +241,9 @@ export type DshProfileErrorCode = 'invalidName' | 'reservedName' | 'exists' | 'n
241
241
  /** 复制档案中途失败(目标目录已回滚,磁盘上不留半套副本) */
242
242
  | 'copyFailed'
243
243
  /** 该档案由 Desktop 应用独占管理(启动 / 删除 / 改名一律拒绝,操作它会让桌面端起不来) */
244
- | 'managedProfile';
244
+ | 'managedProfile'
245
+ /** 目录删不干净(被占用 / 权限不足;message 里附底层原因)—— 绝不是「删成功」 */
246
+ | 'deleteFailed';
245
247
  /** 复制档案的非致命告警码(UI 按码映射文案,绝不静默)。 */
246
248
  export type DshProfileCopyWarning =
247
249
  /** 副本没有 node_modules 却声明了依赖:直接启动会解析不到 bundle,必须先装依赖 */
@@ -5,6 +5,7 @@
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
7
  import { endpoint, requireJsonObject, readJsonBody, writeJson, queryParam } from './kit.js';
8
+ import { isIdleAutosyncRun } from '../core/run-registry.js';
8
9
  import { DEFAULT_ROLLBACK_ON_ERROR } from '../core/import-defaults.js';
9
10
  import { decryptErrorText, isControlledPath, tryDecryptCredentials, writeRequestBodyToFile } from './route-support.js';
10
11
  import { resolveSessionFormatDisposition, sessionFormatAbortResponse } from './session-format.js';
@@ -347,7 +348,11 @@ export function importRoutes(env) {
347
348
  endpoint({ path: '/api/dsh-config-manager/runs', methods: ['GET'] }, async (req, res) => {
348
349
  const url = new URL(req.url ?? '/', 'http://localhost');
349
350
  const scope = queryParam(url, 'scope');
350
- writeJson(res, 200, scope === 'recent' ? runs.listRecent(50) : runs.listActive());
351
+ // 空转的自动同步轮次不进「运行中心」:60s 一次轮询,每轮一张「已完成」卡片与迁移历史同属噪音;
352
+ // running / 真干活的轮次照常列出(判据见 core/run-registry.ts 的 isIdleAutosyncRun)。
353
+ writeJson(res, 200, scope === 'recent'
354
+ ? runs.listRecent(50).filter((run) => !isIdleAutosyncRun(run))
355
+ : runs.listActive());
351
356
  }),
352
357
  // ------------------------------------------------------- runs/cancel
353
358
  // 运行中心「终止」:只在**计划项边界**生效的协作式取消(abort run 级信号)。
@@ -273,7 +273,8 @@ export interface SyncRefScope {
273
273
  /**
274
274
  * 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
275
275
  * 请求体形状(flat,M4 契约):
276
- * - git: { transport:'git', repoUrl, token? } —— token 非空写 SYNC_CREDENTIAL_REF;
276
+ * - git: { transport:'git', repoUrl, subdir?, token? } —— subdir = 仓库内子目录前缀(issue #131);
277
+ * token 非空写 SYNC_CREDENTIAL_REF;
277
278
  * git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
278
279
  * - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
279
280
  * 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
@@ -25,7 +25,7 @@ import { decryptCredentials, SecurityError } from '../security/index.js';
25
25
  import { engineMsg } from '../core/engine-locale.js';
26
26
  import { createPreRestoreAttemptDir } from '../core/restore.js';
27
27
  import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.js';
28
- import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.js';
28
+ import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, normalizeGitSubdir, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.js';
29
29
  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.js';
30
30
  import { SYNC_CHANNELS } from '../sync/sync-config.js';
31
31
  import { normalizeSessionsInclude } from '../sync/sync-selection.js';
@@ -617,7 +617,8 @@ export function makeRestoreExecutor(snapshotDir, host, profile) {
617
617
  /**
618
618
  * 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
619
619
  * 请求体形状(flat,M4 契约):
620
- * - git: { transport:'git', repoUrl, token? } —— token 非空写 SYNC_CREDENTIAL_REF;
620
+ * - git: { transport:'git', repoUrl, subdir?, token? } —— subdir = 仓库内子目录前缀(issue #131);
621
+ * token 非空写 SYNC_CREDENTIAL_REF;
621
622
  * git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
622
623
  * - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
623
624
  * 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
@@ -665,6 +666,10 @@ export async function parseSyncBody(body, deps) {
665
666
  const urlError = validateRepoUrl(repoUrl);
666
667
  if (urlError !== null)
667
668
  throw new SyncRouteError(urlError);
669
+ // issue #131:仓库内子目录前缀(可选;空 = 仓库根)。非法值在这里就拒,绝不先落盘再交给 git。
670
+ const subdirCheck = normalizeGitSubdir(syncStr(body['subdir']));
671
+ if (!subdirCheck.ok)
672
+ throw new SyncRouteError(engineMsg('sync.git.subdirInvalid', { subdir: syncStr(body['subdir']) }));
668
673
  const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined;
669
674
  if (token !== undefined) {
670
675
  try {
@@ -678,7 +683,7 @@ export async function parseSyncBody(body, deps) {
678
683
  return {
679
684
  schemaVersion: 2,
680
685
  transport: 'git',
681
- git: { repoUrl },
686
+ git: { repoUrl, ...(subdirCheck.value === '' ? {} : { subdir: subdirCheck.value }) },
682
687
  };
683
688
  }
684
689
  /** 请求体字段 → 去空白字符串(非字符串 = 空)。 */
@@ -187,14 +187,17 @@ export function syncRoutes(env) {
187
187
  // 远端快照数」(只读自检;后者是「本地一直没真正备份」的预警依据)。
188
188
  // 读不出来时**如实回传错误**(workDirError),不让状态接口静默少一块信息。
189
189
  const gitRepoUrl = full?.git?.repoUrl ?? '';
190
+ // issue #131:自检必须按配置的子目录前缀读(远端快照数来自 <subdir>/snapshots)
191
+ const gitSubdir = full?.git?.subdir ?? '';
190
192
  let workDir = null;
191
193
  if (gitRepoUrl !== '')
192
- workDir = await syncWorkDir.inspect(gitRepoUrl, { detail: opts.workDirDetail });
194
+ workDir = await syncWorkDir.inspect(gitRepoUrl, { detail: opts.workDirDetail, ...(gitSubdir === '' ? {} : { subdir: gitSubdir }) });
193
195
  return {
194
196
  ok: true,
195
197
  configured: full !== null,
196
198
  transport,
197
199
  repoUrl: full?.git?.repoUrl,
200
+ subdir: full?.git?.subdir,
198
201
  // 被丢弃的通道配置成因(默认空数组:字段恒在,客户端不必判 undefined;
199
202
  // 合法配置不产生幻影告警)。code 是机读 token,message 可直接展示。
200
203
  configIssues,
@@ -283,7 +286,7 @@ export function syncRoutes(env) {
283
286
  });
284
287
  return;
285
288
  }
286
- const rebuilt = await syncWorkDir.rebuild(repoUrl, mode);
289
+ const rebuilt = await syncWorkDir.rebuild(repoUrl, mode, full?.git?.subdir);
287
290
  writeJson(res, 200, { ok: true, mode, workDir: { facts: rebuilt } });
288
291
  }
289
292
  catch (error) {
@@ -9,7 +9,15 @@ export declare const DEFAULT_AUTOSYNC_INTERVAL: AutosyncInterval;
9
9
  export declare const DEFAULT_STARTUP_MIN_INTERVAL_MS: number;
10
10
  /** 缺省开启「本地改动即时触发」(真·自动同步;关闭后退回纯定时器) */
11
11
  export declare const DEFAULT_AUTOSYNC_REALTIME = true;
12
- /** 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 1 分钟内下行) */
12
+ /**
13
+ * 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 5 分钟内下行)。
14
+ *
15
+ * 2026-11-09 由 60s 改为 5 分钟(用户拍板):远端探测本身很便宜,但过去每轮还会顺带做一次本地
16
+ * 全量导出判定,plugins 分区要为每个本机源插件跑 npm pack(真机 12 个 ≈12 s、单个 210MB 44.7 s)
17
+ * ⇒ 60 s 一轮等于长期占用一个核。本地改动的即时性由文件监听负责(local-change 触发),
18
+ * 兜底由 interval 负责,远端「有没有新快照」不需要 1 分钟一问。旧配置里已写死的值不在此处迁移
19
+ * (用户显式选过的值优先),需要改的走 POST /sync/autosync 的 remoteCheckMs。
20
+ */
13
21
  export declare const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS: number;
14
22
  /** 远端轮询间隔下限(15 s):再短只是空转 fetch,收益为零 */
15
23
  export declare const MIN_AUTOSYNC_REMOTE_CHECK_MS: number;
@@ -27,8 +27,16 @@ export const DEFAULT_AUTOSYNC_INTERVAL = '30m';
27
27
  export const DEFAULT_STARTUP_MIN_INTERVAL_MS = 5 * 60 * 1000;
28
28
  /** 缺省开启「本地改动即时触发」(真·自动同步;关闭后退回纯定时器) */
29
29
  export const DEFAULT_AUTOSYNC_REALTIME = true;
30
- /** 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 1 分钟内下行) */
31
- export const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS = 60 * 1000;
30
+ /**
31
+ * 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 5 分钟内下行)。
32
+ *
33
+ * 2026-11-09 由 60s 改为 5 分钟(用户拍板):远端探测本身很便宜,但过去每轮还会顺带做一次本地
34
+ * 全量导出判定,plugins 分区要为每个本机源插件跑 npm pack(真机 12 个 ≈12 s、单个 210MB 44.7 s)
35
+ * ⇒ 60 s 一轮等于长期占用一个核。本地改动的即时性由文件监听负责(local-change 触发),
36
+ * 兜底由 interval 负责,远端「有没有新快照」不需要 1 分钟一问。旧配置里已写死的值不在此处迁移
37
+ * (用户显式选过的值优先),需要改的走 POST /sync/autosync 的 remoteCheckMs。
38
+ */
39
+ export const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS = 5 * 60 * 1000;
32
40
  /** 远端轮询间隔下限(15 s):再短只是空转 fetch,收益为零 */
33
41
  export const MIN_AUTOSYNC_REMOTE_CHECK_MS = 15 * 1000;
34
42
  /** 远端轮询间隔上限(60 min):比这更慢就不该叫「实时」了 */
@@ -424,11 +424,11 @@ export class AutoSyncScheduler {
424
424
  * 仍 updatedAt == createdAt;此后每次 autosync 都 `register('autosync')` → RunConflictError
425
425
  * → 后台同步静默停摆(正是下面 finally 注释警告的后果),运行中心里那张卡片也「一直在加载」。
426
426
  */
427
- const finishRun = () => {
427
+ const finishRun = (extra = {}) => {
428
428
  if (runId === null)
429
429
  return;
430
430
  try {
431
- this.runs.finish(runId, { kind: 'autosync' });
431
+ this.runs.finish(runId, { kind: 'autosync', ...extra });
432
432
  }
433
433
  catch {
434
434
  /* 尽力而为:收尾失败不影响同步结果 */
@@ -440,11 +440,17 @@ export class AutoSyncScheduler {
440
440
  // (实测单个 210MB 插件 44.7s/次、每轮重算)。旧实现把这段整个放进 GLOBAL mutation 锁内,60s 一轮的
441
441
  // 轮询于是让锁几乎全程被占(45s/60s),用户任何 destructive 操作(删除档案…)都撞 423「另一个任务正在运行」。
442
442
  // 现在稳态(upToDate)根本不取锁;命中「有活干」才取,并在锁内重跑检测再写。
443
- const preflight = await this.detectPhase(channel, cfg, nowIso, historyId);
443
+ // 远端轮询轮跳过本地导出(reason='remote-poll'):本地改动由 realtime 监听(local-change 触发)
444
+ // 与 30 分钟兜底 interval 负责;这里每 60s 再跑一次全量导出 = 白跑 plugins 的 npm pack
445
+ // (真机单插件 44.7s/轮)。判定口径不变 —— 真要比对时比的仍是载荷字节,不做任何近似。
446
+ const preflight = await this.detectPhase(channel, cfg, nowIso, historyId, {
447
+ localCheck: opts.reason !== 'remote-poll',
448
+ });
444
449
  if (preflight.kind === 'skip') {
445
450
  this.running = false;
446
451
  this.watcher?.resume();
447
- finishRun();
452
+ // 空转轮(什么都没传)打上 idle:运行中心据此不为它留卡片(见 core/run-registry 的 isIdleAutosyncRun)。
453
+ finishRun(preflight.result.skipReason === 'upToDate' ? { idle: true } : {});
448
454
  return preflight.result;
449
455
  }
450
456
  let releaseLock = null;
@@ -799,7 +805,12 @@ export class AutoSyncScheduler {
799
805
  * 全程被占,用户任何 destructive 操作都撞 423(2026-11-07 真机事故的根因)。
800
806
  * 结论**不具权威性**:调用方取到锁之后必须重跑一次(见 runOnceInternal 的 Phase 2)。
801
807
  */
802
- async detectPhase(channel, cfg, nowIso, historyId) {
808
+ async detectPhase(channel, cfg, nowIso, historyId,
809
+ /**
810
+ * localCheck=false = 本轮只回答「远端有没有新快照」,不跑本地导出(60s 远端轮询专用)。
811
+ * 本地是否改动由 realtime 监听与兜底 interval 负责;这不是近似判定 —— 需要比对时比的仍是载荷字节。
812
+ */
813
+ opts = {}) {
803
814
  // 读该通道 sync-config:按通道判定「已配置」——git 看 git.repoUrl、webdav 看 webdav.url。
804
815
  // SEC-03:「未配置」有两种成因 —— 真的没配,或存过的地址被白名单拒掉(读侧丢弃)。
805
816
  // 必须区分:后者如果说成前者的「尚未配置」,用户会一遍遍重填同一个被拒地址。
@@ -862,7 +873,8 @@ export class AutoSyncScheduler {
862
873
  // 定时器只是兜底轮询;真正驱动是这两个「变化」信号。
863
874
  // 列表拿不到(网络失败)时 remoteMetas 为 null → 检测自己再 list 一次,行为与改造前一致
864
875
  const remoteNew = await this.detectRemoteNew(engine, remoteMetas ?? undefined);
865
- const localDirty = await this.detectLocalChange(engine);
876
+ // 关掉本地检测时 localDirty 恒 false:远端也没变 → 立刻 upToDate,一次导出都不跑。
877
+ const localDirty = opts.localCheck === false ? false : await this.detectLocalChange(engine);
866
878
  // SYN-05:首轮(从未跑过)与「远端有新快照」是覆盖风险最高的两个时刻 —— 由
867
879
  // resolveConflictPushPolicy 统一把这两处的 ask 标成 forced。
868
880
  const firstRun = cfg.lastRunAt === undefined || cfg.lastRunAt === '';
@@ -51,6 +51,12 @@ export interface GitAuthor {
51
51
  export interface GitTransportOptions {
52
52
  /** 远端私有仓库地址(https/ssh/本地路径);token 绝不拼入此 URL */
53
53
  repoUrl: string;
54
+ /**
55
+ * 仓库内子目录前缀(issue #131,可缺省):快照布局落在 `<subdir>/snapshots`、
56
+ * `<subdir>/snapshots-encrypted`、`<subdir>/blobs`;空串/缺省 = 仓库根(历史行为)。
57
+ * 多工具共用同一个私有备份仓库时,每个工具各占一个子目录。
58
+ */
59
+ subdir?: string;
54
60
  /** 本地 git 工作副本目录(不存在则创建;已 clone 则复用) */
55
61
  workDir: string;
56
62
  /** token 提供者(http(s) 远端必填;本地/ssh 远端不会被调用) */
@@ -111,6 +117,8 @@ export declare class GitTransport implements SyncTransport {
111
117
  private readonly msg;
112
118
  /** repoUrl 是否为网络地址(本地目录仓库 == false):决定要不要额外禁 file 传输(SEC-12)。 */
113
119
  private readonly networkRepo;
120
+ /** 仓库内子目录前缀('' = 仓库根):快照布局、sparse 面与 adopt 判据都从它派生(issue #131)。 */
121
+ private readonly subdir;
114
122
  constructor(options: GitTransportOptions);
115
123
  /** 最近一次 checkIsPrivate() 的结果;null = 尚未检查 */
116
124
  get isPrivateHint(): boolean | null;
@@ -180,6 +188,21 @@ export declare class GitTransport implements SyncTransport {
180
188
  * 的可操作文案失败,并且**不再升级 SAFE MODE**(见 raiseGitFailure 的 localOnly 标记)。
181
189
  */
182
190
  private ensureCommitIdentity;
191
+ /**
192
+ * 工作副本是按哪个子目录前缀建的(issue #131):读 git 本地配置 `dsh.syncSubdir`。
193
+ * null = 键不存在 ⇒ 本功能上线前建的工作副本,布局 = 仓库根(历史行为)。
194
+ */
195
+ private readStoredSubdir;
196
+ /** 写入布局身份标记(issue #131):git 本地配置 + 同步更新进程内缓存。 */
197
+ private writeLayoutMarker;
198
+ /**
199
+ * 布局身份校验(issue #131):工作副本建好时的前缀必须与当前配置一致。
200
+ *
201
+ * 为什么必须显式报错而不是「照常同步」:sparse-checkout 只在首次 clone 生效 —— 前缀换了以后,
202
+ * 旧工作副本里根本没有 `<新前缀>/` 这棵树,pull 成功、list 读空,用户看到的是
203
+ * 「远端没有快照」。这条错误把出口指回既有的「重建工作副本(重新克隆)」。
204
+ */
205
+ private assertLayoutMatches;
183
206
  /**
184
207
  * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
185
208
  *
@@ -312,6 +335,13 @@ export declare class GitTransport implements SyncTransport {
312
335
  * 解析不出主机(异常地址)走无主机变体,绝不把解析失败的地址硬塞进文案。
313
336
  */
314
337
  private hostKeyMessage;
338
+ /** 子目录前缀下的同步布局相对路径('' 前缀 = 历史布局,逐字不变)。 */
339
+ private relDir;
340
+ /**
341
+ * 三个同步根目录(带前缀):sparse 面、add 路径、adopt 判据都从这里取 ——
342
+ * 任何一处漏加前缀都会让「写入 A、读取 B」(issue #131 的失败面)。
343
+ */
344
+ private syncDirs;
315
345
  private blobsDir;
316
346
  /**
317
347
  * git 通道的 blob 仓实现:工作树内 `blobs/<sha256>`(跨快照共享、按内容寻址)。
@@ -327,7 +357,7 @@ export declare class GitTransport implements SyncTransport {
327
357
  private assertSafeId;
328
358
  private snapshotDir;
329
359
  private snapshotsDir;
330
- /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/) */
360
+ /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/;配了前缀则在 <subdir>/ 下) */
331
361
  private encryptedSnapshotsDir;
332
362
  /** 加密快照密文单文件路径(<id>.json) */
333
363
  private encryptedSnapshotFile;