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.
Files changed (112) hide show
  1. package/lib/adapters/test-helpers.d.ts +7 -0
  2. package/lib/adapters/test-helpers.js +11 -0
  3. package/lib/cli/actions.js +1 -1
  4. package/lib/client.d.ts +14 -2
  5. package/lib/client.js +722 -647
  6. package/lib/core/backup.d.ts +9 -1
  7. package/lib/core/backup.js +21 -0
  8. package/lib/core/local-plugin-host.d.ts +9 -0
  9. package/lib/core/local-plugin-host.js +174 -1
  10. package/lib/core/messages-core.d.ts +3 -0
  11. package/lib/core/messages-core.js +6 -0
  12. package/lib/core/messages.d.ts +8 -0
  13. package/lib/core/messages.js +18 -0
  14. package/lib/core/model-tools.js +2 -0
  15. package/lib/core/phase4-crash-child.js +1 -1
  16. package/lib/core/plugin-cli.d.ts +11 -0
  17. package/lib/core/plugin-cli.js +30 -0
  18. package/lib/core/restore-wal.d.ts +2 -0
  19. package/lib/core/restore-wal.js +11 -6
  20. package/lib/core/restore.d.ts +15 -2
  21. package/lib/core/restore.js +65 -3
  22. package/lib/core/run-registry.d.ts +10 -0
  23. package/lib/core/run-registry.js +17 -0
  24. package/lib/core/snapshot-diff.js +2 -1
  25. package/lib/core/types.d.ts +32 -0
  26. package/lib/index.d.ts +8 -2
  27. package/lib/index.js +24 -21
  28. package/lib/routes/import.js +6 -1
  29. package/lib/routes/route-support.d.ts +7 -1
  30. package/lib/routes/route-support.js +36 -5
  31. package/lib/routes/sync.js +8 -2
  32. package/lib/sync/autosync-config.d.ts +9 -1
  33. package/lib/sync/autosync-config.js +10 -2
  34. package/lib/sync/autosync-scheduler.js +18 -6
  35. package/lib/sync/git/git-transport.d.ts +31 -1
  36. package/lib/sync/git/git-transport.js +119 -23
  37. package/lib/sync/merge-preview-view.d.ts +78 -0
  38. package/lib/sync/merge-preview-view.js +46 -0
  39. package/lib/sync/merge.d.ts +2 -1
  40. package/lib/sync/merge.js +9 -4
  41. package/lib/sync/plugin-removal-apply.d.ts +95 -0
  42. package/lib/sync/plugin-removal-apply.js +158 -0
  43. package/lib/sync/plugin-removals.d.ts +90 -0
  44. package/lib/sync/plugin-removals.js +167 -0
  45. package/lib/sync/sync-config.d.ts +34 -3
  46. package/lib/sync/sync-config.js +38 -5
  47. package/lib/sync/sync-engine.d.ts +34 -43
  48. package/lib/sync/sync-engine.js +50 -42
  49. package/lib/sync/sync-selection.d.ts +8 -0
  50. package/lib/sync/sync-selection.js +6 -0
  51. package/lib/sync/workspace-merge.d.ts +8 -1
  52. package/lib/ui/restore-plan-view.js +1 -0
  53. package/lib/ui/sync-settings-view.d.ts +14 -0
  54. package/lib/ui/sync-settings-view.js +5 -0
  55. package/package.json +1 -1
  56. package/src/adapters/test-helpers.ts +10 -0
  57. package/src/cli/actions.ts +1 -1
  58. package/src/client/common/info-hint-guard.test.ts +2 -1
  59. package/src/client/run-store.test.ts +8 -6
  60. package/src/client/run-store.ts +9 -5
  61. package/src/client/sync/ChannelConfigDialog.tsx +15 -1
  62. package/src/client/sync/SyncPanel.tsx +16 -0
  63. package/src/client/sync/SyncSectionPickerDialog.tsx +17 -1
  64. package/src/client/sync/sync-api.ts +2 -0
  65. package/src/client/sync/sync-locales.ts +10 -0
  66. package/src/client/sync/sync-view.ts +6 -0
  67. package/src/core/backup.ts +21 -1
  68. package/src/core/local-plugin-host.test.ts +31 -2
  69. package/src/core/local-plugin-host.ts +175 -2
  70. package/src/core/messages-core.ts +6 -0
  71. package/src/core/messages.ts +18 -0
  72. package/src/core/model-tools.ts +2 -0
  73. package/src/core/phase4-crash-child.ts +1 -1
  74. package/src/core/plugin-cli.ts +37 -0
  75. package/src/core/restore-plugin-install.test.ts +116 -0
  76. package/src/core/restore-wal.ts +12 -6
  77. package/src/core/restore.ts +79 -4
  78. package/src/core/run-registry-runs.test.ts +26 -1
  79. package/src/core/run-registry.ts +18 -0
  80. package/src/core/smoke.test.ts +5 -0
  81. package/src/core/snapshot-diff.test.ts +1 -1
  82. package/src/core/snapshot-diff.ts +2 -1
  83. package/src/core/types.ts +31 -0
  84. package/src/index.sync.test.ts +27 -0
  85. package/src/index.ts +30 -28
  86. package/src/routes/import.ts +6 -1
  87. package/src/routes/route-support.ts +34 -5
  88. package/src/routes/sync.ts +8 -2
  89. package/src/security/security.test.ts +1 -0
  90. package/src/sync/autosync-config.ts +10 -2
  91. package/src/sync/autosync-scheduler.test.ts +61 -1
  92. package/src/sync/autosync-scheduler.ts +17 -5
  93. package/src/sync/git/git-transport.test.ts +117 -0
  94. package/src/sync/git/git-transport.ts +131 -23
  95. package/src/sync/merge-preview-view.ts +97 -0
  96. package/src/sync/merge.test.ts +17 -15
  97. package/src/sync/merge.ts +10 -3
  98. package/src/sync/plugin-removal-apply.ts +198 -0
  99. package/src/sync/plugin-removals.test.ts +221 -0
  100. package/src/sync/plugin-removals.ts +208 -0
  101. package/src/sync/sync-config.test.ts +59 -1
  102. package/src/sync/sync-config.ts +51 -5
  103. package/src/sync/sync-engine.test.ts +251 -1
  104. package/src/sync/sync-engine.ts +84 -83
  105. package/src/sync/sync-selection.test.ts +29 -7
  106. package/src/sync/sync-selection.ts +13 -0
  107. package/src/sync/workspace-merge.ts +9 -0
  108. package/src/ui/restore-plan-view.test.ts +1 -1
  109. package/src/ui/restore-plan-view.ts +1 -0
  110. package/src/ui/snapshots-view.test.ts +1 -1
  111. package/src/ui/sync-settings-view.test.ts +21 -0
  112. package/src/ui/sync-settings-view.ts +19 -0
@@ -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) */
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 合并预览的**可渲染视图**(分区结果 → 界面结构),与「预览产物能否与基线比对」的判定。
3
+ *
4
+ * 为什么独立成文件:sync-engine 已顶到文件体量棘轮(tests/file-size-ratchet.test.ts),
5
+ * 而这两件事都只依赖 merge.ts 的结果类型与预览文本工具,不碰引擎实例状态;放这里可单测,
6
+ * 也让引擎只管编排。类型经 sync-engine 再导出,既有导入方(model-tools 等)无需改动。
7
+ */
8
+ import { isLocalPluginSpec } from '../core/local-plugin-pack.ts';
9
+ import type { SectionData, SectionId } from '../schema/types.ts';
10
+ import type { MergeConflictReason, MergeSectionResult } from './merge.ts';
11
+ import { previewTextOf } from './merge-preview-text.ts';
12
+
13
+ /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
14
+ export function mergePreviewSectionView(result: MergeSectionResult): MergePreviewSectionView {
15
+ const conflicts: MergePreviewConflictView[] = result.conflicts.map((c) => ({
16
+ path: c.path,
17
+ kind: c.kind,
18
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
19
+ localPreview: previewTextOf(c.local),
20
+ remotePreview: previewTextOf(c.remote),
21
+ ancestorPreview: previewTextOf(c.ancestor),
22
+ }));
23
+ return {
24
+ id: result.id,
25
+ decision: result.decision,
26
+ ...(result.autoMerged !== undefined ? { autoMerged: result.autoMerged } : {}),
27
+ conflictCount: result.conflicts.length,
28
+ conflicts,
29
+ };
30
+ }
31
+
32
+ /**
33
+ * issue #91:走只读 `preview()` 拿到的产物,能否直接与该分区**基线 hash**(push 时按 export() 产物记录)比对。
34
+ *
35
+ * 为什么需要这个判定:`plugins` 适配器的 `preview()` 走 `collect(…, pack=false)` —— 刻意**不做**
36
+ * 本地源(`link:` / `file:`)插件的 `npm pack`。于是当 profile 里存在本地源插件时,预览产物既没有
37
+ * `localTarballs`、插件 spec 也保持原样(export() 会改写成 `file:<tarball>`),与基线**不同口径**:
38
+ * 此时既不能断言「无变化」(本地插件源码改了体积/内容,预览看不见),也不该为了比对去打包
39
+ * (那正是本 issue 的缺陷本身)。
40
+ *
41
+ * 返回 true = 该分区本趟**不可比** ⇒ 调用方只能保守报「有变化」并如实说明原因。
42
+ * 其余分区的 preview() 产物与 export() 逐字节相同(文件类分区不走 preview(),见 previewPush)。
43
+ */
44
+ export function previewCaliberDiffersFromExport(sectionId: SectionId, data: SectionData): boolean {
45
+ if (sectionId !== 'plugins') return false;
46
+ const plugins = (data as { plugins?: { spec?: string }[] }).plugins;
47
+ return Array.isArray(plugins) && plugins.some((p) => isLocalPluginSpec(p?.spec));
48
+ }
49
+
50
+ /** previewMerge 的单条冲突视图(三侧文本都已截断 + redact;绝不回传原始值对象)。 */
51
+ export interface MergePreviewConflictView {
52
+ /** 冲突位置:JSON 分区是 top-level key;文件类分区是 relativePath;'$' = 整分区冲突。 */
53
+ path: string;
54
+ kind: 'key' | 'file';
55
+ /** 冲突成因(可选:旧数据/旧 merge 结果没有该字段,界面缺省按 'both-modified' 措辞)。 */
56
+ reason?: MergeConflictReason;
57
+ /** 本机侧的可读预览(≤ 2 KiB,超出截断加省略号;已过 redact())。 */
58
+ localPreview: string;
59
+ /** 远端侧的可读预览(同上)。 */
60
+ remotePreview: string;
61
+ /** 共同祖先侧的可读预览(同上;无祖先时为空串)。 */
62
+ ancestorPreview: string;
63
+ }
64
+
65
+ /** previewMerge 的单个分区视图。 */
66
+ export interface MergePreviewSectionView {
67
+ id: SectionId;
68
+ decision: MergeSectionResult['decision'];
69
+ /** 自动合并并入的变更点数量(仅 decision === 'merge' 时有意义;缺省 = 未统计)。 */
70
+ autoMerged?: number;
71
+ conflictCount: number;
72
+ conflicts: MergePreviewConflictView[];
73
+ }
74
+
75
+ /** previewMerge 结果(只读、零写入)。 */
76
+ export interface MergePreview {
77
+ /** 预览是否成功产出(远端无快照 → false + message,分区清单为空)。 */
78
+ ok: boolean;
79
+ /** 本次预览针对的**远端**快照 id;'' = 远端无快照。 */
80
+ snapshotId: string;
81
+ /** 是否拿到了本地祖先副本(false = 退化为两方合并 → 所有双侧差异都会呈现为 conflict)。 */
82
+ hasAncestor: boolean;
83
+ sections: MergePreviewSectionView[];
84
+ /** 与 risk.ts 的 classifyMergePlan 同口径计数:auto = 可自动应用,review = 需人工,conflicts = 冲突,skipped = 跳过。 */
85
+ summary: { auto: number; review: number; conflicts: number; skipped: number };
86
+ message?: string;
87
+ reason?: 'remote-empty'; // 远端没有任何快照:首次同步的正常起点,不是故障(客户端据此给「先推送」引导,issue 116)
88
+ /**
89
+ * 本轮合并**将卸载**的插件(issue #132):确认页必须单列出来,用户据此可以整轮取消。
90
+ * 仅在 plugins 分区可应用(useRemote/keepLocal/merge)时才有条目 —— 分区冲突时不删。
91
+ */
92
+ pluginRemovals?: { name: string; version: string }[];
93
+ /** 远端删了、本机却改过 → 不删,等人工裁决(与 conflict 清单同语义,这里为插件专列) */
94
+ pluginRemovalConflicts?: { name: string; ancestorVersion: string; localVersion: string }[];
95
+ /** 考察过但没删的条目及原因(含开关关闭 = 'switch-off',界面据此如实说明) */
96
+ pluginRemovalSkipped?: { name: string; reason: string }[];
97
+ }
@@ -132,34 +132,36 @@ test('merge: 深层嵌套 JSON 合并(不同叶子自动合,未知字段两
132
132
  assert.equal(merged.ui['remoteOnly'], true, '远端新增的未知字段不得被静默丢弃');
133
133
  });
134
134
 
135
+ // 注意:这里**故意**用 settings 的普通数组做样本。plugins 自 issue #132 起有了按包名的专属
136
+ // 合并钩子(见 plugin-removals.test.ts),不再走通用「数组两侧各改即冲突」的口径。
135
137
  test('merge: 数组双侧都改且不同 → conflict(reason=array),不按索引猜', () => {
136
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }] } as unknown as SectionData;
137
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
138
- const rem: SectionData = { version: 1, plugins: [{ spec: 'c' }] } as unknown as SectionData;
139
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
138
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }] } as unknown as SectionData;
139
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
140
+ const rem: SectionData = { version: 1, list: [{ spec: 'c' }] } as unknown as SectionData;
141
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
140
142
  const r = plan.sections[0]!;
141
143
  assert.equal(r.decision, 'conflict');
142
- assert.equal(r.conflicts[0]!.path, 'plugins');
144
+ assert.equal(r.conflicts[0]!.path, 'list');
143
145
  assert.equal(r.conflicts[0]!.reason, 'array');
144
146
  });
145
147
 
146
148
  test('merge: 数组仅一侧改 → 采纳该侧(另一侧键的改动同时保住)', () => {
147
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }], note: 'x' } as unknown as SectionData;
148
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }], note: 'x' } as unknown as SectionData;
149
- const rem: SectionData = { version: 1, plugins: [{ spec: 'a' }], note: 'y' } as unknown as SectionData;
150
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
149
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }], note: 'x' } as unknown as SectionData;
150
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }], note: 'x' } as unknown as SectionData;
151
+ const rem: SectionData = { version: 1, list: [{ spec: 'a' }], note: 'y' } as unknown as SectionData;
152
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
151
153
  const r = plan.sections[0]!;
152
154
  assert.equal(r.decision, 'merge');
153
- const merged = r.merged as unknown as { plugins: unknown[]; note: string };
154
- assert.equal(merged.plugins.length, 2);
155
+ const merged = r.merged as unknown as { list: unknown[]; note: string };
156
+ assert.equal(merged.list.length, 2);
155
157
  assert.equal(merged.note, 'y');
156
158
  });
157
159
 
158
160
  test('merge: 数组双侧改成相同结果 → 收敛为一份(不算冲突)', () => {
159
- const anc: SectionData = { version: 1, plugins: [{ spec: 'a' }] } as unknown as SectionData;
160
- const loc: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
161
- const rem: SectionData = { version: 1, plugins: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
162
- const plan = merge({ plugins: loc }, { plugins: rem }, { plugins: anc });
161
+ const anc: SectionData = { version: 1, list: [{ spec: 'a' }] } as unknown as SectionData;
162
+ const loc: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
163
+ const rem: SectionData = { version: 1, list: [{ spec: 'a' }, { spec: 'b' }] } as unknown as SectionData;
164
+ const plan = merge({ settings: loc }, { settings: rem }, { settings: anc });
163
165
  assert.equal(plan.sections[0]!.decision, 'skip');
164
166
  });
165
167
 
package/src/sync/merge.ts CHANGED
@@ -32,8 +32,9 @@
32
32
  import type { FilesSection, SectionData, SectionId } from '../schema/types.ts';
33
33
  import { hashSection } from './sync-state.ts';
34
34
  import { mergeBytesThreeWay, mergeJsonValues, type TextMergeConflict } from './text-merge.ts';
35
+ import { mergePluginsSection } from './plugin-removals.ts';
35
36
  import { mergeWorkspacesSection } from './workspace-merge.ts';
36
- import type { GranularMerger } from './workspace-merge.ts';
37
+ import type { GranularMergeHooks, GranularMerger } from './workspace-merge.ts';
37
38
 
38
39
  /**
39
40
  * 分区级决胜结果(三方合并,2026-10 收口):
@@ -298,6 +299,10 @@ function mergeFilesSectionGranular(
298
299
  */
299
300
  const GRANULAR_MERGES: Partial<Record<SectionId, GranularMerger>> = {
300
301
  workspaces: mergeWorkspacesSection,
302
+ // plugins(issue #132):plugins 是**数组**,通用 JSON 合并对「两侧各自改过」一律判冲突 ——
303
+ // 本机装了 Y、远端删了 X 就会整分区冲突,X 永远删不掉、Y 也永远同步不出去。
304
+ // 钩子按包名做三方逐条判定(本地新增保留 / 远端删除跟随 / 版本冲突交人工)。
305
+ plugins: mergePluginsSection,
301
306
  };
302
307
 
303
308
  /** 单分区三方合并(决策链见文件头注释)。 */
@@ -307,6 +312,7 @@ function mergeSectionTriple(
307
312
  rData: SectionData | undefined,
308
313
  aData: SectionData | undefined,
309
314
  h: TripleHashes,
315
+ hooks: GranularMergeHooks,
310
316
  ): MergeSectionResult {
311
317
  // ⓪ 形状闸门(先于一切取舍):远端载荷来自不可信输入(解析层只保证整体是合法 JSON,
312
318
  // 不保证每个分区的值形状正确)。值形状不对时**绝不原样采用** —— 那等于把畸形数据
@@ -366,7 +372,7 @@ function mergeSectionTriple(
366
372
  // 没有祖先时也应并集(否则首轮同步就整分区冲突),字段取值分歧由钩子逐键如实报冲突。
367
373
  const granular = GRANULAR_MERGES[id];
368
374
  if (granular !== undefined) {
369
- const res = granular(local, remote, aData);
375
+ const res = granular(local, remote, aData, hooks);
370
376
  if (res !== undefined) {
371
377
  if (res.conflicts.length > 0) return { id, decision: 'conflict', conflicts: res.conflicts };
372
378
  const merged = res.merged;
@@ -433,6 +439,7 @@ export function merge(
433
439
  local: Partial<Record<SectionId, SectionData>>,
434
440
  remote: Partial<Record<SectionId, SectionData>>,
435
441
  ancestor?: Partial<Record<SectionId, SectionData>>,
442
+ hooks: GranularMergeHooks = {},
436
443
  ): MergePlan {
437
444
  const l = local as Record<string, SectionData>;
438
445
  const r = remote as Record<string, SectionData>;
@@ -441,7 +448,7 @@ export function merge(
441
448
  const hashes = computeHashes(l, r, a, ids);
442
449
  const results: MergeSectionResult[] = [];
443
450
  for (const id of ids) {
444
- results.push(mergeSectionTriple(id, l[id], r[id], a ? a[id] : undefined, hashes.get(id)!));
451
+ results.push(mergeSectionTriple(id, l[id], r[id], a ? a[id] : undefined, hashes.get(id)!, hooks));
445
452
  }
446
453
  return { sections: results };
447
454
  }