{"version":3,"sources":["../../src/offline/index.ts","../../src/offline/mirror.ts","../../src/offline/dataSource.ts"],"sourcesContent":["// src/offline/index.ts — @ai-matrx/records/offline\n//\n// A device copy of a Table's records with an offline queue, over the store's own doors. THE MIRROR\n// STAND-IN until data sync (`@ai-matrx/data/sync`) serves custom records: see ./mirror.ts.\n\nimport type { RecordsClient } from \"../core/client\";\nimport type { MirrorDoors } from \"./mirror\";\n\nexport * from \"./mirror\";\nexport * from \"./dataSource\";\n\n/** How many records one pull page asks for. */\nconst PAGE = 200; // internal-bound: the keyset door's page ceiling is higher; one page per round trip\n\n/** The mirror's five doors, from the package's own client (supabase-js under row security). */\nexport function mirrorDoorsFrom(client: Pick<RecordsClient, \"listKeyset\" | \"recordRead\" | \"recordWriteMany\" | \"recordUpdate\" | \"recordUpdateAddingChoices\" | \"recordDelete\">): MirrorDoors {\n  return {\n    async page(tableId, after) {\n      const res = await client.listKeyset({ table_id: tableId, after, limit: PAGE });\n      if (!res.ok) return res;\n      return { ok: true, data: { rows: res.data.rows.map((r) => ({ id: r.id, document: r.document, version: r.version })), cursor: res.data.cursor } };\n    },\n    async read(recordId) {\n      const res = await client.recordRead({ record_id: recordId, withVersion: true });\n      if (!res.ok) return res;\n      return { ok: true, data: { document: res.data.document, version: res.data.version ?? null } };\n    },\n    create: (tableId, id, data) => client.recordWriteMany({ table_id: tableId, rows: [data], ids: [id] }),\n    update: (recordId, patch, expectedVersion, add) =>\n      add && Object.keys(add).length > 0\n        ? client.recordUpdateAddingChoices({ record_id: recordId, patch, add, ...(expectedVersion === null ? {} : { expectedVersion }) })\n        : client.recordUpdate({ record_id: recordId, patch, ...(expectedVersion === null ? {} : { expectedVersion }) }),\n    remove: (recordId) => client.recordDelete({ record_id: recordId }),\n  };\n}\n","// src/offline/mirror.ts — @ai-matrx/records/offline\n//\n// A COPY OF A TABLE'S RECORDS KEPT ON THIS DEVICE, AND THE QUEUE THAT TAKES ITS EDITS UP.\n//\n// 🚨 THIS IS THE MIRROR STAND-IN. The platform's adopted offline engine is data sync (PowerSync +\n// TanStack DB, `@ai-matrx/data/sync`, common-docs projects/matrx-2/data-sync.md). Until it serves\n// custom records, this file keeps a device copy through the store's own doors (supabase-js under\n// row security, never a table) and says so: every status it answers carries `stand_in`.\n//\n// What it refuses to do, each one a lesson of Matrx Local's per-table engines (MXL-D-074: 2,600+\n// cloud notes deleted):\n//\n// 1. ABSENCE IS NOT A DELETE UNTIL THE BREAKER SAYS SO. A pull that would drop more copies than\n//    the mass-delete breaker allows (the same three knobs file sync uses: floor, ratio, max) drops\n//    none of them and says how many it held.\n// 2. A QUEUE OF DELETES OVER THE BREAKER IS HELD. Nothing is archived in the cloud until the person\n//    approves the batch; discarding it restores every copy.\n// 3. AN EDIT IS NEVER LAST-WRITER-WINS. Each queued change remembers the copy it was made against.\n//    Before it goes up the current record is read: fields nobody else touched merge silently; a\n//    field both devices changed differently is a conflict that keeps BOTH copies, and nothing is\n//    written until the person picks. The write itself carries the version just read, so a third\n//    writer in between is a stale write, re-read, never an overwrite.\n// 4. A NEW RECORD'S ID IS MINTED ON THE DEVICE. A lost acknowledgement replays the same id and the\n//    store answers \"already exists\": landed, never a second record.\n// 5. OFFLINE STOPS THE PASS, KEEPS THE QUEUE. `unreachable` is not a refusal; a refusal is not a\n//    retry (it stays, with the store's own sentence, until the person acts).\n\nimport type { RecordsError, RecordsResult } from \"../results\";\n\nexport type Doc = Record<string, unknown>;\n\n/** The five doors the mirror uses, narrowed so a test can stand in for the store exactly. */\nexport interface MirrorDoors {\n  /** One keyset page of the table (`custom.read_records_keyset`), each row with its version. */\n  page(tableId: string, after: string | null): Promise<RecordsResult<{ rows: Array<{ id: string; document: Doc; version: number | null }>; cursor: string | null }>>;\n  /** One record and the version it was read at (`custom.read_record`). */\n  read(recordId: string): Promise<RecordsResult<{ document: Doc; version: number | null }>>;\n  /** A new record with the device-minted id (`custom.record_write_many` with `ids`). */\n  create(tableId: string, id: string, data: Doc): Promise<RecordsResult<unknown>>;\n  /** An edit conditional on the version just read (`custom.record_update`). Answers the new version. */\n  /** `add`: new choices the patch's values need, added to their columns in the same write (`record_update_adding_choices`). */\n  update(recordId: string, patch: Doc, expectedVersion: number | null, add?: ChoiceAdds): Promise<RecordsResult<number>>;\n  /** Archive (`custom.record_delete`; restorable, never a hard delete). */\n  remove(recordId: string): Promise<RecordsResult<unknown>>;\n}\n\nexport type MirrorRowState = \"synced\" | \"pending\" | \"conflict\" | \"refused\";\n\nexport interface MirrorRow {\n  table_id: string;\n  id: string;\n  /** What this device shows: the cloud copy with this device's waiting changes on top. */\n  document: Doc;\n  /** The cloud copy this device last agreed with (null: never reached the cloud). */\n  base: Doc | null;\n  base_version: number | null;\n  state: MirrorRowState;\n  /** In conflict: the cloud's copy now (null: archived in the cloud while this device edited it). */\n  theirs: Doc | null;\n  theirs_version: number | null;\n  /** Archived on this device, waiting to go up. The copy stays until the cloud agrees. */\n  deleted: boolean;\n  updated_at: string;\n}\n\nexport type MirrorOpKind = \"create\" | \"update\" | \"delete\";\n\n/** New choices a change needs, by column key (a person typed a value that is not a choice yet). */\nexport type ChoiceAdds = Record<string, string[]>;\n\n/**\n * Where an update op keeps the new choices it needs, inside its `data` (the store persists `data` as\n * it is). Never a field: a pass takes it off before the field merge and hands it to the door.\n */\nexport const OP_CHOICE_ADDS = \"$add_choices\";\nexport type MirrorOpState = \"waiting\" | \"held\" | \"approved\" | \"refused\" | \"conflict\";\n\nexport interface MirrorOp {\n  seq: number;\n  table_id: string;\n  record_id: string;\n  kind: MirrorOpKind;\n  /** create: the whole record; update: the changed fields; delete: null. */\n  data: Doc | null;\n  state: MirrorOpState;\n  /** The store's own sentence, for `refused`. */\n  error: string | null;\n  created_at: string;\n}\n\nexport interface MirrorTable {\n  table_id: string;\n  kept_at: string;\n  last_pull_at: string | null;\n  last_error: string | null;\n  /** Copies the last pull found gone from the cloud but held back by the breaker. */\n  pull_held: number;\n}\n\n/** Where the copy lives: SQLite on the desktop, memory in a test. Synchronous on purpose (one writer). */\nexport interface MirrorStore {\n  tables(): MirrorTable[];\n  table(tableId: string): MirrorTable | null;\n  putTable(t: MirrorTable): void;\n  dropTable(tableId: string): void;\n  rows(tableId: string): MirrorRow[];\n  row(tableId: string, id: string): MirrorRow | null;\n  putRow(r: MirrorRow): void;\n  dropRow(tableId: string, id: string): void;\n  ops(tableId: string): MirrorOp[];\n  /** Appends; answers the op with its seq. */\n  addOp(op: Omit<MirrorOp, \"seq\">): MirrorOp;\n  putOp(op: MirrorOp): void;\n  dropOp(seq: number): void;\n}\n\n/** The mass-delete breaker: the same three knobs, the same formula as file sync's planner. */\nexport interface MirrorBreaker {\n  floor: number;\n  ratio: number;\n  max: number;\n}\n\nexport function breakerLimit(b: MirrorBreaker, baseSize: number): number {\n  return Math.max(b.floor, Math.min(b.max, Math.floor(baseSize * b.ratio)));\n}\n\nexport type MirrorLog = (level: \"info\" | \"warn\" | \"error\", event: string, fields?: Record<string, unknown>) => void;\n\nexport interface RecordsMirrorOptions {\n  doors: MirrorDoors;\n  store: MirrorStore;\n  /** Read at every pass so a live knob change applies to the next one. */\n  breaker: () => MirrorBreaker;\n  log: MirrorLog;\n  now?: () => string;\n  mintId?: () => string;\n}\n\nexport interface MirrorPassReport {\n  table_id: string;\n  outcome: \"done\" | \"offline\" | \"failed\";\n  pulled: number;\n  pushed: number;\n  merged: number;\n  conflicts: number;\n  refused: number;\n  /** Deletes waiting for the person (queue over the breaker). */\n  held_deletes: number;\n  /** Copies gone from the cloud that the breaker kept on this device. */\n  held_removals: number;\n  error: string | null;\n}\n\nexport interface MirrorTableStatus extends MirrorTable {\n  stand_in: true;\n  records: number;\n  waiting: number;\n  conflicts: number;\n  refused: number;\n  held_deletes: number;\n}\n\nexport interface RecordsMirror {\n  keep(tableId: string): void;\n  /** Stops keeping a copy. Refused while changes are waiting unless `discard` (said in the answer). */\n  forget(tableId: string, opts?: { discard?: boolean }): { ok: true } | { ok: false; message: string };\n  list(tableId: string): MirrorRow[];\n  /** Every copy of a kept table, the ones deleted here and still waiting included. */\n  view(tableId: string): MirrorRow[];\n  /** `id`: a caller-chosen id (a door's `p_ids`); minted on the device otherwise. */\n  create(tableId: string, data: Doc, id?: string): string;\n  update(tableId: string, id: string, patch: Doc, add?: ChoiceAdds): void;\n  remove(tableId: string, id: string): void;\n  /**\n   * Brings back a record deleted on this device whose delete has not reached the store yet (held or\n   * waiting): the delete is dropped, the copy shows again. False when the copy holds no such delete\n   * (the store archived it already: restore it there).\n   */\n  restore(tableId: string, id: string): boolean;\n  /**\n   * Sends what is waiting for one table WITHOUT a pull: only the changed records are read (each\n   * update reads its own record, so the field merge and keep-both conflicts stand) and written; the\n   * delete breaker judges the queue as usual. Calls made while one runs share the next one, so a\n   * burst of edits goes up as one batch. Never throws.\n   */\n  flush(tableId: string): Promise<MirrorPassReport>;\n  /** Pull, then push, for one table or every kept one. Never throws. */\n  sync(tableId?: string): Promise<MirrorPassReport[]>;\n  /** The person approves the held deletes of a table; the next pass archives them. */\n  approveDeletes(tableId: string): number;\n  /** The person discards the held deletes: every copy is shown again, nothing goes up. */\n  discardDeletes(tableId: string): number;\n  /** The person picks a side of a conflict. `mine` re-queues this device's copy against theirs. */\n  resolve(tableId: string, id: string, keep: \"mine\" | \"theirs\"): void;\n  status(): MirrorTableStatus[];\n}\n\nconst same = (a: unknown, b: unknown): boolean => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);\n\nfunction errText(e: RecordsError): string {\n  return e.hint ? `${e.message} ${e.hint}` : e.message;\n}\n\nexport function createRecordsMirror(o: RecordsMirrorOptions): RecordsMirror {\n  const now = o.now ?? (() => new Date().toISOString());\n  const mintId = o.mintId ?? (() => globalThis.crypto.randomUUID());\n  const { store, doors } = o;\n  const running = new Map<string, Promise<MirrorPassReport>>();\n\n  const mustKeep = (tableId: string): void => {\n    if (!store.table(tableId)) throw new Error(`Table ${tableId} is not kept on this device.`);\n  };\n  const opsFor = (tableId: string, id: string): MirrorOp[] => store.ops(tableId).filter((op) => op.record_id === id);\n\n  const keep = (tableId: string): void => {\n    if (store.table(tableId)) return;\n    store.putTable({ table_id: tableId, kept_at: now(), last_pull_at: null, last_error: null, pull_held: 0 });\n    o.log(\"info\", \"records_mirror.kept\", { table_id: tableId });\n  };\n\n  const forget: RecordsMirror[\"forget\"] = (tableId, opts) => {\n    const waiting = store.ops(tableId).length;\n    if (waiting > 0 && !opts?.discard) return { ok: false, message: `${waiting} change${waiting === 1 ? \" is\" : \"s are\"} still waiting to reach the cloud.` };\n    for (const op of store.ops(tableId)) store.dropOp(op.seq);\n    for (const r of store.rows(tableId)) store.dropRow(tableId, r.id);\n    store.dropTable(tableId);\n    o.log(waiting > 0 ? \"warn\" : \"info\", \"records_mirror.forgotten\", { table_id: tableId, discarded: waiting });\n    return { ok: true };\n  };\n\n  const create = (tableId: string, data: Doc, given?: string): string => {\n    mustKeep(tableId);\n    const id = given ?? mintId();\n    store.putRow({ table_id: tableId, id, document: { ...data }, base: null, base_version: null, state: \"pending\", theirs: null, theirs_version: null, deleted: false, updated_at: now() });\n    store.addOp({ table_id: tableId, record_id: id, kind: \"create\", data: { ...data }, state: \"waiting\", error: null, created_at: now() });\n    return id;\n  };\n\n  const mergeAdds = (a: unknown, b: ChoiceAdds | undefined): ChoiceAdds | undefined => {\n    const out: ChoiceAdds = { ...((a as ChoiceAdds | undefined) ?? {}) };\n    for (const [k, v] of Object.entries(b ?? {})) out[k] = [...new Set([...(out[k] ?? []), ...v])];\n    return Object.keys(out).length ? out : undefined;\n  };\n\n  const update = (tableId: string, id: string, given: Doc, add?: ChoiceAdds): void => {\n    mustKeep(tableId);\n    // A CLEARED CELL IS null, NEVER undefined: the device store keeps JSON, and JSON drops an undefined\n    // key, so the change would reach the queue as no change at all (and go up as nothing).\n    const patch: Doc = Object.fromEntries(Object.entries(given).map(([k, v]) => [k, v === undefined ? null : v]));\n    const r = store.row(tableId, id);\n    if (!r || r.deleted) throw new Error(`Record ${id} is not in this device's copy.`);\n    store.putRow({ ...r, document: { ...r.document, ...patch }, state: r.state === \"conflict\" ? \"conflict\" : \"pending\", updated_at: now() });\n    // One waiting change per record: a later edit folds into it (a create stays a create).\n    const open = opsFor(tableId, id).find((op) => (op.kind === \"create\" || op.kind === \"update\") && op.state === \"waiting\");\n    const adds = mergeAdds(open?.data?.[OP_CHOICE_ADDS], add);\n    const data: Doc = { ...(open?.data ?? {}), ...patch };\n    if (adds && open?.kind !== \"create\") data[OP_CHOICE_ADDS] = adds;\n    if (open) store.putOp({ ...open, data });\n    else store.addOp({ table_id: tableId, record_id: id, kind: \"update\", data, state: \"waiting\", error: null, created_at: now() });\n  };\n\n  const remove = (tableId: string, id: string): void => {\n    mustKeep(tableId);\n    const r = store.row(tableId, id);\n    if (!r) return;\n    const ops = opsFor(tableId, id);\n    if (ops.some((op) => op.kind === \"create\")) {\n      // Never reached the cloud: nothing to archive there.\n      for (const op of ops) store.dropOp(op.seq);\n      store.dropRow(tableId, id);\n      return;\n    }\n    for (const op of ops) store.dropOp(op.seq);\n    store.putRow({ ...r, deleted: true, state: \"pending\", updated_at: now() });\n    store.addOp({ table_id: tableId, record_id: id, kind: \"delete\", data: null, state: \"waiting\", error: null, created_at: now() });\n  };\n\n  async function pull(tableId: string, report: MirrorPassReport): Promise<boolean> {\n    const seen = new Map<string, { document: Doc; version: number | null }>();\n    let after: string | null = null;\n    for (;;) {\n      const page = await doors.page(tableId, after);\n      if (!page.ok) {\n        report.outcome = page.error.code === \"unreachable\" ? \"offline\" : \"failed\";\n        report.error = errText(page.error);\n        return false;\n      }\n      for (const row of page.data.rows) seen.set(row.id, { document: row.document, version: row.version });\n      if (!page.data.cursor || page.data.rows.length === 0) break;\n      after = page.data.cursor;\n    }\n    const local = store.rows(tableId);\n    for (const [id, cloud] of seen) {\n      const r = store.row(tableId, id);\n      if (!r) {\n        store.putRow({ table_id: tableId, id, document: cloud.document, base: cloud.document, base_version: cloud.version, state: \"synced\", theirs: null, theirs_version: null, deleted: false, updated_at: now() });\n        report.pulled += 1;\n      } else if (r.state === \"synced\") {\n        // A PULL NEVER MOVES A COPY BACKWARDS: a page read before this device's own write landed\n        // answers an older version than the copy agreed at; the newer one stands.\n        if (r.base_version !== null && cloud.version !== null && cloud.version < r.base_version) continue;\n        if (!same(r.base, cloud.document) || r.base_version !== cloud.version) {\n          store.putRow({ ...r, document: cloud.document, base: cloud.document, base_version: cloud.version, updated_at: now() });\n          report.pulled += 1;\n        }\n      } else if (r.state === \"conflict\") {\n        store.putRow({ ...r, theirs: cloud.document, theirs_version: cloud.version });\n      }\n      // pending / refused: this device's change waits; `base` stays what it was made against.\n    }\n    // Copies the cloud no longer answers.\n    const gone = local.filter((r) => !seen.has(r.id));\n    const removable = gone.filter((r) => r.state === \"synced\");\n    const synced = local.filter((r) => r.state === \"synced\" || r.base !== null).length;\n    const limit = breakerLimit(o.breaker(), synced);\n    const t = store.table(tableId)!;\n    if (removable.length > limit) {\n      report.held_removals = removable.length;\n      o.log(\"warn\", \"records_mirror.pull_held\", { table_id: tableId, held: removable.length, of: synced, limit });\n    } else {\n      for (const r of removable) store.dropRow(tableId, r.id);\n    }\n    for (const r of gone) {\n      if (r.state === \"synced\" || r.base === null) continue; // synced: handled above; never reached the cloud: fine\n      const ops = opsFor(tableId, r.id);\n      if (ops.every((op) => op.kind === \"delete\")) {\n        // Archived on both sides.\n        for (const op of ops) store.dropOp(op.seq);\n        store.dropRow(tableId, r.id);\n      } else if (r.state !== \"conflict\") {\n        // Archived in the cloud while this device edited it: both kept, the person decides.\n        for (const op of ops) store.putOp({ ...op, state: \"conflict\" });\n        store.putRow({ ...r, state: \"conflict\", theirs: null, theirs_version: null });\n      }\n    }\n    store.putTable({ ...t, last_pull_at: now(), last_error: null, pull_held: report.held_removals });\n    return true;\n  }\n\n  async function pushUpdate(op: MirrorOp, report: MirrorPassReport): Promise<\"next\" | \"stop\"> {\n    const r = store.row(op.table_id, op.record_id);\n    if (!r) {\n      store.dropOp(op.seq);\n      return \"next\";\n    }\n    const { [OP_CHOICE_ADDS]: addsRaw, ...patch } = op.data ?? {};\n    const adds = addsRaw as ChoiceAdds | undefined;\n    // NOTHING IS DROPPED SILENTLY: a waiting change that carries no field (lost on its way into the\n    // queue) would \"succeed\" as a write of nothing and the copy would quietly go back. It is refused,\n    // with a sentence, and the copy keeps what this device shows.\n    if (Object.keys(patch).length === 0 && !adds) {\n      const edited = Object.keys(r.document).some((k) => !same(r.document[k], r.base?.[k]));\n      if (!edited) {\n        store.dropOp(op.seq);\n        if (r.state !== \"conflict\") store.putRow({ ...r, state: \"synced\", updated_at: now() });\n        return \"next\";\n      }\n      store.putOp({ ...op, state: \"refused\", error: \"This change reached the queue without its values, so it was not sent. What this computer shows is kept.\" });\n      store.putRow({ ...r, state: \"refused\" });\n      report.refused += 1;\n      o.log(\"error\", \"records_mirror.empty_change_refused\", { table_id: op.table_id, record_id: op.record_id });\n      return \"next\";\n    }\n    for (let attempt = 0; attempt < 3; attempt += 1) {\n      const cur = await doors.read(op.record_id);\n      if (!cur.ok) {\n        if (cur.error.code === \"unreachable\") return \"stop\";\n        if (cur.error.code === \"not_found\") {\n          store.putOp({ ...op, state: \"conflict\" });\n          store.putRow({ ...r, state: \"conflict\", theirs: null, theirs_version: null });\n          report.conflicts += 1;\n          return \"next\";\n        }\n        store.putOp({ ...op, state: \"refused\", error: errText(cur.error) });\n        store.putRow({ ...r, state: \"refused\" });\n        report.refused += 1;\n        return \"next\";\n      }\n      const theirs = cur.data.document;\n      const contested = Object.keys(patch).filter((k) => !same(theirs[k], r.base?.[k]) && !same(theirs[k], patch[k]));\n      if (contested.length > 0) {\n        store.putOp({ ...op, state: \"conflict\" });\n        store.putRow({ ...r, state: \"conflict\", theirs, theirs_version: cur.data.version });\n        report.conflicts += 1;\n        o.log(\"warn\", \"records_mirror.conflict\", { table_id: op.table_id, record_id: op.record_id, fields: contested });\n        return \"next\";\n      }\n      const otherMoved = Object.keys(theirs).some((k) => !(k in patch) && !same(theirs[k], r.base?.[k]));\n      const wrote = await doors.update(op.record_id, patch, cur.data.version, ...(adds ? [adds] : []));\n      if (wrote.ok) {\n        const merged = { ...theirs, ...patch };\n        store.dropOp(op.seq);\n        store.putRow({ ...r, document: merged, base: merged, base_version: wrote.data, state: \"synced\", theirs: null, theirs_version: null, updated_at: now() });\n        report.pushed += 1;\n        if (otherMoved) report.merged += 1;\n        return \"next\";\n      }\n      if (wrote.error.code === \"unreachable\") return \"stop\";\n      if (wrote.error.code === \"stale_write\") continue; // a third writer between the read and the write: read again\n      store.putOp({ ...op, state: \"refused\", error: errText(wrote.error) });\n      store.putRow({ ...r, state: \"refused\" });\n      report.refused += 1;\n      return \"next\";\n    }\n    return \"next\"; // still moving under us: stays waiting for the next pass\n  }\n\n  async function push(tableId: string, report: MirrorPassReport): Promise<void> {\n    const all = store.ops(tableId);\n    // The delete breaker, over the queue as a whole.\n    const deletes = all.filter((op) => op.kind === \"delete\" && (op.state === \"waiting\" || op.state === \"held\"));\n    const base = store.rows(tableId).filter((r) => r.base !== null).length;\n    if (deletes.length > breakerLimit(o.breaker(), base)) {\n      for (const op of deletes) if (op.state !== \"held\") store.putOp({ ...op, state: \"held\" });\n      report.held_deletes = deletes.length;\n      o.log(\"warn\", \"records_mirror.deletes_held\", { table_id: tableId, held: deletes.length, of: base });\n    } else {\n      for (const op of deletes) if (op.state === \"held\") store.putOp({ ...op, state: \"waiting\" });\n    }\n    for (const op of store.ops(tableId)) {\n      if (op.state !== \"waiting\" && op.state !== \"approved\") continue;\n      if (op.kind === \"create\") {\n        const res = await doors.create(tableId, op.record_id, op.data ?? {});\n        if (!res.ok && res.error.code === \"unreachable\") {\n          report.outcome = \"offline\";\n          return;\n        }\n        const r = store.row(tableId, op.record_id);\n        if (res.ok || res.error.code === \"already_exists\") {\n          store.dropOp(op.seq);\n          if (r) store.putRow({ ...r, base: { ...r.document }, base_version: null, state: \"synced\", updated_at: now() });\n          report.pushed += 1;\n        } else {\n          store.putOp({ ...op, state: \"refused\", error: errText(res.error) });\n          if (r) store.putRow({ ...r, state: \"refused\" });\n          report.refused += 1;\n        }\n      } else if (op.kind === \"update\") {\n        if ((await pushUpdate(op, report)) === \"stop\") {\n          report.outcome = \"offline\";\n          return;\n        }\n      } else {\n        const res = await doors.remove(op.record_id);\n        if (!res.ok && res.error.code === \"unreachable\") {\n          report.outcome = \"offline\";\n          return;\n        }\n        if (res.ok || res.error.code === \"not_found\") {\n          store.dropOp(op.seq);\n          store.dropRow(tableId, op.record_id);\n          report.pushed += 1;\n        } else {\n          store.putOp({ ...op, state: \"refused\", error: errText(res.error) });\n          report.refused += 1;\n        }\n      }\n    }\n  }\n\n  async function pass(tableId: string): Promise<MirrorPassReport> {\n    const report: MirrorPassReport = { table_id: tableId, outcome: \"done\", pulled: 0, pushed: 0, merged: 0, conflicts: 0, refused: 0, held_deletes: 0, held_removals: 0, error: null };\n    // ONE WRITER PER TABLE: a send already on the wire finishes before this pass reads a page, or the\n    // page (asked before the send's write landed) would lay the old cloud copy back over this one.\n    const onWire = sending.get(tableId)?.current;\n    if (onWire) await onWire.catch(() => undefined);\n    try {\n      // Pull before push: a device offline for a week never clobbers a week of other people's edits.\n      if (await pull(tableId, report)) await push(tableId, report);\n    } catch (error) {\n      report.outcome = \"failed\";\n      report.error = error instanceof Error ? error.message : String(error);\n    }\n    const t = store.table(tableId);\n    if (t && report.outcome !== \"done\") store.putTable({ ...t, last_error: report.outcome === \"offline\" ? `Offline: ${report.error ?? \"the cloud could not be reached\"}` : report.error });\n    o.log(report.outcome === \"failed\" ? \"error\" : report.outcome === \"offline\" ? \"warn\" : \"info\", \"records_mirror.pass\", { ...report });\n    return report;\n  }\n\n  const restore = (tableId: string, id: string): boolean => {\n    const r = store.row(tableId, id);\n    const deletes = opsFor(tableId, id).filter((op) => op.kind === \"delete\" && op.state !== \"refused\");\n    if (!r || !r.deleted || deletes.length === 0) return false;\n    for (const op of deletes) store.dropOp(op.seq);\n    // Edits made before the delete were dropped with it; what the copy shows goes up again.\n    const patch: Doc = {};\n    for (const k of Object.keys(r.document)) if (!same(r.document[k], r.base?.[k])) patch[k] = r.document[k];\n    const changed = Object.keys(patch).length > 0 && r.base !== null;\n    store.putRow({ ...r, deleted: false, state: changed ? \"pending\" : \"synced\", updated_at: now() });\n    if (changed) store.addOp({ table_id: tableId, record_id: id, kind: \"update\", data: patch, state: \"waiting\", error: null, created_at: now() });\n    o.log(\"info\", \"records_mirror.restored\", { table_id: tableId, record_id: id });\n    return true;\n  };\n\n  async function sendPass(tableId: string): Promise<MirrorPassReport> {\n    const report: MirrorPassReport = { table_id: tableId, outcome: \"done\", pulled: 0, pushed: 0, merged: 0, conflicts: 0, refused: 0, held_deletes: 0, held_removals: 0, error: null };\n    const syncing = running.get(tableId);\n    if (syncing) await syncing; // a full pass sends the same queue: never two writers at once\n    try {\n      await push(tableId, report);\n    } catch (error) {\n      report.outcome = \"failed\";\n      report.error = error instanceof Error ? error.message : String(error);\n    }\n    const t = store.table(tableId);\n    if (t) store.putTable({ ...t, last_error: report.outcome === \"done\" ? null : report.outcome === \"offline\" ? `Offline: ${report.error ?? \"the cloud could not be reached\"}` : report.error });\n    o.log(report.outcome === \"failed\" ? \"error\" : report.outcome === \"offline\" ? \"warn\" : \"info\", \"records_mirror.flush\", { ...report });\n    return report;\n  }\n\n  type Sending = { current: Promise<MirrorPassReport>; next: Promise<MirrorPassReport> | null };\n  const sending = new Map<string, Sending>();\n  const run = (tableId: string, entry: Sending): Promise<MirrorPassReport> =>\n    sendPass(tableId).finally(() => {\n      if (entry.next === null && sending.get(tableId) === entry) sending.delete(tableId);\n    });\n  const flush: RecordsMirror[\"flush\"] = (tableId) => {\n    const live = sending.get(tableId);\n    if (!live) {\n      const entry: Sending = { current: Promise.resolve(null as never), next: null };\n      sending.set(tableId, entry);\n      entry.current = run(tableId, entry);\n      return entry.current;\n    }\n    // A flush is on the wire: this change rides the next one, with every other change made meanwhile.\n    if (!live.next)\n      live.next = live.current.then(() => {\n        live.next = null;\n        live.current = run(tableId, live);\n        return live.current;\n      });\n    return live.next;\n  };\n\n  const sync: RecordsMirror[\"sync\"] = async (tableId) => {\n    const ids = tableId ? [tableId] : store.tables().map((t) => t.table_id);\n    const out: MirrorPassReport[] = [];\n    for (const id of ids) {\n      if (!store.table(id)) continue;\n      let p = running.get(id);\n      if (!p) {\n        p = pass(id).finally(() => running.delete(id));\n        running.set(id, p);\n      }\n      out.push(await p);\n    }\n    return out;\n  };\n\n  const approveDeletes = (tableId: string): number => {\n    const held = store.ops(tableId).filter((op) => op.kind === \"delete\" && op.state === \"held\");\n    for (const op of held) store.putOp({ ...op, state: \"approved\" });\n    o.log(\"info\", \"records_mirror.deletes_approved\", { table_id: tableId, count: held.length });\n    return held.length;\n  };\n\n  const discardDeletes = (tableId: string): number => {\n    const held = store.ops(tableId).filter((op) => op.kind === \"delete\" && op.state === \"held\");\n    for (const op of held) {\n      store.dropOp(op.seq);\n      const r = store.row(tableId, op.record_id);\n      if (r) store.putRow({ ...r, deleted: false, state: \"synced\", document: r.base ?? r.document });\n    }\n    o.log(\"info\", \"records_mirror.deletes_discarded\", { table_id: tableId, count: held.length });\n    return held.length;\n  };\n\n  const resolve: RecordsMirror[\"resolve\"] = (tableId, id, keepSide) => {\n    const r = store.row(tableId, id);\n    if (!r || r.state !== \"conflict\") return;\n    const ops = opsFor(tableId, id);\n    for (const op of ops) store.dropOp(op.seq);\n    if (keepSide === \"theirs\") {\n      if (r.theirs === null) store.dropRow(tableId, id);\n      else store.putRow({ ...r, document: r.theirs, base: r.theirs, base_version: r.theirs_version, state: \"synced\", theirs: null, theirs_version: null, deleted: false, updated_at: now() });\n      return;\n    }\n    if (r.theirs === null) {\n      // Archived in the cloud: this device's copy goes up as a new record, nothing lost.\n      store.dropRow(tableId, id);\n      create(tableId, r.document);\n      return;\n    }\n    const patch: Doc = {};\n    for (const k of Object.keys(r.document)) if (!same(r.document[k], r.theirs[k])) patch[k] = r.document[k];\n    store.putRow({ ...r, base: r.theirs, base_version: r.theirs_version, state: \"pending\", theirs: null, theirs_version: null, updated_at: now() });\n    store.addOp({ table_id: tableId, record_id: id, kind: \"update\", data: patch, state: \"waiting\", error: null, created_at: now() });\n  };\n\n  const status = (): MirrorTableStatus[] =>\n    store.tables().map((t) => {\n      const ops = store.ops(t.table_id);\n      const rows = store.rows(t.table_id);\n      return {\n        ...t,\n        stand_in: true as const,\n        records: rows.filter((r) => !r.deleted).length,\n        waiting: ops.filter((op) => op.state === \"waiting\" || op.state === \"approved\").length,\n        conflicts: rows.filter((r) => r.state === \"conflict\").length,\n        refused: ops.filter((op) => op.state === \"refused\").length,\n        held_deletes: ops.filter((op) => op.state === \"held\").length,\n      };\n    });\n\n  return { keep, forget, list: (tableId) => store.rows(tableId).filter((r) => !r.deleted), view: (tableId) => store.rows(tableId), create, update, remove, restore, flush, sync, approveDeletes, discardDeletes, resolve, status };\n}\n\n/** A store in memory: tests, and a host that has nowhere durable yet (said by its caller). */\nexport function memoryMirrorStore(): MirrorStore {\n  const tables = new Map<string, MirrorTable>();\n  const rows = new Map<string, MirrorRow>();\n  const ops = new Map<number, MirrorOp>();\n  let seq = 0;\n  const key = (t: string, id: string): string => `${t}\\u0000${id}`;\n  return {\n    tables: () => [...tables.values()],\n    table: (id) => tables.get(id) ?? null,\n    putTable: (t) => void tables.set(t.table_id, { ...t }),\n    dropTable: (id) => void tables.delete(id),\n    rows: (t) => [...rows.values()].filter((r) => r.table_id === t).map((r) => ({ ...r })),\n    row: (t, id) => {\n      const r = rows.get(key(t, id));\n      return r ? { ...r } : null;\n    },\n    putRow: (r) => void rows.set(key(r.table_id, r.id), { ...r }),\n    dropRow: (t, id) => void rows.delete(key(t, id)),\n    ops: (t) => [...ops.values()].filter((op) => op.table_id === t).sort((a, b) => a.seq - b.seq).map((op) => ({ ...op })),\n    addOp: (op) => {\n      seq += 1;\n      const full = { ...op, seq };\n      ops.set(seq, full);\n      return { ...full };\n    },\n    putOp: (op) => void ops.set(op.seq, { ...op }),\n    dropOp: (s) => void ops.delete(s),\n  };\n}\n","// src/offline/dataSource.ts — @ai-matrx/records/offline\n//\n// THE ONE WRITE PATH FOR A KEPT TABLE, AND ITS GRID WITH OR WITHOUT A CONNECTION. A host wraps the\n// data source of a kept Table's screens with `offlineDataSource(base, tableId, port)` and hands the\n// result to the package's own screens (records-ui's TablePage, the web's table editor): nothing is\n// forked, the grid never knows. A Table the device does not keep is never wrapped: it is exactly today.\n//\n// For the kept Table:\n//   - a row edit, a new row and a delete (`record_update`, `record_write`, `record_write_many`,\n//     `record_change_many`, `record_delete`) go into the device's queue (the records mirror,\n//     ./mirror.ts) and the host runs the table's pass at once, bounded (flush on write): online the\n//     change reaches the store before the grid hears back, offline it waits for the next pass. A mass\n//     delete is held by the mirror's breaker until the person decides;\n//   - a read goes to `base`; its answer is remembered, and when `base` cannot be reached the\n//     remembered answer is served instead. Either way this device's waiting changes are laid over the\n//     rows in it (an edited cell shows its new value, a deleted row is gone, a new row is listed);\n//   - a record the copy does not hold, and anything the queue cannot carry (a new choice, a move, a\n//     column change), goes to `base` as before; offline that is the store's own refusal, never dropped.\n//\n// 🚨 One path: nothing else in this package routes a kept Table's writes (guard:\n// `src/offline/one-write-path.test.ts`).\n\nimport type { RecordsDataSource, RecordsRealtimePort } from \"../ports\";\nimport type { ChoiceAdds, Doc, RecordsMirror } from \"./mirror\";\n\n/** `kept: false` is \"not this device's copy\": the call goes to the cloud as it always did. */\nexport type KeptAnswer<T> = { kept: true; data: T } | { kept: false };\n\nexport type KeptChange =\n  | { kind: \"create\"; data: Doc; id?: string }\n  | { kind: \"update\"; id: string; patch: Doc; add?: ChoiceAdds }\n  | { kind: \"delete\"; id: string }\n  /** Undo of a delete this device has not sent yet (the grid's Restore / Undo). */\n  | { kind: \"restore\"; id: string };\n\nexport interface GridRow {\n  id: string;\n  document: Doc;\n  deleted: boolean;\n  /** Made on this device and not yet in the store. */\n  local_only: boolean;\n  /** The store's version this copy was last agreed at (null: never reached the store). */\n  version?: number | null;\n  /** This device holds a change to the row the store does not have yet. */\n  waiting?: boolean;\n}\n\n/** What the host's device copy answers for ONE kept Table (the desktop: main's records mirror, over IPC). */\nexport interface KeptTablePort {\n  /** This device's view of the table: each record as shown here, deleted-and-waiting included. */\n  rows(): Promise<GridRow[]>;\n  /**\n   * Queue a change, run the table's pass (bounded), answer. `id` is the record's; `version` the\n   * store's once the change reached it, else one past the copy's base. `kept: false` for a record the\n   * copy does not hold.\n   */\n  write(change: KeptChange): Promise<KeptAnswer<{ id: string; version: number }>>;\n  remember(key: string, answer: unknown): Promise<void>;\n  recall(key: string): Promise<unknown | undefined>;\n}\n\n/** Envelope keys a door adds to a write; never stored as a field of the record. */\nconst ENVELOPE = [\"_op_id\"];\n\nconst strip = (d: unknown): Doc => {\n  if (!d || typeof d !== \"object\" || Array.isArray(d)) return {};\n  const out: Doc = { ...(d as Doc) };\n  for (const k of ENVELOPE) delete out[k];\n  return out;\n};\n\ntype Answer = { data: unknown; error: { code?: string; message: string; hint?: string | null; details?: string | null } | null };\n\n/** supabase-js resolves a dropped network as an error with no SQLSTATE (a FetchError) or a 5xx HTTP status. */\nexport function isUnreachable(error: Answer[\"error\"]): boolean {\n  if (!error) return false;\n  const code = String(error.code ?? \"\");\n  if (code === \"\") return true;\n  if (/^\\d{3}$/.test(code)) return Number(code) >= 500 || /fetch|network/i.test(error.message);\n  return false;\n}\n\n/** Lay this device's view over a door answer: every `{id, document}` row is patched, deleted ones removed, new ones appended to row lists. */\nexport function overlay(answer: unknown, rows: GridRow[]): unknown {\n  const byId = new Map(rows.map((r) => [r.id, r]));\n  const added = rows.filter((r) => r.local_only && !r.deleted);\n  const isRowList = (v: unknown[]): boolean =>\n    v.length > 0 && v.every((x) => x && typeof x === \"object\" && typeof (x as { id?: unknown }).id === \"string\" && typeof (x as { document?: unknown }).document === \"object\");\n  const walk = (v: unknown): unknown => {\n    if (Array.isArray(v)) {\n      const isRows = isRowList(v);\n      if (!isRows) return v.map(walk);\n      const kept = v\n        .filter((x) => !byId.get((x as { id: string }).id)?.deleted)\n        .map((x) => {\n          const mine = byId.get((x as { id: string }).id);\n          return mine\n            ? { ...(x as object), document: { ...((x as { document: Doc }).document ?? {}), ...mine.document }, ...(mine.waiting || mine.local_only ? { waiting: true } : {}) }\n            : x;\n        });\n      const present = new Set(kept.map((x) => (x as { id: string }).id));\n      const level = (v[0] as { level?: unknown }).level;\n      return [...kept, ...added.filter((r) => !present.has(r.id)).map((r) => ({ id: r.id, document: r.document, waiting: true, ...(level === undefined ? {} : { level }) }))];\n    }\n    if (v && typeof v === \"object\") {\n      const o = v as Record<string, unknown>;\n      if (typeof o[\"record_id\"] === \"string\" && o[\"document\"] && typeof o[\"document\"] === \"object\") {\n        const mine = byId.get(o[\"record_id\"] as string);\n        if (mine) return { ...o, document: { ...(o[\"document\"] as Doc), ...mine.document } };\n      }\n      const out = Object.fromEntries(Object.entries(o).map(([k, x]) => [k, walk(x)]));\n      // THE COUNT FOLLOWS THE COPY (Matrx 2 kept table, 2026-10-23): a page answer `{ total, rows }`\n      // whose rows gained this device's new rows (or lost its deletes) says the same in its total, so\n      // a footer never reads \"1-35 of 35\" over 36 rows.\n      const before = o[\"rows\"];\n      const after = out[\"rows\"];\n      const total = typeof o[\"total\"] === \"number\" ? o[\"total\"] : typeof o[\"total\"] === \"string\" && o[\"total\"].trim() !== \"\" ? Number(o[\"total\"]) : NaN;\n      if (Array.isArray(after) && Number.isFinite(total)) {\n        const shift = Array.isArray(before) && isRowList(before) ? after.length - before.length : 0;\n        if (shift !== 0) out[\"total\"] = Math.max(0, total + shift);\n      }\n      return out;\n    }\n    return v;\n  };\n  return walk(answer);\n}\n\n/**\n * The whole table's row count (`record_aggregate` with one `count`, no grouping, filter or search —\n * the grid's page total) counts this device's new rows and leaves out its waiting deletes, as the\n * page it totals does. Any other aggregate is the store's answer as it stands.\n */\nexport function countFollowsCopy(answer: unknown, args: Record<string, unknown>, rows: GridRow[]): unknown {\n  const empty = (v: unknown): boolean => v == null || (Array.isArray(v) ? v.length === 0 : typeof v === \"object\" ? Object.keys(v as object).length === 0 : typeof v === \"string\" ? v.trim() === \"\" : false);\n  const measures = args[\"p_measures\"];\n  const onlyCount = Array.isArray(measures) && measures.length === 1 && (measures[0] as { op?: unknown })?.op === \"count\";\n  if (!onlyCount || !empty(args[\"p_group_by\"]) || !empty(args[\"p_filter\"]) || !empty(args[\"p_search\"]) || !empty(args[\"p_bucket\"])) return answer;\n  if (!Array.isArray(answer) || answer.length !== 1) return answer;\n  const row = answer[0] as Record<string, unknown>;\n  const counted = Number(row[\"row_count\"]);\n  if (!Number.isFinite(counted)) return answer;\n  const shift = rows.filter((r) => r.local_only && !r.deleted).length - rows.filter((r) => r.deleted && !r.local_only).length;\n  return shift === 0 ? answer : [{ ...row, row_count: Math.max(0, counted + shift) }];\n}\n\nconst keyOf = (fn: string, args: Record<string, unknown>, schema: string | undefined): string => {\n  const rest = { ...args };\n  delete rest[\"p_organization_id\"];\n  return `${schema ?? \"custom\"}.${fn}:${JSON.stringify(rest, Object.keys(rest).sort())}`;\n};\n\nexport interface OfflineDataSourceOptions {\n  /** A port that threw: the call went to `base` instead, and this says so. */\n  onError?: (door: string, error: unknown) => void;\n  /** When a delete happened (tests pin it). */\n  now?: () => string;\n}\n\n/** The kept Table's data source. Wrap ONLY a kept Table's screens; every other Table keeps `base`. */\nexport function offlineDataSource(base: RecordsDataSource, tableId: string, port: KeptTablePort, options: OfflineDataSourceOptions = {}): RecordsDataSource {\n  const now = options.now ?? ((): string => new Date().toISOString());\n  const forTable = (args: Record<string, unknown>): boolean => args[\"p_table_id\"] === undefined || args[\"p_table_id\"] === tableId;\n\n  /** null: not a write the copy takes (the call goes to `base`). */\n  async function write(fn: string, args: Record<string, unknown>): Promise<Answer | null> {\n    if (!forTable(args)) return null;\n    const one = async (change: KeptChange) => port.write(change);\n    switch (fn) {\n      case \"record_update\": {\n        if (typeof args[\"p_record_id\"] !== \"string\") return null;\n        const a = await one({ kind: \"update\", id: args[\"p_record_id\"], patch: strip(args[\"p_patch\"]) });\n        return a.kept ? { data: a.data.version, error: null } : null;\n      }\n      case \"record_update_adding_choices\": {\n        // A typed value that is not a choice yet: the patch and its new choices wait together.\n        if (typeof args[\"p_record_id\"] !== \"string\") return null;\n        const add = args[\"p_add\"] && typeof args[\"p_add\"] === \"object\" ? (args[\"p_add\"] as ChoiceAdds) : undefined;\n        const a = await one({ kind: \"update\", id: args[\"p_record_id\"], patch: strip(args[\"p_patch\"]), ...(add ? { add } : {}) });\n        return a.kept ? { data: a.data.version, error: null } : null;\n      }\n      case \"record_restore\": {\n        if (typeof args[\"p_record_id\"] !== \"string\") return null;\n        const a = await one({ kind: \"restore\", id: args[\"p_record_id\"] });\n        return a.kept ? { data: null, error: null } : null;\n      }\n      case \"record_delete\": {\n        if (typeof args[\"p_record_id\"] !== \"string\") return null;\n        const a = await one({ kind: \"delete\", id: args[\"p_record_id\"] });\n        return a.kept ? { data: now(), error: null } : null;\n      }\n      case \"record_write\": {\n        if (args[\"p_table_id\"] !== tableId) return null;\n        const a = await one({ kind: \"create\", data: strip(args[\"p_data\"]) });\n        return a.kept ? { data: a.data.id, error: null } : null;\n      }\n      case \"record_write_many\": {\n        if (args[\"p_table_id\"] !== tableId) return null;\n        const rows = (args[\"p_rows\"] as unknown[] | undefined) ?? [];\n        const ids = (args[\"p_ids\"] as string[] | undefined) ?? [];\n        const made: string[] = [];\n        for (let i = 0; i < rows.length; i += 1) {\n          const id = ids[i];\n          const a = await one({ kind: \"create\", data: strip(rows[i]), ...(id ? { id } : {}) });\n          if (!a.kept) return made.length === 0 ? null : { data: null, error: { code: \"P0001\", message: `${made.length} of ${rows.length} rows were kept on this device; the rest were not saved.` } };\n          made.push(a.data.id);\n        }\n        return { data: made, error: null };\n      }\n      case \"record_change_many\": {\n        if (args[\"p_table_id\"] !== tableId) return null;\n        const changes = (args[\"p_changes\"] as Array<Record<string, unknown>> | undefined) ?? [];\n        if (changes.length === 0) return null;\n        // All or none, as the door is: a change the copy cannot carry sends the whole batch to the store.\n        if (!changes.every((c) => c[\"op\"] === \"insert\" || ((c[\"op\"] === \"update\" || c[\"op\"] === \"archive\") && typeof c[\"record_id\"] === \"string\"))) return null;\n        const held = new Set((await port.rows()).map((r) => r.id));\n        if (!changes.every((c) => c[\"op\"] === \"insert\" || held.has(String(c[\"record_id\"])))) return null;\n        const out: unknown[] = [];\n        for (const c of changes) {\n          if (c[\"op\"] === \"insert\") {\n            const a = await one({ kind: \"create\", data: strip(c[\"data\"]) });\n            if (a.kept) out.push({ op: \"insert\", id: a.data.id });\n          } else if (c[\"op\"] === \"update\") {\n            const a = await one({ kind: \"update\", id: String(c[\"record_id\"]), patch: strip(c[\"patch\"]) });\n            if (a.kept) out.push({ op: \"update\", id: a.data.id, version: a.data.version });\n          } else {\n            const a = await one({ kind: \"delete\", id: String(c[\"record_id\"]) });\n            if (a.kept) out.push({ op: \"archive\", id: a.data.id, archived_at: now() });\n          }\n        }\n        return { data: out, error: null };\n      }\n      default:\n        return null;\n    }\n  }\n\n  /**\n   * The version check before an edit (`record_headers`): a record made on this device is not in the\n   * store yet, and offline the store cannot answer at all, so the copy answers for the records it holds\n   * (its last agreed version, 1 for a new one). Without this an edit to a new or offline row is refused\n   * as \"could not be checked\" (walker 2026-10-21).\n   */\n  async function headers(args: Record<string, unknown>, opts: { schema?: string } | undefined) {\n    const ids = Array.isArray(args[\"p_ids\"]) ? (args[\"p_ids\"] as unknown[]).filter((x): x is string => typeof x === \"string\") : [];\n    const answer = (await base.rpc(\"record_headers\", args, opts)) as Answer;\n    if (answer.error && !isUnreachable(answer.error)) return answer as never;\n    let rows: GridRow[];\n    try {\n      rows = await port.rows();\n    } catch (error) {\n      options.onError?.(\"record_headers\", error);\n      return answer as never;\n    }\n    const held = new Map(rows.filter((r) => !r.deleted).map((r) => [r.id, r]));\n    const got = (answer.error ? [] : ((answer.data as Array<{ id: string }> | null) ?? [])).filter((h) => !held.get(h.id)?.local_only);\n    const have = new Set(got.map((h) => h.id));\n    const at = now();\n    const mine = ids.filter((id) => !have.has(id) && held.has(id)).map((id) => ({ id, table_id: tableId, created_at: at, updated_at: at, version: held.get(id)?.version ?? 1, deleted_at: null, mine: true, created_by: null }));\n    if (answer.error && mine.length === 0) return answer as never;\n    return { data: [...got, ...mine], error: null } as never;\n  }\n\n  const wrapped: RecordsDataSource = {\n    async rpc(fn, args, opts) {\n      if (opts?.schema !== undefined && opts.schema !== \"custom\") return base.rpc(fn, args, opts);\n      try {\n        const queued = await write(fn, args);\n        if (queued) return queued as never;\n      } catch (error) {\n        options.onError?.(fn, error);\n        return base.rpc(fn, args, opts);\n      }\n      if (fn === \"record_headers\") return headers(args, opts);\n      if (fn.startsWith(\"record_\") && !fn.startsWith(\"record_aggregate\") && !fn.startsWith(\"record_page\")) return base.rpc(fn, args, opts);\n      if (!forTable(args)) return base.rpc(fn, args, opts);\n      const key = keyOf(fn, args, opts?.schema);\n      const answer = (await base.rpc(fn, args, opts)) as Answer;\n      const laid = async (data: unknown): Promise<unknown> => {\n        const rows = await port.rows();\n        return fn === \"record_aggregate\" ? countFollowsCopy(data, args, rows) : overlay(data, rows);\n      };\n      try {\n        if (!answer.error) {\n          await port.remember(key, answer.data);\n          return { ...answer, data: await laid(answer.data) } as never;\n        }\n        if (!isUnreachable(answer.error)) return answer as never;\n        const held = await port.recall(key);\n        if (held === undefined) return answer as never;\n        return { data: await laid(held), error: null } as never;\n      } catch (error) {\n        options.onError?.(fn, error);\n        return answer as never;\n      }\n    },\n    schema: (name) => base.schema(name),\n  };\n  if (base.opensInOneCall !== undefined) wrapped.opensInOneCall = base.opensInOneCall;\n  return wrapped;\n}\n\n/** Where remembered read answers live (the desktop: its State DB). */\nexport interface RememberedAnswers {\n  get(tableId: string, key: string): unknown | undefined;\n  set(tableId: string, key: string, answer: unknown): void;\n}\n\nexport function memoryAnswers(): RememberedAnswers {\n  const m = new Map<string, unknown>();\n  return { get: (t, k) => m.get(`${t}\\u0000${k}`), set: (t, k, v) => void m.set(`${t}\\u0000${k}`, v) };\n}\n\nexport interface GridPortOptions {\n  answers: RememberedAnswers;\n  /**\n   * Sends what is waiting, run after each write (the host bounds it; the change stays queued either\n   * way). Default: the mirror's own `flush` — no pull, only the changed records, a burst batched.\n   */\n  flush?: () => Promise<unknown>;\n  /**\n   * Deletes are never flushed one by one: a pass per delete would let a row-by-row mass delete slip\n   * under the breaker. They wait this long after the last one, then go up as ONE batch the breaker\n   * judges whole.\n   */\n  deleteQuietMs?: number;\n}\n\n/** A grid's multi-row delete arrives as a burst of calls milliseconds apart; this outlasts it. */\nconst DELETE_QUIET_MS = 2_000; // internal-bound: longer than a multi-select delete's burst, short enough to feel immediate\n\n/** The port over a records mirror for one kept Table: what a host serves to `offlineDataSource` (directly, or across IPC). */\nexport function gridPortFromMirror(mirror: RecordsMirror, tableId: string, o: GridPortOptions): KeptTablePort {\n  const held = (id: string) => mirror.view(tableId).find((r) => r.id === id && !r.deleted) ?? null;\n  const send = o.flush ?? (() => mirror.flush(tableId));\n  let deleteTimer: ReturnType<typeof setTimeout> | null = null;\n  const flushDeletesSoon = (): void => {\n    if (deleteTimer) clearTimeout(deleteTimer);\n    deleteTimer = setTimeout(() => {\n      deleteTimer = null;\n      void send();\n    }, o.deleteQuietMs ?? DELETE_QUIET_MS);\n  };\n  return {\n    rows: async () => mirror.view(tableId).map((r) => ({ id: r.id, document: r.document, deleted: r.deleted, local_only: r.base === null, version: r.base_version, waiting: r.state !== \"synced\" })),\n    async write(change) {\n      if (!mirror.status().some((t) => t.table_id === tableId)) return { kept: false };\n      if (change.kind === \"create\") {\n        const id = mirror.create(tableId, change.data, change.id);\n        await send();\n        return { kept: true, data: { id, version: held(id)?.base_version ?? 1 } };\n      }\n      if (change.kind === \"restore\") {\n        if (!mirror.restore(tableId, change.id)) return { kept: false };\n        await send();\n        return { kept: true, data: { id: change.id, version: held(change.id)?.base_version ?? 1 } };\n      }\n      const before = held(change.id);\n      if (!before) return { kept: false };\n      if (change.kind === \"delete\") {\n        mirror.remove(tableId, change.id);\n        flushDeletesSoon();\n        return { kept: true, data: { id: change.id, version: (before.base_version ?? 0) + 1 } };\n      }\n      mirror.update(tableId, change.id, change.patch, change.add);\n      await send();\n      const after = held(change.id);\n      // The store's own version once it took the change; while it waits, one past the copy's base.\n      const version = after && after.state === \"synced\" && after.base_version !== null ? after.base_version : (before.base_version ?? 0) + 1;\n      return { kept: true, data: { id: change.id, version } };\n    },\n    remember: async (k, v) => o.answers.set(tableId, k, v),\n    recall: async (k) => o.answers.get(tableId, k),\n  };\n}\n\n/**\n * A kept Table's screens re-read when the DEVICE COPY changes — a pass that pushed or pulled, an\n * approved mass delete, a conflict picked, a reconnect — not only when this page wrote. The page\n * hook already re-reads on a realtime nudge (`records(null)`: the whole page), and a kept Table's\n * reads come through `offlineDataSource`, so the answer is the store's with this device's waiting\n * changes laid over it, or the remembered one offline. `onCopyChanged` is the host's signal (the\n * desktop: main's records mirror `changed` event, for this table); `base` is the host's own port, if\n * it has one, and keeps working beside it.\n */\nexport function copyChangesRealtime(tableId: string, onCopyChanged: (listener: () => void) => () => void, base?: RecordsRealtimePort): RecordsRealtimePort {\n  return {\n    subscribeRecords(args, sink) {\n      const stopBase = base?.subscribeRecords(args, sink);\n      const stopCopy = args.table_id === tableId ? onCopyChanged(() => sink.records(null)) : null;\n      return () => {\n        stopBase?.();\n        stopCopy?.();\n      };\n    },\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0EO,IAAM,iBAAiB;AAiDvB,SAAS,aAAa,GAAkB,UAA0B;AACvE,SAAO,KAAK,IAAI,EAAE,OAAO,KAAK,IAAI,EAAE,KAAK,KAAK,MAAM,WAAW,EAAE,KAAK,CAAC,CAAC;AAC1E;AAyEA,IAAM,OAAO,CAAC,GAAY,MAAwB,KAAK,UAAU,KAAK,IAAI,MAAM,KAAK,UAAU,KAAK,IAAI;AAExG,SAAS,QAAQ,GAAyB;AACxC,SAAO,E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