dsh-config-manager 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/adapters/mcp.js +9 -2
- package/lib/adapters/plugins.js +65 -10
- package/lib/adapters/prompts.js +15 -4
- package/lib/adapters/test-helpers.d.ts +15 -1
- package/lib/adapters/test-helpers.js +11 -0
- package/lib/cli/help.d.ts +1 -1
- package/lib/cli/help.js +21 -14
- package/lib/cli/index.js +118 -104
- package/lib/cli/sessions-repair.js +58 -22
- package/lib/cli/web/client-script.d.ts +1 -1
- package/lib/cli/web/client-script.js +71 -5
- package/lib/cli/web/page.d.ts +9 -19
- package/lib/cli/web/page.js +277 -173
- package/lib/cli/web/routes.js +85 -25
- package/lib/client.d.ts +93 -27
- package/lib/client.js +11461 -11339
- package/lib/core/messages.d.ts +10 -0
- package/lib/core/messages.js +20 -0
- package/lib/core/model-tools.js +7 -1
- package/lib/core/patch-chain.d.ts +65 -0
- package/lib/core/patch-chain.js +100 -0
- package/lib/core/patch-document.d.ts +32 -4
- package/lib/core/patch-document.js +48 -17
- package/lib/core/patch-secret-guard.d.ts +1 -1
- package/lib/core/patch-secret-guard.js +1 -1
- package/lib/core/types.d.ts +16 -1
- package/lib/index.d.ts +9 -4
- package/lib/index.js +42 -47
- package/lib/routes/sync.js +6 -0
- package/lib/sync/autosync-scheduler.d.ts +13 -1
- package/lib/sync/autosync-scheduler.js +73 -17
- package/lib/sync/local-changes.d.ts +15 -0
- package/lib/sync/local-changes.js +39 -0
- package/lib/sync/merge-keyed.d.ts +68 -0
- package/lib/sync/merge-keyed.js +124 -0
- package/lib/sync/patch-line-identity.d.ts +19 -0
- package/lib/sync/patch-line-identity.js +99 -0
- package/lib/sync/pending-merge.d.ts +8 -1
- package/lib/sync/pending-merge.js +13 -5
- package/lib/sync/plugin-removals.d.ts +15 -15
- package/lib/sync/plugin-removals.js +134 -83
- package/lib/sync/push-skip.d.ts +55 -0
- package/lib/sync/push-skip.js +70 -0
- package/lib/sync/sync-engine.d.ts +22 -12
- package/lib/sync/sync-engine.js +53 -70
- package/lib/sync/workspace-merge.d.ts +8 -2
- package/lib/ui/artifact-view.d.ts +1 -1
- package/lib/ui/foreign-view.d.ts +14 -0
- package/lib/ui/foreign-view.js +34 -0
- package/lib/ui/i18n.d.ts +5 -0
- package/lib/ui/i18n.js +11 -0
- package/lib/ui/selection-model.d.ts +2 -2
- package/lib/ui/selection-model.js +7 -3
- package/lib/utils/async-once.d.ts +11 -0
- package/lib/utils/async-once.js +15 -0
- package/lib/utils/patch-chain-read.d.ts +51 -0
- package/lib/utils/patch-chain-read.js +240 -0
- package/package.json +2 -2
- package/src/adapters/mcp.ts +9 -2
- package/src/adapters/plugins.test.ts +115 -0
- package/src/adapters/plugins.ts +64 -11
- package/src/adapters/prompts.ts +15 -4
- package/src/adapters/test-helpers.ts +15 -1
- package/src/cli/help.ts +21 -14
- package/src/cli/index.ts +105 -107
- package/src/cli/sessions-repair.ts +55 -22
- package/src/cli/web/client-script.ts +71 -5
- package/src/cli/web/page.ts +327 -208
- package/src/cli/web/routes.ts +85 -25
- package/src/cli/web/web.test.ts +38 -0
- package/src/client/ConfigManagerSection.tsx +8 -4
- package/src/client/about/AboutPanel.tsx +2 -6
- package/src/client/api.ts +2 -1
- package/src/client/common/ContentPicker.tsx +11 -12
- package/src/client/common/plan-text-redaction.test.ts +2 -2
- package/src/client/config-manager.module.css +10 -0
- package/src/client/environment/EnvironmentPanel.tsx +2 -4
- package/src/client/environment/maintenance/DiskUsageCard.tsx +4 -5
- package/src/client/home/BackupScheduleCard.tsx +52 -49
- package/src/client/home/HomePanel.tsx +2 -2
- package/src/client/import/ForeignImportView.tsx +60 -3
- package/src/client/import/ImportWizardView.tsx +2 -1
- package/src/client/import/PathMappingForm.tsx +32 -5
- package/src/client/import/import-wizard-split.test.ts +1 -1
- package/src/client/library/BackupInspectView.tsx +4 -2
- package/src/client/library/LibraryActions.tsx +60 -12
- package/src/client/library/LibraryPanel.tsx +9 -10
- package/src/client/locales/backup.ts +5 -0
- package/src/client/locales/foreign.ts +2 -0
- package/src/client/locales/import.ts +2 -0
- package/src/client/locales/restore.ts +2 -0
- package/src/client/market/MarketImportReview.tsx +4 -4
- package/src/client/market/MarketPanel.tsx +20 -36
- package/src/client/market/MyConfigsView.tsx +3 -10
- package/src/client/recovery/RecoveryPanel.tsx +4 -6
- package/src/client/recovery/RollbackCard.tsx +74 -59
- package/src/client/recovery/rollback-enabled.ts +29 -0
- package/src/client/recovery/use-recovery-write.ts +5 -0
- package/src/client/sync/AutosyncCard.tsx +3 -1
- package/src/client/sync/MergePreviewView.tsx +2 -2
- package/src/client/sync/PushPreviewCard.tsx +2 -1
- package/src/client/sync/SyncConfirmView.tsx +127 -130
- package/src/client/sync/SyncLogList.tsx +14 -10
- package/src/client/sync/SyncPanel.tsx +37 -28
- package/src/client/sync/SyncSettingsDialog.tsx +10 -21
- package/src/client/sync/history-model.ts +2 -0
- package/src/client/sync/sync-api.ts +1 -1
- package/src/client/sync/sync-locales.ts +8 -0
- package/src/client/sync/sync-push-preview.test.ts +9 -0
- package/src/client/sync/sync-view.ts +34 -0
- package/src/core/messages.ts +20 -0
- package/src/core/model-tools.ts +7 -1
- package/src/core/patch-chain.test.ts +83 -0
- package/src/core/patch-chain.ts +150 -0
- package/src/core/patch-document.test.ts +48 -1
- package/src/core/patch-document.ts +66 -15
- package/src/core/patch-layers.test.ts +1 -1
- package/src/core/patch-secret-guard.ts +1 -1
- package/src/core/smoke.test.ts +2 -1
- package/src/core/types.ts +16 -1
- package/src/index.facade.test.ts +186 -6
- package/src/index.ts +53 -47
- package/src/routes/sync.ts +6 -0
- package/src/security/security.test.ts +1 -1
- package/src/sync/autosync-scheduler.test.ts +98 -0
- package/src/sync/autosync-scheduler.ts +78 -17
- package/src/sync/local-changes.ts +40 -0
- package/src/sync/merge-keyed.test.ts +167 -0
- package/src/sync/merge-keyed.ts +160 -0
- package/src/sync/messages.ts +1 -0
- package/src/sync/patch-line-identity.test.ts +73 -0
- package/src/sync/patch-line-identity.ts +105 -0
- package/src/sync/pending-merge.test.ts +41 -0
- package/src/sync/pending-merge.ts +13 -5
- package/src/sync/plugin-removals.test.ts +199 -39
- package/src/sync/plugin-removals.ts +150 -64
- package/src/sync/push-skip.test.ts +326 -0
- package/src/sync/push-skip.ts +102 -0
- package/src/sync/sync-engine.ts +68 -67
- package/src/sync/workspace-merge.ts +9 -2
- package/src/ui/artifact-view.ts +1 -1
- package/src/ui/foreign-view.test.ts +49 -0
- package/src/ui/foreign-view.ts +47 -0
- package/src/ui/i18n.ts +11 -0
- package/src/ui/selection-model.test.ts +14 -0
- package/src/ui/selection-model.ts +7 -4
- package/src/utils/async-once.ts +14 -0
- package/src/utils/patch-chain-read.test.ts +171 -0
- package/src/utils/patch-chain-read.ts +259 -0
- package/src/utils/patch-yaml.test.ts +8 -2
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
* → engine.applyMergePlan(autoApply) 写入本地
|
|
33
33
|
* - Phase C: 完整双向 → engine.push() 上传。两处策略:
|
|
34
34
|
* ① 无冲突且推送被远端推进挡下 → skipped/partial + skipReason='conflict'(等人工);
|
|
35
|
-
* ② conflictPolicy='local'(**只有用户显式选过才生效**;缺省 ask
|
|
35
|
+
* ② conflictPolicy='local'(**只有用户显式选过才生效**;缺省 ask)且本轮有冲突**或仍有待裁决存量** → **不写本地**,
|
|
36
36
|
* 改 engine.push({force:true}) 把本机版本推成新的远端最新(被覆盖的远端旧版本仍在远端历史快照里
|
|
37
37
|
* 可回滚),状态记 partial + skipReason='conflict-kept-local'(绝不谎报 success);
|
|
38
38
|
* SYN-05:首轮 / 远端有新快照时即使选了 local 也降级 ask 并记 forced=true(见
|
|
@@ -65,6 +65,7 @@ import type { AutosyncConfig, AutosyncInterval } from './autosync-config.ts';
|
|
|
65
65
|
import { readSyncConfigFor, isGitConfig, isWebDavConfig, isS3Config, isGistConfig, SYNC_CHANNELS } from './sync-config.ts';
|
|
66
66
|
import type { SyncConfig, SyncConfigIssue, SyncTransportType } from './sync-config.ts';
|
|
67
67
|
import { readSyncHistory, appendAutosyncEntry, markAutosyncNotified } from './sync-history.ts';
|
|
68
|
+
import { loadSyncState } from './sync-state.ts';
|
|
68
69
|
import { repeatHistorySignature } from './autosync-repeat.ts';
|
|
69
70
|
import { classifyMergePlan } from './risk.ts';
|
|
70
71
|
import type { AutosyncHistoryEntry } from './sync-history.ts';
|
|
@@ -143,7 +144,10 @@ export interface AutosyncRunResult {
|
|
|
143
144
|
* - **首轮**(从未跑过)或**远端有新快照**:即使显式选了 'local' 也强制降级 ask(forcedAsk)——
|
|
144
145
|
* 这两个时刻正是「远端最新改动只在历史快照里」的事故现场,静默覆盖等于替用户丢数据;
|
|
145
146
|
* 降级记 forced,界面才能说清「这次没按你的 local 走」;
|
|
146
|
-
* - 只有「显式 local + 非高危时刻 + 真有冲突」才 force
|
|
147
|
+
* - 只有「显式 local + 非高危时刻 + 真有冲突」才 force;
|
|
148
|
+
* - 「真有冲突」= **本轮新判出的冲突** ∪ **磁盘上仍在等裁决的分区**(`held`,issue #146 F9):
|
|
149
|
+
* local 是用户的**长期决定**,不能只对本轮新冲突生效 —— 否则上一轮攒下的待裁决永远等不到结论,
|
|
150
|
+
* 每轮都「不推也不报错」地空转(用户明明选了「本机优先」)。只读条数、不读内容,判定仍是纯函数。
|
|
147
151
|
*
|
|
148
152
|
* 纯函数(无状态、无 I/O):调度层与单测共用同一份判定,避免两处各写一遍阈值。
|
|
149
153
|
*/
|
|
@@ -152,12 +156,15 @@ export function resolveConflictPushPolicy(args: {
|
|
|
152
156
|
firstRun: boolean;
|
|
153
157
|
remoteNew: boolean;
|
|
154
158
|
conflicted: number;
|
|
159
|
+
/** 磁盘上仍在等裁决的分区数(缺省 0 = 只看本轮冲突;读不到状态也按 0 处理,绝不因此 force)。 */
|
|
160
|
+
held?: number;
|
|
155
161
|
}): { policy: AutosyncConflictPolicy; force: boolean; forcedAsk: boolean } {
|
|
156
162
|
const configured = args.configuredPolicy ?? DEFAULT_AUTOSYNC_CONFLICT_POLICY;
|
|
157
163
|
// forcedAsk 只描述「用户选了 local,但本轮被降级」——缺省 ask 不算被强制(那不是用户的决定被推翻)。
|
|
158
164
|
const forcedAsk = configured === 'local' && (args.firstRun || args.remoteNew);
|
|
159
165
|
const policy: AutosyncConflictPolicy = forcedAsk ? 'ask' : configured;
|
|
160
|
-
|
|
166
|
+
const outstanding = args.conflicted + (args.held ?? 0);
|
|
167
|
+
return { policy, force: policy === 'local' && outstanding > 0, forcedAsk };
|
|
161
168
|
}
|
|
162
169
|
|
|
163
170
|
/**
|
|
@@ -250,6 +257,12 @@ export interface AutoSyncSchedulerOptions {
|
|
|
250
257
|
makeWatcher?: (opts: WatcherFactoryOptions) => SyncWatcher;
|
|
251
258
|
/** 触发合并窗口(ms):连续保存/连续远端探测只跑一轮。缺省 3000。 */
|
|
252
259
|
minTriggerGapMs?: number;
|
|
260
|
+
/**
|
|
261
|
+
* 读磁盘上仍在等裁决的分区(issue #146 F9)。缺省读 `<syncDir>/sync-state.json` 的 pendingMerge,
|
|
262
|
+
* 与 SyncEngine 的 stateDir 同源(装配处两处都是 syncDir);测试注入内存实现,免碰真实文件。
|
|
263
|
+
* 读失败 → 空数组(判定退回「只看本轮冲突」的老口径),绝不因为读不到状态就 force。
|
|
264
|
+
*/
|
|
265
|
+
readPendingMerge?: () => Promise<readonly SectionId[]>;
|
|
253
266
|
}
|
|
254
267
|
|
|
255
268
|
export class AutoSyncScheduler {
|
|
@@ -295,6 +308,7 @@ export class AutoSyncScheduler {
|
|
|
295
308
|
private readonly profile: string | undefined;
|
|
296
309
|
private readonly makeWatcher: ((opts: WatcherFactoryOptions) => SyncWatcher) | undefined;
|
|
297
310
|
private readonly minTriggerGapMs: number;
|
|
311
|
+
private readonly readPendingMerge: () => Promise<readonly SectionId[]>;
|
|
298
312
|
/** SEC-03:已 warn 过的「地址被拒」成因(键 = 通道 + 成因文本),进程内去重。 */
|
|
299
313
|
private readonly reportedConfigIssues = new Set<string>();
|
|
300
314
|
private stopped = false;
|
|
@@ -330,6 +344,13 @@ export class AutoSyncScheduler {
|
|
|
330
344
|
this.profile = opts.profile;
|
|
331
345
|
this.makeWatcher = opts.makeWatcher ?? defaultMakeWatcher;
|
|
332
346
|
this.minTriggerGapMs = opts.minTriggerGapMs ?? 3000;
|
|
347
|
+
this.readPendingMerge = opts.readPendingMerge ?? (async () => {
|
|
348
|
+
try {
|
|
349
|
+
return (await loadSyncState(this.syncDir)).pendingMerge?.sections ?? [];
|
|
350
|
+
} catch {
|
|
351
|
+
return [];
|
|
352
|
+
}
|
|
353
|
+
});
|
|
333
354
|
}
|
|
334
355
|
|
|
335
356
|
/**
|
|
@@ -807,16 +828,32 @@ export class AutoSyncScheduler {
|
|
|
807
828
|
* SYN-05:首轮 / 远端有新快照时即使显式选了 local 也强制降级 ask(forced=true 进结果与
|
|
808
829
|
* 历史),绝不在这两个高危时刻替用户覆盖远端最新。
|
|
809
830
|
*/
|
|
831
|
+
// issue #146(F9):local 是用户的长期决定 —— 存量待裁决必须能被它消解,否则上一轮攒下的
|
|
832
|
+
// 分区永远等不到结论(每轮"既不推也不报错"地空转)。只在策略是 local 时读一次磁盘,
|
|
833
|
+
// 读失败按 0 处理(退回老口径:只扣不推 + 由下面的 all-conflicted 如实上报)。
|
|
834
|
+
const heldFromState = cfg.conflictPolicy === 'local' ? await this.readPendingMerge() : [];
|
|
810
835
|
const pushDecision = resolveConflictPushPolicy({
|
|
811
836
|
...(cfg.conflictPolicy !== undefined ? { configuredPolicy: cfg.conflictPolicy } : {}),
|
|
812
837
|
firstRun,
|
|
813
838
|
remoteNew,
|
|
814
839
|
conflicted: conflictedSections.length,
|
|
840
|
+
held: heldFromState.length,
|
|
815
841
|
});
|
|
816
842
|
const forcePush = pushDecision.force;
|
|
817
843
|
const forcedMark = pushDecision.forcedAsk ? { forced: true as const } : {};
|
|
844
|
+
// issue #146:本轮**仍未裁决**的分区(分区级冲突 + 下行被扣下的叶级冲突)绝不上行。
|
|
845
|
+
// 冲突分区在 Phase B 被有意跳过(绝不写本地),但推送侧原本照样导出本机版本 ——
|
|
846
|
+
// 真机事故里 plugins 就这样被 30 → 28 → 26 一路压小。force = 用户明确「用本机覆盖远端」,不扣。
|
|
847
|
+
const heldUp = forcePush ? [] : [...new Set([...conflictedSections, ...heldLeafSections])];
|
|
848
|
+
// 先落盘待裁决:引擎推送成功时只在**已有记录**上保留 since,本轮首次判出的冲突要靠这里写下来。
|
|
849
|
+
const pendingRecorded = heldUp.length > 0;
|
|
850
|
+
if (pendingRecorded) await this.recordPendingMerge(engine, heldUp);
|
|
818
851
|
// Phase C: 完整双向 → engine.push() 上传。P0-A:外部 push 包 intent journal。
|
|
819
|
-
const rawPush = async () => engine.push(
|
|
852
|
+
const rawPush = async () => engine.push({
|
|
853
|
+
...(forcePush ? { force: true } : {}),
|
|
854
|
+
// 空数组也传:本轮没判出新冲突时,磁盘上上一轮留下的待裁决仍要扣下(issue #146)。
|
|
855
|
+
skipSections: heldUp,
|
|
856
|
+
});
|
|
820
857
|
const pushReport = (this.phase3Recovery !== undefined && this.lockCtxForJournal !== null)
|
|
821
858
|
? (await this.phase3Recovery.runExternalIntent({
|
|
822
859
|
operationType: 'autosync-push', lockCtx: this.lockCtxForJournal,
|
|
@@ -853,8 +890,9 @@ export class AutoSyncScheduler {
|
|
|
853
890
|
createdAt: nowIso, failureCountAtRun: 0,
|
|
854
891
|
...forcedMark,
|
|
855
892
|
});
|
|
856
|
-
// 冲突分区落成待裁决(P2
|
|
857
|
-
|
|
893
|
+
// 冲突分区落成待裁决(P2):首页与同步页据此给出裁决入口。推送前已写过就不再写一次
|
|
894
|
+
// (重复写会按 lastMergedRemoteSnapshotId 重算 since,抹掉首次判出冲突的时间)。
|
|
895
|
+
if (!pendingRecorded) await this.recordPendingMerge(engine, conflictedSections);
|
|
858
896
|
await this.writeFinalConfig(cfg, conflictResult, nowIso, historyId, channel);
|
|
859
897
|
return conflictResult;
|
|
860
898
|
}
|
|
@@ -878,15 +916,27 @@ export class AutoSyncScheduler {
|
|
|
878
916
|
// 也绝不因为它报成 failed:网络与凭据都是好的,只是远端有内容要用户确认)。
|
|
879
917
|
// conflictPolicy='local' 时冲突已被「本机覆盖远端」消解,但远端那一版确实被盖掉了 →
|
|
880
918
|
// 同样记 partial,skipReason 换成 conflict-kept-local(界面据此说清「本机已覆盖远端」)。
|
|
881
|
-
|
|
882
|
-
|
|
919
|
+
// force 消解的对象 = 本轮冲突 ∪ 磁盘存量(F9):只覆盖本轮会让台账把「覆盖了远端」这件事
|
|
920
|
+
// 说成一次普通成功 —— 用户从来看不出自己那句「本机优先」到底动过哪些分区。
|
|
921
|
+
const keptLocalSections = forcePush
|
|
922
|
+
? [...new Set([...conflictedSections, ...heldFromState])]
|
|
923
|
+
: [];
|
|
924
|
+
const keptLocal = keptLocalSections.length > 0;
|
|
925
|
+
const partial = keptLocal || conflictedSections.length > 0;
|
|
926
|
+
// issue #146(follow-up):引擎把「冲突未裁决 ⇒ 本轮一个分区都没上行」回成 skipped:'all-conflicted'。
|
|
927
|
+
// 以前这里只看 ok/conflict,于是整轮被记成「上传·成功」—— 用户从此看不出有分区被扣下,
|
|
928
|
+
// #146 的「显示成已推送」在自动同步路径原地复发。全扣下与部分扣下都必须落到台账。
|
|
929
|
+
const allConflicted = pushReport.skipped === 'all-conflicted';
|
|
930
|
+
const pushWarnings = pushReport.warnings ?? [];
|
|
883
931
|
const skipReason = keptLocal
|
|
884
932
|
? ('conflict-kept-local' as const)
|
|
885
933
|
: partial
|
|
886
934
|
? ('conflict' as const)
|
|
887
|
-
:
|
|
935
|
+
: allConflicted
|
|
936
|
+
? ('all-conflicted' as const)
|
|
937
|
+
: undefined;
|
|
888
938
|
const reportedConflicted = keptLocal
|
|
889
|
-
?
|
|
939
|
+
? keptLocalSections
|
|
890
940
|
: partial
|
|
891
941
|
? conflictedSections
|
|
892
942
|
: deferredSections;
|
|
@@ -901,30 +951,41 @@ export class AutoSyncScheduler {
|
|
|
901
951
|
// 纯告警(插件没装上、undo 有残留等)与冲突无关,套上 'conflict' 会让
|
|
902
952
|
// 界面上出现「跳过原因:冲突」「另有 N 个分区待确认」,而 conflictedSections 是空的。
|
|
903
953
|
const heldDegraded = heldLeafSections.length > 0;
|
|
954
|
+
// 引擎告警(分区导出失败 / 非 portable 跳过 / 扣下说明)同样要上屏:静默少推比失败更糟。
|
|
955
|
+
const allWarnings = [...downlinkWarnings, ...pushWarnings];
|
|
956
|
+
// 引擎 push 回传的告警(provider namespace 未配置、目录为空…)是常规事实噪声,只上屏不降级;
|
|
957
|
+
// 状态降级只认「有分区被扣下」与下行冲突 —— 否则每轮都变成 partial,用户就学不会 partial 的含义。
|
|
904
958
|
const degraded = downlinkWarnings.length > 0 || heldDegraded;
|
|
905
|
-
const finalPartial = partial || degraded;
|
|
959
|
+
const finalPartial = partial || degraded || allConflicted;
|
|
960
|
+
// 一个分区都没上行 = 「成功但跳过」,不是「成功」也不是「失败」(#146 验收口径②)。
|
|
961
|
+
const finalStatus = allConflicted && appliedSections.length === 0
|
|
962
|
+
? ('skipped' as const)
|
|
963
|
+
: finalPartial ? ('partial' as const) : ('success' as const);
|
|
906
964
|
const finalSkipReason = skipReason
|
|
907
965
|
?? (heldDegraded ? ('conflict' as const) : degraded ? ('warning' as const) : undefined);
|
|
908
966
|
// 扣下的叶级冲突所在分区也要出现在「待处理分区」里(与分区级冲突合并去重)
|
|
909
967
|
const finalConflicted = [...new Set([...reportedConflicted, ...heldLeafSections])];
|
|
910
968
|
const result: AutosyncRunResult = {
|
|
911
|
-
status:
|
|
969
|
+
status: finalStatus,
|
|
912
970
|
direction: appliedSections.length ? 'both' : 'push',
|
|
913
|
-
appliedSections,
|
|
971
|
+
appliedSections, historyId,
|
|
972
|
+
// issue #146:全扣下时 snapshotId 为空 —— 绝不写空 id(界面会当成「推了某份快照」)。
|
|
973
|
+
...(pushReport.snapshotId !== '' ? { pushedSnapshotId: pushReport.snapshotId } : {}),
|
|
914
974
|
...(finalSkipReason !== undefined || adoptedReason !== undefined ? { skipReason: finalSkipReason ?? adoptedReason } : {}),
|
|
915
975
|
...(finalConflicted.length > 0 ? { conflictedSections: finalConflicted } : {}),
|
|
916
|
-
...(
|
|
976
|
+
...(allWarnings.length > 0 ? { warnings: allWarnings } : {}),
|
|
917
977
|
...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
|
|
918
978
|
consecutiveFailures: 0,
|
|
919
979
|
...forcedMark,
|
|
920
980
|
};
|
|
921
981
|
await this.appendHistory(channel, {
|
|
922
982
|
direction: appliedSections.length ? 'both' : 'push',
|
|
923
|
-
status:
|
|
924
|
-
appliedSections,
|
|
983
|
+
status: finalStatus,
|
|
984
|
+
appliedSections,
|
|
985
|
+
...(pushReport.snapshotId !== '' ? { pushedSnapshotId: pushReport.snapshotId } : {}),
|
|
925
986
|
...(finalSkipReason !== undefined || adoptedReason !== undefined ? { skipReason: finalSkipReason ?? adoptedReason } : {}),
|
|
926
987
|
...(finalConflicted.length > 0 ? { conflictedSections: finalConflicted } : {}),
|
|
927
|
-
...(
|
|
988
|
+
...(allWarnings.length > 0 ? { warnings: allWarnings } : {}),
|
|
928
989
|
...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
|
|
929
990
|
createdAt: nowIso, failureCountAtRun: 0,
|
|
930
991
|
...forcedMark,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「本地有没有会进载荷的改动」的判定(§3.1 上传「看变化」;从 sync-engine 拆出,体量棘轮只许下调)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一层:判据必须与推送载荷**同集合、同字节口径** —— 比对里剔掉的易变字段必须同时从
|
|
5
|
+
* 载荷剔除,否则每轮轮询都真推一次(字节口径的唯一实现是 adapters/file-collection.ts 的
|
|
6
|
+
* comparableContent(),实测见 docs/evidence/sync-channel.md)。散在引擎里既没法单测,也没人敢改。
|
|
7
|
+
*/
|
|
8
|
+
import { sanitizeSectionData } from '../core/section-sanitize.ts';
|
|
9
|
+
import type { ConfigAdapter, HostContext, SecretScanner } from '../core/types.ts';
|
|
10
|
+
import { isFileSection } from '../schema/config.ts';
|
|
11
|
+
import type { SectionData } from '../schema/types.ts';
|
|
12
|
+
import { hashSection } from './sync-state.ts';
|
|
13
|
+
import type { SyncState } from './sync-state.ts';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 任一候选分区(= 会进载荷的那一批)的导出 hash ≠ 基线 ⇒ true。
|
|
17
|
+
* - 从未同步(state.sections 为空)→ true;
|
|
18
|
+
* - 基线缺该分区 → true(比不出来的不能当成「没变」);
|
|
19
|
+
* - 单项导出失败 → 跳过该项(与 push 单项跳过语义一致),绝不当成「有变化」去触发空推。
|
|
20
|
+
* 只读本地导出 + sync-state,不碰远端。
|
|
21
|
+
*/
|
|
22
|
+
export async function hasLocalSectionChanges(args: {
|
|
23
|
+
state: SyncState; adapters: readonly ConfigAdapter[]; ctx: HostContext; scanner: SecretScanner;
|
|
24
|
+
}): Promise<boolean> {
|
|
25
|
+
const { state, adapters, ctx, scanner } = args;
|
|
26
|
+
if (Object.keys(state.sections).length === 0) return true;
|
|
27
|
+
for (const adapter of adapters) {
|
|
28
|
+
let section;
|
|
29
|
+
try {
|
|
30
|
+
section = await adapter.export(ctx, { includeSecrets: false });
|
|
31
|
+
} catch {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const data = isFileSection(adapter.id) ? section.data : sanitizeSectionData(adapter, scanner, section.data).sanitized;
|
|
35
|
+
const recorded = state.sections[adapter.id];
|
|
36
|
+
if (recorded === undefined) return true;
|
|
37
|
+
if (recorded.hash !== hashSection(data as SectionData)) return true;
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通用按键三方合并(issue #145):一个纯函数的规则表。
|
|
3
|
+
*
|
|
4
|
+
* 这里只测「按键逐条的取/舍/冲突」与顺序 —— 具体集合(插件、patch 行……)的键与身份
|
|
5
|
+
* 由各自的调用方给,见 plugin-removals.test.ts。
|
|
6
|
+
*/
|
|
7
|
+
import { test } from 'node:test';
|
|
8
|
+
import assert from 'node:assert/strict';
|
|
9
|
+
|
|
10
|
+
import { mergeKeyedList } from './merge-keyed.ts';
|
|
11
|
+
|
|
12
|
+
interface Item { key: string; value: string }
|
|
13
|
+
|
|
14
|
+
const spec = {
|
|
15
|
+
keyOf: (item: Item) => item.key,
|
|
16
|
+
identityOf: (item: Item) => item.value,
|
|
17
|
+
pathOf: (key: string) => `items.${key}`,
|
|
18
|
+
followDelete: true,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function item(key: string, value: string): Item {
|
|
22
|
+
return { key, value };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
test('mergeKeyedList: 两侧同键同身份 → 保留本机,不算合并点', () => {
|
|
26
|
+
const res = mergeKeyedList({ local: [item('a', '1')], remote: [item('a', '1')], ancestor: [item('a', '1')], spec });
|
|
27
|
+
assert.deepEqual(res.merged, [item('a', '1')]);
|
|
28
|
+
assert.deepEqual(res.conflicts, []);
|
|
29
|
+
assert.equal(res.mergePoints, 0);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('mergeKeyedList: 单侧改动(另一侧等于祖先)→ 取改动侧', () => {
|
|
33
|
+
const fromLocal = mergeKeyedList({ local: [item('a', '2')], remote: [item('a', '1')], ancestor: [item('a', '1')], spec });
|
|
34
|
+
assert.deepEqual(fromLocal.merged, [item('a', '2')]);
|
|
35
|
+
assert.equal(fromLocal.mergePoints, 1);
|
|
36
|
+
const fromRemote = mergeKeyedList({ local: [item('a', '1')], remote: [item('a', '3')], ancestor: [item('a', '1')], spec });
|
|
37
|
+
assert.deepEqual(fromRemote.merged, [item('a', '3')]);
|
|
38
|
+
assert.equal(fromRemote.mergePoints, 1);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('mergeKeyedList: 两侧都改 → both-modified(不猜用哪一侧)', () => {
|
|
42
|
+
const res = mergeKeyedList({ local: [item('a', '2')], remote: [item('a', '3')], ancestor: [item('a', '1')], spec });
|
|
43
|
+
assert.equal(res.conflicts.length, 1);
|
|
44
|
+
assert.equal(res.conflicts[0]!.reason, 'both-modified');
|
|
45
|
+
assert.equal(res.conflicts[0]!.path, 'items.a');
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('mergeKeyedList: 无祖先时本机独有保留、远端独有采纳;两侧同键不同身份 → both-modified', () => {
|
|
49
|
+
const res = mergeKeyedList({ local: [item('mine', '1'), item('both', 'x')], remote: [item('theirs', '1'), item('both', 'y')], ancestor: undefined, spec });
|
|
50
|
+
assert.deepEqual(res.merged.map((i) => i.key), ['mine', 'theirs']);
|
|
51
|
+
assert.deepEqual(res.conflicts.map((c) => c.reason), ['both-modified']);
|
|
52
|
+
assert.equal(res.conflicts[0]!.path, 'items.both');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('mergeKeyedList: followDelete=true → 本机未改且远端删了,跟随删除', () => {
|
|
56
|
+
const res = mergeKeyedList({ local: [item('a', '1')], remote: [], ancestor: [item('a', '1')], spec });
|
|
57
|
+
assert.deepEqual(res.merged, []);
|
|
58
|
+
assert.equal(res.mergePoints, 1);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('mergeKeyedList: followDelete=false → 远端删了也保留本机,且不计合并点', () => {
|
|
62
|
+
const res = mergeKeyedList({ local: [item('a', '1')], remote: [], ancestor: [item('a', '1')], spec: { ...spec, followDelete: false } });
|
|
63
|
+
assert.deepEqual(res.merged, [item('a', '1')]);
|
|
64
|
+
assert.equal(res.mergePoints, 0);
|
|
65
|
+
assert.deepEqual(res.conflicts, []);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('mergeKeyedList: 本机改过而远端删了 → modify-delete;本机删了而远端改过 → delete-modify', () => {
|
|
69
|
+
const modified = mergeKeyedList({ local: [item('a', '2')], remote: [], ancestor: [item('a', '1')], spec });
|
|
70
|
+
assert.deepEqual(modified.conflicts.map((c) => c.reason), ['modify-delete']);
|
|
71
|
+
const deleted = mergeKeyedList({ local: [], remote: [item('a', '2')], ancestor: [item('a', '1')], spec });
|
|
72
|
+
assert.deepEqual(deleted.conflicts.map((c) => c.reason), ['delete-modify']);
|
|
73
|
+
assert.deepEqual(deleted.merged, []);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('mergeKeyedList: 本机删过、远端未改 → 跟随本机删除(不复活)', () => {
|
|
77
|
+
const res = mergeKeyedList({ local: [], remote: [item('a', '1')], ancestor: [item('a', '1')], spec });
|
|
78
|
+
assert.deepEqual(res.merged, []);
|
|
79
|
+
assert.deepEqual(res.conflicts, []);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('mergeKeyedList: 两侧都没有 → 消失(祖先里的条目不会凭空回来)', () => {
|
|
83
|
+
const res = mergeKeyedList({ local: [], remote: [], ancestor: [item('a', '1')], spec });
|
|
84
|
+
assert.deepEqual(res.merged, []);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('mergeKeyedList: 顺序 = 本机顺序,远端独有的键按远端顺序追加', () => {
|
|
88
|
+
const res = mergeKeyedList({
|
|
89
|
+
local: [item('b', '1'), item('a', '1')],
|
|
90
|
+
remote: [item('c', '1'), item('a', '1'), item('d', '1')],
|
|
91
|
+
ancestor: undefined,
|
|
92
|
+
spec,
|
|
93
|
+
});
|
|
94
|
+
assert.deepEqual(res.merged.map((i) => i.key), ['b', 'a', 'c', 'd']);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('mergeKeyedList: keepLocal 命中的条目以本机为准 —— 既不被远端删掉,也不报冲突', () => {
|
|
98
|
+
const keep = { ...spec, keepLocal: (i: Item) => i.key === 'self' };
|
|
99
|
+
const deleted = mergeKeyedList({ local: [item('self', '1')], remote: [], ancestor: [item('self', '1')], spec: keep });
|
|
100
|
+
assert.deepEqual(deleted.merged, [item('self', '1')]);
|
|
101
|
+
assert.deepEqual(deleted.conflicts, []);
|
|
102
|
+
const changed = mergeKeyedList({ local: [item('self', '2')], remote: [item('self', '3')], ancestor: [item('self', '1')], spec: keep });
|
|
103
|
+
assert.deepEqual(changed.merged, [item('self', '2')]);
|
|
104
|
+
assert.deepEqual(changed.conflicts, []);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test('mergeKeyedList: 空键的条目让整轮退回通用路径(malformed,不按位置对齐)', () => {
|
|
108
|
+
const res = mergeKeyedList({ local: [item('', '1')], remote: [item('', '2')], ancestor: undefined, spec });
|
|
109
|
+
assert.deepEqual(res.merged, []);
|
|
110
|
+
assert.deepEqual(res.conflicts, []);
|
|
111
|
+
assert.equal(res.malformed, true, '没有身份键 = 形状不支持按键合并');
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test('mergeKeyedList: 同键重复 → malformed(绝不「留一条丢一条」,复审 P1-2)', () => {
|
|
115
|
+
const res = mergeKeyedList({ local: [item('a', '1'), item('a', '2')], remote: [item('a', '1')], ancestor: undefined, spec });
|
|
116
|
+
assert.equal(res.malformed, true);
|
|
117
|
+
assert.deepEqual(res.merged, []);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test('mergeKeyedList: 非对象条目 → malformed(畸形数据交回通用路径)', () => {
|
|
121
|
+
const res = mergeKeyedList<Item>({ local: [null as unknown as Item], remote: [], ancestor: undefined, spec });
|
|
122
|
+
assert.equal(res.malformed, true);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('mergeKeyedList: 采纳远端时 compose 合成(本机态字段留在本机,复审 P0-2)', () => {
|
|
126
|
+
const composed = { ...spec, compose: (l: Item, r: Item) => ({ key: r.key, value: r.value + '/keep:' + l.value }) };
|
|
127
|
+
const res = mergeKeyedList({ local: [item('a', '1')], remote: [item('a', '2')], ancestor: [item('a', '1')], spec: composed });
|
|
128
|
+
assert.deepEqual(res.merged, [item('a', '2/keep:1')]);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('mergeKeyedList: keepLocal 只在本机独有时不计合并点(复审 P2-3)', () => {
|
|
132
|
+
const keep = { ...spec, keepLocal: (i: Item) => i.key === 'self' };
|
|
133
|
+
const res = mergeKeyedList({ local: [item('self', '1')], remote: [], ancestor: undefined, spec: keep });
|
|
134
|
+
assert.equal(res.mergePoints, 0);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('mergeKeyedList: 身份上下文每键只算一次,并交给该键各条目的 identityOf 复用(性能,2026-11-15)', () => {
|
|
138
|
+
const seen: unknown[] = [];
|
|
139
|
+
let contextCalls = 0;
|
|
140
|
+
let identityCalls = 0;
|
|
141
|
+
const cached = {
|
|
142
|
+
keyOf: (i: Item) => i.key,
|
|
143
|
+
identityContextOf: (peers: readonly Item[]) => {
|
|
144
|
+
contextCalls += 1;
|
|
145
|
+
return peers.map((p) => p.value).join(',');
|
|
146
|
+
},
|
|
147
|
+
identityOf: (i: Item, _peers: readonly Item[], ctx?: unknown) => {
|
|
148
|
+
identityCalls += 1;
|
|
149
|
+
seen.push(ctx);
|
|
150
|
+
return i.value;
|
|
151
|
+
},
|
|
152
|
+
pathOf: (key: string) => `items.${key}`,
|
|
153
|
+
followDelete: true,
|
|
154
|
+
};
|
|
155
|
+
const res = mergeKeyedList({
|
|
156
|
+
local: [item('a', '1'), item('b', '2')],
|
|
157
|
+
remote: [item('a', '9'), item('b', '2')],
|
|
158
|
+
ancestor: [item('a', '0'), item('b', '2')],
|
|
159
|
+
spec: cached,
|
|
160
|
+
});
|
|
161
|
+
assert.equal(contextCalls, 2, '两个键 → 只算两次上下文');
|
|
162
|
+
assert.equal(new Set(seen).size, 2, '同一键上的各条目拿到同一个上下文实例');
|
|
163
|
+
assert.ok(identityCalls <= 6, '每条目最多问一次身份,实际 ' + identityCalls);
|
|
164
|
+
assert.equal(res.conflicts.length, 1, '缓存不改变结论:a 两侧都改 → 冲突');
|
|
165
|
+
assert.equal(res.conflicts[0]!.path, 'items.a');
|
|
166
|
+
});
|
|
167
|
+
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通用「按键三方合并」(issue #145)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一个模块:plugins 分区里除插件清单外还有几组**有序条目集**(patch 行、本地 tarball、
|
|
5
|
+
* patch 文件),它们共同的语义是「同一键 = 同一条目」。通用 JSON 合并不认这个语义 —— 数组
|
|
6
|
+
* 两侧各改一次就判整分区冲突,于是 patch 行永远合不进去(issue #145 的两道门之一)。规则三处
|
|
7
|
+
* 完全相同,故只写一份。
|
|
8
|
+
*
|
|
9
|
+
* 规则(与 git 同口径;祖先只用来判断「谁动过它」,绝不猜):
|
|
10
|
+
* - 两侧同键且内容身份相同 → 保留本机;
|
|
11
|
+
* - 某一侧与祖先相同 → 取另一侧(mergePoints + 1);
|
|
12
|
+
* - 两侧都改(或没有祖先且两者不同)→ both-modified;
|
|
13
|
+
* - 只有本机:无祖先 = 本机独有 → 保留;有祖先且未改 → followDelete ? 跟随删除 : 保留并记进
|
|
14
|
+
* keptAgainstDelete(开关关着 = 一个都不删,见 issue #145 的裁决);有祖先且已改 → modify-delete;
|
|
15
|
+
* - 只有远端:无祖先 = 远端独有 → 采纳;有祖先且未改 → 本机删过它,跟随删除;有祖先且已改 →
|
|
16
|
+
* delete-modify;
|
|
17
|
+
* - 顺序 = 本机顺序,远端独有的键按远端相对顺序追加;
|
|
18
|
+
* - keepLocal 命中的条目永远以本机为准(既删不掉,也不报冲突)。
|
|
19
|
+
*
|
|
20
|
+
* 冲突只回报、不进 merged:调用方拿到非空 conflicts 时按整分区冲突处置(与既有钩子同口径,
|
|
21
|
+
* 绝不「合一半就落地」)。纯函数、零 I/O。
|
|
22
|
+
*/
|
|
23
|
+
import type { MergeConflict } from './merge.ts';
|
|
24
|
+
|
|
25
|
+
/** 单条目的冲突理由:只可能是这三种(跨侧改同一个键 / 一侧删一侧改)。 */
|
|
26
|
+
export type KeyedConflictReason = 'both-modified' | 'modify-delete' | 'delete-modify';
|
|
27
|
+
|
|
28
|
+
export interface KeyedMergeSpec<T> {
|
|
29
|
+
/** 身份键(同键 = 同一条目);返回空串 = 该条目没有身份,跳过不参与合并。 */
|
|
30
|
+
keyOf(item: T): string;
|
|
31
|
+
/**
|
|
32
|
+
* 内容身份(相等 = 这一侧没改过它)。peers 是同一键上出现过的三侧原值,供「按需归一化」用
|
|
33
|
+
* —— patch 行要按三侧 redactedPaths 并集把被剥空的叶子归零后再比(issue #145 门②)。
|
|
34
|
+
*/
|
|
35
|
+
identityOf(item: T, peers: readonly T[], context?: unknown): string;
|
|
36
|
+
/**
|
|
37
|
+
* 一次算好同一键上三侧共用的身份上下文(如 patch 行的 redactedPaths 并集),
|
|
38
|
+
* 由 identityOf 第三参取用 —— 每个键只算一次,不再每条目重算(性能,2026-11-15)。
|
|
39
|
+
*/
|
|
40
|
+
identityContextOf?(peers: readonly T[]): unknown;
|
|
41
|
+
/** 冲突路径(给人看的定位,如 `plugins.alpha`)。 */
|
|
42
|
+
pathOf(key: string): string;
|
|
43
|
+
/** 本机未改、远端删了:true = 跟随删除;false = 保留本机(不报冲突、不计合并点)。 */
|
|
44
|
+
followDelete: boolean;
|
|
45
|
+
/** 永远以本机为准的条目(本插件自己这类「删了会坏事」的东西):不删、不报冲突。 */
|
|
46
|
+
keepLocal?(item: T): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* 采纳远端那一侧时怎么合成(缺省 = 直接取远端对象)。
|
|
49
|
+
* 只有「本机没改、远端改了」这一条分支会调它;用途是把**本机态字段**(如插件启停)留在本机,
|
|
50
|
+
* 其余字段听远端 —— 否则远端升一次版本就会把本机停用改回启用(issue #145 复审 P0-2)。
|
|
51
|
+
*/
|
|
52
|
+
compose?(l: T, r: T): T;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface KeyedMergeResult<T> {
|
|
56
|
+
merged: T[];
|
|
57
|
+
conflicts: MergeConflict[];
|
|
58
|
+
/** 自动并入的变更点(「两侧各自的改动都保住了」处数) */
|
|
59
|
+
mergePoints: number;
|
|
60
|
+
/**
|
|
61
|
+
* 输入形状不支持按键合并(同键重复 / 没有身份键 / 非对象条目):此时 merged 恒空,
|
|
62
|
+
* 调用方**必须**退回通用路径 —— 绝不在这里「留一条丢一条」(复审 P1-2)。
|
|
63
|
+
*/
|
|
64
|
+
malformed: boolean;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface KeyedIndex<T> {
|
|
68
|
+
index: Map<string, T>;
|
|
69
|
+
/** 同键重复 / 空键 / 非对象条目:任一出现就不许按键合并 */
|
|
70
|
+
malformed: boolean;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function indexByKey<T>(list: readonly T[] | undefined, keyOf: (item: T) => string): KeyedIndex<T> {
|
|
74
|
+
const index = new Map<string, T>();
|
|
75
|
+
let malformed = false;
|
|
76
|
+
for (const item of list ?? []) {
|
|
77
|
+
if (item === null || typeof item !== 'object') { malformed = true; continue; }
|
|
78
|
+
const key = keyOf(item);
|
|
79
|
+
if (key === '') { malformed = true; continue; }
|
|
80
|
+
if (index.has(key)) { malformed = true; continue; }
|
|
81
|
+
index.set(key, item);
|
|
82
|
+
}
|
|
83
|
+
return { index, malformed };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function mergeKeyedList<T>(args: {
|
|
87
|
+
local: readonly T[];
|
|
88
|
+
remote: readonly T[];
|
|
89
|
+
ancestor: readonly T[] | undefined;
|
|
90
|
+
spec: KeyedMergeSpec<T>;
|
|
91
|
+
}): KeyedMergeResult<T> {
|
|
92
|
+
const { spec } = args;
|
|
93
|
+
const localIdx = indexByKey(args.local, spec.keyOf);
|
|
94
|
+
const remoteIdx = indexByKey(args.remote, spec.keyOf);
|
|
95
|
+
const ancestorIdx = indexByKey(args.ancestor, spec.keyOf);
|
|
96
|
+
if (localIdx.malformed || remoteIdx.malformed || ancestorIdx.malformed) {
|
|
97
|
+
return { merged: [], conflicts: [], mergePoints: 0, malformed: true };
|
|
98
|
+
}
|
|
99
|
+
const { index: localIndex } = localIdx;
|
|
100
|
+
const { index: remoteIndex } = remoteIdx;
|
|
101
|
+
const { index: ancestorIndex } = ancestorIdx;
|
|
102
|
+
|
|
103
|
+
const order: string[] = [...localIndex.keys()];
|
|
104
|
+
for (const key of remoteIndex.keys()) if (!localIndex.has(key)) order.push(key);
|
|
105
|
+
|
|
106
|
+
const merged: T[] = [];
|
|
107
|
+
const conflicts: MergeConflict[] = [];
|
|
108
|
+
let mergePoints = 0;
|
|
109
|
+
|
|
110
|
+
for (const key of order) {
|
|
111
|
+
const l = localIndex.get(key);
|
|
112
|
+
const r = remoteIndex.get(key);
|
|
113
|
+
const a = ancestorIndex.get(key);
|
|
114
|
+
const peers = [l, r, a].filter((item): item is T => item !== undefined);
|
|
115
|
+
// 同一键的并集/路径解析只做一次;同一条目在一轮合并里被问到多次也只算一次。
|
|
116
|
+
const context = spec.identityContextOf?.(peers);
|
|
117
|
+
const identities = new Map<T, string>();
|
|
118
|
+
const identity = (item: T | undefined): string => {
|
|
119
|
+
if (item === undefined) return '';
|
|
120
|
+
const cached = identities.get(item);
|
|
121
|
+
if (cached !== undefined || identities.has(item)) return cached ?? '';
|
|
122
|
+
const value = spec.identityOf(item, peers, context);
|
|
123
|
+
identities.set(item, value);
|
|
124
|
+
return value;
|
|
125
|
+
};
|
|
126
|
+
const conflict = (reason: KeyedConflictReason): void => {
|
|
127
|
+
conflicts.push({ path: spec.pathOf(key), kind: 'key', reason, autoMergeAttempted: false, local: l ?? null, remote: r ?? null, ancestor: a ?? null });
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
if (l !== undefined && spec.keepLocal?.(l) === true) {
|
|
131
|
+
merged.push(l);
|
|
132
|
+
// 只有真的采纳了远端内容才算一个合并点(远端根本没这条时不算,复审 P2-3)
|
|
133
|
+
if (r !== undefined && identity(l) !== identity(r)) mergePoints += 1;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (l !== undefined && r !== undefined) {
|
|
137
|
+
const [li, ri] = [identity(l), identity(r)];
|
|
138
|
+
if (li === ri) { merged.push(l); continue; }
|
|
139
|
+
if (a === undefined) { conflict('both-modified'); continue; }
|
|
140
|
+
const ai = identity(a);
|
|
141
|
+
if (li === ai) { merged.push(spec.compose?.(l, r) ?? r); mergePoints += 1; continue; }
|
|
142
|
+
if (ri === ai) { merged.push(l); mergePoints += 1; continue; }
|
|
143
|
+
conflict('both-modified');
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (l !== undefined) {
|
|
147
|
+
if (a === undefined) { merged.push(l); mergePoints += 1; continue; } // 本机独有
|
|
148
|
+
if (identity(l) !== identity(a)) { conflict('modify-delete'); continue; } // 本机改过 → 交人工
|
|
149
|
+
if (spec.followDelete) { mergePoints += 1; continue; } // 跟随远端删除
|
|
150
|
+
merged.push(l);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (r !== undefined) {
|
|
154
|
+
if (a === undefined) { merged.push(r); mergePoints += 1; continue; } // 远端独有
|
|
155
|
+
if (identity(r) !== identity(a)) { conflict('delete-modify'); continue; } // 本机删了、远端改过 → 交人工
|
|
156
|
+
mergePoints += 1; // 远端未改,本机删过它 → 跟随本机删除
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { merged, conflicts, mergePoints, malformed: false };
|
|
160
|
+
}
|
package/src/sync/messages.ts
CHANGED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* patch 行的内容身份与它的缓存(issue #145 门② / 性能 2026-11-15)。
|
|
3
|
+
*
|
|
4
|
+
* 缓存只影响「算几次」,不许影响「算出什么」:这里逐条钉住带上下文 / 不带上下文、
|
|
5
|
+
* 冷缓存 / 热缓存的结果完全一致,并钉住入参 raw 不被改写。
|
|
6
|
+
*/
|
|
7
|
+
import { test } from 'node:test';
|
|
8
|
+
import assert from 'node:assert/strict';
|
|
9
|
+
|
|
10
|
+
import { patchIdentityContext, patchLineIdentity, redactedUnion } from './patch-line-identity.ts';
|
|
11
|
+
import type { PatchLine } from '../schema/types.ts';
|
|
12
|
+
|
|
13
|
+
function line(over: Partial<PatchLine> = {}): PatchLine {
|
|
14
|
+
return {
|
|
15
|
+
file: 'cfg.yml',
|
|
16
|
+
lineId: 'l1',
|
|
17
|
+
raw: { config: { apiKey: '', model: 'x', list: [{ token: '' }] } },
|
|
18
|
+
...over,
|
|
19
|
+
} as PatchLine;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
test('patchLineIdentity: 带上下文与逐次重算结果一致(本机剥空 vs 远端明文算同一行)', () => {
|
|
23
|
+
const local = line({ redactedPaths: ['raw.config.apiKey', 'raw.config.list[0].token'] });
|
|
24
|
+
const remote = line({ raw: { config: { apiKey: 'sk-live', model: 'x', list: [{ token: 'sk-2' }] } } });
|
|
25
|
+
const peers = [local, remote];
|
|
26
|
+
const context = patchIdentityContext(peers);
|
|
27
|
+
assert.equal(patchLineIdentity(local, peers, context), patchLineIdentity(local, peers));
|
|
28
|
+
assert.equal(patchLineIdentity(remote, peers, context), patchLineIdentity(remote, peers));
|
|
29
|
+
assert.equal(patchLineIdentity(local, peers, context), patchLineIdentity(remote, peers, context));
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('patchLineIdentity: 两侧都写了自己的值(都不在剥空声明里)仍然不同 —— 缓存不抹掉真改动', () => {
|
|
33
|
+
const local = line({ redactedPaths: ['raw.config.apiKey'], raw: { config: { apiKey: '', model: 'x' } } });
|
|
34
|
+
const remote = line({ raw: { config: { apiKey: 'sk-live', model: 'y' } } });
|
|
35
|
+
const peers = [local, remote];
|
|
36
|
+
const context = patchIdentityContext(peers);
|
|
37
|
+
assert.notEqual(patchLineIdentity(local, peers, context), patchLineIdentity(remote, peers, context));
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('patchLineIdentity: 上下文可跨多条行复用,结果与每行各自重算一致(500 行三侧逐行对齐)', () => {
|
|
41
|
+
for (let i = 0; i < 500; i += 1) {
|
|
42
|
+
const local = line({ file: 'f' + (i % 20) + '.yml', lineId: 'l' + i, redactedPaths: ['raw.config.apiKey'] });
|
|
43
|
+
const remote = line({ file: 'f' + (i % 20) + '.yml', lineId: 'l' + i, raw: { config: { apiKey: 'sk-' + i, model: 'x' } } });
|
|
44
|
+
const peers = [local, remote];
|
|
45
|
+
const context = patchIdentityContext(peers);
|
|
46
|
+
assert.equal(patchLineIdentity(local, peers, context), patchLineIdentity(local, peers));
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('patchLineIdentity: 解析缓存不改变对非法路径的处理(不认识就放过,不猜形状)', () => {
|
|
51
|
+
const clean = line({ raw: { config: { apiKey: 'sk-live' } } });
|
|
52
|
+
const weird = line({ raw: { config: { apiKey: 'sk-live' } }, redactedPaths: ['raw..config', 'not a path['] });
|
|
53
|
+
const peers = [weird];
|
|
54
|
+
const context = patchIdentityContext(peers);
|
|
55
|
+
assert.deepEqual(context.segments, [], '两条路径都解析不了 → 空上下文');
|
|
56
|
+
assert.equal(patchLineIdentity(weird, peers, context), patchLineIdentity(clean, [clean]));
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('patchLineIdentity: 不改写入参 raw(归一化只在副本上做)', () => {
|
|
60
|
+
const raw = { config: { apiKey: '' } };
|
|
61
|
+
const local = line({ raw, redactedPaths: ['raw.config.apiKey'] });
|
|
62
|
+
patchLineIdentity(local, [local], patchIdentityContext([local]));
|
|
63
|
+
assert.deepEqual(raw, { config: { apiKey: '' } });
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test('patchLineIdentity: 键序不稳定不算改动(上下文与缓存都不影响)', () => {
|
|
67
|
+
const a = line({ raw: { config: { apiKey: 'sk-live', model: 'x' } } });
|
|
68
|
+
const b = line({ raw: { config: { model: 'x', apiKey: 'sk-live' } } });
|
|
69
|
+
const peers = [a, b];
|
|
70
|
+
const context = patchIdentityContext(peers);
|
|
71
|
+
assert.equal(patchLineIdentity(a, peers, context), patchLineIdentity(b, peers, context));
|
|
72
|
+
assert.deepEqual(redactedUnion(peers), []);
|
|
73
|
+
});
|