Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(contacts): track acknowledged conflict members
Chris74b69f7bbede
diff --git a/packages/maker-core/src/contacts/__tests__/contactsSync.test.ts b/packages/maker-core/src/contacts/__tests__/contactsSync.test.tsindex 9938855ea8..fbfaac449d 100644--- a/packages/maker-core/src/contacts/__tests__/contactsSync.test.ts+++ b/packages/maker-core/src/contacts/__tests__/contactsSync.test.ts@@ -154,6 +154,73 @@ describe("contacts device sync", () => {).toEqual(mergeContactsSyncStates(a!, mergeContactsSyncStates(b!, c!)));});+ it("同 stamp 的确认成员元数据按完整写入稳定裁决", () => {+ const a = createStore();+ a.activateDeviceSync();+ const contact = a.createContact({+ kind: "person",+ displayName: "元数据裁决",+ });+ const plain = stateOf(a);+ const enriched = structuredClone(plain);+ enriched.contacts.find((entry) => entry.id === contact.id)!.status = {+ ...enriched.contacts.find((entry) => entry.id === contact.id)!.status,+ acknowledgedConflicts: [+ {+ platform: "email",+ normalizedValue: "[email protected]",+ membershipHash: "a".repeat(64),+ },+ ],+ };++ expect(mergeContactsSyncStates(plain, enriched)).toEqual(+ mergeContactsSyncStates(enriched, plain),+ );+ });++ it("确认成员元数据使用同步层上限,不收紧多设备合并后的合法身份数", () => {+ const store = createStore();+ store.activateDeviceSync();+ const contact = store.createContact({+ kind: "person",+ displayName: "多身份确认",+ });+ const state = stateOf(store);+ const record = state.contacts.find((entry) => entry.id === contact.id)!;+ record.status.acknowledgedConflicts = Array.from(+ { length: 20 },+ (_, index) => ({+ platform: "custom",+ normalizedValue: `identity-${index}`,+ membershipHash: index.toString(16).padStart(64, "0"),+ }),+ );++ expect(isValidContactsSyncState(state)).toBe(true);+ });++ it("确认成员元数据按全状态总量限制,不能按联系人重复放大", () => {+ const store = createStore();+ store.activateDeviceSync();+ const first = store.createContact({ kind: "person", displayName: "甲" });+ const second = store.createContact({ kind: "person", displayName: "乙" });+ const state = stateOf(store);+ const oversized = Array.from({ length: 50_001 }, (_, index) => ({+ platform: "custom",+ normalizedValue: `identity-${index}`,+ membershipHash: index.toString(16).padStart(64, "0"),+ }));+ state.contacts.find(+ (contact) => contact.id === first.id,+ )!.status.acknowledgedConflicts = oversized;+ state.contacts.find(+ (contact) => contact.id === second.id,+ )!.status.acknowledgedConflicts = structuredClone(oversized);++ expect(isValidContactsSyncState(state)).toBe(false);+ });+it("已知对端版本后只发送缺失记录,增量合并结果与全量一致", () => {const a = createStore();const b = createStore();@@ -281,6 +348,99 @@ describe("contacts device sync", () => {expect(b.stats().pending).toBe(1);});+ it("旧客户端丢失确认凭据后不靠 Lamport 大小吞掉新冲突", () => {+ const a = createStore();+ const b = createStore();+ const c = createStore();+ a.activateDeviceSync();+ b.activateDeviceSync();+ c.activateDeviceSync();+ const aContact = a.createContact({+ kind: "person",+ displayName: "甲",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ b.createContact({+ kind: "person",+ displayName: "乙",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(a, b);+ a.updateContact(aContact.id, { status: "confirmed" });+ const confirmedState = stateOf(a);+ const confirmedStamp = confirmedState.contacts.find(+ (contact) => contact.id === aContact.id,+ )!.status.stamp;+ const cContact = c.createContact({+ kind: "person",+ displayName: "离线新成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ const cIdentityStamp = stateOf(c).identities.find(+ (identity) => identity.value.value.contactId === cContact.id,+ )!.value.stamp;+ expect(cIdentityStamp.counter).toBeLessThan(confirmedStamp.counter);++ // 模拟旧客户端接收新版状态时丢掉未知确认字段,随后再并入自己+ // 低 counter 创建的新成员。+ const legacyState = structuredClone(confirmedState);+ delete legacyState.contacts.find((contact) => contact.id === aContact.id)!+ .status.acknowledgedConflicts;+ const legacyWithNewConflict = mergeContactsSyncStates(+ legacyState,+ stateOf(c),+ );+ expect(isValidContactsSyncState(legacyState)).toBe(true);++ const db = databases.at(-3)!;+ db.prepare(+ `UPDATE contacts_sync_state SET state_json = ? WHERE singleton = 1`,+ ).run(JSON.stringify(legacyWithNewConflict));+ const reconciled = stateOf(a);++ expect(a.getContact(aContact.id).status).toBe("pending");+ expect(a.getContact(cContact.id).status).toBe("pending");+ expect(+ reconciled.contacts.find((contact) => contact.id === aContact.id)!.status+ .acknowledgedConflicts ?? [],+ ).toHaveLength(0);+ });++ it("确认成员凭据进入增量包后,接收设备保留明确确认", () => {+ const a = createStore();+ const b = createStore();+ const c = createStore();+ a.activateDeviceSync();+ b.activateDeviceSync();+ c.activateDeviceSync();+ const aContact = a.createContact({+ kind: "person",+ displayName: "甲",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(b, a);+ c.createContact({+ kind: "person",+ displayName: "冲突成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(a, c);+ const beforeConfirmation = stateOf(b);+ a.updateContact(aContact.id, { status: "confirmed" });+ const confirmedState = stateOf(a);+ const delta = createContactsSyncDelta(+ confirmedState,+ beforeConfirmation.clocks,+ );++ expect(+ delta.contacts.find((contact) => contact.id === aContact.id)!.status+ .acknowledgedConflicts,+ ).toHaveLength(1);+ expect(b.mergeDeviceSyncState(delta)).toBe(true);+ expect(b.getContact(aContact.id).status).toBe("confirmed");+ });+it("用户确认后出现更新的同身份冲突时,所有关联联系人重新变成待确认", () => {const a = createStore();const b = createStore();@@ -315,6 +475,166 @@ describe("contacts device sync", () => {expect(b.getContact(bContact.id).status).toBe("pending");});+ it("用户确认后离线低 counter 设备新增同身份时,双方都重新待确认且往返幂等", () => {+ const a = createStore();+ const b = createStore();+ a.activateDeviceSync();+ b.activateDeviceSync();+ const aContact = a.createContact({+ kind: "person",+ displayName: "甲",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ const firstConflict = createStore();+ firstConflict.activateDeviceSync();+ firstConflict.createContact({+ kind: "person",+ displayName: "旧冲突成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(a, firstConflict);+ expect(a.getContact(aContact.id).status).toBe("pending");++ a.updateContact(aContact.id, { status: "confirmed" });+ const confirmedState = stateOf(a);+ const confirmedStatus = confirmedState.contacts.find(+ (contact) => contact.id === aContact.id,+ )!.status.stamp;+ const bContact = b.createContact({+ kind: "person",+ displayName: "离线新冲突成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ const bIdentityStamp = stateOf(b).identities.find(+ (identity) => identity.value.value.contactId === bContact.id,+ )!.value.stamp;+ expect(bIdentityStamp.counter).toBeLessThan(confirmedStatus.counter);++ exchange(a, b);+ exchange(b, a);+ exchange(a, b);+ for (const store of [a, b]) {+ expect(store.getContact(aContact.id).status).toBe("pending");+ expect(store.getContact(bContact.id).status).toBe("pending");+ }+ const converged = stateOf(a);+ expect(b.mergeDeviceSyncState(converged)).toBe(false);+ expect(stateOf(b)).toEqual(converged);+ });++ it("已见旧冲突的设备后来新增同身份成员时,离线确认仍失效并最终收敛", () => {+ const a = createStore();+ const b = createStore();+ const c = createStore();+ const d = createStore();+ a.activateDeviceSync();+ b.activateDeviceSync();+ c.activateDeviceSync();+ d.activateDeviceSync();+ const aContact = a.createContact({+ kind: "person",+ displayName: "甲",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ c.createContact({+ kind: "person",+ displayName: "旧冲突成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(a, c);+ exchange(b, a);+ expect(b.listContacts({ status: "pending" })).toHaveLength(2);++ a.updateContact(aContact.id, { status: "confirmed" });+ const confirmedStamp = stateOf(a).contacts.find(+ (contact) => contact.id === aContact.id,+ )!.status.stamp;+ const bContact = d.createContact({+ kind: "person",+ displayName: "D 离线新成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ const bIdentityStamp = stateOf(d).identities.find(+ (identity) => identity.value.value.contactId === bContact.id,+ )!.value.stamp;+ expect(bIdentityStamp.counter).toBeLessThan(confirmedStamp.counter);++ exchange(b, d);+ exchange(a, b);+ exchange(b, a);+ exchange(a, b);+ for (const store of [a, b]) {+ expect(store.getContact(aContact.id).status).toBe("pending");+ expect(store.getContact(bContact.id).status).toBe("pending");+ expect(store.listContacts({ status: "pending" })).toHaveLength(3);+ }+ expect(stateOf(a)).toEqual(stateOf(b));+ });++ it("完整新冲突之后的明确确认可传播到仍缺成员的设备", () => {+ const a = createStore();+ const b = createStore();+ const c = createStore();+ a.activateDeviceSync();+ b.activateDeviceSync();+ c.activateDeviceSync();+ const aContact = a.createContact({+ kind: "person",+ displayName: "甲",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(b, a);+ const cContact = c.createContact({+ kind: "person",+ displayName: "新冲突成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(a, c);+ expect(a.getContact(aContact.id).status).toBe("pending");+ expect(a.getContact(cContact.id).status).toBe("pending");++ a.updateContact(aContact.id, { status: "confirmed" });+ stateOf(a);+ exchange(b, a);++ expect(b.getContact(aContact.id).status).toBe("confirmed");+ expect(b.getContact(cContact.id).status).toBe("pending");+ });++ it("低 counter 新冲突通过增量包到达时也会使既有确认失效", () => {+ const a = createStore();+ const b = createStore();+ a.activateDeviceSync();+ b.activateDeviceSync();+ const aContact = a.createContact({+ kind: "person",+ displayName: "甲",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ const oldConflict = createStore();+ oldConflict.activateDeviceSync();+ oldConflict.createContact({+ kind: "person",+ displayName: "旧冲突成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ exchange(a, oldConflict);+ a.updateContact(aContact.id, { status: "confirmed" });+ const confirmedState = stateOf(a);++ const bContact = b.createContact({+ kind: "person",+ displayName: "增量新成员",+ identities: [{ platform: "email", value: "[email protected]" }],+ });+ const delta = createContactsSyncDelta(stateOf(b), confirmedState.clocks);+ expect(delta.identities).toHaveLength(1);+ expect(a.mergeDeviceSyncState(delta)).toBe(true);++ expect(a.getContact(aContact.id).status).toBe("pending");+ expect(a.getContact(bContact.id).status).toBe("pending");+ });+it("FTS 重建失败后重复接收相同状态仍会重试", () => {const a = createStore();const b = createStore();diff --git a/packages/maker-core/src/contacts/sync/capture.ts b/packages/maker-core/src/contacts/sync/capture.tsindex 66ff77e097..0eae68947a 100644--- a/packages/maker-core/src/contacts/sync/capture.ts+++ b/packages/maker-core/src/contacts/sync/capture.ts@@ -10,10 +10,12 @@ import {nextContactsSyncStamp,stableContactsSyncJson,} from "./merge.js";+import { collectContactsIdentityConflicts } from "./conflicts.js";import {type ContactsDataSnapshot,type ContactsSnapshotContact,type ContactsSyncContact,+ type ContactsSyncConflictMembership,type ContactsSyncEntity,type ContactsSyncStamp,type ContactsSyncState,@@ -164,49 +166,110 @@ export function captureContactsSnapshot(current: ContactsDataSnapshot,nodeId: string,): { state: ContactsSyncState; changed: boolean } {- if (equal(previous, current)) return { state, changed: false };- const next = nextContactsSyncStamp(state, nodeId);- return {- changed: true,- state: {+ const snapshotChanged = !equal(previous, current);+ let stamp: ContactsSyncStamp | undefined;+ let capturedState = state;+ if (snapshotChanged) {+ const next = nextContactsSyncStamp(state, nodeId);+ stamp = next.stamp;+ capturedState = {...next.state,contacts: captureContacts(state.contacts,previous.contacts,current.contacts,- next.stamp,+ stamp,),identities: captureEntities(state.identities,previous.identities,current.identities,- next.stamp,+ stamp,),events: captureEntities(state.events,previous.events,current.events,- next.stamp,+ stamp,),groups: captureEntities(state.groups,previous.groups,current.groups,- next.stamp,+ stamp,),memberships: captureEntities(state.memberships,previous.memberships,current.memberships,- next.stamp,+ stamp,{ reusableId: true },),relations: captureEntities(state.relations,previous.relations,current.relations,- next.stamp,+ stamp,),+ };+ }+ const beforeContacts = new Map(+ previous.contacts.map((contact) => [contact.id, contact]),+ );+ const currentContacts = new Map(+ current.contacts.map((contact) => [contact.id, contact]),+ );+ const conflicts = collectContactsIdentityConflicts(capturedState);+ const explicitlyConfirmed = new Set(+ [...currentContacts.keys()].filter(+ (contactId) =>+ beforeContacts.get(contactId)?.status === "pending" &&+ currentContacts.get(contactId)?.status === "confirmed",+ ),+ );+ if (explicitlyConfirmed.size === 0) {+ return { state: capturedState, changed: snapshotChanged };+ }+ const membershipsByContact = new Map<+ string,+ ContactsSyncConflictMembership[]+ >();+ for (const conflict of conflicts) {+ for (const contactId of conflict.owners) {+ if (!explicitlyConfirmed.has(contactId)) continue;+ const memberships = membershipsByContact.get(contactId) ?? [];+ memberships.push({+ platform: conflict.platform,+ normalizedValue: conflict.normalizedValue,+ membershipHash: conflict.membershipHash,+ });+ membershipsByContact.set(contactId, memberships);+ }+ }+ return {+ changed: true,+ state: {+ ...capturedState,+ contacts: capturedState.contacts.map((contact) => {+ if (!explicitlyConfirmed.has(contact.id)) return contact;+ const acknowledgedConflicts = (+ membershipsByContact.get(contact.id) ?? []+ ).sort((left, right) =>+ compareContactsSyncText(+ `${left.platform}\u0000${left.normalizedValue}`,+ `${right.platform}\u0000${right.normalizedValue}`,+ ),+ );+ return {+ ...contact,+ status: {+ ...contact.status,+ ...(acknowledgedConflicts.length > 0+ ? { acknowledgedConflicts }+ : {}),+ },+ };+ }),},};}diff --git a/packages/maker-core/src/contacts/sync/conflicts.ts b/packages/maker-core/src/contacts/sync/conflicts.tsnew file mode 100644index 0000000000..e6ef2e38c7--- /dev/null+++ b/packages/maker-core/src/contacts/sync/conflicts.ts@@ -0,0 +1,72 @@+import { createHash } from "node:crypto";++import { compareContactsSyncText } from "./merge.js";+import {+ type ContactsSyncEntity,+ type ContactsSyncIdentityValue,+ type ContactsSyncState,+} from "./types.js";++export interface ContactsIdentityConflict {+ platform: string;+ normalizedValue: string;+ owners: Set<string>;+ membershipHash: string;+}++export function collectContactsIdentityConflicts(+ state: ContactsSyncState,+): ContactsIdentityConflict[] {+ const contactIds = new Set(+ state.contacts+ .filter((contact) => !contact.deleted)+ .map((contact) => contact.id),+ );+ const recordsByKey = new Map<+ string,+ Array<ContactsSyncEntity<ContactsSyncIdentityValue>>+ >();+ for (const record of state.identities) {+ if (record.deleted || !contactIds.has(record.value.value.contactId))+ continue;+ const value = record.value.value;+ const key = `${value.platform}\u0000${value.normalizedValue}`;+ const records = recordsByKey.get(key) ?? [];+ records.push(record);+ recordsByKey.set(key, records);+ }++ const conflicts: ContactsIdentityConflict[] = [];+ for (const [key, records] of recordsByKey) {+ const owners = new Set(+ records.map((record) => record.value.value.contactId),+ );+ if (owners.size <= 1) continue;+ const sortedRecords = [...records].sort((left, right) =>+ compareContactsSyncText(left.id, right.id),+ );+ const first = sortedRecords[0]!.value.value;+ const membershipHash = createHash("sha256")+ .update(+ JSON.stringify(+ sortedRecords.map((record) => [+ record.id,+ record.value.value.contactId,+ ]),+ ),+ )+ .digest("hex");+ conflicts.push({+ platform: first.platform,+ normalizedValue: first.normalizedValue,+ owners,+ membershipHash,+ });+ }+ return conflicts.sort((left, right) =>+ compareContactsSyncText(+ `${left.platform}\u0000${left.normalizedValue}`,+ `${right.platform}\u0000${right.normalizedValue}`,+ ),+ );+}diff --git a/packages/maker-core/src/contacts/sync/materialize.ts b/packages/maker-core/src/contacts/sync/materialize.tsindex 108c05c910..b814ad85d3 100644--- a/packages/maker-core/src/contacts/sync/materialize.ts+++ b/packages/maker-core/src/contacts/sync/materialize.ts@@ -7,6 +7,7 @@*/import { compareContactsSyncStamp, compareContactsSyncText } from "./merge.js";+import { collectContactsIdentityConflicts } from "./conflicts.js";import {type ContactsDataSnapshot,type ContactsSnapshotContact,@@ -16,8 +17,6 @@ import {type ContactsSnapshotMembership,type ContactsSnapshotRelation,type ContactsSyncEntity,- type ContactsSyncIdentityValue,- type ContactsSyncStamp,type ContactsSyncState,} from "./types.js";@@ -72,9 +71,6 @@ function uniqueBy<T>(export function materializeContactsSyncState(state: ContactsSyncState,): ContactsDataSnapshot {- const contactsById = new Map(- state.contacts.map((record) => [record.id, record]),- );const contacts = state.contacts.filter((record) => !record.deleted).map<ContactsSnapshotContact>((record) => ({@@ -91,6 +87,12 @@ export function materializeContactsSyncState(updatedAt: record.updatedAt.value,})).sort(byId);+ const contactsById = new Map(+ contacts.map((contact) => [contact.id, contact]),+ );+ const contactRecordsById = new Map(+ state.contacts.map((contact) => [contact.id, contact]),+ );const contactIds = new Set(contacts.map((contact) => contact.id));// contact_groups.name 的 UNIQUE 与 ContactsGroupsRepo 都是精确字符串语义;@@ -106,48 +108,7 @@ export function materializeContactsSyncState(const identityCandidates = liveEntities(state.identities).filter((record) =>contactIds.has(record.value.value.contactId),);- const identityOwners = new Map<string, Set<string>>();- const identityRecordsByKey = new Map<- string,- Array<ContactsSyncEntity<ContactsSyncIdentityValue>>- >();- const latestConflictStampByContact = new Map<string, ContactsSyncStamp>();- for (const record of identityCandidates) {- const value = record.value.value;- const key = `${value.platform}\u0000${value.normalizedValue}`;- const owners = identityOwners.get(key) ?? new Set<string>();- owners.add(value.contactId);- identityOwners.set(key, owners);- const records = identityRecordsByKey.get(key) ?? [];- records.push(record);- identityRecordsByKey.set(key, records);- }- const conflictedContactIds = new Set<string>();- for (const [key, owners] of identityOwners.entries()) {- if (owners.size <= 1) continue;- let latestConflictStamp: ContactsSyncStamp | undefined;- for (const record of identityRecordsByKey.get(key) ?? []) {- const value = record.value.value;- conflictedContactIds.add(value.contactId);- if (- !latestConflictStamp ||- compareContactsSyncStamp(latestConflictStamp, record.value.stamp) < 0- ) {- latestConflictStamp = record.value.stamp;- }- }- if (!latestConflictStamp) continue;- for (const contactId of owners) {- const previous = latestConflictStampByContact.get(contactId);- if (- !previous ||- compareContactsSyncStamp(previous, latestConflictStamp) < 0- ) {- latestConflictStampByContact.set(contactId, latestConflictStamp);- }- }- }-+ const conflicts = collectContactsIdentityConflicts(state);const identities = uniqueBy(identityCandidates,(value) => `${value.platform}\u0000${value.normalizedValue}`,@@ -160,20 +121,27 @@ export function materializeContactsSyncState(// 同一身份被并发分给不同联系人时,SQLite 只能物化一个确定性赢家;把所有// 相关档案标成待确认,避免另一边被隐藏后用户完全不知道发生过冲突。- // 用户确认后会产生一个晚于冲突身份 stamp 的 status stamp;此时尊重用户- // 的裁决,不要在下一次 reconcile / 往返同步时把它重新打回 pending。- for (const contact of contacts) {- if (!conflictedContactIds.has(contact.id)) continue;- const status = contactsById.get(contact.id)?.status;- const conflictStamp = latestConflictStampByContact.get(contact.id);- if (- status &&- conflictStamp &&- compareContactsSyncStamp(status.stamp, conflictStamp) > 0- ) {- continue;+ // Lamport stamp 只提供确定性全序,不能证明确认写入见过某个离线成员。+ // 只有确认记录的成员指纹与当前冲突完全一致,才保留 confirmed。+ for (const conflict of conflicts) {+ for (const contactId of conflict.owners) {+ const contact = contactsById.get(contactId);+ if (!contact) continue;+ const acknowledgement = contactRecordsById+ .get(contactId)+ ?.status.acknowledgedConflicts?.find(+ (membership) =>+ membership.platform === conflict.platform &&+ membership.normalizedValue === conflict.normalizedValue,+ );+ if (+ contact.status === "confirmed" &&+ acknowledgement?.membershipHash === conflict.membershipHash+ ) {+ continue;+ }+ contact.status = "pending";}- contact.status = "pending";}const events = liveEntities(state.events)diff --git a/packages/maker-core/src/contacts/sync/merge.ts b/packages/maker-core/src/contacts/sync/merge.tsindex aa1beea654..fda79c1419 100644--- a/packages/maker-core/src/contacts/sync/merge.ts+++ b/packages/maker-core/src/contacts/sync/merge.ts@@ -64,11 +64,10 @@ function mergeStamped<T>(const order = compareContactsSyncStamp(a.stamp, b.stamp);if (order > 0) return a;if (order < 0) return b;- // 同 stamp 理论上来自同一次写入;异常状态仍按规范化 JSON 值稳定裁决,- // 不能让对象 key 的输入顺序影响跨设备赢家。- return stableContactsSyncJson(a.value) >= stableContactsSyncJson(b.value)- ? a- : b;+ // 同 stamp 理论上来自同一次写入;异常状态仍按完整 stamped value 的+ // 规范化 JSON 稳定裁决。这样附着在写入上的向后兼容元数据也不会让+ // 合并结果依赖参数顺序。+ return stableContactsSyncJson(a) >= stableContactsSyncJson(b) ? a : b;}function mergeContact(diff --git a/packages/maker-core/src/contacts/sync/types.ts b/packages/maker-core/src/contacts/sync/types.tsindex 7cd5643594..c2e3a146f3 100644--- a/packages/maker-core/src/contacts/sync/types.ts+++ b/packages/maker-core/src/contacts/sync/types.ts@@ -25,6 +25,21 @@ export interface ContactsStampedValue<T> {stamp: ContactsSyncStamp;}+/** 一次确认写入时已知的同身份冲突成员指纹。 */+export interface ContactsSyncConflictMembership {+ platform: string;+ normalizedValue: string;+ membershipHash: string;+}++export interface ContactsSyncStatusValue extends ContactsStampedValue<ContactStatus> {+ /**+ * 跟随 status 写入,旧客户端会把未知字段随整个 stamped value 原样转发;+ * 若旧客户端自己改写 status,则视为一次没有因果确认信息的新裁决。+ */+ acknowledgedConflicts?: ContactsSyncConflictMembership[];+}+export interface ContactsSyncContact {id: string;kind: ContactsStampedValue<ContactKind>;@@ -33,7 +48,7 @@ export interface ContactsSyncContact {summary: ContactsStampedValue<string>;narrative: ContactsStampedValue<string>;agentNotes: ContactsStampedValue<string>;- status: ContactsStampedValue<ContactStatus>;+ status: ContactsSyncStatusValue;source: ContactsStampedValue<ContactSource>;createdAt: ContactsStampedValue<string>;updatedAt: ContactsStampedValue<string>;diff --git a/packages/maker-core/src/contacts/sync/validation.ts b/packages/maker-core/src/contacts/sync/validation.tsindex 5ff41d032b..81ce607f0d 100644--- a/packages/maker-core/src/contacts/sync/validation.ts+++ b/packages/maker-core/src/contacts/sync/validation.ts@@ -12,6 +12,7 @@ import {membershipSyncId,type ContactsDataSnapshot,type ContactsStampedValue,+ type ContactsSyncConflictMembership,type ContactsSyncEntity,type ContactsSyncStamp,type ContactsSyncState,@@ -133,12 +134,7 @@ function isContact(value: unknown): boolean {))return false;- if (- !isStamped(value.status, (v): v is "confirmed" | "pending" =>- isContactStatus(v),- )- )- return false;+ if (!isStatus(value.status)) return false;if (!isStamped(value.source, (v): v is "manual" | "agent" | "import" =>isContactSource(v),@@ -152,6 +148,45 @@ function isContact(value: unknown): boolean {return value.deleted === undefined || isStamp(value.deleted);}+function isConflictMembership(+ value: unknown,+): value is ContactsSyncConflictMembership {+ return (+ isRecord(value) &&+ isString(value.platform, 32, false) &&+ /^[a-z0-9_-]+$/.test(value.platform as string) &&+ isString(value.normalizedValue, MAX_NORMALIZED_IDENTITY_VALUE_LEN, false) &&+ isString(value.membershipHash, 64, false) &&+ /^[a-f0-9]{64}$/.test(value.membershipHash as string)+ );+}++function isStatus(value: unknown): boolean {+ if (+ !isStamped(value, (candidate): candidate is "confirmed" | "pending" =>+ isContactStatus(candidate),+ )+ ) {+ return false;+ }+ if (!isRecord(value) || value.acknowledgedConflicts === undefined)+ return true;+ if (+ !Array.isArray(value.acknowledgedConflicts) ||+ value.acknowledgedConflicts.length > CONTACTS_SYNC_MAX_ROWS_PER_TABLE+ ) {+ return false;+ }+ const keys = new Set<string>();+ for (const membership of value.acknowledgedConflicts) {+ if (!isConflictMembership(membership)) return false;+ const key = `${membership.platform}\u0000${membership.normalizedValue}`;+ if (keys.has(key)) return false;+ keys.add(key);+ }+ return true;+}+function isIdentity(value: unknown): value is {contactId: string;platform: string;@@ -166,11 +201,7 @@ function isIdentity(value: unknown): value is {isString(value.platform, 32, false) &&/^[a-z0-9_-]+$/.test(value.platform) &&isString(value.value, DEFAULT_CONTACTS_CONFIG.maxIdentityValueLen, false) &&- isString(- value.normalizedValue,- MAX_NORMALIZED_IDENTITY_VALUE_LEN,- false,- ) &&+ isString(value.normalizedValue, MAX_NORMALIZED_IDENTITY_VALUE_LEN, false) &&isUnboundedLocalText(value.label) &&isUnboundedLocalText(value.note) &&isString(value.createdAt, 64, false)@@ -384,9 +415,15 @@ export function isValidContactsSyncState()return false;const contactIds = new Set<string>();+ let acknowledgedConflictCount = 0;for (const contact of value.contacts) {if (!isContact(contact) || contactIds.has((contact as { id: string }).id))return false;+ acknowledgedConflictCount +=+ (contact as { status: { acknowledgedConflicts?: unknown[] } }).status+ .acknowledgedConflicts?.length ?? 0;+ if (acknowledgedConflictCount > CONTACTS_SYNC_MAX_ROWS_PER_TABLE)+ return false;contactIds.add((contact as { id: string }).id);}if (!isEntityArray(value.identities, isIdentity)) return false;