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
package/lib/index.js
CHANGED
|
@@ -80,7 +80,9 @@ import { ImportUserSkippedError } from './core/types.js';
|
|
|
80
80
|
import { PLUGIN_NPM_PACKAGE } from './core/update-check.js';
|
|
81
81
|
import { planSelfUpdate, runSelfUpdate } from './core/self-update.js';
|
|
82
82
|
import { createAdapters } from './adapters/index.js';
|
|
83
|
-
import { describePatchDocument, describePatchLayoutDrift, planPatchDocument,
|
|
83
|
+
import { describePatchDocument, describePatchLayoutDrift, planPatchDocument, unprovidedTopLevelIds } from './core/patch-document.js';
|
|
84
|
+
import { alignOverrideNames, patchChainIndex } from './core/patch-chain.js';
|
|
85
|
+
import { PatchChainCache, downgradeProvidedInserts, readExistingPatchDocument, readPatchChainFromProfile, } from './utils/patch-chain-read.js';
|
|
84
86
|
import { isPatchLayerRel, profilePatchRel, readEffectivePatchLines, USER_PATCH_FILE } from './core/patch-layers.js';
|
|
85
87
|
import { createLocalPluginPackHook } from './core/local-plugin-host.js';
|
|
86
88
|
import { ENCRYPTED_CONTAINER_CODE, createEncryptionProvider, readContainerKind, encryptArchive } from './security/index.js';
|
|
@@ -149,7 +151,7 @@ export const name = 'config-manager';
|
|
|
149
151
|
/** Services required before the engine can mount (present in every profile). */
|
|
150
152
|
export const inject = ['settings', 'credentials'];
|
|
151
153
|
/** Plugin version, kept in sync with package.json ("version"). */
|
|
152
|
-
export const PLUGIN_VERSION = '0.
|
|
154
|
+
export const PLUGIN_VERSION = '0.10.0';
|
|
153
155
|
/** Plugin own package name — excluded from its own exported plugins list. */
|
|
154
156
|
const PLUGIN_NAME = 'dsh-config-manager';
|
|
155
157
|
/**
|
|
@@ -1389,6 +1391,8 @@ export class DshSessionStoreFacade {
|
|
|
1389
1391
|
}
|
|
1390
1392
|
}
|
|
1391
1393
|
}
|
|
1394
|
+
/** 生效链缓存时长(#144):一次导入逐行写 patch,逐行重读 30+ 个 bundle 纯属浪费;写盘即 invalidate。 */
|
|
1395
|
+
const PATCH_CHAIN_CACHE_MS = 2000;
|
|
1392
1396
|
/**
|
|
1393
1397
|
* Patch-file facade:patch 的**两层**都在 home 根内 ——
|
|
1394
1398
|
* - 用户(home)层:`$DSH_HOME/cordis.patch.yml`
|
|
@@ -1488,65 +1492,56 @@ export class DshPatchFileFacade {
|
|
|
1488
1492
|
}
|
|
1489
1493
|
async applyPatchChanges(file, changes) {
|
|
1490
1494
|
const p = this.patchPath(file);
|
|
1491
|
-
//
|
|
1492
|
-
//
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
//
|
|
1496
|
-
|
|
1497
|
-
// - 存在但解析不了(含未知方言 / YAML 本身有错)→ 抛错,不改写。
|
|
1498
|
-
let existing = null;
|
|
1495
|
+
// 0. 生效链兜底(#144):id 已被别层(bundle 最典型)提供时再写 insert = 两条「新增」抢同一 id
|
|
1496
|
+
// ⇒ 插件保存配置必报 overridden。统一降级成顶层覆盖行(含 mcp/prompts/激活行)。
|
|
1497
|
+
const chain = await this.readPatchChainQuietly();
|
|
1498
|
+
const { effective, downgraded } = downgradeProvidedInserts(chain, file, changes);
|
|
1499
|
+
// 1. 读既有文档:只有真不存在才算空文档;读不到 / 解析不了一律抛错(#75:当空文档 = 删行)。
|
|
1500
|
+
let doc;
|
|
1499
1501
|
try {
|
|
1500
|
-
|
|
1502
|
+
doc = await readExistingPatchDocument(p);
|
|
1501
1503
|
}
|
|
1502
1504
|
catch (err) {
|
|
1503
|
-
|
|
1504
|
-
throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err });
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
let doc;
|
|
1508
|
-
if (existing !== null && existing.trim() !== '') {
|
|
1509
|
-
try {
|
|
1510
|
-
doc = loadPatchDocument(existing);
|
|
1511
|
-
}
|
|
1512
|
-
catch (err) {
|
|
1513
|
-
throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err });
|
|
1514
|
-
}
|
|
1505
|
+
throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err });
|
|
1515
1506
|
}
|
|
1516
|
-
// 2.
|
|
1517
|
-
|
|
1518
|
-
//
|
|
1519
|
-
|
|
1520
|
-
// turned one update into "every insert-only entry (MCP servers, most notably) is
|
|
1521
|
-
// gone after restart".
|
|
1522
|
-
const plan = planPatchDocument(doc, changes);
|
|
1507
|
+
// 2. 经 core/patch-document.ts 重建(#133):顶层行只覆盖、查不到 id 就整行丢弃,只有 insert 成员才新增。
|
|
1508
|
+
const plan = planPatchDocument(doc, effective);
|
|
1509
|
+
// 2b. 顶层行的 name 必须与既有条目逐字一致(#144):不一致宿主 `patch: name mismatch … skipping` 整行丢弃。
|
|
1510
|
+
const items = chain === null ? plan.items : alignOverrideNames(plan.items, patchChainIndex(chain));
|
|
1523
1511
|
const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
|
|
1524
|
-
+ dumpPatchDocument(
|
|
1525
|
-
// 3.
|
|
1526
|
-
// text we just serialized and require both id sets to match the plan item by item.
|
|
1527
|
-
// A serializer or dialect change that flattens or swallows insert blocks stops here
|
|
1528
|
-
// (zero write) instead of silently degrading every patch row to an override.
|
|
1512
|
+
+ dumpPatchDocument(items);
|
|
1513
|
+
// 3. 写盘前结构自检:重新解析刚序列化的文本,两组 id 必须与计划逐项一致(序列化退化即零写入)。
|
|
1529
1514
|
const drift = describePatchLayoutDrift(plan, describePatchDocument(loadPatchDocument(text)));
|
|
1530
1515
|
if (drift !== null) {
|
|
1531
1516
|
throw new Error(this.msg('host.patchSemanticDrift', { file, detail: drift }));
|
|
1532
1517
|
}
|
|
1533
|
-
// 4.
|
|
1534
|
-
//
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1518
|
+
// 4. 覆盖行孤儿守卫(#133 起、#144 改判到整条链):只拒绝「任何一层都没提供这个 id」的顶层行;
|
|
1519
|
+
// 且只在**整链可信**(零失败层)时拒绝 —— 缺口层可能恰好提供该 id,拒绝 = 用户永久卡死。
|
|
1520
|
+
const chainTrusted = chain !== null && chain.failures.length === 0;
|
|
1521
|
+
if (chainTrusted) {
|
|
1522
|
+
const orphans = unprovidedTopLevelIds([...chain.sources.map((source) => source.doc), doc], plan.topLevelIds);
|
|
1523
|
+
if (orphans.length > 0) {
|
|
1524
|
+
throw new Error(this.msg('host.patchRefuseUnknownId', { file, ids: orphans.join(', ') }));
|
|
1525
|
+
}
|
|
1540
1526
|
}
|
|
1541
1527
|
await atomicWriteFile(p, text);
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1528
|
+
// 盘面变了:销毁链缓存,否则同一批次里「刚写下的行」对后续判定不可见
|
|
1529
|
+
this.chainCache.invalidate();
|
|
1530
|
+
return { downgraded };
|
|
1531
|
+
}
|
|
1532
|
+
/** 生效链缓存(见 `utils/patch-chain-read.ts`):一次导入逐行写 patch,不必逐行重读 30+ 个 bundle。 */
|
|
1533
|
+
chainCache = new PatchChainCache(PATCH_CHAIN_CACHE_MS);
|
|
1534
|
+
/** 读整条生效 patch 链(issue #144):bundle 层 → profile 层 → home 层,宿主合并序。 */
|
|
1535
|
+
async readPatchChain() {
|
|
1536
|
+
return this.chainCache.get(() => readPatchChainFromProfile(this.homeDir, this.profile));
|
|
1537
|
+
}
|
|
1538
|
+
/** 读链失败(profile 清单整体不可读等)→ `null`:判定退化为两层,绝不阻断写入。 */
|
|
1539
|
+
async readPatchChainQuietly() {
|
|
1545
1540
|
try {
|
|
1546
|
-
return
|
|
1541
|
+
return await this.readPatchChain();
|
|
1547
1542
|
}
|
|
1548
1543
|
catch {
|
|
1549
|
-
return
|
|
1544
|
+
return null;
|
|
1550
1545
|
}
|
|
1551
1546
|
}
|
|
1552
1547
|
}
|
package/lib/routes/sync.js
CHANGED
|
@@ -444,6 +444,9 @@ export function syncRoutes(env) {
|
|
|
444
444
|
...(sections === undefined ? {} : { sections }),
|
|
445
445
|
...sessionsOpt,
|
|
446
446
|
...(encrypt || includeSecrets ? { encrypt: true, includeSecrets } : {}),
|
|
447
|
+
// 空数组 = 连磁盘上的历史待裁决一起扣下(issue #146:预览与实推必须同口径,
|
|
448
|
+
// 否则「没得推」的预览会漏掉「其实还挂着冲突」这一事实)。
|
|
449
|
+
skipSections: [],
|
|
447
450
|
}), ROUTE_TIMEOUT_MS, msg('host.syncPushTimeout'))
|
|
448
451
|
: await withTimeout(engine.push({
|
|
449
452
|
...(snapshotId === undefined ? {} : { snapshotId }),
|
|
@@ -451,6 +454,9 @@ export function syncRoutes(env) {
|
|
|
451
454
|
...sessionsOpt,
|
|
452
455
|
...(encrypt || includeSecrets ? { encrypt: true, includeSecrets, password: effectiveEncryptPassword ?? '' } : {}),
|
|
453
456
|
...(force ? { force: true } : {}),
|
|
457
|
+
// 手动推送同样扣下仍在等裁决的分区(issue #146):本机没合完就整分区上行,
|
|
458
|
+
// 正是「远端 30 个插件被压回 26 个」的成因。force 时引擎自己短路,不受影响。
|
|
459
|
+
skipSections: [],
|
|
454
460
|
}), ROUTE_TIMEOUT_MS, msg('host.syncPushTimeout'));
|
|
455
461
|
await writeSyncConfig(syncDir, syncCfg, cloudSecrets);
|
|
456
462
|
writeJson(res, 200, report);
|
|
@@ -60,7 +60,10 @@ export interface AutosyncRunResult {
|
|
|
60
60
|
* - **首轮**(从未跑过)或**远端有新快照**:即使显式选了 'local' 也强制降级 ask(forcedAsk)——
|
|
61
61
|
* 这两个时刻正是「远端最新改动只在历史快照里」的事故现场,静默覆盖等于替用户丢数据;
|
|
62
62
|
* 降级记 forced,界面才能说清「这次没按你的 local 走」;
|
|
63
|
-
* - 只有「显式 local + 非高危时刻 + 真有冲突」才 force
|
|
63
|
+
* - 只有「显式 local + 非高危时刻 + 真有冲突」才 force;
|
|
64
|
+
* - 「真有冲突」= **本轮新判出的冲突** ∪ **磁盘上仍在等裁决的分区**(`held`,issue #146 F9):
|
|
65
|
+
* local 是用户的**长期决定**,不能只对本轮新冲突生效 —— 否则上一轮攒下的待裁决永远等不到结论,
|
|
66
|
+
* 每轮都「不推也不报错」地空转(用户明明选了「本机优先」)。只读条数、不读内容,判定仍是纯函数。
|
|
64
67
|
*
|
|
65
68
|
* 纯函数(无状态、无 I/O):调度层与单测共用同一份判定,避免两处各写一遍阈值。
|
|
66
69
|
*/
|
|
@@ -69,6 +72,8 @@ export declare function resolveConflictPushPolicy(args: {
|
|
|
69
72
|
firstRun: boolean;
|
|
70
73
|
remoteNew: boolean;
|
|
71
74
|
conflicted: number;
|
|
75
|
+
/** 磁盘上仍在等裁决的分区数(缺省 0 = 只看本轮冲突;读不到状态也按 0 处理,绝不因此 force)。 */
|
|
76
|
+
held?: number;
|
|
72
77
|
}): {
|
|
73
78
|
policy: AutosyncConflictPolicy;
|
|
74
79
|
force: boolean;
|
|
@@ -166,6 +171,12 @@ export interface AutoSyncSchedulerOptions {
|
|
|
166
171
|
makeWatcher?: (opts: WatcherFactoryOptions) => SyncWatcher;
|
|
167
172
|
/** 触发合并窗口(ms):连续保存/连续远端探测只跑一轮。缺省 3000。 */
|
|
168
173
|
minTriggerGapMs?: number;
|
|
174
|
+
/**
|
|
175
|
+
* 读磁盘上仍在等裁决的分区(issue #146 F9)。缺省读 `<syncDir>/sync-state.json` 的 pendingMerge,
|
|
176
|
+
* 与 SyncEngine 的 stateDir 同源(装配处两处都是 syncDir);测试注入内存实现,免碰真实文件。
|
|
177
|
+
* 读失败 → 空数组(判定退回「只看本轮冲突」的老口径),绝不因为读不到状态就 force。
|
|
178
|
+
*/
|
|
179
|
+
readPendingMerge?: () => Promise<readonly SectionId[]>;
|
|
169
180
|
}
|
|
170
181
|
export declare class AutoSyncScheduler {
|
|
171
182
|
private readonly syncDir;
|
|
@@ -209,6 +220,7 @@ export declare class AutoSyncScheduler {
|
|
|
209
220
|
private readonly profile;
|
|
210
221
|
private readonly makeWatcher;
|
|
211
222
|
private readonly minTriggerGapMs;
|
|
223
|
+
private readonly readPendingMerge;
|
|
212
224
|
/** SEC-03:已 warn 过的「地址被拒」成因(键 = 通道 + 成因文本),进程内去重。 */
|
|
213
225
|
private readonly reportedConfigIssues;
|
|
214
226
|
private stopped;
|
|
@@ -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(见
|
|
@@ -50,6 +50,7 @@ import { engineMsg } from './messages.js';
|
|
|
50
50
|
import { readAutosyncConfig, writeAutosyncConfig, clampRemoteCheckMs, DEFAULT_AUTOSYNC_REALTIME, DEFAULT_AUTOSYNC_REMOTE_CHECK_MS, DEFAULT_AUTOSYNC_AUTO_APPLY_TIER, DEFAULT_AUTOSYNC_CONFLICT_POLICY, } from './autosync-config.js';
|
|
51
51
|
import { readSyncConfigFor, isGitConfig, isWebDavConfig, isS3Config, isGistConfig, SYNC_CHANNELS } from './sync-config.js';
|
|
52
52
|
import { readSyncHistory, appendAutosyncEntry, markAutosyncNotified } from './sync-history.js';
|
|
53
|
+
import { loadSyncState } from './sync-state.js';
|
|
53
54
|
import { repeatHistorySignature } from './autosync-repeat.js';
|
|
54
55
|
import { classifyMergePlan } from './risk.js';
|
|
55
56
|
import { SyncWatcher } from './sync-watcher.js';
|
|
@@ -87,7 +88,10 @@ export function shouldTriggerStartupRun(lastRunAt, startupMinIntervalMs, nowMs =
|
|
|
87
88
|
* - **首轮**(从未跑过)或**远端有新快照**:即使显式选了 'local' 也强制降级 ask(forcedAsk)——
|
|
88
89
|
* 这两个时刻正是「远端最新改动只在历史快照里」的事故现场,静默覆盖等于替用户丢数据;
|
|
89
90
|
* 降级记 forced,界面才能说清「这次没按你的 local 走」;
|
|
90
|
-
* - 只有「显式 local + 非高危时刻 + 真有冲突」才 force
|
|
91
|
+
* - 只有「显式 local + 非高危时刻 + 真有冲突」才 force;
|
|
92
|
+
* - 「真有冲突」= **本轮新判出的冲突** ∪ **磁盘上仍在等裁决的分区**(`held`,issue #146 F9):
|
|
93
|
+
* local 是用户的**长期决定**,不能只对本轮新冲突生效 —— 否则上一轮攒下的待裁决永远等不到结论,
|
|
94
|
+
* 每轮都「不推也不报错」地空转(用户明明选了「本机优先」)。只读条数、不读内容,判定仍是纯函数。
|
|
91
95
|
*
|
|
92
96
|
* 纯函数(无状态、无 I/O):调度层与单测共用同一份判定,避免两处各写一遍阈值。
|
|
93
97
|
*/
|
|
@@ -96,7 +100,8 @@ export function resolveConflictPushPolicy(args) {
|
|
|
96
100
|
// forcedAsk 只描述「用户选了 local,但本轮被降级」——缺省 ask 不算被强制(那不是用户的决定被推翻)。
|
|
97
101
|
const forcedAsk = configured === 'local' && (args.firstRun || args.remoteNew);
|
|
98
102
|
const policy = forcedAsk ? 'ask' : configured;
|
|
99
|
-
|
|
103
|
+
const outstanding = args.conflicted + (args.held ?? 0);
|
|
104
|
+
return { policy, force: policy === 'local' && outstanding > 0, forcedAsk };
|
|
100
105
|
}
|
|
101
106
|
export class AutoSyncScheduler {
|
|
102
107
|
syncDir;
|
|
@@ -140,6 +145,7 @@ export class AutoSyncScheduler {
|
|
|
140
145
|
profile;
|
|
141
146
|
makeWatcher;
|
|
142
147
|
minTriggerGapMs;
|
|
148
|
+
readPendingMerge;
|
|
143
149
|
/** SEC-03:已 warn 过的「地址被拒」成因(键 = 通道 + 成因文本),进程内去重。 */
|
|
144
150
|
reportedConfigIssues = new Set();
|
|
145
151
|
stopped = false;
|
|
@@ -174,6 +180,14 @@ export class AutoSyncScheduler {
|
|
|
174
180
|
this.profile = opts.profile;
|
|
175
181
|
this.makeWatcher = opts.makeWatcher ?? defaultMakeWatcher;
|
|
176
182
|
this.minTriggerGapMs = opts.minTriggerGapMs ?? 3000;
|
|
183
|
+
this.readPendingMerge = opts.readPendingMerge ?? (async () => {
|
|
184
|
+
try {
|
|
185
|
+
return (await loadSyncState(this.syncDir)).pendingMerge?.sections ?? [];
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
});
|
|
177
191
|
}
|
|
178
192
|
/**
|
|
179
193
|
* 追加一条自动同步历史(自动带上触发通道;0x 安全:绝不覆盖调用方显式 transport)。
|
|
@@ -658,16 +672,33 @@ export class AutoSyncScheduler {
|
|
|
658
672
|
* SYN-05:首轮 / 远端有新快照时即使显式选了 local 也强制降级 ask(forced=true 进结果与
|
|
659
673
|
* 历史),绝不在这两个高危时刻替用户覆盖远端最新。
|
|
660
674
|
*/
|
|
675
|
+
// issue #146(F9):local 是用户的长期决定 —— 存量待裁决必须能被它消解,否则上一轮攒下的
|
|
676
|
+
// 分区永远等不到结论(每轮"既不推也不报错"地空转)。只在策略是 local 时读一次磁盘,
|
|
677
|
+
// 读失败按 0 处理(退回老口径:只扣不推 + 由下面的 all-conflicted 如实上报)。
|
|
678
|
+
const heldFromState = cfg.conflictPolicy === 'local' ? await this.readPendingMerge() : [];
|
|
661
679
|
const pushDecision = resolveConflictPushPolicy({
|
|
662
680
|
...(cfg.conflictPolicy !== undefined ? { configuredPolicy: cfg.conflictPolicy } : {}),
|
|
663
681
|
firstRun,
|
|
664
682
|
remoteNew,
|
|
665
683
|
conflicted: conflictedSections.length,
|
|
684
|
+
held: heldFromState.length,
|
|
666
685
|
});
|
|
667
686
|
const forcePush = pushDecision.force;
|
|
668
687
|
const forcedMark = pushDecision.forcedAsk ? { forced: true } : {};
|
|
688
|
+
// issue #146:本轮**仍未裁决**的分区(分区级冲突 + 下行被扣下的叶级冲突)绝不上行。
|
|
689
|
+
// 冲突分区在 Phase B 被有意跳过(绝不写本地),但推送侧原本照样导出本机版本 ——
|
|
690
|
+
// 真机事故里 plugins 就这样被 30 → 28 → 26 一路压小。force = 用户明确「用本机覆盖远端」,不扣。
|
|
691
|
+
const heldUp = forcePush ? [] : [...new Set([...conflictedSections, ...heldLeafSections])];
|
|
692
|
+
// 先落盘待裁决:引擎推送成功时只在**已有记录**上保留 since,本轮首次判出的冲突要靠这里写下来。
|
|
693
|
+
const pendingRecorded = heldUp.length > 0;
|
|
694
|
+
if (pendingRecorded)
|
|
695
|
+
await this.recordPendingMerge(engine, heldUp);
|
|
669
696
|
// Phase C: 完整双向 → engine.push() 上传。P0-A:外部 push 包 intent journal。
|
|
670
|
-
const rawPush = async () => engine.push(
|
|
697
|
+
const rawPush = async () => engine.push({
|
|
698
|
+
...(forcePush ? { force: true } : {}),
|
|
699
|
+
// 空数组也传:本轮没判出新冲突时,磁盘上上一轮留下的待裁决仍要扣下(issue #146)。
|
|
700
|
+
skipSections: heldUp,
|
|
701
|
+
});
|
|
671
702
|
const pushReport = (this.phase3Recovery !== undefined && this.lockCtxForJournal !== null)
|
|
672
703
|
? (await this.phase3Recovery.runExternalIntent({
|
|
673
704
|
operationType: 'autosync-push', lockCtx: this.lockCtxForJournal,
|
|
@@ -704,8 +735,10 @@ export class AutoSyncScheduler {
|
|
|
704
735
|
createdAt: nowIso, failureCountAtRun: 0,
|
|
705
736
|
...forcedMark,
|
|
706
737
|
});
|
|
707
|
-
// 冲突分区落成待裁决(P2
|
|
708
|
-
|
|
738
|
+
// 冲突分区落成待裁决(P2):首页与同步页据此给出裁决入口。推送前已写过就不再写一次
|
|
739
|
+
// (重复写会按 lastMergedRemoteSnapshotId 重算 since,抹掉首次判出冲突的时间)。
|
|
740
|
+
if (!pendingRecorded)
|
|
741
|
+
await this.recordPendingMerge(engine, conflictedSections);
|
|
709
742
|
await this.writeFinalConfig(cfg, conflictResult, nowIso, historyId, channel);
|
|
710
743
|
return conflictResult;
|
|
711
744
|
}
|
|
@@ -729,15 +762,27 @@ export class AutoSyncScheduler {
|
|
|
729
762
|
// 也绝不因为它报成 failed:网络与凭据都是好的,只是远端有内容要用户确认)。
|
|
730
763
|
// conflictPolicy='local' 时冲突已被「本机覆盖远端」消解,但远端那一版确实被盖掉了 →
|
|
731
764
|
// 同样记 partial,skipReason 换成 conflict-kept-local(界面据此说清「本机已覆盖远端」)。
|
|
732
|
-
|
|
733
|
-
|
|
765
|
+
// force 消解的对象 = 本轮冲突 ∪ 磁盘存量(F9):只覆盖本轮会让台账把「覆盖了远端」这件事
|
|
766
|
+
// 说成一次普通成功 —— 用户从来看不出自己那句「本机优先」到底动过哪些分区。
|
|
767
|
+
const keptLocalSections = forcePush
|
|
768
|
+
? [...new Set([...conflictedSections, ...heldFromState])]
|
|
769
|
+
: [];
|
|
770
|
+
const keptLocal = keptLocalSections.length > 0;
|
|
771
|
+
const partial = keptLocal || conflictedSections.length > 0;
|
|
772
|
+
// issue #146(follow-up):引擎把「冲突未裁决 ⇒ 本轮一个分区都没上行」回成 skipped:'all-conflicted'。
|
|
773
|
+
// 以前这里只看 ok/conflict,于是整轮被记成「上传·成功」—— 用户从此看不出有分区被扣下,
|
|
774
|
+
// #146 的「显示成已推送」在自动同步路径原地复发。全扣下与部分扣下都必须落到台账。
|
|
775
|
+
const allConflicted = pushReport.skipped === 'all-conflicted';
|
|
776
|
+
const pushWarnings = pushReport.warnings ?? [];
|
|
734
777
|
const skipReason = keptLocal
|
|
735
778
|
? 'conflict-kept-local'
|
|
736
779
|
: partial
|
|
737
780
|
? 'conflict'
|
|
738
|
-
:
|
|
781
|
+
: allConflicted
|
|
782
|
+
? 'all-conflicted'
|
|
783
|
+
: undefined;
|
|
739
784
|
const reportedConflicted = keptLocal
|
|
740
|
-
?
|
|
785
|
+
? keptLocalSections
|
|
741
786
|
: partial
|
|
742
787
|
? conflictedSections
|
|
743
788
|
: deferredSections;
|
|
@@ -752,30 +797,41 @@ export class AutoSyncScheduler {
|
|
|
752
797
|
// 纯告警(插件没装上、undo 有残留等)与冲突无关,套上 'conflict' 会让
|
|
753
798
|
// 界面上出现「跳过原因:冲突」「另有 N 个分区待确认」,而 conflictedSections 是空的。
|
|
754
799
|
const heldDegraded = heldLeafSections.length > 0;
|
|
800
|
+
// 引擎告警(分区导出失败 / 非 portable 跳过 / 扣下说明)同样要上屏:静默少推比失败更糟。
|
|
801
|
+
const allWarnings = [...downlinkWarnings, ...pushWarnings];
|
|
802
|
+
// 引擎 push 回传的告警(provider namespace 未配置、目录为空…)是常规事实噪声,只上屏不降级;
|
|
803
|
+
// 状态降级只认「有分区被扣下」与下行冲突 —— 否则每轮都变成 partial,用户就学不会 partial 的含义。
|
|
755
804
|
const degraded = downlinkWarnings.length > 0 || heldDegraded;
|
|
756
|
-
const finalPartial = partial || degraded;
|
|
805
|
+
const finalPartial = partial || degraded || allConflicted;
|
|
806
|
+
// 一个分区都没上行 = 「成功但跳过」,不是「成功」也不是「失败」(#146 验收口径②)。
|
|
807
|
+
const finalStatus = allConflicted && appliedSections.length === 0
|
|
808
|
+
? 'skipped'
|
|
809
|
+
: finalPartial ? 'partial' : 'success';
|
|
757
810
|
const finalSkipReason = skipReason
|
|
758
811
|
?? (heldDegraded ? 'conflict' : degraded ? 'warning' : undefined);
|
|
759
812
|
// 扣下的叶级冲突所在分区也要出现在「待处理分区」里(与分区级冲突合并去重)
|
|
760
813
|
const finalConflicted = [...new Set([...reportedConflicted, ...heldLeafSections])];
|
|
761
814
|
const result = {
|
|
762
|
-
status:
|
|
815
|
+
status: finalStatus,
|
|
763
816
|
direction: appliedSections.length ? 'both' : 'push',
|
|
764
|
-
appliedSections,
|
|
817
|
+
appliedSections, historyId,
|
|
818
|
+
// issue #146:全扣下时 snapshotId 为空 —— 绝不写空 id(界面会当成「推了某份快照」)。
|
|
819
|
+
...(pushReport.snapshotId !== '' ? { pushedSnapshotId: pushReport.snapshotId } : {}),
|
|
765
820
|
...(finalSkipReason !== undefined || adoptedReason !== undefined ? { skipReason: finalSkipReason ?? adoptedReason } : {}),
|
|
766
821
|
...(finalConflicted.length > 0 ? { conflictedSections: finalConflicted } : {}),
|
|
767
|
-
...(
|
|
822
|
+
...(allWarnings.length > 0 ? { warnings: allWarnings } : {}),
|
|
768
823
|
...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
|
|
769
824
|
consecutiveFailures: 0,
|
|
770
825
|
...forcedMark,
|
|
771
826
|
};
|
|
772
827
|
await this.appendHistory(channel, {
|
|
773
828
|
direction: appliedSections.length ? 'both' : 'push',
|
|
774
|
-
status:
|
|
775
|
-
appliedSections,
|
|
829
|
+
status: finalStatus,
|
|
830
|
+
appliedSections,
|
|
831
|
+
...(pushReport.snapshotId !== '' ? { pushedSnapshotId: pushReport.snapshotId } : {}),
|
|
776
832
|
...(finalSkipReason !== undefined || adoptedReason !== undefined ? { skipReason: finalSkipReason ?? adoptedReason } : {}),
|
|
777
833
|
...(finalConflicted.length > 0 ? { conflictedSections: finalConflicted } : {}),
|
|
778
|
-
...(
|
|
834
|
+
...(allWarnings.length > 0 ? { warnings: allWarnings } : {}),
|
|
779
835
|
...(heldLeafSections.length > 0 ? { heldSections: heldLeafSections } : {}),
|
|
780
836
|
createdAt: nowIso, failureCountAtRun: 0,
|
|
781
837
|
...forcedMark,
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ConfigAdapter, HostContext, SecretScanner } from '../core/types.ts';
|
|
2
|
+
import type { SyncState } from './sync-state.ts';
|
|
3
|
+
/**
|
|
4
|
+
* 任一候选分区(= 会进载荷的那一批)的导出 hash ≠ 基线 ⇒ true。
|
|
5
|
+
* - 从未同步(state.sections 为空)→ true;
|
|
6
|
+
* - 基线缺该分区 → true(比不出来的不能当成「没变」);
|
|
7
|
+
* - 单项导出失败 → 跳过该项(与 push 单项跳过语义一致),绝不当成「有变化」去触发空推。
|
|
8
|
+
* 只读本地导出 + sync-state,不碰远端。
|
|
9
|
+
*/
|
|
10
|
+
export declare function hasLocalSectionChanges(args: {
|
|
11
|
+
state: SyncState;
|
|
12
|
+
adapters: readonly ConfigAdapter[];
|
|
13
|
+
ctx: HostContext;
|
|
14
|
+
scanner: SecretScanner;
|
|
15
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,39 @@
|
|
|
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.js';
|
|
9
|
+
import { isFileSection } from '../schema/config.js';
|
|
10
|
+
import { hashSection } from './sync-state.js';
|
|
11
|
+
/**
|
|
12
|
+
* 任一候选分区(= 会进载荷的那一批)的导出 hash ≠ 基线 ⇒ true。
|
|
13
|
+
* - 从未同步(state.sections 为空)→ true;
|
|
14
|
+
* - 基线缺该分区 → true(比不出来的不能当成「没变」);
|
|
15
|
+
* - 单项导出失败 → 跳过该项(与 push 单项跳过语义一致),绝不当成「有变化」去触发空推。
|
|
16
|
+
* 只读本地导出 + sync-state,不碰远端。
|
|
17
|
+
*/
|
|
18
|
+
export async function hasLocalSectionChanges(args) {
|
|
19
|
+
const { state, adapters, ctx, scanner } = args;
|
|
20
|
+
if (Object.keys(state.sections).length === 0)
|
|
21
|
+
return true;
|
|
22
|
+
for (const adapter of adapters) {
|
|
23
|
+
let section;
|
|
24
|
+
try {
|
|
25
|
+
section = await adapter.export(ctx, { includeSecrets: false });
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
const data = isFileSection(adapter.id) ? section.data : sanitizeSectionData(adapter, scanner, section.data).sanitized;
|
|
31
|
+
const recorded = state.sections[adapter.id];
|
|
32
|
+
if (recorded === undefined)
|
|
33
|
+
return true;
|
|
34
|
+
if (recorded.hash !== hashSection(data))
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=local-changes.js.map
|
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
export type KeyedConflictReason = 'both-modified' | 'modify-delete' | 'delete-modify';
|
|
26
|
+
export interface KeyedMergeSpec<T> {
|
|
27
|
+
/** 身份键(同键 = 同一条目);返回空串 = 该条目没有身份,跳过不参与合并。 */
|
|
28
|
+
keyOf(item: T): string;
|
|
29
|
+
/**
|
|
30
|
+
* 内容身份(相等 = 这一侧没改过它)。peers 是同一键上出现过的三侧原值,供「按需归一化」用
|
|
31
|
+
* —— patch 行要按三侧 redactedPaths 并集把被剥空的叶子归零后再比(issue #145 门②)。
|
|
32
|
+
*/
|
|
33
|
+
identityOf(item: T, peers: readonly T[], context?: unknown): string;
|
|
34
|
+
/**
|
|
35
|
+
* 一次算好同一键上三侧共用的身份上下文(如 patch 行的 redactedPaths 并集),
|
|
36
|
+
* 由 identityOf 第三参取用 —— 每个键只算一次,不再每条目重算(性能,2026-11-15)。
|
|
37
|
+
*/
|
|
38
|
+
identityContextOf?(peers: readonly T[]): unknown;
|
|
39
|
+
/** 冲突路径(给人看的定位,如 `plugins.alpha`)。 */
|
|
40
|
+
pathOf(key: string): string;
|
|
41
|
+
/** 本机未改、远端删了:true = 跟随删除;false = 保留本机(不报冲突、不计合并点)。 */
|
|
42
|
+
followDelete: boolean;
|
|
43
|
+
/** 永远以本机为准的条目(本插件自己这类「删了会坏事」的东西):不删、不报冲突。 */
|
|
44
|
+
keepLocal?(item: T): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* 采纳远端那一侧时怎么合成(缺省 = 直接取远端对象)。
|
|
47
|
+
* 只有「本机没改、远端改了」这一条分支会调它;用途是把**本机态字段**(如插件启停)留在本机,
|
|
48
|
+
* 其余字段听远端 —— 否则远端升一次版本就会把本机停用改回启用(issue #145 复审 P0-2)。
|
|
49
|
+
*/
|
|
50
|
+
compose?(l: T, r: T): T;
|
|
51
|
+
}
|
|
52
|
+
export interface KeyedMergeResult<T> {
|
|
53
|
+
merged: T[];
|
|
54
|
+
conflicts: MergeConflict[];
|
|
55
|
+
/** 自动并入的变更点(「两侧各自的改动都保住了」处数) */
|
|
56
|
+
mergePoints: number;
|
|
57
|
+
/**
|
|
58
|
+
* 输入形状不支持按键合并(同键重复 / 没有身份键 / 非对象条目):此时 merged 恒空,
|
|
59
|
+
* 调用方**必须**退回通用路径 —— 绝不在这里「留一条丢一条」(复审 P1-2)。
|
|
60
|
+
*/
|
|
61
|
+
malformed: boolean;
|
|
62
|
+
}
|
|
63
|
+
export declare function mergeKeyedList<T>(args: {
|
|
64
|
+
local: readonly T[];
|
|
65
|
+
remote: readonly T[];
|
|
66
|
+
ancestor: readonly T[] | undefined;
|
|
67
|
+
spec: KeyedMergeSpec<T>;
|
|
68
|
+
}): KeyedMergeResult<T>;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
function indexByKey(list, keyOf) {
|
|
2
|
+
const index = new Map();
|
|
3
|
+
let malformed = false;
|
|
4
|
+
for (const item of list ?? []) {
|
|
5
|
+
if (item === null || typeof item !== 'object') {
|
|
6
|
+
malformed = true;
|
|
7
|
+
continue;
|
|
8
|
+
}
|
|
9
|
+
const key = keyOf(item);
|
|
10
|
+
if (key === '') {
|
|
11
|
+
malformed = true;
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
if (index.has(key)) {
|
|
15
|
+
malformed = true;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
index.set(key, item);
|
|
19
|
+
}
|
|
20
|
+
return { index, malformed };
|
|
21
|
+
}
|
|
22
|
+
export function mergeKeyedList(args) {
|
|
23
|
+
const { spec } = args;
|
|
24
|
+
const localIdx = indexByKey(args.local, spec.keyOf);
|
|
25
|
+
const remoteIdx = indexByKey(args.remote, spec.keyOf);
|
|
26
|
+
const ancestorIdx = indexByKey(args.ancestor, spec.keyOf);
|
|
27
|
+
if (localIdx.malformed || remoteIdx.malformed || ancestorIdx.malformed) {
|
|
28
|
+
return { merged: [], conflicts: [], mergePoints: 0, malformed: true };
|
|
29
|
+
}
|
|
30
|
+
const { index: localIndex } = localIdx;
|
|
31
|
+
const { index: remoteIndex } = remoteIdx;
|
|
32
|
+
const { index: ancestorIndex } = ancestorIdx;
|
|
33
|
+
const order = [...localIndex.keys()];
|
|
34
|
+
for (const key of remoteIndex.keys())
|
|
35
|
+
if (!localIndex.has(key))
|
|
36
|
+
order.push(key);
|
|
37
|
+
const merged = [];
|
|
38
|
+
const conflicts = [];
|
|
39
|
+
let mergePoints = 0;
|
|
40
|
+
for (const key of order) {
|
|
41
|
+
const l = localIndex.get(key);
|
|
42
|
+
const r = remoteIndex.get(key);
|
|
43
|
+
const a = ancestorIndex.get(key);
|
|
44
|
+
const peers = [l, r, a].filter((item) => item !== undefined);
|
|
45
|
+
// 同一键的并集/路径解析只做一次;同一条目在一轮合并里被问到多次也只算一次。
|
|
46
|
+
const context = spec.identityContextOf?.(peers);
|
|
47
|
+
const identities = new Map();
|
|
48
|
+
const identity = (item) => {
|
|
49
|
+
if (item === undefined)
|
|
50
|
+
return '';
|
|
51
|
+
const cached = identities.get(item);
|
|
52
|
+
if (cached !== undefined || identities.has(item))
|
|
53
|
+
return cached ?? '';
|
|
54
|
+
const value = spec.identityOf(item, peers, context);
|
|
55
|
+
identities.set(item, value);
|
|
56
|
+
return value;
|
|
57
|
+
};
|
|
58
|
+
const conflict = (reason) => {
|
|
59
|
+
conflicts.push({ path: spec.pathOf(key), kind: 'key', reason, autoMergeAttempted: false, local: l ?? null, remote: r ?? null, ancestor: a ?? null });
|
|
60
|
+
};
|
|
61
|
+
if (l !== undefined && spec.keepLocal?.(l) === true) {
|
|
62
|
+
merged.push(l);
|
|
63
|
+
// 只有真的采纳了远端内容才算一个合并点(远端根本没这条时不算,复审 P2-3)
|
|
64
|
+
if (r !== undefined && identity(l) !== identity(r))
|
|
65
|
+
mergePoints += 1;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (l !== undefined && r !== undefined) {
|
|
69
|
+
const [li, ri] = [identity(l), identity(r)];
|
|
70
|
+
if (li === ri) {
|
|
71
|
+
merged.push(l);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (a === undefined) {
|
|
75
|
+
conflict('both-modified');
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const ai = identity(a);
|
|
79
|
+
if (li === ai) {
|
|
80
|
+
merged.push(spec.compose?.(l, r) ?? r);
|
|
81
|
+
mergePoints += 1;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (ri === ai) {
|
|
85
|
+
merged.push(l);
|
|
86
|
+
mergePoints += 1;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
conflict('both-modified');
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (l !== undefined) {
|
|
93
|
+
if (a === undefined) {
|
|
94
|
+
merged.push(l);
|
|
95
|
+
mergePoints += 1;
|
|
96
|
+
continue;
|
|
97
|
+
} // 本机独有
|
|
98
|
+
if (identity(l) !== identity(a)) {
|
|
99
|
+
conflict('modify-delete');
|
|
100
|
+
continue;
|
|
101
|
+
} // 本机改过 → 交人工
|
|
102
|
+
if (spec.followDelete) {
|
|
103
|
+
mergePoints += 1;
|
|
104
|
+
continue;
|
|
105
|
+
} // 跟随远端删除
|
|
106
|
+
merged.push(l);
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (r !== undefined) {
|
|
110
|
+
if (a === undefined) {
|
|
111
|
+
merged.push(r);
|
|
112
|
+
mergePoints += 1;
|
|
113
|
+
continue;
|
|
114
|
+
} // 远端独有
|
|
115
|
+
if (identity(r) !== identity(a)) {
|
|
116
|
+
conflict('delete-modify');
|
|
117
|
+
continue;
|
|
118
|
+
} // 本机删了、远端改过 → 交人工
|
|
119
|
+
mergePoints += 1; // 远端未改,本机删过它 → 跟随本机删除
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return { merged, conflicts, mergePoints, malformed: false };
|
|
123
|
+
}
|
|
124
|
+
//# sourceMappingURL=merge-keyed.js.map
|