{"version":3,"sources":["../../src/versions/index.ts","../../src/versions/recordVersions.ts","../../src/versions/askOnce.ts","../../src/versions/refusals.ts","../../src/versions/rowVersion.ts","../../src/versions/writeOnTheWinningVersion.ts"],"sourcesContent":["\"use client\";\n\n// @ai-matrx/records/versions — THE VERSION RULE, for any screen a company builds (moved whole from\n// @ai-matrx/records-ui, 2026-10-08): every update of an existing record carries the version the person\n// saw. `useRecordVersions` / `useTableVersion` hold the versions at load; `updateRecordAt`,\n// `changeRecordsAt`, `movePipelineCardAt(s)`, `restoreAt` and `updateOnTheWinningVersion` are the\n// write doors that refuse a missing version in their own words; `askOnce` keeps one question in flight\n// per client; `refusal` builds a refusal shaped like the store's own. `recordRead` now answers the\n// record's `version` too, so a single-record edit needs no second read.\nexport * from \"./recordVersions\";\nexport * from \"./askOnce\";\nexport * from \"./refusals\";\nexport * from \"./writeOnTheWinningVersion\";\n","\"use client\";\n\n// src/versions/recordVersions.ts — @ai-matrx/records/versions (moved whole from records-ui 2026-10-08) · lane VIEWS-AND-FIELDS, sublane VW (2026-10-02)\n//\n// ONE RULE, ONE PLACE: EVERY UPDATE OF AN EXISTING RECORD CARRIES THE VERSION THE PERSON SAW.\n//\n// The store's `record_update`, `record_update_adding_choices`, `record_change_many` and\n// `pipeline_move` do a hard compare-and-set when handed a version, and a write with NO version is\n// last-write-wins (proven on the nightly clone, 2026-10-02: a `record_change_many` update with no\n// `expected_version` overwrote a colleague's change). So a screen that forgets the version — or\n// reads a fresh one just before writing — silently overwrites a colleague.\n//\n// This module is the ONLY file in the package that may call those doors (census guard:\n// `every-update-carries-the-version-it-saw.test.tsx`). It holds:\n//\n//   · `useRecordVersions(rows)` — THE VERSIONS AT LOAD. Seeded from the row's own `version` when the\n//     host's read carries one, else ONE `custom.record_headers` read for the rows whose CONTENT is new\n//     (keyed by record id and by what the row holds — never by the array's identity, so a parent that\n//     rebuilds the row array every render never re-reads a version without re-drawing the record:\n//     verifier D1, a Rule view sorted in the browser). Rows re-read with new content (a reload, a\n//     realtime notice) are read again. A version only ever goes up; a write this screen made raises it.\n//   · `updateRecordAt`, `changeRecordsAt`, `movePipelineCardAt`, `movePipelineCardsAt`, `restoreAt` —\n//     the write doors, each REFUSING a missing version with its own words (`VERSION_UNREAD_LABEL`),\n//     never sending it as \"no version\".\n//\n// WHAT THIS CANNOT CLOSE (reported, store-side): the read doors answer documents, never versions, so\n// the version is a SECOND read just after the rows. A colleague's write landing between the two is\n// drawn old and versioned new. Only a read door that answers `version` per row closes that gap.\n\nimport { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport type { RecordChange, RecordChangeResult, RecordsError, RecordsResult, ReadRow, RestoreResult, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\nimport { askOnce } from \"./askOnce\";\nimport { refusal } from \"./refusals\";\n\n/** THE CONFLICT, on a card, a badge and the floating notice — the store said somebody else won. */\nexport const STALE_MOVE_LABEL = \"Changed by someone else\";\n/** THE VERSION COULD NOT BE READ, so nothing was written — never shown as a conflict. */\nexport const VERSION_UNREAD_LABEL = \"Could not check for changes\";\n\nconst UNREAD_SENTENCE = \"Nothing was saved: this record's latest changes could not be checked.\";\nconst UNREAD_REMEDY = \"Reload, then try again.\";\nconst SEEN_MOVED_SENTENCE = \"Nothing was saved: someone else changed this record since you opened it.\";\n\n/** The refusal for \"the version the person saw is not known\". */\nexport function versionUnread(): RecordsError {\n  return { ...refusal(\"stale_read\", UNREAD_SENTENCE, UNREAD_REMEDY), detail: { version_unread: true } };\n}\n\n/** Is this refusal \"the version could not be read\" (never \"somebody else changed it\")? */\nexport function isVersionUnread(error: RecordsError | null | undefined): boolean {\n  const detail = error?.detail as { version_unread?: unknown } | undefined;\n  return Boolean(detail && detail.version_unread === true);\n}\n\n/** Is this refusal \"somebody else changed it first\"? */\nexport function isChangedElsewhere(error: RecordsError | null | undefined): boolean {\n  return error?.code === \"stale_write\";\n}\n\nexport { ownVersion } from \"./rowVersion\";\nimport { ownVersion } from \"./rowVersion\";\n\n/** What a row holds, as one string — a re-read with the same content is not a new drawing. */\nfunction signatureOf(row: ReadRow): string {\n  const own = ownVersion(row);\n  if (own !== null) return `v${own}`;\n  try {\n    return JSON.stringify(row.document ?? null);\n  } catch {\n    return String(Math.random());\n  }\n}\n\n/** A short, stable name for what these rows hold (FNV-1a over their signatures) — part of a shared read's key. */\nfunction contentKey(signatures: readonly string[]): string {\n  let hash = 0x811c9dc5;\n  for (const sig of signatures) {\n    for (let i = 0; i < sig.length; i += 1) {\n      hash ^= sig.charCodeAt(i);\n      hash = Math.imul(hash, 0x01000193) >>> 0;\n    }\n    hash ^= 0x2;\n    hash = Math.imul(hash, 0x01000193) >>> 0;\n  }\n  return hash.toString(36);\n}\n\nexport interface RecordVersions {\n  /** The version the person saw this record at; waits for the read of freshly drawn rows. `null` = unread. */\n  seen: (id: Uuid) => Promise<number | null>;\n  /** The same, for many records at once. */\n  seenMany: (ids: readonly Uuid[]) => Promise<Map<Uuid, number | null>>;\n  /** A write this screen made moved the record on (a version only goes up). */\n  wrote: (id: Uuid, version: number) => void;\n  /**\n   * Read these records' versions again now: the person pressed Reload, or the store refused a write\n   * because somebody else won (`PT409`) — the rows are re-read too, so the next write is against what\n   * the person then sees. A change that moved only the version (who sees the row) never re-reads by\n   * content, so without this the row stayed refused until the screen was opened again (verifier V10).\n   */\n  refresh: (ids: readonly Uuid[]) => void;\n}\n\n/**\n * How long the versions read at load are shared between the screens that ask the same ids — one page\n * open, including the records client rebuilt when the active organization resolves (~1.5-2 s in, after\n * a load that itself takes a while). Only the load's read is shared: a read after a write or a Reload\n * always asks, so this window never holds a version a write changed. 3 s ended inside that rebuild on a\n * loaded runner (the seeded-grid test, 2026-10-08).\n */\nconst HEADERS_SHARED_MS = 10_000;\n\n/**\n * HOW A READ IS SHARED. `first`: the rows this screen draws for the first time — shared for\n * `HEADERS_SHARED_MS` with every screen drawing the SAME CONTENT. `redrawn`: rows drawn again with new\n * content (a reload, a realtime notice) — shared only with the screens asking while it is in flight for\n * that same content, never answered from a read finished earlier. `none`: a read after a write or a\n * Reload — always asks.\n *\n * THE KEY CARRIES WHAT THE ROWS HOLD (2026-10-19, publish-gate flake). It used to be the ids alone, so a\n * re-read after the desk's own write (content A, version 2) was kept ten seconds under\n * `record_headers:<id>`, and the realtime notice of a colleague's change a moment later (content B,\n * version 3) asked the same key and was answered version 2: the next edit named 2, was refused as a\n * conflict with the colleague the person had already SEEN, and was resent on 3. It showed whenever the\n * grid re-read rows after a write (`reloadAfterWrite` while realtime is not yet live — a loaded machine).\n */\ntype HeadersSharing = \"first\" | \"redrawn\" | \"none\";\n\n/**\n * THE VERSIONS AT LOAD for the rows a screen drew. Stable across re-renders (one handle); re-reads only\n * the rows whose content changed. `mayRead` leaves out rows the screen will never write (a viewer's).\n */\nexport function useRecordVersions(\n  client: Pick<RecordsClient, \"recordHeaders\">,\n  rows: readonly ReadRow[],\n  mayRead?: (row: ReadRow) => boolean,\n): RecordVersions {\n  const versions = useRef(new Map<Uuid, number>());\n  const drawn = useRef(new Map<Uuid, string>());\n  const unread = useRef(new Set<Uuid>());\n  const pending = useRef(new Map<Uuid, { gen: number; read: Promise<void> }>());\n  const generation = useRef(0);\n  const mayReadRef = useRef(mayRead);\n  mayReadRef.current = mayRead;\n  const rowsRef = useRef(rows);\n  rowsRef.current = rows;\n\n  // THE KEY IS WHAT THE ROWS HOLD, NEVER THE ARRAY: a new array with the same rows reads nothing.\n  const key = useMemo(() => rows.map((row) => `${row.id}\\u0001${signatureOf(row)}`).join(\"\\u0002\"), [rows]);\n\n  const raise = (id: Uuid, version: number) => {\n    const held = versions.current.get(id);\n    if (held === undefined || version > held) versions.current.set(id, version);\n    unread.current.delete(id);\n  };\n\n  const readHeaders = useCallback(\n    (toRead: Uuid[], sharing: HeadersSharing = \"none\", content = \"\") => {\n      if (toRead.length === 0) return;\n      generation.current += 1;\n      const gen = generation.current;\n      const markUnread = (id: Uuid) => {\n        versions.current.delete(id);\n        unread.current.add(id);\n      };\n      // The versions of what is drawn are one question for every screen that draws the same rows with\n      // the same content (the grid, its editing layer, the move layer) and, at load, for a records\n      // client rebuilt a moment later: asked once. A read after a write or a Reload always asks.\n      const asking =\n        sharing === \"none\"\n          ? client.recordHeaders({ ids: toRead })\n          : askOnce(\n              client,\n              `record_headers:${sharing}:${toRead.join(\",\")}@${content}`,\n              () => client.recordHeaders({ ids: toRead }),\n              sharing === \"first\" ? HEADERS_SHARED_MS : 0,\n            );\n      const read = asking\n        .then(\n          (res) => {\n            const found = new Set<Uuid>();\n            if (res.ok) {\n              for (const header of res.data ?? []) {\n                found.add(header.id);\n                if (pending.current.get(header.id)?.gen === gen) raise(header.id, header.version);\n              }\n            }\n            // A FAILED OR SILENT READ IS AN UNREAD VERSION: said as its own refusal, never a guess.\n            for (const id of toRead) if (!found.has(id) && pending.current.get(id)?.gen === gen) markUnread(id);\n          },\n          () => {\n            for (const id of toRead) if (pending.current.get(id)?.gen === gen) markUnread(id);\n          },\n        )\n        .finally(() => {\n          for (const id of toRead) if (pending.current.get(id)?.gen === gen) pending.current.delete(id);\n        });\n      // A read already asked still answers for the rows it was asked for; a newer read of the same\n      // record supersedes it by generation.\n      for (const id of toRead) pending.current.set(id, { gen, read });\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [client],\n  );\n\n  useEffect(() => {\n    const first: Uuid[] = [];\n    const firstSigs: string[] = [];\n    const redrawn: Uuid[] = [];\n    const redrawnSigs: string[] = [];\n    for (const row of rowsRef.current) {\n      if (mayReadRef.current && !mayReadRef.current(row)) continue;\n      const sig = signatureOf(row);\n      const before = drawn.current.get(row.id);\n      if (before === sig) continue;\n      drawn.current.set(row.id, sig);\n      const own = ownVersion(row);\n      if (own !== null) raise(row.id, own);\n      else if (before === undefined) {\n        first.push(row.id);\n        firstSigs.push(sig);\n      } else {\n        redrawn.push(row.id);\n        redrawnSigs.push(sig);\n      }\n    }\n    readHeaders(first, \"first\", contentKey(firstSigs));\n    readHeaders(redrawn, \"redrawn\", contentKey(redrawnSigs));\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [readHeaders, key]);\n\n  /** Read these records' versions again now — the person pressed Reload. */\n  const refresh = useCallback((ids: readonly Uuid[]) => readHeaders([...ids]), [readHeaders]);\n\n  const seen = useCallback(async (id: Uuid): Promise<number | null> => {\n    for (let guard = 0; guard < 5; guard += 1) {\n      const waiting = pending.current.get(id);\n      if (!waiting) break;\n      await waiting.read;\n    }\n    if (unread.current.has(id)) return null;\n    return versions.current.get(id) ?? null;\n  }, []);\n\n  const seenMany = useCallback(\n    async (ids: readonly Uuid[]) => {\n      const out = new Map<Uuid, number | null>();\n      for (const id of ids) out.set(id, await seen(id));\n      return out;\n    },\n    [seen],\n  );\n\n  /*\n   * A WRITE THIS SCREEN MADE: its version raises the record's, and the record's header is read once\n   * more. `record_update` answers the version from BEFORE the store's own automations ran (a stage\n   * rule that notifies moves v3 to v4 with nothing on screen changing — verifier V10), so the next\n   * write waits for the header, never for a conflict with the store itself.\n   */\n  const wrote = useCallback(\n    (id: Uuid, version: number) => {\n      raise(id, version);\n      readHeaders([id]);\n    },\n    [readHeaders],\n  );\n\n  return useMemo(() => ({ seen, seenMany, wrote, refresh }), [seen, seenMany, wrote, refresh]);\n}\n\n/** One record's version, read now — for a screen that shows something else first (a preview, a proposal). */\nexport async function readVersionNow(client: Pick<RecordsClient, \"recordHeaders\">, id: Uuid): Promise<number | null> {\n  try {\n    const res = await client.recordHeaders({ ids: [id] });\n    if (!res.ok) return null;\n    return (res.data ?? []).find((h) => h.id === id)?.version ?? null;\n  } catch {\n    return null;\n  }\n}\n\n/* ═══ THE WRITE DOORS ════════════════════════════════════════════════════════════════════════ */\n\n/** ONE record's update, against the version the person saw (`add`: words that also become choices). */\nexport async function updateRecordAt(\n  client: Pick<RecordsClient, \"recordUpdate\" | \"recordUpdateAddingChoices\">,\n  args: { record_id: Uuid; patch: Record<string, unknown>; version: number | null; add?: Record<string, string[]> | undefined },\n): Promise<RecordsResult<number>> {\n  if (args.version === null) return { ok: false, error: versionUnread() };\n  return args.add\n    ? client.recordUpdateAddingChoices({ record_id: args.record_id, patch: args.patch, add: args.add, expectedVersion: args.version })\n    : client.recordUpdate({ record_id: args.record_id, patch: args.patch, expectedVersion: args.version });\n}\n\n/** One change of a batch: an update NAMES the version it was made against (`null` = unread). */\nexport type VersionedChange =\n  | Extract<RecordChange, { op: \"insert\" }>\n  | Extract<RecordChange, { op: \"archive\" }>\n  | { op: \"update\"; record_id: Uuid; patch: Record<string, unknown>; expected_version: number | null };\n\n/** MANY CHANGES TO ONE TABLE, ONE TRANSACTION. Any update with an unread version refuses the batch. */\nexport async function changeRecordsAt(\n  client: Pick<RecordsClient, \"recordChangeMany\">,\n  args: { table_id: Uuid; changes: readonly VersionedChange[] },\n): Promise<RecordsResult<RecordChangeResult[]>> {\n  const sent: RecordChange[] = [];\n  for (const change of args.changes) {\n    if (change.op !== \"update\") {\n      sent.push(change);\n      continue;\n    }\n    if (change.expected_version === null) return { ok: false, error: versionUnread() };\n    sent.push({ op: \"update\", record_id: change.record_id, patch: change.patch as never, expected_version: change.expected_version });\n  }\n  return client.recordChangeMany({ table_id: args.table_id, changes: sent });\n}\n\n/** A pipeline card to another stage, against the version the board drew it at. */\nexport async function movePipelineCardAt(\n  client: Pick<RecordsClient, \"pipelineMove\">,\n  args: { record_id: Uuid; to: string; also?: Record<string, unknown> | undefined; version: number | null },\n): ReturnType<RecordsClient[\"pipelineMove\"]> {\n  if (args.version === null) return { ok: false, error: versionUnread() };\n  return client.pipelineMove({\n    record_id: args.record_id,\n    to: args.to,\n    ...(args.also ? { also: args.also } : {}),\n    expected_version: args.version,\n  });\n}\n\n/** Many pipeline cards, one call; every card names its version or the batch is not sent. */\nexport async function movePipelineCardsAt(\n  client: Pick<RecordsClient, \"pipelineMoveMany\">,\n  args: { moves: ReadonlyArray<{ record_id: Uuid; stage: string; version: number | null }> },\n): ReturnType<RecordsClient[\"pipelineMoveMany\"]> {\n  if (args.moves.some((m) => m.version === null)) return { ok: false, error: versionUnread() };\n  return client.pipelineMoveMany({\n    moves: args.moves.map((m) => ({ record_id: m.record_id, stage: m.stage, expected_version: m.version as number })),\n  });\n}\n\n/**\n * PUT A VERSION BACK (one column, or the whole record), only while the record is still at the version\n * the person saw the preview at. The restore doors take no expected version, so the check is ONE\n * header read just before — a colleague's change since the preview is refused as a conflict; only a\n * write landing inside that one round trip can still slip past (reported: needs a store-side version).\n */\nexport async function restoreAt(\n  client: Pick<RecordsClient, \"recordHeaders\" | \"valueRestore\" | \"restoreVersion\">,\n  args: { record_id: Uuid; version: number; field_key?: string | null | undefined; seenVersion: number | null },\n): Promise<RecordsResult<RestoreResult>> {\n  if (args.seenVersion === null) return { ok: false, error: versionUnread() };\n  const now = await readVersionNow(client, args.record_id);\n  if (now === null) return { ok: false, error: versionUnread() };\n  if (now !== args.seenVersion) {\n    return {\n      ok: false,\n      error: { ...refusal(\"stale_write\", SEEN_MOVED_SENTENCE, UNREAD_REMEDY), detail: { expected_version: args.seenVersion, current_version: now } },\n    };\n  }\n  return args.field_key\n    ? client.valueRestore({ record_id: args.record_id, field_key: args.field_key, version: args.version })\n    : client.restoreVersion({ record_id: args.record_id, version: args.version });\n}\n\n/**\n * A TABLE'S OWN VERSION, read now. `custom.record_headers` answers RECORDS only (it never returns a\n * Table's row: measured on the clone 2026-10-02, 0 rows for a Table id), so a Table's version is the\n * newest of its revisions (`custom.io_revisions`, which does answer a Table — v10 for Cedar Ridge PT's\n * Patient Visits). The history can fall behind the record; a write on it goes through\n * `updateOnTheWinningVersion`, which resends once on the winning version when the column it changes\n * is still what the screen drew.\n */\nexport async function readTableVersionNow(client: Pick<RecordsClient, \"revisions\" | \"recordHeaders\">, tableId: Uuid): Promise<number | null> {\n  // `record_headers` FIRST: once it answers Tables too (sublane FD's migration, on the clone only as of\n  // 2026-10-02) its version is the record's own and never lags. Until then it answers no row for a\n  // Table, and the revisions stand in.\n  const header = await readVersionNow(client, tableId);\n  if (header !== null) return header;\n  try {\n    const res = await client.revisions({ record_id: tableId });\n    if (!res.ok) return null;\n    return (res.data ?? []).reduce<number | null>((best, r) => (best === null || r.version > best ? r.version : best), null);\n  } catch {\n    return null;\n  }\n}\n\n/**\n * A TABLE'S OWN RECORD (its name, its row label): the version of the table document this screen drew,\n * read again whenever that document arrives with new content (never per render).\n */\nexport function useTableVersion(\n  client: Pick<RecordsClient, \"revisions\" | \"recordHeaders\">,\n  tableId: Uuid | null | undefined,\n  table: unknown,\n): () => Promise<number | null> {\n  const key = useMemo(() => {\n    try {\n      return `${tableId ?? \"\"}\\u0001${JSON.stringify(table ?? null)}`;\n    } catch {\n      return String(tableId ?? \"\");\n    }\n  }, [tableId, table]);\n  // READ WHEN A WRITE ASKS, NEVER ON LOAD (lane TABLE-ACTIONS T5.3): two grid controls each read\n  // the table's version on every table open — 2 × `record_headers` + 2 × `io_revisions` for a\n  // number used only when somebody renames the title column. The first ask after the drawn table\n  // changed reads it once; later asks share that read. A write goes through\n  // `updateOnTheWinningVersion`, which compares the column it changes with what the screen drew, so\n  // a version read at press time loses nothing the load-time read protected.\n  const read = useRef<{ key: string; version: Promise<number | null> } | null>(null);\n  const clientRef = useRef(client);\n  clientRef.current = client;\n  const keyRef = useRef(key);\n  keyRef.current = key;\n  return useCallback(async () => {\n    if (!tableId) return null;\n    if (read.current && read.current.key === keyRef.current) return read.current.version;\n    const version = readTableVersionNow(clientRef.current, tableId);\n    read.current = { key: keyRef.current, version };\n    return version;\n  }, [tableId]);\n}\n","// src/versions/askOnce.ts — @ai-matrx/records/versions (moved whole from records-ui 2026-10-08)\n//\n// ONE QUESTION IN FLIGHT, ONE ANSWER FOR EVERY ASKER (lane TABLE-ACTIONS T5.3, PROOF-BOOK 1.18).\n//\n// A table open asked `custom.field_options` 13 times for 2 choice columns (the colors, the label\n// lookup, the paste planner and each re-run of their effects each asked on their own) and the\n// header menus' value counts twice per column. Every asker of the same question, on the same\n// client, within `freshMs` of the last answer, gets that one answer. A refusal is never kept: the\n// next asker asks again. A write that changes the answer calls `forgetAsked` with its prefix.\n\nimport { onTableStructureChanged, type RecordsClient } from \"@ai-matrx/records/core\";\n\ntype Answer = { ok: boolean };\n\ntype Held = Map<string, { at: number; epoch: number; answer: Promise<unknown> }>;\n\n/**\n * A Table's shape moved (a column or its choices were written by anybody on this page): everything\n * kept before that moment is stale, whatever its age. This is what lets the freshness window cover a\n * whole page open (lane DEDUPE-READS) instead of two seconds.\n */\nlet structureEpoch = 0;\nonTableStructureChanged(() => {\n  structureEpoch += 1;\n});\n\nconst asked = new WeakMap<object, Held>();\n/** Per data source (the host's one supabase client survives a records client's rebuild) and per person. */\nconst byPerson = new WeakMap<object, Map<string, Held>>();\n\n/**\n * WHO IS ASKING, NOT WHICH OBJECT (lane SEED-ENTITY). The records client is REBUILT when the active\n * organization resolves (~1.5 s into a page); its reads re-fire from effects keyed on the client. The\n * questions kept here are semantic (a table, a column, a set of ids — never the organization), and the\n * answer is the same person's, so a rebuilt client over the SAME data source for the SAME person\n * shares them. A client with no data source in its config (a test double) keeps its own.\n */\nfunction heldFor(client: object): Held {\n  const config = (client as { config?: { dataSource?: unknown; actor?: { actor?: string; user_id?: string | null; on_behalf_of?: string | null } } }).config;\n  const source = config?.dataSource;\n  if (source && typeof source === \"object\" && config?.actor) {\n    const who = [config.actor.actor ?? \"-\", config.actor.user_id ?? \"-\", config.actor.on_behalf_of ?? \"-\"].join(\"|\");\n    let persons = byPerson.get(source);\n    if (!persons) {\n      persons = new Map();\n      byPerson.set(source, persons);\n    }\n    let held = persons.get(who);\n    if (!held) {\n      held = new Map();\n      persons.set(who, held);\n    }\n    return held;\n  }\n  let held = asked.get(client);\n  if (!held) {\n    held = new Map();\n    asked.set(client, held);\n  }\n  return held;\n}\n\n/**\n * `freshMs` > 0: the answer is kept that long after it was asked. `freshMs` <= 0: shared only while it\n * is IN FLIGHT — an asker after it settled asks again (for answers that may move at any moment).\n */\nexport function askOnce<T extends Answer>(client: object, key: string, ask: () => Promise<T>, freshMs: number): Promise<T> {\n  const held = heldFor(client);\n  const now = Date.now();\n  const kept = held.get(key);\n  if (kept && kept.epoch === structureEpoch && (freshMs <= 0 || now - kept.at <= freshMs)) return kept.answer as Promise<T>;\n  const entry: { at: number; epoch: number; answer: Promise<unknown> } = { at: now, epoch: structureEpoch, answer: Promise.resolve() };\n  const drop = () => {\n    if (held.get(key) === entry) held.delete(key);\n  };\n  const answer = ask().then(\n    (result) => {\n      if (!result.ok || freshMs <= 0) drop();\n      return result;\n    },\n    (thrown: unknown) => {\n      drop();\n      throw thrown;\n    },\n  );\n  entry.answer = answer;\n  held.set(key, entry);\n  return answer;\n}\n\n/** Tests only: forget everything kept for every client (tests that share one data source across cases). */\nexport function forgetAllAsked(client: object): void {\n  heldFor(client).clear();\n}\n\n/** Forget every kept answer whose key starts with `prefix` (a write changed what it answers). */\nexport function forgetAsked(client: object, prefix: string): void {\n  const held = heldFor(client);\n  for (const key of [...held.keys()]) if (key.startsWith(prefix)) held.delete(key);\n}\n\n/**\n * How long a column's choices are shared between askers: one page open, including the records\n * client being rebuilt when the active organization resolves (~2 s in) and every effect that re-runs\n * after it. 2 s ended just before the second fire (lane DEDUPE-READS: Spaces measured one at hydration\n * and one ~2 s later). A write on this page ends it at once (`structureEpoch`); another person's edit\n * shows within this window at most.\n */\nexport const FIELD_OPTIONS_FRESH_MS = 10_000;\n\n/** A column's choices, asked once for every asker in the same moment (`custom.field_options`). */\nexport function fieldOptionsOnce(\n  client: Pick<RecordsClient, \"fieldOptions\">,\n  fieldId: string,\n): ReturnType<RecordsClient[\"fieldOptions\"]> {\n  return askOnce(client, `field_options:${fieldId}`, () => client.fieldOptions({ field_id: fieldId }), FIELD_OPTIONS_FRESH_MS);\n}\n\n/** How long a page of badges is shared between askers: the one page open, ended by any explicit refresh. */\nexport const ENRICH_CELLS_FRESH_MS = 5_000;\n","// src/versions/refusals.ts — @ai-matrx/records/versions (moved whole from records-ui 2026-10-08)\n//\n// THE ONE BUILDER FOR A REFUSAL THIS PACKAGE WRITES ITSELF (lane REFUSAL-SWEEP,\n// 2026-09-23).\n//\n// `RefusalNotice` takes a `RecordsError`, and the store's own refusals arrive as\n// one. But twenty-six places in this package refused something IN THE BROWSER —\n// an answer not filled in, a file the browser could not read, a spreadsheet that\n// could not be written, a picker that could not list its choices — and each of\n// them held a bare string and printed it in red: no heading, no remedy, and in\n// five of them the store's `error.message` verbatim, straight past the\n// machine-identity filter every other screen goes through.\n//\n// So a refusal this package writes is built HERE, as the same object the store\n// hands back, and drawn by the same `RefusalNotice`. A person cannot tell which\n// half of the system said no and has no reason to care; `plainWords.ts` still\n// judges the sentence by shape, and the remedy is the one THIS call site knows\n// (the hint wins over the code's generic remedy — see `refusalForAPerson`).\n\nimport type { RecordsError, RecordsErrorCode } from \"@ai-matrx/records\";\n\n/**\n * A refusal in this package's own words.\n *\n * @param code     what KIND of refusal — picks the notice's title and its fallback remedy.\n * @param sentence what happened, for a person.\n * @param remedy   what to do now, when this call site knows better than the code's default.\n * @param diagnostic an engineer's note (a thrown message, a status) — rendered out of sight.\n */\nexport function refusal(\n  code: RecordsErrorCode,\n  sentence: string,\n  remedy?: string | null,\n  diagnostic?: string | null,\n): RecordsError {\n  return {\n    code,\n    message: sentence,\n    ours: true,\n    ...(remedy ? { hint: remedy } : {}),\n    ...(diagnostic ? { diagnostic } : {}),\n  } as RecordsError;\n}\n\n/**\n * A refusal made from something THROWN in the browser. The thrown text is an\n * engineer's (a parser's \"Unexpected token } in JSON at position 14\", a\n * library's stack) and goes out of sight; the person reads `sentence`.\n */\nexport function refusalFromThrown(\n  thrown: unknown,\n  sentence: string,\n  remedy?: string | null,\n  code: RecordsErrorCode = \"internal\",\n): RecordsError {\n  const said = thrown instanceof Error ? thrown.message : String(thrown ?? \"\");\n  return refusal(code, sentence, remedy, said ? `Thrown: ${said}` : null);\n}\n\n/**\n * The store's refusal when there is one, otherwise this package's own sentence —\n * for the call sites whose answer MAY carry an error (`res.error?.message ?? \"…\"`\n * was the old shape, and it printed the store's message raw).\n */\nexport function refusalOr(error: RecordsError | null | undefined, code: RecordsErrorCode, sentence: string): RecordsError {\n  return error ?? refusal(code, sentence);\n}\n\n/**\n * Whatever a host callback threw, as a refusal: the store's own `RecordsError`\n * when that is what arrived (it is drawn with its own words and remedy), and\n * otherwise `refusalFromThrown` — the thrown text out of sight, `sentence` in view.\n */\nexport function asRefusal(\n  thrown: unknown,\n  sentence: string,\n  remedy?: string | null,\n  code: RecordsErrorCode = \"internal\",\n): RecordsError {\n  const t = thrown as Partial<RecordsError> | null | undefined;\n  if (t && typeof t === \"object\" && typeof t.code === \"string\" && typeof t.message === \"string\" && !(thrown instanceof Error)) {\n    return t as RecordsError;\n  }\n  return refusalFromThrown(thrown, sentence, remedy, code);\n}\n","// src/versions/rowVersion.ts — @ai-matrx/records/versions · pure (server-safe)\nimport type { ReadRow } from \"@ai-matrx/records\";\n\n/** The version a row carries itself, when the host's read gave it one. */\nexport function ownVersion(row: ReadRow): number | null {\n  const v = (row as ReadRow & { version?: unknown }).version;\n  return typeof v === \"number\" ? v : null;\n}\n","// src/versions/writeOnTheWinningVersion.ts — @ai-matrx/records/versions (moved whole from records-ui 2026-10-08) · lane RECORDS-UI-FIX (2026-09-23)\n//\n// ONE ANSWER TO \"THE STORE SAID SOMEBODY ELSE WON\" — for every screen that writes a\n// record it read earlier (the record form, a saved view; the grid's cell session\n// applies the same rule inside its own queue).\n//\n// 🚨 WHY IT EXISTS. A screen reads the version it writes against from the record's\n// HISTORY, and the history can be short of the record: a write that changes nothing\n// still moves `version` and records no history row (reproduced on the dev clone,\n// 2026-09-23 — `custom.record_update` of an identical value: version 1 → 2, history\n// still 1; 68 live records were already in that state). So a person who is the only\n// writer is told \"Someone else changed this record while you were working on it\",\n// and every retry says it again.\n//\n// THE RULE. The refusal carries each patched column's CURRENT value\n// (`contested_fields`). When every one of them is still what this screen started\n// from, whatever \"won\" did not touch what this person is changing, so the patch is\n// sent once more on the version the refusal names. Anything else is a real conflict\n// and is handed back for the person to decide. A saved view passes `always` — it is\n// the person's own arrangement, and their latest press is the one that stands.\n\nimport type { RecordsResult, Uuid } from \"@ai-matrx/records\";\nimport { asWriteConflict, type RecordsClient } from \"@ai-matrx/records/core\";\nimport { updateRecordAt } from \"./recordVersions\";\n\n/** Two values the way a person would compare them: empty is empty, a list is its contents. */\nexport function sameStoredValue(left: unknown, right: unknown): boolean {\n  if (left === right) return true;\n  const empty = (v: unknown) => v === null || v === undefined || v === \"\";\n  if (empty(left) || empty(right)) return empty(left) && empty(right);\n  if (typeof left === \"object\" || typeof right === \"object\") {\n    try {\n      return JSON.stringify(left) === JSON.stringify(right);\n    } catch {\n      return false;\n    }\n  }\n  return false;\n}\n\nexport async function updateOnTheWinningVersion(\n  client: Pick<RecordsClient, \"recordUpdate\" | \"recordUpdateAddingChoices\">,\n  recordId: Uuid,\n  patch: Record<string, unknown>,\n  expectedVersion: number | null,\n  /** What this screen started from, per patched column — or `always` to resend regardless. */\n  base: Record<string, unknown> | \"always\",\n): Promise<RecordsResult<number>> {\n  // THE ONE WRITE DOOR (`recordVersions.ts`): an unread version (`null`) is refused in its own words,\n  // never sent as \"no version\" — which the store takes as last-write-wins (lane VW, verifier D6).\n  const send = (expected: number | null) => updateRecordAt(client, { record_id: recordId, patch, version: expected });\n  const first = await send(expectedVersion);\n  if (first.ok) return first;\n  const conflict = asWriteConflict(first.error, recordId);\n  if (!conflict) return first;\n  const untouched =\n    base === \"always\" ||\n    Object.keys(patch).every((key) => sameStoredValue(conflict.contested_fields[key], base[key]));\n  if (!untouched) return first;\n  return send(conflict.current_version);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6BA,mBAAwD;;;ACnBxD,kBAA4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