import Database from "better-sqlite3"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { CANONICAL_PUBLIC_KEY } from "./coordinator-ed25519-key-id-test-fixtures.js"; import { recordProjectBoundaryMigration } from "./project-boundary-migration-records.js"; import { refreshTestScopeRows } from "./scope-membership-cache-test-fixtures.js"; import { prepareScopeServingStore } from "./scope-serving-proof-store.js"; import { SecretScanner } from "./secret-scanner.js"; import * as syncAuth from "./sync-auth.js"; import type { RequestJsonExecutor } from "./sync-http-client.js"; import * as http from "./sync-http-client.js"; import * as identity from "./sync-identity.js"; import { syncOnce } from "./sync-pass.js"; import { applyReplicationOps, getReplicationCursor, setReplicationCursor, } from "./sync-replication.js"; import { initTestSchema, insertTestSession } from "./test-utils.js"; import type { ReplicationOp } from "./types.js"; /* * A transitioned group's scopes transfer only while this device's window is * open. A closed window is a pause: the device sends no scoped request, applies * nothing that arrives, and keeps its cursors and baselines for the next pass. */ const LOCAL = "window-local"; const PEER = "window-peer"; const FINGERPRINT = "window-fingerprint"; const SHARED = "window-shared"; const T = "2026-01-01T00:00:00Z"; const BASELINE = `${T}|baseline`; const BOUNDARY = { generation: 1, snapshot_id: "window-snapshot", baseline_cursor: BASELINE, retained_floor_cursor: null, }; const BASE_URL = "http://window.example.test:47337"; const HOUR = 60 * 60_000; let db: InstanceType; let monotonic = 1_000_000; /** Moves the wall clock and this process's monotonic clock forward together. */ function elapse(ms: number) { vi.setSystemTime(new Date(Date.now() + ms)); monotonic += ms; } beforeEach(async () => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(new Date("2026-11-02T12:00:00Z")); monotonic = 1_000_000; vi.spyOn(performance, "now").mockImplementation(() => monotonic); db = new Database(":memory:"); initTestSchema(db); vi.spyOn(identity, "ensureDeviceIdentity").mockReturnValue([LOCAL, "ed25519 fixture"]); vi.spyOn(syncAuth, "buildDirectPeerAuthHeaders").mockReturnValue({}); vi.spyOn(http, "requestJson").mockImplementation(async () => { throw new Error("unexpected_default_http"); }); db.prepare( "INSERT INTO sync_device(device_id, public_key, fingerprint, created_at) VALUES (?, ?, 'fp-local', ?)", ).run(LOCAL, CANONICAL_PUBLIC_KEY, T); db.prepare( "INSERT INTO sync_peers(peer_device_id, public_key, pinned_fingerprint, created_at) VALUES (?, ?, ?, ?)", ).run(PEER, CANONICAL_PUBLIC_KEY, FINGERPRINT, T); db.prepare(`INSERT INTO replication_scopes(scope_id, label, kind, authority_type, coordinator_id, group_id, membership_epoch, status, created_at, updated_at) VALUES (?, ?, 'team', 'coordinator', 'coordinator-1', 'group-1', 1, 'active', ?, ?)`).run( SHARED, SHARED, T, T, ); for (const deviceId of [LOCAL, PEER]) db.prepare(`INSERT INTO scope_memberships(scope_id, device_id, role, status, membership_epoch, updated_at) VALUES (?, ?, 'member', 'active', 1, ?)`).run(SHARED, deviceId, T); setReplicationCursor(db, PEER, { lastApplied: BASELINE, lastAcked: BASELINE }); prepareScopeServingStore( db, { coordinatorId: "coordinator-1", groupId: "group-1", generation: "ddc460b1-6dd8-4489-ab5c-799c2319af62", }, [], ); await refreshTestScopeRows(db, {}, { now: new Date() }); }); afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); db.close(); }); function peerOp(id: string, scopeId = SHARED, createdAt = "2026-01-02T00:00:00Z"): ReplicationOp { return { op_id: id, entity_type: "memory_item", entity_id: `${id}-memory`, op_type: "upsert", payload_json: JSON.stringify({ kind: "discovery", title: `Peer ${id}`, body_text: "Peer content", visibility: "shared", scope_id: scopeId, }), clock_rev: 5, clock_updated_at: createdAt, clock_device_id: PEER, device_id: PEER, created_at: createdAt, scope_id: scopeId, }; } interface PeerAnswers { /** The scopes the peer lists. Defaults to SHARED. */ scopes?: string[]; scopedOps?: ReplicationOp[]; /** Scoped ops for scopes other than SHARED. */ opsByScope?: Record; /** Ops of the peer's default stream, which can carry any scope. */ defaultOps?: ReplicationOp[]; /** Serve the snapshot in two pages. */ twoPages?: boolean; snapshotItems?: unknown[]; /** Runs while the peer serves a snapshot page, before anything is applied. */ duringSnapshot?: () => void; /** The scoped boundary the peer's status names for an initial bootstrap. */ statusResetScope?: string; /** The default pull answers with a reset to this scoped boundary. */ defaultResetScope?: string; /** The peer's own window closes: it pauses SHARED's scoped ops, or a snapshot's second page. */ peerPauses?: "scoped-ops" | "second-page"; } const PAUSED_REPLY: Reply = [503, { error: "transfer_paused" }]; type Reply = Awaited>; function statusReply(answers: PeerAnswers): Reply { return [ 200, { fingerprint: FINGERPRINT, protocol_version: "2", sync_capability: "scoped", sync_reset: { ...BOUNDARY, scope_id: answers.statusResetScope ?? null }, authorized_scopes: (answers.scopes ?? [SHARED]).map((id) => ({ scope_id: id, label: id, authority_type: "coordinator", membership_epoch: 1, sync_reset: { ...BOUNDARY, scope_id: id }, })), }, ]; } function snapshotReply( answers: PeerAnswers, scopeId: string | null, pageToken: string | null, ): Reply { answers.duringSnapshot?.(); const first = answers.twoPages === true && !pageToken; return [ 200, { ...BOUNDARY, scope_id: scopeId, reset_required: false, skipped: 0, items: answers.snapshotItems ?? [], has_more: first, next_page_token: first ? "page-2" : null, }, ]; } function opsReply(answers: PeerAnswers, scopeId: string | null): Reply { if (answers.defaultResetScope && !scopeId) return [ 409, { ...BOUNDARY, reset_required: true, reason: "stale_cursor", scope_id: answers.defaultResetScope, }, ]; const scoped = scopeId === SHARED ? answers.scopedOps : answers.opsByScope?.[scopeId ?? ""]; const ops = (scopeId ? scoped : answers.defaultOps) ?? []; const last = ops.at(-1); return [ 200, { ...BOUNDARY, scope_id: scopeId, reset_required: false, skipped: 0, ops, next_cursor: last ? `${last.created_at}|${last.op_id}` : null, }, ]; } /** A peer whose own window is open: it lists the scope and serves it. */ function peer(answers: PeerAnswers, requests: string[]): RequestJsonExecutor { return async (method, url) => { const { pathname, searchParams } = new URL(url); const scopeId = searchParams.get("scope_id"); requests.push(`${method} ${pathname}${scopeId ? `?scope_id=${scopeId}` : ""}`); if (pathname === "/v1/status") return statusReply(answers); if (method === "POST") return [200, { applied: 0, skipped: 0, errors: [] }]; if (pathname === "/v1/snapshot") { if (answers.peerPauses === "second-page" && searchParams.get("page_token")) return PAUSED_REPLY; return snapshotReply(answers, scopeId, searchParams.get("page_token")); } if (answers.peerPauses === "scoped-ops" && scopeId === SHARED) return PAUSED_REPLY; return opsReply(answers, scopeId); }; } async function pull(answers: PeerAnswers) { const requests: string[] = []; const result = await syncOnce(db, PEER, [BASE_URL], { requestExecutor: peer(answers, requests), scanner: new SecretScanner(), }); return { result, requests }; } function grant(scopeId: string, groupId: string) { db.prepare(`INSERT INTO replication_scopes(scope_id, label, kind, authority_type, coordinator_id, group_id, membership_epoch, status, created_at, updated_at) VALUES (?, ?, 'team', 'coordinator', 'coordinator-1', ?, 1, 'active', ?, ?)`).run( scopeId, scopeId, groupId, T, T, ); for (const deviceId of [LOCAL, PEER]) db.prepare(`INSERT INTO scope_memberships(scope_id, device_id, role, status, membership_epoch, updated_at) VALUES (?, ?, 'member', 'active', 1, ?)`).run(scopeId, deviceId, T); } const memories = () => db .prepare("SELECT title FROM memory_items WHERE scope_id = ? ORDER BY title") .pluck() .all(SHARED); /** A pass whose only effect was pausing SHARED: not a failure, and SHARED reported as paused. */ function expectPausedPass(result: Awaited>["result"]) { expect(result.ok, JSON.stringify(result)).toBe(true); expect(result.error).toBeUndefined(); expect(result.perScopeResults?.find((scope) => scope.scope_id === SHARED)).toMatchObject({ paused: true, error: "transfer_paused", }); } const scopedRequests = (requests: string[]) => requests.filter((request) => request.includes(`scope_id=${SHARED}`)); describe("a caught-up receiver whose window closed", () => { beforeEach(() => { setReplicationCursor(db, PEER, { lastApplied: BASELINE, lastAcked: BASELINE }, SHARED); }); it("does not pull a fresh peer's new memories, and keeps its cursor", async () => { elapse(HOUR + 60_000); const { requests } = await pull({ scopedOps: [peerOp("after-window")] }); expect(scopedRequests(requests)).toEqual([]); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER, SHARED)).toEqual([BASELINE, BASELINE]); }); it("continues from its cursor after a verified refresh", async () => { elapse(HOUR + 60_000); await pull({ scopedOps: [peerOp("after-window")] }); await refreshTestScopeRows(db, {}, { now: new Date() }); const { requests } = await pull({ scopedOps: [peerOp("after-window")] }); expect(scopedRequests(requests)).toContain(`GET /v1/ops?scope_id=${SHARED}`); expect(memories()).toEqual(["Peer after-window"]); expect(getReplicationCursor(db, PEER, SHARED)[0]).toBe("2026-01-02T00:00:00Z|after-window"); }); }); describe("a receiver with no progress in the scope", () => { it("requests no snapshot while its window is closed", async () => { elapse(HOUR + 60_000); const { requests } = await pull({ snapshotItems: [{ entity_id: "unused" }] }); expect(scopedRequests(requests)).toEqual([]); expect(memories()).toEqual([]); }); }); describe("a snapshot whose scoped boundary the peer names in a direct reply", () => { const item = { entity_id: "named-key", op_type: "upsert", payload_json: JSON.stringify({ kind: "discovery", title: "Named memory", body_text: "Named body", active: 1, created_at: T, updated_at: T, scope_id: SHARED, visibility: "shared", }), clock_rev: 1, clock_updated_at: T, clock_device_id: PEER, }; const snapshotRequests = (requests: string[]) => requests.filter((request) => request.startsWith("GET /v1/snapshot")); it("starts no initial bootstrap of it while this device's window is closed", async () => { for (const table of ["replication_cursors", "replication_cursors_v2"]) db.prepare(`DELETE FROM ${table} WHERE peer_device_id = ?`).run(PEER); elapse(HOUR + 60_000); const { requests } = await pull({ statusResetScope: SHARED, snapshotItems: [item] }); expect(snapshotRequests(requests)).toEqual([]); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER)).toEqual([null, null]); }); it("starts no reset bootstrap of it while this device's window is closed", async () => { elapse(HOUR + 60_000); const { requests } = await pull({ defaultResetScope: SHARED, snapshotItems: [item] }); expect(snapshotRequests(requests)).toEqual([]); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER)).toEqual([BASELINE, BASELINE]); }); it("requests no further page and applies nothing once the window closes mid-download", async () => { db.prepare("DELETE FROM replication_cursors WHERE peer_device_id = ?").run(PEER); db.prepare("DELETE FROM replication_cursors_v2 WHERE peer_device_id = ?").run(PEER); const { result, requests } = await pull({ statusResetScope: SHARED, snapshotItems: [item], twoPages: true, duringSnapshot: () => elapse(HOUR + 60_000), }); expect(snapshotRequests(requests)).toHaveLength(1); expectPausedPass(result); expect(memories()).toEqual([]); }); it("requests no further page of a reset snapshot once the window closes mid-download", async () => { const { result, requests } = await pull({ defaultResetScope: SHARED, snapshotItems: [item], twoPages: true, duringSnapshot: () => elapse(HOUR + 60_000), }); expect(snapshotRequests(requests)).toHaveLength(1); expectPausedPass(result); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER)).toEqual([BASELINE, BASELINE]); }); it("applies nothing from a one-page snapshot when the window closes during it", async () => { db.prepare("DELETE FROM replication_cursors WHERE peer_device_id = ?").run(PEER); db.prepare("DELETE FROM replication_cursors_v2 WHERE peer_device_id = ?").run(PEER); const { result } = await pull({ statusResetScope: SHARED, snapshotItems: [item], duringSnapshot: () => elapse(HOUR + 60_000), }); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER)).toEqual([null, null]); // The write's refusal is the pause, as when the window closes before a page. expectPausedPass(result); }); it("applies nothing from a one-page reset snapshot when the window closes during it", async () => { const { result } = await pull({ defaultResetScope: SHARED, snapshotItems: [item], duringSnapshot: () => elapse(HOUR + 60_000), }); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER)).toEqual([BASELINE, BASELINE]); expectPausedPass(result); }); it("bootstraps it once a verified refresh opens the window", async () => { for (const table of ["replication_cursors", "replication_cursors_v2"]) db.prepare(`DELETE FROM ${table} WHERE peer_device_id = ?`).run(PEER); await pull({ statusResetScope: SHARED, snapshotItems: [item] }); expect(memories()).toEqual(["Named memory"]); }); }); describe("a window that closes while a transfer is in flight", () => { const snapshotItem = { entity_id: "snapshot-key", op_type: "upsert", payload_json: JSON.stringify({ kind: "discovery", title: "Snapshot memory", body_text: "Snapshot body", active: 1, created_at: T, updated_at: T, scope_id: SHARED, visibility: "shared", }), clock_rev: 1, clock_updated_at: T, clock_device_id: PEER, }; it("applies the snapshot while the window stays open", async () => { await pull({ snapshotItems: [snapshotItem] }); expect(memories()).toEqual(["Snapshot memory"]); }); it("applies nothing from the snapshot and keeps the scope's baseline", async () => { const before = getReplicationCursor(db, PEER, SHARED); const { result } = await pull({ snapshotItems: [snapshotItem], duringSnapshot: () => elapse(HOUR + 60_000), }); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER, SHARED)).toEqual(before); // The write's refusal is the scope's pause, which does not fail the pass. expect(result.ok, JSON.stringify(result)).toBe(true); expect(result.perScopeResults?.find((scope) => scope.scope_id === SHARED)).toMatchObject({ paused: true, }); }); it("merges nothing into a scope it already holds rows in, and pauses it", async () => { db.prepare("DELETE FROM replication_cursors_v2 WHERE peer_device_id = ? AND scope_id = ?").run( PEER, SHARED, ); db.prepare(`INSERT INTO memory_items(session_id, kind, title, body_text, confidence, active, created_at, updated_at, metadata_json, rev, visibility, scope_id, import_key) VALUES (?, 'discovery', 'Local memory', 'Local body', 1, 1, ?, ?, '{}', 1, 'shared', ?, 'local-key')`).run(insertTestSession(db), T, T, SHARED); const { result } = await pull({ snapshotItems: [snapshotItem], duringSnapshot: () => elapse(HOUR + 60_000), }); expect(memories()).toEqual(["Local memory"]); expect(result.ok, JSON.stringify(result)).toBe(true); expect(result.perScopeResults?.find((scope) => scope.scope_id === SHARED)).toMatchObject({ paused: true, }); }); it("applies no operations that arrived after it closed", () => { elapse(HOUR + 60_000); expect(() => applyReplicationOps(db, [peerOp("arrived")], LOCAL, undefined, { inboundScopeValidation: { peerDeviceId: PEER, pinnedFingerprint: FINGERPRINT }, }), ).toThrow("transfer_paused"); expect(memories()).toEqual([]); }); }); describe("a snapshot of a scope whose group has not transitioned", () => { const OLD = "window-old"; const NEW = "window-new"; it("still replaces a copy held in a transitioned group's scope after that window closed", async () => { // Arrange: a Project moved from OLD, in the transitioned group, to NEW in another // group. This device holds the older copy, and the peer is proven in both scopes. grant(OLD, "group-1"); grant(NEW, "group-2"); await refreshTestScopeRows(db, {}, { now: new Date() }); recordProjectBoundaryMigration(db, { boundaryScopeId: NEW, sourceScopeId: OLD, state: "committed", generation: 1, now: T, }); const session = db .prepare("INSERT INTO sessions(started_at, project) VALUES (?, 'fixture')") .run(T).lastInsertRowid; db.prepare(`INSERT INTO memory_items(session_id, kind, title, body_text, confidence, tags_text, active, created_at, updated_at, metadata_json, import_key, origin_device_id, rev, visibility, scope_id) VALUES (?, 'discovery', 'Held', 'Held body', 0.5, '', 1, ?, ?, '{}', 'moved-key', ?, 1, 'shared', ?)`).run(session, T, T, PEER, OLD); elapse(HOUR + 60_000); // Act: the peer serves NEW, whose transfers do not depend on OLD's window. await pull({ scopes: [NEW], snapshotItems: [ { entity_id: "moved-key", op_type: "upsert", payload_json: JSON.stringify({ kind: "discovery", title: "Moved memory", body_text: "Moved body", active: 1, created_at: T, updated_at: "2026-01-03T00:00:00Z", scope_id: NEW, visibility: "shared", }), clock_rev: 2, clock_updated_at: "2026-01-03T00:00:00Z", clock_device_id: PEER, }, ], }); // Assert: the closed window did not hold the item back while its boundary advanced. expect( db.prepare("SELECT title, scope_id FROM memory_items WHERE import_key = 'moved-key'").all(), ).toEqual([{ title: "Moved memory", scope_id: NEW }]); }); }); describe("one paused Project among others in a pass", () => { const NEW = "window-new"; it("applies the other Projects, holds the paused one, and does not fail the pass", async () => { grant(NEW, "group-2"); await refreshTestScopeRows(db, {}, { now: new Date() }); setReplicationCursor(db, PEER, { lastApplied: BASELINE, lastAcked: BASELINE }, SHARED); setReplicationCursor(db, PEER, { lastApplied: BASELINE, lastAcked: BASELINE }, NEW); elapse(HOUR + 60_000); const { result } = await pull({ scopes: [SHARED, NEW], // The default stream carries the paused Project's op ahead of the other's. defaultOps: [ peerOp("default-paused", SHARED, "2026-01-02T00:00:01Z"), peerOp("default-other", NEW, "2026-01-02T00:00:02Z"), ], scopedOps: [peerOp("scoped-paused")], opsByScope: { [NEW]: [peerOp("scoped-other", NEW)] }, }); expect(result.ok, JSON.stringify(result)).toBe(true); expect(result.error).toBeUndefined(); expect( db .prepare("SELECT title FROM memory_items WHERE scope_id = ? ORDER BY title") .pluck() .all(NEW), ).toEqual(["Peer default-other", "Peer scoped-other"]); expect(memories()).toEqual([]); // The default cursor stays before the held op, and the paused scope keeps its cursor. expect(getReplicationCursor(db, PEER)[0]).toBe(BASELINE); expect(getReplicationCursor(db, PEER, SHARED)).toEqual([BASELINE, BASELINE]); }); }); describe("a peer whose own window closed", () => { const snapshotItem = { entity_id: "peer-paused-key", op_type: "upsert", payload_json: JSON.stringify({ kind: "discovery", title: "Peer paused memory", body_text: "Peer paused body", active: 1, created_at: T, updated_at: T, scope_id: SHARED, visibility: "shared", }), clock_rev: 1, clock_updated_at: T, clock_device_id: PEER, }; const sharedResult = (result: Awaited>["result"]) => result.perScopeResults?.find((scope) => scope.scope_id === SHARED); it("pauses the scope's pull without failing the pass, and keeps its cursor", async () => { setReplicationCursor(db, PEER, { lastApplied: BASELINE, lastAcked: BASELINE }, SHARED); const { result } = await pull({ scopedOps: [peerOp("unused")], peerPauses: "scoped-ops" }); expect(result.ok, JSON.stringify(result)).toBe(true); expect(result.error).toBeUndefined(); expect(sharedResult(result)).toMatchObject({ paused: true, error: "transfer_paused" }); expect(getReplicationCursor(db, PEER, SHARED)).toEqual([BASELINE, BASELINE]); }); it("pauses a scope's snapshot between pages without failing the pass", async () => { const before = getReplicationCursor(db, PEER, SHARED); const { result } = await pull({ snapshotItems: [snapshotItem], twoPages: true, peerPauses: "second-page", }); expect(result.ok, JSON.stringify(result)).toBe(true); expect(sharedResult(result)).toMatchObject({ paused: true }); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER, SHARED)).toEqual(before); }); it("pauses a direct bootstrap between pages and changes nothing", async () => { for (const table of ["replication_cursors", "replication_cursors_v2"]) db.prepare(`DELETE FROM ${table} WHERE peer_device_id = ?`).run(PEER); const { result } = await pull({ statusResetScope: SHARED, snapshotItems: [snapshotItem], twoPages: true, peerPauses: "second-page", }); expectPausedPass(result); expect(memories()).toEqual([]); expect(getReplicationCursor(db, PEER)).toEqual([null, null]); }); }); describe("a peer's move retraction from a paused scope", () => { const NEW = "window-new"; const KEY = "retracted-key"; const retraction: ReplicationOp = { op_id: "retraction-1", entity_type: "memory_item", entity_id: KEY, op_type: "reassign_scope", payload_json: JSON.stringify({ operation_id: "move-1", memory_id: KEY, old_scope_id: SHARED, new_scope_id: NEW, side: "old", revision: 2, }), clock_rev: 2, clock_updated_at: "2026-01-02T00:00:00Z", clock_device_id: PEER, device_id: PEER, created_at: "2026-01-02T00:00:00Z", scope_id: SHARED, }; const held = () => db.prepare("SELECT scope_id, active FROM memory_items WHERE import_key = ?").all(KEY); beforeEach(async () => { grant(NEW, "group-2"); await refreshTestScopeRows(db, {}, { now: new Date() }); db.prepare(`INSERT INTO memory_items(session_id, kind, title, body_text, confidence, active, created_at, updated_at, metadata_json, rev, visibility, scope_id, import_key, origin_device_id) VALUES (?, 'discovery', 'Peer memory', 'Peer body', 1, 1, ?, ?, '{}', 1, 'shared', ?, ?, ?)`).run( insertTestSession(db), T, T, SHARED, KEY, PEER, ); }); it("removes this device's copy while the window is open", async () => { await pull({ defaultOps: [retraction] }); expect(held()).toEqual([{ scope_id: SHARED, active: 0 }]); }); it("keeps this device's copy and the cursor while the window is closed", async () => { elapse(HOUR + 60_000); const { result } = await pull({ defaultOps: [retraction] }); expect(result.ok, JSON.stringify(result)).toBe(true); expect(held()).toEqual([{ scope_id: SHARED, active: 1 }]); expect(getReplicationCursor(db, PEER)[0]).toBe(BASELINE); }); }); describe("an empty store's first sync", () => { it("does not fail when a scope the peer advertises pauses after the default bootstrap", async () => { // Arrange: no progress with the peer, and this device's window has closed. for (const table of ["replication_cursors", "replication_cursors_v2"]) db.prepare(`DELETE FROM ${table} WHERE peer_device_id = ?`).run(PEER); elapse(HOUR + 60_000); // Act: the peer names the default boundary, then advertises SHARED. const { result, requests } = await pull({ snapshotItems: [] }); // Assert: the default bootstrap ran, SHARED waited, and the pass is not a failure. expect(requests).toContain("GET /v1/snapshot"); expect(scopedRequests(requests)).toEqual([]); expectPausedPass(result); }); });