dsh-config-manager 0.6.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 (49) hide show
  1. package/lib/client.d.ts +5 -0
  2. package/lib/client.js +605 -566
  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 +3 -0
  6. package/lib/core/messages.js +8 -0
  7. package/lib/core/run-registry.d.ts +10 -0
  8. package/lib/core/run-registry.js +17 -0
  9. package/lib/index.d.ts +3 -2
  10. package/lib/index.js +8 -6
  11. package/lib/routes/import.js +6 -1
  12. package/lib/routes/route-support.d.ts +2 -1
  13. package/lib/routes/route-support.js +8 -3
  14. package/lib/routes/sync.js +5 -2
  15. package/lib/sync/autosync-config.d.ts +9 -1
  16. package/lib/sync/autosync-config.js +10 -2
  17. package/lib/sync/autosync-scheduler.js +18 -6
  18. package/lib/sync/git/git-transport.d.ts +31 -1
  19. package/lib/sync/git/git-transport.js +119 -23
  20. package/lib/sync/sync-config.d.ts +34 -3
  21. package/lib/sync/sync-config.js +38 -5
  22. package/lib/ui/sync-settings-view.d.ts +4 -0
  23. package/lib/ui/sync-settings-view.js +3 -0
  24. package/package.json +1 -1
  25. package/src/client/run-store.test.ts +1 -1
  26. package/src/client/run-store.ts +5 -0
  27. package/src/client/sync/ChannelConfigDialog.tsx +15 -1
  28. package/src/client/sync/SyncPanel.tsx +6 -0
  29. package/src/client/sync/sync-api.ts +2 -0
  30. package/src/client/sync/sync-locales.ts +6 -0
  31. package/src/core/local-plugin-host.test.ts +31 -2
  32. package/src/core/local-plugin-host.ts +175 -2
  33. package/src/core/messages.ts +8 -0
  34. package/src/core/run-registry-runs.test.ts +26 -1
  35. package/src/core/run-registry.ts +18 -0
  36. package/src/index.sync.test.ts +27 -0
  37. package/src/index.ts +10 -8
  38. package/src/routes/import.ts +6 -1
  39. package/src/routes/route-support.ts +7 -3
  40. package/src/routes/sync.ts +5 -2
  41. package/src/sync/autosync-config.ts +10 -2
  42. package/src/sync/autosync-scheduler.test.ts +61 -1
  43. package/src/sync/autosync-scheduler.ts +17 -5
  44. package/src/sync/git/git-transport.test.ts +117 -0
  45. package/src/sync/git/git-transport.ts +131 -23
  46. package/src/sync/sync-config.test.ts +59 -1
  47. package/src/sync/sync-config.ts +51 -5
  48. package/src/ui/sync-settings-view.test.ts +1 -0
  49. package/src/ui/sync-settings-view.ts +7 -0
@@ -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
- /** 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 1 分钟内下行) */
41
- export const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS = 60 * 1000;
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
- const preflight = await this.detectPhase(channel, cfg, nowIso, historyId);
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
- finishRun();
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
- const localDirty = await this.detectLocalChange(engine);
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
+
@@ -31,7 +31,7 @@ import type { SnapshotDirManifest } from '../layout.ts';
31
31
  import { BLOB_SECTIONS, gcBlobs, referencedBlobHashes } from '../blob-store.ts';
32
32
  import type { BlobSink } from '../blob-store.ts';
33
33
  import { deserializeSnapshot, serializeSnapshot } from '../snapshot-json.ts';
34
- import { classifyRepoUrl, isPrivateRepoHost } from '../sync-config.ts';
34
+ import { classifyRepoUrl, isPrivateRepoHost, normalizeGitSubdir } from '../sync-config.ts';
35
35
  import {
36
36
  classifyNetworkErrorText, computeSnapshotMeta, DEFAULT_SYNC_TIMEOUT_MS, isEncryptedSections,
37
37
  SyncTransportError, withSyncRetry,
@@ -120,13 +120,24 @@ const inspectFactsCache = new Map<string, { at: number; detail: boolean; facts:
120
120
  */
121
121
  const INSPECT_WORKDIR_LOCK_TIMEOUT_MS = 1_500;
122
122
 
123
- function inspectFactsCacheKey(workDir: string, repoUrl: string): string {
124
- return workDir + '\u0000' + repoUrl;
123
+ /**
124
+ * 工作副本布局身份的进程内缓存(key = workDir,值同 `readStoredSubdir()`,issue #131)。
125
+ *
126
+ * 为什么缓存:每次操作都要校验布局,而读一次 git 本地配置就是一次 git 子进程启动
127
+ * (Windows 真机约 80 ms,正是 L-04 在削的那笔开销)。布局身份是**工作副本的属性**,
128
+ * 只有本类写入(clone / adopt)与重建(reclone)会改它 —— 那三处显式更新缓存。
129
+ */
130
+ const storedSubdirCache = new Map<string, string | null>();
131
+
132
+ function inspectFactsCacheKey(workDir: string, repoUrl: string, subdir: string): string {
133
+ // 子目录前缀必须进 key:同一工作副本路径在不同前缀下的「远端快照数」是不同的答案(issue #131)。
134
+ return workDir + '\u0000' + repoUrl + '\u0000' + subdir;
125
135
  }
126
136
 
127
137
  /** 清空自检缓存(测试隔离用;生产路径由 `withWorkdir` 逐 key 失效)。 */
128
138
  export function clearInspectFactsCache(): void {
129
139
  inspectFactsCache.clear();
140
+ storedSubdirCache.clear();
130
141
  }
131
142
 
132
143
  /** 凭据提供者:token 只从这里读取,绝不在任何地方持久化 */
@@ -139,6 +150,12 @@ export interface GitAuthor { name: string; email: string; }
139
150
  export interface GitTransportOptions {
140
151
  /** 远端私有仓库地址(https/ssh/本地路径);token 绝不拼入此 URL */
141
152
  repoUrl: string;
153
+ /**
154
+ * 仓库内子目录前缀(issue #131,可缺省):快照布局落在 `<subdir>/snapshots`、
155
+ * `<subdir>/snapshots-encrypted`、`<subdir>/blobs`;空串/缺省 = 仓库根(历史行为)。
156
+ * 多工具共用同一个私有备份仓库时,每个工具各占一个子目录。
157
+ */
158
+ subdir?: string;
142
159
  /** 本地 git 工作副本目录(不存在则创建;已 clone 则复用) */
143
160
  workDir: string;
144
161
  /** token 提供者(http(s) 远端必填;本地/ssh 远端不会被调用) */
@@ -190,7 +207,22 @@ const ADOPT_ROOT_ALLOW = new Set<string>([SNAPSHOTS_REL, SNAPSHOTS_ENCRYPTED_REL
190
207
  * 远端仓库比同步内容大几个数量级时(报告者现场:1.8 GB 仓库 / 6 MB 内容),全量 clone 与全量 fetch
191
208
  * 都要拉完整对象图,而工作副本真正需要的只有这三个目录。
192
209
  */
193
- const SYNC_ROOT_DIRS: readonly string[] = [...ADOPT_ROOT_ALLOW];
210
+ /* 具体的 sparse 面在 `syncDirs()` 里按子目录前缀派生(issue #131),基名与 ADOPT_ROOT_ALLOW 同源。 */
211
+ /**
212
+ * 工作副本的**布局身份**键(git 本地配置,issue #131):记录这份工作副本是按哪个子目录前缀建的。
213
+ *
214
+ * 为什么必须落盘:sparse-checkout 只在首次 clone 时生效 —— 前缀从「仓库根」改成 `DSH备份` 后,
215
+ * 旧工作副本里根本没有 `DSH备份/` 这棵树,pull 会成功、list 会读空,用户看到的是
216
+ * 「远端没有快照」(issue #104 那类最难自查的假象)。存成 git 本地配置而不是工作树里的文件:
217
+ * 工作树文件会让 `status --porcelain` 恒 dirty,adopt 直接拒绝。
218
+ */
219
+ const SUBDIR_CONFIG_KEY = 'dsh.syncSubdir';
220
+ /**
221
+ * 标记值的版本前缀(issue #131)。为什么带前缀:读侧必须能区分「本插件写的」与「任何别的值」——
222
+ * 值不匹配前缀一律按「读不出」处理(回落历史布局 = 仓库根),这样伪造/污染的配置不会凭空
223
+ * 造出一条假的「布局已变」错误。空子目录写作 `1:`,仍是可判读的有效标记。
224
+ */
225
+ const SUBDIR_MARKER_PREFIX = '1:';
194
226
  /**
195
227
  * 走网络的 git 子命令:一律附加低速上限(issue #122)。
196
228
  *
@@ -378,6 +410,8 @@ export class GitTransport implements SyncTransport {
378
410
  private readonly msg: MsgFunc;
379
411
  /** repoUrl 是否为网络地址(本地目录仓库 == false):决定要不要额外禁 file 传输(SEC-12)。 */
380
412
  private readonly networkRepo: boolean;
413
+ /** 仓库内子目录前缀('' = 仓库根):快照布局、sparse 面与 adopt 判据都从它派生(issue #131)。 */
414
+ private readonly subdir: string;
381
415
 
382
416
  constructor(options: GitTransportOptions) {
383
417
  if (typeof options.repoUrl !== 'string' || options.repoUrl.length === 0) {
@@ -401,6 +435,12 @@ export class GitTransport implements SyncTransport {
401
435
  throw new GitTransportError(this.msg('sync.git.repoUrlInvalid', { url: REPO_URL_PLACEHOLDER }));
402
436
  }
403
437
  this.networkRepo = repoShape.kind !== 'local';
438
+ // issue #131:子目录前缀在构造期就收窄(与 repoUrl 同一条纪律:非法值绝不进 git 子进程)。
439
+ const subdirCheck = normalizeGitSubdir(options.subdir ?? '');
440
+ if (!subdirCheck.ok) {
441
+ throw new GitTransportError(this.msg('sync.git.subdirInvalid', { subdir: String(options.subdir ?? '') }));
442
+ }
443
+ this.subdir = subdirCheck.value;
404
444
  this.o = {
405
445
  repoUrl: options.repoUrl,
406
446
  workDir: options.workDir,
@@ -498,7 +538,7 @@ export class GitTransport implements SyncTransport {
498
538
  await fsx.writeFile(file, new TextEncoder().encode(serializeSnapshot(snapshot)));
499
539
  // 同 id 旧散文件目录残留 → 一并清理(形态切换不残留)
500
540
  await fsx.remove(this.snapshotDir(snapshot.id));
501
- rel = `${SNAPSHOTS_ENCRYPTED_REL}/${snapshot.id}.json`;
541
+ rel = `${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}/${snapshot.id}.json`;
502
542
  } else {
503
543
  const dir = this.snapshotDir(snapshot.id);
504
544
  if (await fsx.exists(dir)) await fsx.remove(dir); // 覆盖语义:先清旧目录,避免残留旧文件
@@ -519,11 +559,11 @@ export class GitTransport implements SyncTransport {
519
559
  }
520
560
  // 同 id 旧密文单文件残留 → 一并清理(形态切换不残留)
521
561
  await fsx.remove(this.encryptedSnapshotFile(snapshot.id));
522
- rel = `${SNAPSHOTS_REL}/${snapshot.id}`;
562
+ rel = `${this.relDir(SNAPSHOTS_REL)}/${snapshot.id}`;
523
563
  }
524
564
  // blob 仓与快照同一次提交:引用文件与它引用的字节绝不跨 commit 分离
525
565
  const hasBlobs = await fsx.exists(this.blobsDir());
526
- await this.runGit(hasBlobs ? ['add', '--', rel, BLOBS_REL] : ['add', '--', rel]);
566
+ await this.runGit(hasBlobs ? ['add', '--', rel, this.relDir(BLOBS_REL)] : ['add', '--', rel]);
527
567
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
528
568
  if (diff.code !== 0) {
529
569
  const verb = existed ? 'update' : 'add';
@@ -588,10 +628,10 @@ export class GitTransport implements SyncTransport {
588
628
  let rel: string;
589
629
  if (plainExists) {
590
630
  await fsx.remove(plainDir);
591
- rel = `${SNAPSHOTS_REL}/${id}`;
631
+ rel = `${this.relDir(SNAPSHOTS_REL)}/${id}`;
592
632
  } else {
593
633
  await fsx.remove(encFile);
594
- rel = `${SNAPSHOTS_ENCRYPTED_REL}/${id}.json`;
634
+ rel = `${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}/${id}.json`;
595
635
  }
596
636
  await this.runGit(['add', '-A', '--', rel]);
597
637
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
@@ -684,7 +724,7 @@ export class GitTransport implements SyncTransport {
684
724
  } finally {
685
725
  // 除纯只读自检外,任何操作都可能改变工作副本状态(push 改 ahead、fetch 改远端引用、
686
726
  // 重建删目录、失败也可能已留下 commit)→ 收尾即丢弃自检缓存,绝不让「写后读」看到旧事实。
687
- if (opts.readonly !== true) inspectFactsCache.delete(inspectFactsCacheKey(this.o.workDir, this.o.repoUrl));
727
+ if (opts.readonly !== true) inspectFactsCache.delete(inspectFactsCacheKey(this.o.workDir, this.o.repoUrl, this.subdir));
688
728
  }
689
729
  }
690
730
 
@@ -699,6 +739,8 @@ export class GitTransport implements SyncTransport {
699
739
  // 而失败面表现为旧地址的网络超时(真机:局域网地址 → Tailscale 地址后同步长期失败),
700
740
  // 用户会误判成网络/凭据问题。
701
741
  await this.reconcileOrigin();
742
+ // issue #131:布局身份(子目录前缀)与当前配置不一致 ⇒ 明确报「需重建」,绝不照常同步
743
+ await this.assertLayoutMatches();
702
744
  // 真机 issue:仓库级提交身份此前**只在首次 clone 时**写过(见本方法末尾),已有 .git 的分支
703
745
  // 直接 return —— 换机器/换工作副本/用户清过本地配置之后,每次 commit 都以 exit 128 失败
704
746
  // ("unable to auto-detect email address"),交易停在 NEEDS_ATTENTION,用户只看到
@@ -724,6 +766,8 @@ export class GitTransport implements SyncTransport {
724
766
  // 仓库级提交身份(写入远端历史,可经 author 选项覆盖;不改全局配置)
725
767
  await this.runGit(['config', 'user.name', this.o.author.name]);
726
768
  await this.runGit(['config', 'user.email', this.o.author.email]);
769
+ // 记录布局身份(issue #131):此后前缀再变,assertLayoutMatches 能把它判出来
770
+ await this.writeLayoutMarker();
727
771
  this.repoReady = true;
728
772
  }
729
773
 
@@ -755,6 +799,48 @@ export class GitTransport implements SyncTransport {
755
799
  }
756
800
  }
757
801
 
802
+ /**
803
+ * 工作副本是按哪个子目录前缀建的(issue #131):读 git 本地配置 `dsh.syncSubdir`。
804
+ * null = 键不存在 ⇒ 本功能上线前建的工作副本,布局 = 仓库根(历史行为)。
805
+ */
806
+ private async readStoredSubdir(): Promise<string | null> {
807
+ const cached = storedSubdirCache.get(this.o.workDir);
808
+ if (cached !== undefined) return cached;
809
+ try {
810
+ const r = await this.runGit(['config', '--get', SUBDIR_CONFIG_KEY], { allowNonZero: true });
811
+ const raw = r.code === 0 ? r.stdout.trim() : '';
812
+ // 键不存在 / 前缀不符(不是本插件写的标记,或被人改坏)⇒ 不知道,按历史布局处理
813
+ const value = raw.startsWith(SUBDIR_MARKER_PREFIX) ? raw.slice(SUBDIR_MARKER_PREFIX.length) : null;
814
+ storedSubdirCache.set(this.o.workDir, value);
815
+ return value;
816
+ } catch {
817
+ return null; // 读不出 = 不知道,按历史布局处理(不拿猜测阻断同步;失败不进缓存,下次再读)
818
+ }
819
+ }
820
+
821
+ /** 写入布局身份标记(issue #131):git 本地配置 + 同步更新进程内缓存。 */
822
+ private async writeLayoutMarker(): Promise<void> {
823
+ await this.runGit(['config', SUBDIR_CONFIG_KEY, SUBDIR_MARKER_PREFIX + this.subdir]);
824
+ storedSubdirCache.set(this.o.workDir, this.subdir);
825
+ }
826
+
827
+ /**
828
+ * 布局身份校验(issue #131):工作副本建好时的前缀必须与当前配置一致。
829
+ *
830
+ * 为什么必须显式报错而不是「照常同步」:sparse-checkout 只在首次 clone 生效 —— 前缀换了以后,
831
+ * 旧工作副本里根本没有 `<新前缀>/` 这棵树,pull 成功、list 读空,用户看到的是
832
+ * 「远端没有快照」。这条错误把出口指回既有的「重建工作副本(重新克隆)」。
833
+ */
834
+ private async assertLayoutMatches(): Promise<void> {
835
+ const stored = (await this.readStoredSubdir()) ?? '';
836
+ if (stored === this.subdir) return;
837
+ const label = (prefix: string): string => (prefix === '' ? this.msg('sync.git.subdirRoot') : prefix);
838
+ throw new GitTransportError(
839
+ this.msg('sync.git.subdirChanged', { stored: label(stored), expected: label(this.subdir) }),
840
+ { kind: 'protocol', retryable: false },
841
+ );
842
+ }
843
+
758
844
  /**
759
845
  * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
760
846
  *
@@ -784,7 +870,8 @@ export class GitTransport implements SyncTransport {
784
870
  const head = await this.runGit(['rev-parse', '--verify', '--quiet', 'HEAD'], { allowNonZero: true });
785
871
  if (head.code !== 0) return; // 空仓库:没有可 checkout 的树,后续 push 会建分支
786
872
  const target = branch === '' ? 'HEAD' : branch;
787
- const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...SYNC_ROOT_DIRS], { allowNonZero: true });
873
+ // issue #131:sparse 面跟着子目录前缀走 —— 共用仓库里其它工具的目录绝不被 materialize
874
+ const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...this.syncDirs()], { allowNonZero: true });
788
875
  if (sparse.code !== 0) {
789
876
  // 老 git 没有 cone 模式:宁可全量落地(修复前行为),也不留下一个空工作树
790
877
  await this.runGit(['checkout', target], { allowNonZero: true });
@@ -891,7 +978,7 @@ export class GitTransport implements SyncTransport {
891
978
  * 因此放进 `detail: true`(供「重建工作副本」前评估数据量等场景显式索取)。
892
979
  */
893
980
  async inspectWorkDir(opts: { detail?: boolean } = {}): Promise<GitWorkDirFacts> {
894
- const key = inspectFactsCacheKey(this.o.workDir, this.o.repoUrl);
981
+ const key = inspectFactsCacheKey(this.o.workDir, this.o.repoUrl, this.subdir);
895
982
  const detail = opts.detail === true;
896
983
  const hit = inspectFactsCache.get(key);
897
984
  // 命中即返回:不必排队等锁,也不必再 spawn 一条 git(这是首页/切页/轮询的常态路径)。
@@ -947,8 +1034,8 @@ export class GitTransport implements SyncTransport {
947
1034
  // 每个快照是一级子项;`.gitkeep` 只是占位,不是快照
948
1035
  .filter((line) => line !== '' && !line.endsWith(SNAPSHOT_KEEP_FILE)).length;
949
1036
  };
950
- const plain = await countTree(`origin/${branch}:${SNAPSHOTS_REL}`);
951
- const encrypted = await countTree(`origin/${branch}:${SNAPSHOTS_ENCRYPTED_REL}`);
1037
+ const plain = await countTree(`origin/${branch}:${this.relDir(SNAPSHOTS_REL)}`);
1038
+ const encrypted = await countTree(`origin/${branch}:${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}`);
952
1039
  // 两个目录都不存在 = 远端分支根本没有快照布局(0);分支/引用读不出 = null(不猜)
953
1040
  remoteSnapshots = plain === null && encrypted === null ? 0 : (plain ?? 0) + (encrypted ?? 0);
954
1041
  }
@@ -1006,6 +1093,7 @@ export class GitTransport implements SyncTransport {
1006
1093
  return;
1007
1094
  }
1008
1095
  await fs.rm(this.o.workDir, { recursive: true, force: true });
1096
+ storedSubdirCache.delete(this.o.workDir); // 旧副本连同它的布局身份一起没了
1009
1097
  await this.ensureRepo();
1010
1098
  }
1011
1099
 
@@ -1047,6 +1135,8 @@ export class GitTransport implements SyncTransport {
1047
1135
  );
1048
1136
  }
1049
1137
  await this.reconcileOrigin();
1138
+ // issue #131:采纳远端历史也不许跨布局 —— 前缀变了要先重建工作副本
1139
+ await this.assertLayoutMatches();
1050
1140
  const branchRes = await this.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { allowNonZero: true });
1051
1141
  const branch = branchRes.code === 0 ? branchRes.stdout.trim() : '';
1052
1142
  if (branch === '' || branch === 'HEAD') {
@@ -1079,9 +1169,13 @@ export class GitTransport implements SyncTransport {
1079
1169
  { kind: 'protocol', retryable: false },
1080
1170
  );
1081
1171
  }
1082
- // ② 远端顶层只能是快照布局
1083
- const treeRes = await this.runGit(['ls-tree', '--name-only', `origin/${branch}`], { allowNonZero: true });
1084
- if (treeRes.code !== 0) {
1172
+ // ② 同步布局只能是那三个目录。配了子目录前缀时校验的是 <subdir>/ **子树**(issue #131):
1173
+ // 共用仓库里其它工具的目录在仓库根,那不是本插件的同步内容,也不该被判成「污染」。
1174
+ const treeish = this.subdir === '' ? `origin/${branch}` : `origin/${branch}:${this.subdir}`;
1175
+ const treeRes = await this.runGit(['ls-tree', '--name-only', treeish], { allowNonZero: true });
1176
+ // 子树不存在 = 远端还没有该前缀的同步内容(首次 push 会建它),不是错误;
1177
+ // 仓库根读不出来才是真异常(引用在上面已验过存在)。
1178
+ if (treeRes.code !== 0 && this.subdir === '') {
1085
1179
  throw new GitTransportError(
1086
1180
  this.msg('sync.git.cmdFailed', {
1087
1181
  args: `ls-tree --name-only origin/${branch}`,
@@ -1091,7 +1185,7 @@ export class GitTransport implements SyncTransport {
1091
1185
  { kind: 'unknown', retryable: true },
1092
1186
  );
1093
1187
  }
1094
- const unknownEntries = treeRes.stdout
1188
+ const unknownEntries = (treeRes.code === 0 ? treeRes.stdout : '')
1095
1189
  .split('\n')
1096
1190
  .map((name) => name.trim().replace(/\/$/, ''))
1097
1191
  .filter((name) => name !== '' && !ADOPT_ROOT_ALLOW.has(name));
@@ -1112,6 +1206,7 @@ export class GitTransport implements SyncTransport {
1112
1206
  }
1113
1207
  // 让后续 pull --ff-only 有 upstream 可用(忽略失败:分支可能已被删/重命名)
1114
1208
  await this.runGit(['branch', '--set-upstream-to', `origin/${branch}`, branch], { allowNonZero: true });
1209
+ await this.writeLayoutMarker();
1115
1210
  this.repoReady = true;
1116
1211
  }
1117
1212
 
@@ -1395,8 +1490,21 @@ export class GitTransport implements SyncTransport {
1395
1490
  : this.msg('sync.git.hostKeyUnverified', { host });
1396
1491
  }
1397
1492
 
1493
+ /** 子目录前缀下的同步布局相对路径('' 前缀 = 历史布局,逐字不变)。 */
1494
+ private relDir(base: string): string {
1495
+ return this.subdir === '' ? base : `${this.subdir}/${base}`;
1496
+ }
1497
+
1498
+ /**
1499
+ * 三个同步根目录(带前缀):sparse 面、add 路径、adopt 判据都从这里取 ——
1500
+ * 任何一处漏加前缀都会让「写入 A、读取 B」(issue #131 的失败面)。
1501
+ */
1502
+ private syncDirs(): string[] {
1503
+ return [this.relDir(SNAPSHOTS_REL), this.relDir(SNAPSHOTS_ENCRYPTED_REL), this.relDir(BLOBS_REL)];
1504
+ }
1505
+
1398
1506
  private blobsDir(): string {
1399
- return path.join(this.o.workDir, BLOBS_REL);
1507
+ return path.join(this.o.workDir, this.relDir(BLOBS_REL));
1400
1508
  }
1401
1509
 
1402
1510
  /**
@@ -1464,7 +1572,7 @@ export class GitTransport implements SyncTransport {
1464
1572
  if (!readable) return;
1465
1573
  const deleted = await gcBlobs({ sink: this.blobSink(fsx), referenced, nowMs: Date.now() });
1466
1574
  if (deleted.length === 0) return;
1467
- await this.runGit(['add', '-A', '--', BLOBS_REL]);
1575
+ await this.runGit(['add', '-A', '--', this.relDir(BLOBS_REL)]);
1468
1576
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
1469
1577
  if (diff.code === 0) return;
1470
1578
  await this.runGit(['commit', '-m', `sync: gc ${deleted.length} blob(s)`]);
@@ -1482,12 +1590,12 @@ export class GitTransport implements SyncTransport {
1482
1590
  }
1483
1591
 
1484
1592
  private snapshotsDir(): string {
1485
- return joinFs(this.o.workDir, SNAPSHOTS_REL);
1593
+ return joinFs(this.o.workDir, this.relDir(SNAPSHOTS_REL));
1486
1594
  }
1487
1595
 
1488
- /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/) */
1596
+ /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/;配了前缀则在 <subdir>/ 下) */
1489
1597
  private encryptedSnapshotsDir(): string {
1490
- return joinFs(this.o.workDir, SNAPSHOTS_ENCRYPTED_REL);
1598
+ return joinFs(this.o.workDir, this.relDir(SNAPSHOTS_ENCRYPTED_REL));
1491
1599
  }
1492
1600
 
1493
1601
  /** 加密快照密文单文件路径(<id>.json) */