Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(contacts): bound sync comparison and index acknowledgements
Chris0afe05a64f80
diff --git a/packages/maker-core/src/contacts/__tests__/contactsSync.test.ts b/packages/maker-core/src/contacts/__tests__/contactsSync.test.tsindex edf4f393a3..95f8de7798 100644--- a/packages/maker-core/src/contacts/__tests__/contactsSync.test.ts+++ b/packages/maker-core/src/contacts/__tests__/contactsSync.test.ts@@ -7,6 +7,7 @@ import { MakerContactsStore } from "../store.js";import {createContactsSyncDelta,mergeContactsSyncStates,+ stableContactsSyncJson,} from "../sync/merge.js";import { materializeContactsSyncState } from "../sync/materialize.js";import {@@ -179,6 +180,25 @@ describe("contacts device sync", () => {);});+ it("深层 stamped 扩展字段不会耗尽规范化调用栈", () => {+ const store = createStore();+ const contact = store.createContact({+ kind: "person",+ displayName: "深层扩展",+ });+ store.activateDeviceSync();+ const state = stateOf(store);+ const contactRecord = state.contacts.find((entry) => entry.id === contact.id)!;+ let extension: Record<string, unknown> = { leaf: "ok" };+ for (let depth = 0; depth < 10_000; depth += 1) {+ extension = { next: extension };+ }+ (contactRecord.status as unknown as Record<string, unknown>).extension =+ extension;++ expect(() => stableContactsSyncJson(contactRecord.status)).not.toThrow();+ });+it("确认成员元数据使用同步层上限,不收紧多设备合并后的合法身份数", () => {const store = createStore();store.activateDeviceSync();@@ -378,6 +398,43 @@ describe("contacts device sync", () => {).toBe("confirmed");});+ it("大量确认凭据仍按冲突 key 线性索引并保留确认状态", () => {+ const a = createStore();+ const b = createStore();+ a.activateDeviceSync();+ b.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 state = stateOf(a);+ const contact = state.contacts.find((entry) => entry.id === aContact.id)!;+ const acknowledgement = contact.status.acknowledgedConflicts![0]!;+ contact.status.acknowledgedConflicts = [+ ...Array.from({ length: 50_000 }, (_, index) => ({+ platform: "custom",+ normalizedValue: `unrelated-${index}`,+ membershipHash: index.toString(16).padStart(64, "0"),+ })),+ acknowledgement,+ ];++ expect(+ materializeContactsSyncState(state).contacts.find(+ (entry) => entry.id === aContact.id,+ )!.status,+ ).toBe("confirmed");+ });+it("清理同 owner 重复 identity 不撤销确认", () => {const a = createStore();const b = createStore();diff --git a/packages/maker-core/src/contacts/sync/materialize.ts b/packages/maker-core/src/contacts/sync/materialize.tsindex b814ad85d3..b58a5b0687 100644--- a/packages/maker-core/src/contacts/sync/materialize.ts+++ b/packages/maker-core/src/contacts/sync/materialize.ts@@ -16,6 +16,7 @@ import {type ContactsSnapshotIdentity,type ContactsSnapshotMembership,type ContactsSnapshotRelation,+ type ContactsSyncConflictMembership,type ContactsSyncEntity,type ContactsSyncState,} from "./types.js";@@ -90,9 +91,22 @@ export function materializeContactsSyncState(const contactsById = new Map(contacts.map((contact) => [contact.id, contact]),);- const contactRecordsById = new Map(- state.contacts.map((contact) => [contact.id, contact]),- );+ const acknowledgementsByContactId = new Map<+ string,+ Map<string, ContactsSyncConflictMembership>+ >();+ for (const contact of state.contacts) {+ const acknowledgements = contact.status.acknowledgedConflicts;+ if (!acknowledgements || acknowledgements.length === 0) continue;+ const byConflictKey = new Map<string, ContactsSyncConflictMembership>();+ for (const acknowledgement of acknowledgements) {+ byConflictKey.set(+ `${acknowledgement.platform}\u0000${acknowledgement.normalizedValue}`,+ acknowledgement,+ );+ }+ acknowledgementsByContactId.set(contact.id, byConflictKey);+ }const contactIds = new Set(contacts.map((contact) => contact.id));// contact_groups.name 的 UNIQUE 与 ContactsGroupsRepo 都是精确字符串语义;@@ -124,16 +138,13 @@ export function materializeContactsSyncState(// Lamport stamp 只提供确定性全序,不能证明确认写入见过某个离线成员。// 只有确认记录的成员指纹与当前冲突完全一致,才保留 confirmed。for (const conflict of conflicts) {+ const conflictKey = `${conflict.platform}\u0000${conflict.normalizedValue}`;for (const contactId of conflict.owners) {const contact = contactsById.get(contactId);if (!contact) continue;- const acknowledgement = contactRecordsById+ const acknowledgement = acknowledgementsByContactId.get(contactId)- ?.status.acknowledgedConflicts?.find(- (membership) =>- membership.platform === conflict.platform &&- membership.normalizedValue === conflict.normalizedValue,- );+ ?.get(conflictKey);if (contact.status === "confirmed" &&acknowledgement?.membershipHash === conflict.membershipHashdiff --git a/packages/maker-core/src/contacts/sync/merge.ts b/packages/maker-core/src/contacts/sync/merge.tsindex fda79c1419..17b7a801ae 100644--- a/packages/maker-core/src/contacts/sync/merge.ts+++ b/packages/maker-core/src/contacts/sync/merge.ts@@ -21,23 +21,75 @@ export function compareContactsSyncText(a: string, b: string): number {return a < b ? -1 : a > b ? 1 : 0;}-/** JSON-compatible serialization with recursively sorted object keys. */+const MAX_STABLE_JSON_NODES = 100_000;++/**+ * JSON-compatible serialization with sorted object keys.+ *+ * This is deliberately iterative: stamped values may carry unknown extension+ * fields from a newer client, and a deeply nested extension must not overflow+ * the codec worker's call stack. The node budget keeps malformed cyclic or+ * unexpectedly broad values bounded while preserving deterministic ordering for+ * normal JSON-shaped sync data.+ */export function stableContactsSyncJson(value: unknown): string {- if (value === null || typeof value !== "object") {- return JSON.stringify(value) ?? "null";- }- if (Array.isArray(value)) {- return `[${value.map((entry) => stableContactsSyncJson(entry)).join(",")}]`;+ type Frame =+ | { kind: "value"; value: unknown }+ | { kind: "text"; text: string };++ const output: string[] = [];+ const stack: Frame[] = [{ kind: "value", value }];+ const seen = new WeakSet<object>();+ let nodes = 0;++ while (stack.length > 0) {+ const frame = stack.pop()!;+ if (frame.kind === "text") {+ output.push(frame.text);+ continue;+ }++ nodes += 1;+ if (nodes > MAX_STABLE_JSON_NODES) {+ output.push('"[truncated]"');+ continue;+ }++ const current = frame.value;+ if (current === null || typeof current !== "object") {+ output.push(JSON.stringify(current) ?? "null");+ continue;+ }+ if (seen.has(current)) {+ output.push('"[circular]"');+ continue;+ }+ seen.add(current);++ if (Array.isArray(current)) {+ output.push("[");+ stack.push({ kind: "text", text: "]" });+ for (let index = current.length - 1; index >= 0; index -= 1) {+ stack.push({ kind: "value", value: current[index] });+ if (index > 0) stack.push({ kind: "text", text: "," });+ }+ continue;+ }++ const keys = Object.keys(current)+ .filter((key) => current[key] !== undefined)+ .sort(compareContactsSyncText);+ output.push("{");+ stack.push({ kind: "text", text: "}" });+ for (let index = keys.length - 1; index >= 0; index -= 1) {+ const key = keys[index]!;+ stack.push({ kind: "value", value: current[key] });+ stack.push({ kind: "text", text: `:${JSON.stringify(key)}` });+ if (index > 0) stack.push({ kind: "text", text: "," });+ }}- const record = value as Record<string, unknown>;- const keys = Object.keys(record)- .filter((key) => record[key] !== undefined)- .sort(compareContactsSyncText);- return `{${keys- .map(- (key) => `${JSON.stringify(key)}:${stableContactsSyncJson(record[key])}`,- )- .join(",")}}`;++ return output.join("");}export function compareContactsSyncStamp(