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
@@ -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;
@@ -26,7 +26,7 @@ import { createSnapshotFs, joinFs } from '../fs.js';
26
26
  import { readSnapshotFromDir, SNAPSHOT_BLOB_REFS_SUFFIX, SNAPSHOT_KEEP_CONTENT, SNAPSHOT_KEEP_FILE, SNAPSHOT_MANIFEST_FILE, writeSnapshotToDir } from '../layout.js';
27
27
  import { BLOB_SECTIONS, gcBlobs, referencedBlobHashes } from '../blob-store.js';
28
28
  import { deserializeSnapshot, serializeSnapshot } from '../snapshot-json.js';
29
- import { classifyRepoUrl, isPrivateRepoHost } from '../sync-config.js';
29
+ import { classifyRepoUrl, isPrivateRepoHost, normalizeGitSubdir } from '../sync-config.js';
30
30
  import { classifyNetworkErrorText, computeSnapshotMeta, DEFAULT_SYNC_TIMEOUT_MS, isEncryptedSections, SyncTransportError, withSyncRetry, } from '../transport.js';
31
31
  import { markLocalOnlyExternalFailure } from '../../core/external-failure.js';
32
32
  import { parseJsonSafe } from '../../utils/json.js';
@@ -64,12 +64,22 @@ const inspectFactsCache = new Map();
64
64
  * 缺省的 300 s:一次自动同步持锁就能让同步页每次打开都白等 10 s(真机 2026-10-27)。
65
65
  */
66
66
  const INSPECT_WORKDIR_LOCK_TIMEOUT_MS = 1_500;
67
- function inspectFactsCacheKey(workDir, repoUrl) {
68
- return workDir + '\u0000' + repoUrl;
67
+ /**
68
+ * 工作副本布局身份的进程内缓存(key = workDir,值同 `readStoredSubdir()`,issue #131)。
69
+ *
70
+ * 为什么缓存:每次操作都要校验布局,而读一次 git 本地配置就是一次 git 子进程启动
71
+ * (Windows 真机约 80 ms,正是 L-04 在削的那笔开销)。布局身份是**工作副本的属性**,
72
+ * 只有本类写入(clone / adopt)与重建(reclone)会改它 —— 那三处显式更新缓存。
73
+ */
74
+ const storedSubdirCache = new Map();
75
+ function inspectFactsCacheKey(workDir, repoUrl, subdir) {
76
+ // 子目录前缀必须进 key:同一工作副本路径在不同前缀下的「远端快照数」是不同的答案(issue #131)。
77
+ return workDir + '\u0000' + repoUrl + '\u0000' + subdir;
69
78
  }
70
79
  /** 清空自检缓存(测试隔离用;生产路径由 `withWorkdir` 逐 key 失效)。 */
71
80
  export function clearInspectFactsCache() {
72
81
  inspectFactsCache.clear();
82
+ storedSubdirCache.clear();
73
83
  }
74
84
  /**
75
85
  * git 通道错误:继承统一错误基类(kind / retryable / status 分类对上层可见)。
@@ -103,7 +113,22 @@ const ADOPT_ROOT_ALLOW = new Set([SNAPSHOTS_REL, SNAPSHOTS_ENCRYPTED_REL, BLOBS_
103
113
  * 远端仓库比同步内容大几个数量级时(报告者现场:1.8 GB 仓库 / 6 MB 内容),全量 clone 与全量 fetch
104
114
  * 都要拉完整对象图,而工作副本真正需要的只有这三个目录。
105
115
  */
106
- const SYNC_ROOT_DIRS = [...ADOPT_ROOT_ALLOW];
116
+ /* 具体的 sparse 面在 `syncDirs()` 里按子目录前缀派生(issue #131),基名与 ADOPT_ROOT_ALLOW 同源。 */
117
+ /**
118
+ * 工作副本的**布局身份**键(git 本地配置,issue #131):记录这份工作副本是按哪个子目录前缀建的。
119
+ *
120
+ * 为什么必须落盘:sparse-checkout 只在首次 clone 时生效 —— 前缀从「仓库根」改成 `DSH备份` 后,
121
+ * 旧工作副本里根本没有 `DSH备份/` 这棵树,pull 会成功、list 会读空,用户看到的是
122
+ * 「远端没有快照」(issue #104 那类最难自查的假象)。存成 git 本地配置而不是工作树里的文件:
123
+ * 工作树文件会让 `status --porcelain` 恒 dirty,adopt 直接拒绝。
124
+ */
125
+ const SUBDIR_CONFIG_KEY = 'dsh.syncSubdir';
126
+ /**
127
+ * 标记值的版本前缀(issue #131)。为什么带前缀:读侧必须能区分「本插件写的」与「任何别的值」——
128
+ * 值不匹配前缀一律按「读不出」处理(回落历史布局 = 仓库根),这样伪造/污染的配置不会凭空
129
+ * 造出一条假的「布局已变」错误。空子目录写作 `1:`,仍是可判读的有效标记。
130
+ */
131
+ const SUBDIR_MARKER_PREFIX = '1:';
107
132
  /**
108
133
  * 走网络的 git 子命令:一律附加低速上限(issue #122)。
109
134
  *
@@ -287,6 +312,8 @@ export class GitTransport {
287
312
  msg;
288
313
  /** repoUrl 是否为网络地址(本地目录仓库 == false):决定要不要额外禁 file 传输(SEC-12)。 */
289
314
  networkRepo;
315
+ /** 仓库内子目录前缀('' = 仓库根):快照布局、sparse 面与 adopt 判据都从它派生(issue #131)。 */
316
+ subdir;
290
317
  constructor(options) {
291
318
  if (typeof options.repoUrl !== 'string' || options.repoUrl.length === 0) {
292
319
  throw new GitTransportError(zhMsg('sync.git.repoUrlRequired'));
@@ -309,6 +336,12 @@ export class GitTransport {
309
336
  throw new GitTransportError(this.msg('sync.git.repoUrlInvalid', { url: REPO_URL_PLACEHOLDER }));
310
337
  }
311
338
  this.networkRepo = repoShape.kind !== 'local';
339
+ // issue #131:子目录前缀在构造期就收窄(与 repoUrl 同一条纪律:非法值绝不进 git 子进程)。
340
+ const subdirCheck = normalizeGitSubdir(options.subdir ?? '');
341
+ if (!subdirCheck.ok) {
342
+ throw new GitTransportError(this.msg('sync.git.subdirInvalid', { subdir: String(options.subdir ?? '') }));
343
+ }
344
+ this.subdir = subdirCheck.value;
312
345
  this.o = {
313
346
  repoUrl: options.repoUrl,
314
347
  workDir: options.workDir,
@@ -406,7 +439,7 @@ export class GitTransport {
406
439
  await fsx.writeFile(file, new TextEncoder().encode(serializeSnapshot(snapshot)));
407
440
  // 同 id 旧散文件目录残留 → 一并清理(形态切换不残留)
408
441
  await fsx.remove(this.snapshotDir(snapshot.id));
409
- rel = `${SNAPSHOTS_ENCRYPTED_REL}/${snapshot.id}.json`;
442
+ rel = `${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}/${snapshot.id}.json`;
410
443
  }
411
444
  else {
412
445
  const dir = this.snapshotDir(snapshot.id);
@@ -431,11 +464,11 @@ export class GitTransport {
431
464
  }
432
465
  // 同 id 旧密文单文件残留 → 一并清理(形态切换不残留)
433
466
  await fsx.remove(this.encryptedSnapshotFile(snapshot.id));
434
- rel = `${SNAPSHOTS_REL}/${snapshot.id}`;
467
+ rel = `${this.relDir(SNAPSHOTS_REL)}/${snapshot.id}`;
435
468
  }
436
469
  // blob 仓与快照同一次提交:引用文件与它引用的字节绝不跨 commit 分离
437
470
  const hasBlobs = await fsx.exists(this.blobsDir());
438
- await this.runGit(hasBlobs ? ['add', '--', rel, BLOBS_REL] : ['add', '--', rel]);
471
+ await this.runGit(hasBlobs ? ['add', '--', rel, this.relDir(BLOBS_REL)] : ['add', '--', rel]);
439
472
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
440
473
  if (diff.code !== 0) {
441
474
  const verb = existed ? 'update' : 'add';
@@ -498,11 +531,11 @@ export class GitTransport {
498
531
  let rel;
499
532
  if (plainExists) {
500
533
  await fsx.remove(plainDir);
501
- rel = `${SNAPSHOTS_REL}/${id}`;
534
+ rel = `${this.relDir(SNAPSHOTS_REL)}/${id}`;
502
535
  }
503
536
  else {
504
537
  await fsx.remove(encFile);
505
- rel = `${SNAPSHOTS_ENCRYPTED_REL}/${id}.json`;
538
+ rel = `${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}/${id}.json`;
506
539
  }
507
540
  await this.runGit(['add', '-A', '--', rel]);
508
541
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
@@ -597,7 +630,7 @@ export class GitTransport {
597
630
  // 除纯只读自检外,任何操作都可能改变工作副本状态(push 改 ahead、fetch 改远端引用、
598
631
  // 重建删目录、失败也可能已留下 commit)→ 收尾即丢弃自检缓存,绝不让「写后读」看到旧事实。
599
632
  if (opts.readonly !== true)
600
- inspectFactsCache.delete(inspectFactsCacheKey(this.o.workDir, this.o.repoUrl));
633
+ inspectFactsCache.delete(inspectFactsCacheKey(this.o.workDir, this.o.repoUrl, this.subdir));
601
634
  }
602
635
  }
603
636
  async ensureRepo() {
@@ -612,6 +645,8 @@ export class GitTransport {
612
645
  // 而失败面表现为旧地址的网络超时(真机:局域网地址 → Tailscale 地址后同步长期失败),
613
646
  // 用户会误判成网络/凭据问题。
614
647
  await this.reconcileOrigin();
648
+ // issue #131:布局身份(子目录前缀)与当前配置不一致 ⇒ 明确报「需重建」,绝不照常同步
649
+ await this.assertLayoutMatches();
615
650
  // 真机 issue:仓库级提交身份此前**只在首次 clone 时**写过(见本方法末尾),已有 .git 的分支
616
651
  // 直接 return —— 换机器/换工作副本/用户清过本地配置之后,每次 commit 都以 exit 128 失败
617
652
  // ("unable to auto-detect email address"),交易停在 NEEDS_ATTENTION,用户只看到
@@ -635,6 +670,8 @@ export class GitTransport {
635
670
  // 仓库级提交身份(写入远端历史,可经 author 选项覆盖;不改全局配置)
636
671
  await this.runGit(['config', 'user.name', this.o.author.name]);
637
672
  await this.runGit(['config', 'user.email', this.o.author.email]);
673
+ // 记录布局身份(issue #131):此后前缀再变,assertLayoutMatches 能把它判出来
674
+ await this.writeLayoutMarker();
638
675
  this.repoReady = true;
639
676
  }
640
677
  /**
@@ -668,6 +705,45 @@ export class GitTransport {
668
705
  /* best-effort:写入失败留给后续 commit 以 config 分类暴露,不在这里阻断同步 */
669
706
  }
670
707
  }
708
+ /**
709
+ * 工作副本是按哪个子目录前缀建的(issue #131):读 git 本地配置 `dsh.syncSubdir`。
710
+ * null = 键不存在 ⇒ 本功能上线前建的工作副本,布局 = 仓库根(历史行为)。
711
+ */
712
+ async readStoredSubdir() {
713
+ const cached = storedSubdirCache.get(this.o.workDir);
714
+ if (cached !== undefined)
715
+ return cached;
716
+ try {
717
+ const r = await this.runGit(['config', '--get', SUBDIR_CONFIG_KEY], { allowNonZero: true });
718
+ const raw = r.code === 0 ? r.stdout.trim() : '';
719
+ // 键不存在 / 前缀不符(不是本插件写的标记,或被人改坏)⇒ 不知道,按历史布局处理
720
+ const value = raw.startsWith(SUBDIR_MARKER_PREFIX) ? raw.slice(SUBDIR_MARKER_PREFIX.length) : null;
721
+ storedSubdirCache.set(this.o.workDir, value);
722
+ return value;
723
+ }
724
+ catch {
725
+ return null; // 读不出 = 不知道,按历史布局处理(不拿猜测阻断同步;失败不进缓存,下次再读)
726
+ }
727
+ }
728
+ /** 写入布局身份标记(issue #131):git 本地配置 + 同步更新进程内缓存。 */
729
+ async writeLayoutMarker() {
730
+ await this.runGit(['config', SUBDIR_CONFIG_KEY, SUBDIR_MARKER_PREFIX + this.subdir]);
731
+ storedSubdirCache.set(this.o.workDir, this.subdir);
732
+ }
733
+ /**
734
+ * 布局身份校验(issue #131):工作副本建好时的前缀必须与当前配置一致。
735
+ *
736
+ * 为什么必须显式报错而不是「照常同步」:sparse-checkout 只在首次 clone 生效 —— 前缀换了以后,
737
+ * 旧工作副本里根本没有 `<新前缀>/` 这棵树,pull 成功、list 读空,用户看到的是
738
+ * 「远端没有快照」。这条错误把出口指回既有的「重建工作副本(重新克隆)」。
739
+ */
740
+ async assertLayoutMatches() {
741
+ const stored = (await this.readStoredSubdir()) ?? '';
742
+ if (stored === this.subdir)
743
+ return;
744
+ const label = (prefix) => (prefix === '' ? this.msg('sync.git.subdirRoot') : prefix);
745
+ throw new GitTransportError(this.msg('sync.git.subdirChanged', { stored: label(stored), expected: label(this.subdir) }), { kind: 'protocol', retryable: false });
746
+ }
671
747
  /**
672
748
  * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
673
749
  *
@@ -698,7 +774,8 @@ export class GitTransport {
698
774
  if (head.code !== 0)
699
775
  return; // 空仓库:没有可 checkout 的树,后续 push 会建分支
700
776
  const target = branch === '' ? 'HEAD' : branch;
701
- const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...SYNC_ROOT_DIRS], { allowNonZero: true });
777
+ // issue #131:sparse 面跟着子目录前缀走 —— 共用仓库里其它工具的目录绝不被 materialize
778
+ const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...this.syncDirs()], { allowNonZero: true });
702
779
  if (sparse.code !== 0) {
703
780
  // 老 git 没有 cone 模式:宁可全量落地(修复前行为),也不留下一个空工作树
704
781
  await this.runGit(['checkout', target], { allowNonZero: true });
@@ -803,7 +880,7 @@ export class GitTransport {
803
880
  * 因此放进 `detail: true`(供「重建工作副本」前评估数据量等场景显式索取)。
804
881
  */
805
882
  async inspectWorkDir(opts = {}) {
806
- const key = inspectFactsCacheKey(this.o.workDir, this.o.repoUrl);
883
+ const key = inspectFactsCacheKey(this.o.workDir, this.o.repoUrl, this.subdir);
807
884
  const detail = opts.detail === true;
808
885
  const hit = inspectFactsCache.get(key);
809
886
  // 命中即返回:不必排队等锁,也不必再 spawn 一条 git(这是首页/切页/轮询的常态路径)。
@@ -859,8 +936,8 @@ export class GitTransport {
859
936
  // 每个快照是一级子项;`.gitkeep` 只是占位,不是快照
860
937
  .filter((line) => line !== '' && !line.endsWith(SNAPSHOT_KEEP_FILE)).length;
861
938
  };
862
- const plain = await countTree(`origin/${branch}:${SNAPSHOTS_REL}`);
863
- const encrypted = await countTree(`origin/${branch}:${SNAPSHOTS_ENCRYPTED_REL}`);
939
+ const plain = await countTree(`origin/${branch}:${this.relDir(SNAPSHOTS_REL)}`);
940
+ const encrypted = await countTree(`origin/${branch}:${this.relDir(SNAPSHOTS_ENCRYPTED_REL)}`);
864
941
  // 两个目录都不存在 = 远端分支根本没有快照布局(0);分支/引用读不出 = null(不猜)
865
942
  remoteSnapshots = plain === null && encrypted === null ? 0 : (plain ?? 0) + (encrypted ?? 0);
866
943
  }
@@ -913,6 +990,7 @@ export class GitTransport {
913
990
  return;
914
991
  }
915
992
  await fs.rm(this.o.workDir, { recursive: true, force: true });
993
+ storedSubdirCache.delete(this.o.workDir); // 旧副本连同它的布局身份一起没了
916
994
  await this.ensureRepo();
917
995
  }
918
996
  /**
@@ -947,6 +1025,8 @@ export class GitTransport {
947
1025
  throw new GitTransportError(this.msg('sync.git.adoptDirty', { dir: this.o.workDir }), { kind: 'protocol', retryable: false });
948
1026
  }
949
1027
  await this.reconcileOrigin();
1028
+ // issue #131:采纳远端历史也不许跨布局 —— 前缀变了要先重建工作副本
1029
+ await this.assertLayoutMatches();
950
1030
  const branchRes = await this.runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { allowNonZero: true });
951
1031
  const branch = branchRes.code === 0 ? branchRes.stdout.trim() : '';
952
1032
  if (branch === '' || branch === 'HEAD') {
@@ -973,16 +1053,20 @@ export class GitTransport {
973
1053
  }
974
1054
  throw new GitTransportError(this.msg('sync.git.adoptNoRemoteBranch', { branch, heads: heads.slice(0, 3).join(', ') }), { kind: 'protocol', retryable: false });
975
1055
  }
976
- // ② 远端顶层只能是快照布局
977
- const treeRes = await this.runGit(['ls-tree', '--name-only', `origin/${branch}`], { allowNonZero: true });
978
- if (treeRes.code !== 0) {
1056
+ // ② 同步布局只能是那三个目录。配了子目录前缀时校验的是 <subdir>/ **子树**(issue #131):
1057
+ // 共用仓库里其它工具的目录在仓库根,那不是本插件的同步内容,也不该被判成「污染」。
1058
+ const treeish = this.subdir === '' ? `origin/${branch}` : `origin/${branch}:${this.subdir}`;
1059
+ const treeRes = await this.runGit(['ls-tree', '--name-only', treeish], { allowNonZero: true });
1060
+ // 子树不存在 = 远端还没有该前缀的同步内容(首次 push 会建它),不是错误;
1061
+ // 仓库根读不出来才是真异常(引用在上面已验过存在)。
1062
+ if (treeRes.code !== 0 && this.subdir === '') {
979
1063
  throw new GitTransportError(this.msg('sync.git.cmdFailed', {
980
1064
  args: `ls-tree --name-only origin/${branch}`,
981
1065
  code: String(treeRes.code),
982
1066
  err: this.mask(treeRes.stderr, await this.readTokenOnce()),
983
1067
  }), { kind: 'unknown', retryable: true });
984
1068
  }
985
- const unknownEntries = treeRes.stdout
1069
+ const unknownEntries = (treeRes.code === 0 ? treeRes.stdout : '')
986
1070
  .split('\n')
987
1071
  .map((name) => name.trim().replace(/\/$/, ''))
988
1072
  .filter((name) => name !== '' && !ADOPT_ROOT_ALLOW.has(name));
@@ -997,6 +1081,7 @@ export class GitTransport {
997
1081
  }
998
1082
  // 让后续 pull --ff-only 有 upstream 可用(忽略失败:分支可能已被删/重命名)
999
1083
  await this.runGit(['branch', '--set-upstream-to', `origin/${branch}`, branch], { allowNonZero: true });
1084
+ await this.writeLayoutMarker();
1000
1085
  this.repoReady = true;
1001
1086
  }
1002
1087
  /**
@@ -1278,8 +1363,19 @@ export class GitTransport {
1278
1363
  ? this.msg('sync.git.hostKeyUnverifiedNoHost')
1279
1364
  : this.msg('sync.git.hostKeyUnverified', { host });
1280
1365
  }
1366
+ /** 子目录前缀下的同步布局相对路径('' 前缀 = 历史布局,逐字不变)。 */
1367
+ relDir(base) {
1368
+ return this.subdir === '' ? base : `${this.subdir}/${base}`;
1369
+ }
1370
+ /**
1371
+ * 三个同步根目录(带前缀):sparse 面、add 路径、adopt 判据都从这里取 ——
1372
+ * 任何一处漏加前缀都会让「写入 A、读取 B」(issue #131 的失败面)。
1373
+ */
1374
+ syncDirs() {
1375
+ return [this.relDir(SNAPSHOTS_REL), this.relDir(SNAPSHOTS_ENCRYPTED_REL), this.relDir(BLOBS_REL)];
1376
+ }
1281
1377
  blobsDir() {
1282
- return path.join(this.o.workDir, BLOBS_REL);
1378
+ return path.join(this.o.workDir, this.relDir(BLOBS_REL));
1283
1379
  }
1284
1380
  /**
1285
1381
  * git 通道的 blob 仓实现:工作树内 `blobs/<sha256>`(跨快照共享、按内容寻址)。
@@ -1357,7 +1453,7 @@ export class GitTransport {
1357
1453
  const deleted = await gcBlobs({ sink: this.blobSink(fsx), referenced, nowMs: Date.now() });
1358
1454
  if (deleted.length === 0)
1359
1455
  return;
1360
- await this.runGit(['add', '-A', '--', BLOBS_REL]);
1456
+ await this.runGit(['add', '-A', '--', this.relDir(BLOBS_REL)]);
1361
1457
  const diff = await this.runGit(['diff', '--cached', '--quiet'], { allowNonZero: true });
1362
1458
  if (diff.code === 0)
1363
1459
  return;
@@ -1373,11 +1469,11 @@ export class GitTransport {
1373
1469
  return joinFs(this.snapshotsDir(), id);
1374
1470
  }
1375
1471
  snapshotsDir() {
1376
- return joinFs(this.o.workDir, SNAPSHOTS_REL);
1472
+ return joinFs(this.o.workDir, this.relDir(SNAPSHOTS_REL));
1377
1473
  }
1378
- /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/) */
1474
+ /** 加密快照密文单文件目录(<workDir>/snapshots-encrypted/;配了前缀则在 <subdir>/ 下) */
1379
1475
  encryptedSnapshotsDir() {
1380
- return joinFs(this.o.workDir, SNAPSHOTS_ENCRYPTED_REL);
1476
+ return joinFs(this.o.workDir, this.relDir(SNAPSHOTS_ENCRYPTED_REL));
1381
1477
  }
1382
1478
  /** 加密快照密文单文件路径(<id>.json) */
1383
1479
  encryptedSnapshotFile(id) {
@@ -0,0 +1,78 @@
1
+ import type { SectionData, SectionId } from '../schema/types.ts';
2
+ import type { MergeConflictReason, MergeSectionResult } from './merge.ts';
3
+ /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
4
+ export declare function mergePreviewSectionView(result: MergeSectionResult): MergePreviewSectionView;
5
+ /**
6
+ * issue #91:走只读 `preview()` 拿到的产物,能否直接与该分区**基线 hash**(push 时按 export() 产物记录)比对。
7
+ *
8
+ * 为什么需要这个判定:`plugins` 适配器的 `preview()` 走 `collect(…, pack=false)` —— 刻意**不做**
9
+ * 本地源(`link:` / `file:`)插件的 `npm pack`。于是当 profile 里存在本地源插件时,预览产物既没有
10
+ * `localTarballs`、插件 spec 也保持原样(export() 会改写成 `file:<tarball>`),与基线**不同口径**:
11
+ * 此时既不能断言「无变化」(本地插件源码改了体积/内容,预览看不见),也不该为了比对去打包
12
+ * (那正是本 issue 的缺陷本身)。
13
+ *
14
+ * 返回 true = 该分区本趟**不可比** ⇒ 调用方只能保守报「有变化」并如实说明原因。
15
+ * 其余分区的 preview() 产物与 export() 逐字节相同(文件类分区不走 preview(),见 previewPush)。
16
+ */
17
+ export declare function previewCaliberDiffersFromExport(sectionId: SectionId, data: SectionData): boolean;
18
+ /** previewMerge 的单条冲突视图(三侧文本都已截断 + redact;绝不回传原始值对象)。 */
19
+ export interface MergePreviewConflictView {
20
+ /** 冲突位置:JSON 分区是 top-level key;文件类分区是 relativePath;'$' = 整分区冲突。 */
21
+ path: string;
22
+ kind: 'key' | 'file';
23
+ /** 冲突成因(可选:旧数据/旧 merge 结果没有该字段,界面缺省按 'both-modified' 措辞)。 */
24
+ reason?: MergeConflictReason;
25
+ /** 本机侧的可读预览(≤ 2 KiB,超出截断加省略号;已过 redact())。 */
26
+ localPreview: string;
27
+ /** 远端侧的可读预览(同上)。 */
28
+ remotePreview: string;
29
+ /** 共同祖先侧的可读预览(同上;无祖先时为空串)。 */
30
+ ancestorPreview: string;
31
+ }
32
+ /** previewMerge 的单个分区视图。 */
33
+ export interface MergePreviewSectionView {
34
+ id: SectionId;
35
+ decision: MergeSectionResult['decision'];
36
+ /** 自动合并并入的变更点数量(仅 decision === 'merge' 时有意义;缺省 = 未统计)。 */
37
+ autoMerged?: number;
38
+ conflictCount: number;
39
+ conflicts: MergePreviewConflictView[];
40
+ }
41
+ /** previewMerge 结果(只读、零写入)。 */
42
+ export interface MergePreview {
43
+ /** 预览是否成功产出(远端无快照 → false + message,分区清单为空)。 */
44
+ ok: boolean;
45
+ /** 本次预览针对的**远端**快照 id;'' = 远端无快照。 */
46
+ snapshotId: string;
47
+ /** 是否拿到了本地祖先副本(false = 退化为两方合并 → 所有双侧差异都会呈现为 conflict)。 */
48
+ hasAncestor: boolean;
49
+ sections: MergePreviewSectionView[];
50
+ /** 与 risk.ts 的 classifyMergePlan 同口径计数:auto = 可自动应用,review = 需人工,conflicts = 冲突,skipped = 跳过。 */
51
+ summary: {
52
+ auto: number;
53
+ review: number;
54
+ conflicts: number;
55
+ skipped: number;
56
+ };
57
+ message?: string;
58
+ reason?: 'remote-empty';
59
+ /**
60
+ * 本轮合并**将卸载**的插件(issue #132):确认页必须单列出来,用户据此可以整轮取消。
61
+ * 仅在 plugins 分区可应用(useRemote/keepLocal/merge)时才有条目 —— 分区冲突时不删。
62
+ */
63
+ pluginRemovals?: {
64
+ name: string;
65
+ version: string;
66
+ }[];
67
+ /** 远端删了、本机却改过 → 不删,等人工裁决(与 conflict 清单同语义,这里为插件专列) */
68
+ pluginRemovalConflicts?: {
69
+ name: string;
70
+ ancestorVersion: string;
71
+ localVersion: string;
72
+ }[];
73
+ /** 考察过但没删的条目及原因(含开关关闭 = 'switch-off',界面据此如实说明) */
74
+ pluginRemovalSkipped?: {
75
+ name: string;
76
+ reason: string;
77
+ }[];
78
+ }
@@ -0,0 +1,46 @@
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.js';
9
+ import { previewTextOf } from './merge-preview-text.js';
10
+ /** plan 的单个分区结果 → 预览视图(三侧都只回传可读文本,绝不回传原始值)。 */
11
+ export function mergePreviewSectionView(result) {
12
+ const conflicts = result.conflicts.map((c) => ({
13
+ path: c.path,
14
+ kind: c.kind,
15
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
16
+ localPreview: previewTextOf(c.local),
17
+ remotePreview: previewTextOf(c.remote),
18
+ ancestorPreview: previewTextOf(c.ancestor),
19
+ }));
20
+ return {
21
+ id: result.id,
22
+ decision: result.decision,
23
+ ...(result.autoMerged !== undefined ? { autoMerged: result.autoMerged } : {}),
24
+ conflictCount: result.conflicts.length,
25
+ conflicts,
26
+ };
27
+ }
28
+ /**
29
+ * issue #91:走只读 `preview()` 拿到的产物,能否直接与该分区**基线 hash**(push 时按 export() 产物记录)比对。
30
+ *
31
+ * 为什么需要这个判定:`plugins` 适配器的 `preview()` 走 `collect(…, pack=false)` —— 刻意**不做**
32
+ * 本地源(`link:` / `file:`)插件的 `npm pack`。于是当 profile 里存在本地源插件时,预览产物既没有
33
+ * `localTarballs`、插件 spec 也保持原样(export() 会改写成 `file:<tarball>`),与基线**不同口径**:
34
+ * 此时既不能断言「无变化」(本地插件源码改了体积/内容,预览看不见),也不该为了比对去打包
35
+ * (那正是本 issue 的缺陷本身)。
36
+ *
37
+ * 返回 true = 该分区本趟**不可比** ⇒ 调用方只能保守报「有变化」并如实说明原因。
38
+ * 其余分区的 preview() 产物与 export() 逐字节相同(文件类分区不走 preview(),见 previewPush)。
39
+ */
40
+ export function previewCaliberDiffersFromExport(sectionId, data) {
41
+ if (sectionId !== 'plugins')
42
+ return false;
43
+ const plugins = data.plugins;
44
+ return Array.isArray(plugins) && plugins.some((p) => isLocalPluginSpec(p?.spec));
45
+ }
46
+ //# sourceMappingURL=merge-preview-view.js.map
@@ -30,6 +30,7 @@
30
30
  * 文件级(FilesSection 内的 relativePath)才是真正的删除语义,那里按 modify/delete 判冲突。
31
31
  */
32
32
  import type { SectionData, SectionId } from '../schema/types.ts';
33
+ import type { GranularMergeHooks } from './workspace-merge.ts';
33
34
  /**
34
35
  * 分区级决胜结果(三方合并,2026-10 收口):
35
36
  * - 'skip' :双侧相对祖先都未改(或本就无变化)—— 不产生任何写入;
@@ -74,4 +75,4 @@ export interface MergePlan {
74
75
  sections: MergeSectionResult[];
75
76
  }
76
77
  /** 主入口:三方合并。纯函数,无副作用。 */
77
- export declare function merge(local: Partial<Record<SectionId, SectionData>>, remote: Partial<Record<SectionId, SectionData>>, ancestor?: Partial<Record<SectionId, SectionData>>): MergePlan;
78
+ export declare function merge(local: Partial<Record<SectionId, SectionData>>, remote: Partial<Record<SectionId, SectionData>>, ancestor?: Partial<Record<SectionId, SectionData>>, hooks?: GranularMergeHooks): MergePlan;
package/lib/sync/merge.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { hashSection } from './sync-state.js';
2
2
  import { mergeBytesThreeWay, mergeJsonValues } from './text-merge.js';
3
+ import { mergePluginsSection } from './plugin-removals.js';
3
4
  import { mergeWorkspacesSection } from './workspace-merge.js';
4
5
  /** 收集 local/remote/ancestor 三个快照中出现过的所有分区 id。 */
5
6
  function unionSectionIds(local, remote, ancestor) {
@@ -223,9 +224,13 @@ function mergeFilesSectionGranular(local, remote, ancestor) {
223
224
  */
224
225
  const GRANULAR_MERGES = {
225
226
  workspaces: mergeWorkspacesSection,
227
+ // plugins(issue #132):plugins 是**数组**,通用 JSON 合并对「两侧各自改过」一律判冲突 ——
228
+ // 本机装了 Y、远端删了 X 就会整分区冲突,X 永远删不掉、Y 也永远同步不出去。
229
+ // 钩子按包名做三方逐条判定(本地新增保留 / 远端删除跟随 / 版本冲突交人工)。
230
+ plugins: mergePluginsSection,
226
231
  };
227
232
  /** 单分区三方合并(决策链见文件头注释)。 */
228
- function mergeSectionTriple(id, lData, rData, aData, h) {
233
+ function mergeSectionTriple(id, lData, rData, aData, h, hooks) {
229
234
  // ⓪ 形状闸门(先于一切取舍):远端载荷来自不可信输入(解析层只保证整体是合法 JSON,
230
235
  // 不保证每个分区的值形状正确)。值形状不对时**绝不原样采用** —— 那等于把畸形数据
231
236
  // 写进本机配置;一律按 conflict(reason='format') 交用户裁决。
@@ -288,7 +293,7 @@ function mergeSectionTriple(id, lData, rData, aData, h) {
288
293
  // 没有祖先时也应并集(否则首轮同步就整分区冲突),字段取值分歧由钩子逐键如实报冲突。
289
294
  const granular = GRANULAR_MERGES[id];
290
295
  if (granular !== undefined) {
291
- const res = granular(local, remote, aData);
296
+ const res = granular(local, remote, aData, hooks);
292
297
  if (res !== undefined) {
293
298
  if (res.conflicts.length > 0)
294
299
  return { id, decision: 'conflict', conflicts: res.conflicts };
@@ -358,7 +363,7 @@ function mergeSectionTriple(id, lData, rData, aData, h) {
358
363
  };
359
364
  }
360
365
  /** 主入口:三方合并。纯函数,无副作用。 */
361
- export function merge(local, remote, ancestor) {
366
+ export function merge(local, remote, ancestor, hooks = {}) {
362
367
  const l = local;
363
368
  const r = remote;
364
369
  const a = ancestor;
@@ -366,7 +371,7 @@ export function merge(local, remote, ancestor) {
366
371
  const hashes = computeHashes(l, r, a, ids);
367
372
  const results = [];
368
373
  for (const id of ids) {
369
- results.push(mergeSectionTriple(id, l[id], r[id], a ? a[id] : undefined, hashes.get(id)));
374
+ results.push(mergeSectionTriple(id, l[id], r[id], a ? a[id] : undefined, hashes.get(id), hooks));
370
375
  }
371
376
  return { sections: results };
372
377
  }