{"version":3,"sources":["../../src/setup/index.ts","../../src/recordType.ts","../../src/core/primedBundle.ts","../../src/results.ts","../../src/core/pgError.ts","../../src/core/transient.ts","../../src/core/doorCall.ts","../../src/core/recordChanges.ts","../../src/archive.ts","../../src/aggregate.ts","../../src/record.ts","../../src/subscription.ts","../../src/rowLabel.ts","../../src/relation.ts","../../src/formulaLook.ts","../../src/ops.ts","../../src/scopes/types.ts","../../src/scopes/codec.ts","../../src/scopes/rules.ts","../../src/scopes/doors.ts","../../src/core/pickListDoors.ts","../../src/choice.ts","../../src/placement.ts","../../src/level.ts","../../src/core/keysetCursor.ts","../../src/table.ts","../../src/grid.ts","../../src/store.generated.ts","../../src/core/doors.ts","../../src/core/supabase.ts","../../src/drill.ts","../../src/core/query.ts","../../src/core/client.ts","../../src/relativeDays.ts","../../src/entity/core/errors.ts","../../src/entity/core/client.ts","../../src/entity/port/port.ts","../../src/entity/core/realtime.ts","../../src/entity/core/wire.ts","../../src/entity/port/rows.ts","../../src/objectOrganization.ts","../../src/realtime/index.ts","../../src/search/index.ts"],"sourcesContent":["// @ai-matrx/records/setup — ONE CALL that gives a company everything it needs to put our record store\n// inside its own system: the typed client (tables, records, versions, archive), live changes, search\n// across tables, platform records (contacts, projects, tasks) and a slot for the associations store.\n// React-free; works in a browser, a Node script or a server.\n//\n//   const matrx = await createRecords({ auth: sessionAuth(supabase), organizationId });\n//   const rows = await matrx.records.list({ table_id, limit: 50 });\n//   const stop = matrx.watch(table_id, { records: (ids) => reload(ids) });\n//\n// HOW IT SIGNS IN IS A PORT. `sessionAuth(supabase)` is a supabase-js client carrying a signed-in\n// person's session — the only mode today. An organization API key will plug in as another\n// `RecordsAuthPort` (it hands back a database client bearing a short-lived token for the key's own\n// identity, so row security, doors and live changes work unchanged); nothing else here changes.\n//\n// THE ORGANIZATION IS THE HOST'S. `organizationId` is where new things are saved and which\n// organization a write runs in; reads span every organization the signed-in identity belongs to.\n// Nothing here picks one.\n\nimport { createRealtimeManager, type RealtimeManager } from \"@ai-matrx/data/realtime\";\nimport { createRecordsClient, type RecordsClient } from \"../core/client\";\nimport { supabaseDataSource } from \"../core/supabase\";\nimport { createEntityClient } from \"../entity/core/client\";\nimport { createEntityDataPort, type CreateEntityDataPortOptions, type EntityDataPort } from \"../entity/port/port\";\nimport { whereIdOpensPort, type ObjectOrganizationAnswer, type RecordOrganizationPort } from \"../objectOrganization\";\nimport type { RecordsConfig, RecordsChangeSink, RecordsDataSource, RecordsErrorSink, RecordsRealtimePort, RowAgentPort, RowAgentTarget } from \"../ports\";\nimport type { Uuid } from \"../record\";\nimport { createOpLedger } from \"../ops\";\nimport { createRecordsRealtimePort } from \"../realtime\";\nimport { listStoreRecordCandidates, searchRecords, type RecordSearchHit, type RecordSearchRequest } from \"../search\";\nimport type { RecordsResult } from \"../results\";\n\n/** A signed-in database identity: the client every door and live change rides, and who it is. */\nexport interface RecordsSession {\n  /** A supabase-js client (or anything shaped like one) carrying the identity's access token. */\n  supabase: object;\n  /** The identity's user id, when known (the live-change echo test and the client's own mirror use it). */\n  userId?: Uuid;\n}\n\n/** How setup signs in. Session today; an organization API key later — same port. */\nexport interface RecordsAuthPort {\n  readonly kind: \"session\" | \"api_key\";\n  session(): Promise<RecordsSession>;\n}\n\n/** A supabase-js client that already carries a signed-in person (browser sign-in, `signInWithPassword`, SSR cookies). */\nexport function sessionAuth(supabase: object, userId?: Uuid): RecordsAuthPort {\n  return {\n    kind: \"session\",\n    async session() {\n      if (userId) return { supabase, userId };\n      const auth = (supabase as { auth?: { getUser?: () => Promise<{ data?: { user?: { id?: string } | null } }> } }).auth;\n      const found = auth?.getUser ? (await auth.getUser()).data?.user?.id : undefined;\n      return found ? { supabase, userId: found } : { supabase };\n    },\n  };\n}\n\nexport interface CreateRecordsOptions<TAssociations = never> {\n  auth: RecordsAuthPort;\n  /**\n   * Where new things are saved and which organization a write runs in. `null` = no writes, reads across\n   * all. A function receives every organization the identity belongs to and answers the host's choice.\n   */\n  organizationId: Uuid | null | ((organizationIds: readonly Uuid[]) => Uuid | null);\n  /** Who is acting. Default: the signed-in person (`user`). An agent acting for a person names `on_behalf_of`. */\n  actor?: RecordsConfig[\"actor\"];\n  /**\n   * Live changes. Default `true`: one realtime manager over the session's client. Pass your own\n   * `RealtimeManager` to share a socket, or `false` for none (`watch` then says so and returns a no-op).\n   */\n  live?: boolean | RealtimeManager;\n  /**\n   * Platform-record aliases (`{ contacts: { kind: \"entity\", token: \"party\" } }`) for `entities`. Optional.\n   */\n  entityAliases?: CreateEntityDataPortOptions[\"aliases\"];\n  /** The associations store (`@ai-matrx/associations/core` `createAssociationsStore`) bound by the host; handed back as-is. */\n  associations?: TAssociations;\n  /**\n   * WHICH ORGANIZATION OWNS A RECORD — a port. Default: `custom.where_id_opens`, one call per ask. A host\n   * that keeps answers across remounts or seeds them from a server render binds its own.\n   */\n  organizationOf?: RecordOrganizationPort;\n  /** RUN AN AGENT ON A ROW — a port the host binds (the run belongs to `@ai-matrx/agents`). Unbound, there is none. */\n  rowAgent?: RowAgentPort;\n  onError?: RecordsErrorSink;\n}\n\nexport interface RecordsSetup<TAssociations = never> {\n  /** How this setup signed in. */\n  readonly authKind: RecordsAuthPort[\"kind\"];\n  /** The signed-in identity's user id, when known. */\n  readonly userId: Uuid | undefined;\n  /** Every organization the identity belongs to (reads span them; the host filters visibly). */\n  readonly organizationIds: readonly Uuid[];\n  /** Where this setup's writes go (the host's choice), or null. */\n  readonly organizationId: Uuid | null;\n  /** The typed client over the store's doors: tables, records, versions, archive and restore, views, forms… */\n  readonly records: RecordsClient;\n  /** The data source the doors ride — hand it to any other section (`records/forms`, `records/search`). */\n  readonly dataSource: RecordsDataSource;\n  /** Platform records (contacts, projects, tasks) through the same port shape custom tables use. */\n  readonly entities: EntityDataPort;\n  /** The live-changes manager, or null when `live: false`. */\n  readonly realtime: RealtimeManager | null;\n  /** Search every table the identity can see (never narrowed by `organizationId`). */\n  search(request: RecordSearchRequest): Promise<RecordsResult<RecordSearchHit[]>>;\n  /** Candidates for a \"link a record\" picker. */\n  recordCandidates(args: { search?: string; limit?: number }): ReturnType<typeof listStoreRecordCandidates>;\n  /**\n   * Watch one table's records (other people's changes; this setup's own writes are dropped). `records(ids)`\n   * names the changed records (`null` = re-read the page); `shape()` = the table's columns moved.\n   */\n  watch(tableId: Uuid, sink: Partial<RecordsChangeSink>, organizationId?: Uuid): () => void;\n  /** The associations store the host bound, if any. */\n  readonly associations: TAssociations | undefined;\n  /** Which organization owns an object (table, record, form…), read from the object — never the person's pick. */\n  organizationOf(id: Uuid): Promise<ObjectOrganizationAnswer>;\n  /** The host's agent runner, or null when none is bound (agent buttons are then not drawn). */\n  readonly rowAgent: RowAgentPort | null;\n  /** Run an agent on a row through the bound runner; refuses by name when none is bound. */\n  runAgentOnRow(target: RowAgentTarget): Promise<RecordsResult<void>>;\n  /** Close live channels (a Node script calls this before it exits). */\n  close(): void;\n}\n\nexport async function createRecords<TAssociations = never>(options: CreateRecordsOptions<TAssociations>): Promise<RecordsSetup<TAssociations>> {\n  const { supabase, userId } = await options.auth.session();\n  const dataSource = supabaseDataSource(supabase);\n\n  const members = await createEntityClient({ dataSource }).memberOrganizations();\n  const organizationIds: Uuid[] = members.ok ? [...members.data] : [];\n  if (!members.ok) console.warn(`[@ai-matrx/records/setup] could not read this identity's organizations: ${members.error.message}`);\n  const organizationId = typeof options.organizationId === \"function\" ? options.organizationId(organizationIds) : options.organizationId;\n  if (organizationId && !organizationIds.includes(organizationId)) organizationIds.push(organizationId);\n\n  let realtime: RealtimeManager | null = null;\n  let ownsRealtime = false;\n  if (options.live === undefined || options.live === true) {\n    realtime = createRealtimeManager({ client: supabase as Parameters<typeof createRealtimeManager>[0][\"client\"], actorId: userId });\n    ownsRealtime = true;\n  } else if (options.live) {\n    realtime = options.live;\n  }\n  // OWN-WRITE DETECTION IS THIS SETUP'S: one ledger shared by its client, its entity port and its\n  // live port, so a second setup in the same process hears this one's writes (ops.ts).\n  const opLedger = createOpLedger();\n  const realtimePort: RecordsRealtimePort | undefined = realtime ? createRecordsRealtimePort({ manager: realtime, ledger: opLedger }) : undefined;\n\n  const actor = options.actor ?? { actor: \"user\" as const, ...(userId ? { user_id: userId } : {}) };\n  const records = createRecordsClient({\n    dataSource,\n    actor,\n    organizationId,\n    organizationIds,\n    opLedger,\n    ...(realtimePort ? { realtime: realtimePort } : {}),\n    ...(options.onError ? { onError: options.onError } : {}),\n  });\n\n  const entities = createEntityDataPort({\n    dataSource,\n    aliases: options.entityAliases ?? {},\n    opLedger,\n    ...(organizationId ? { organization: organizationId } : {}),\n  });\n\n  const organizationIdChosen = organizationId;\n  const organizationPort = options.organizationOf ?? whereIdOpensPort(dataSource);\n  let warnedNotLive = false;\n  return {\n    authKind: options.auth.kind,\n    userId,\n    organizationIds,\n    organizationId,\n    records,\n    dataSource,\n    entities,\n    realtime,\n    search: (request) => searchRecords(dataSource, request),\n    recordCandidates: (args) => listStoreRecordCandidates(dataSource, args),\n    watch(tableId, sink, organizationId) {\n      const activeOrganizationId = organizationIdChosen;\n      const org = organizationId ?? activeOrganizationId;\n      if (!realtimePort || !org) {\n        if (!warnedNotLive) {\n          warnedNotLive = true;\n          console.warn(`[@ai-matrx/records/setup] watch(${tableId}) is not live: ${realtimePort ? \"no organization to watch (pass one)\" : \"live changes are off (live: false)\"}.`);\n        }\n        return () => {};\n      }\n      return realtimePort.subscribeRecords({ organization_id: org, table_id: tableId }, { records: sink.records ?? (() => {}), shape: sink.shape ?? (() => {}) });\n    },\n    associations: options.associations,\n    organizationOf: (id) => organizationPort.organizationOf(id),\n    rowAgent: options.rowAgent ?? null,\n    async runAgentOnRow(target) {\n      if (!options.rowAgent) {\n        return {\n          ok: false,\n          error: { code: \"not_supported\", message: \"No agent runner is bound: pass createRecords({ rowAgent }) to run an agent on a row.\" },\n        };\n      }\n      await options.rowAgent.run(target);\n      return { ok: true, data: undefined };\n    },\n    close() {\n      if (ownsRealtime) realtime?.dispose();\n    },\n  };\n}\n","// src/recordType.ts — @ai-matrx/records · lane CLOSE-CORE (CD-CORE-15, acceptance test 8 \"Type field\")\n//\n// A TABLE WHOSE TYPE FIELD DECIDES ITS COLUMNS. A Shape table whose Kind is its type field: a Circle has a\n// Radius, a Rectangle a Width and a Height. Which columns one record has is the STORE's answer\n// (`custom.applicable_fields` with that record's type, `client.fields({ recordType })`); these helpers are only\n// the pure facts a screen needs around that answer:\n//   · which type a record IS (its type field's value),\n//   · the question a table's OWN screens ask (`EVERY_RECORD_TYPE`: the grid's columns, Column settings,\n//     filters list Radius and Width side by side), and\n//   · whether a column a screen already holds applies to a record's type, so a grid draws a Rectangle's Radius\n//     cell as \"does not apply\" instead of an empty box that invites a value the store would put away.\n\n/** Anything that names the record types it applies to: a Field, or one of its Rules. */\nexport interface NamesRecordTypes {\n  applies_to_types?: readonly string[] | null | undefined;\n}\n\n/** Asked of `client.fields` / `useFields`: every column of the table, whichever record types it applies to. */\nexport const EVERY_RECORD_TYPE = \"*\";\n\n/** The words of a type as a person may have written them: \"Big circle\", \"big_circle\" and \"BIG-CIRCLE\" agree. */\nfunction typeWord(value: string): string {\n  return value.trim().toLowerCase().replace(/[\\s_-]+/g, \" \");\n}\n\n/**\n * The record type of one record: the value of its table's type field (a choice's key), or undefined when the\n * table has no type field or the record has no type yet. A list value reads as its first choice.\n */\nexport function recordTypeOf(\n  table: { type_field?: string | null | undefined } | null | undefined,\n  document: Record<string, unknown> | null | undefined,\n): string | undefined {\n  const key = table?.type_field;\n  if (!key || !document) return undefined;\n  const raw = document[key];\n  const value = Array.isArray(raw) ? raw[0] : raw;\n  return typeof value === \"string\" && value.trim() !== \"\" ? value : undefined;\n}\n\n/** A column every record has (it names no record types). */\nexport function fieldAppliesToEveryType(field: NamesRecordTypes): boolean {\n  return !Array.isArray(field.applies_to_types) || field.applies_to_types.length === 0;\n}\n\n/**\n * Whether a column applies to a record of this type. A column that names no types applies to every record; one\n * that names types applies only to a record whose type is one of them, compared as words (the store also\n * matches a choice's id, so a column declared by option id may read as applying here only after the store says\n * so — a screen asks the store when it matters).\n */\nexport function fieldAppliesToType(field: NamesRecordTypes, recordType: string | null | undefined): boolean {\n  if (fieldAppliesToEveryType(field)) return true;\n  if (recordType === undefined || recordType === null || recordType === \"\") return false;\n  if (recordType === EVERY_RECORD_TYPE) return true;\n  const wanted = typeWord(recordType);\n  return (field.applies_to_types ?? []).some((t) => typeof t === \"string\" && typeWord(t) === wanted);\n}\n\n/** The record types a column names, as they were written. Empty for a column every record has. */\nexport function typesOfField(field: NamesRecordTypes): string[] {\n  return fieldAppliesToEveryType(field) ? [] : (field.applies_to_types ?? []).filter((t): t is string => typeof t === \"string\");\n}\n","// src/core/primedBundle.ts — A TABLE PAGE'S BUNDLE, ASKED BEFORE THE PAGE'S SCRIPT HAS BOOTED (lane PAGE-BUNDLE-2).\n//\n// THE USE CASE: Dr. Patel's front desk opens \"Visits\" from a link. The server that renders the page\n// already holds her session, so it asks `custom.table_page_bundle` AS HER while the browser is still\n// downloading the page's script, and hands the answer (a promise, streamed) to the page. The records\n// client that mounts a moment later finds it here and asks nothing: its first wave of doors is already\n// answered. Without this the bundle was asked only after the whole app had booted (~1 s on production).\n//\n// HOW IT STAYS THE SAME: the primed answer is exactly what `custom.table_page_bundle` answered for the\n// same organization, Table and view, so `callDoor`'s part-by-part matching (name and every argument)\n// is unchanged. It is used ONCE and only while fresh (PRIMED_TTL_MS); an answer that is an error, or\n// not a bundle, is ignored and the bundle is asked as it always was. A primed answer never turns a\n// refusal into \"empty\": a refusing part is still asked by its own door.\n\n/** What a data source's `rpc` answers for `custom.table_page_bundle` (PostgREST's `{ data, error }`). */\nexport interface PrimedBundleAnswer {\n  data: unknown;\n  error: unknown;\n}\n\nconst PRIMED_TTL_MS = 15_000;\n\n/**\n * ONE REGISTRY FOR EVERY COPY OF THIS FILE. The package's entries (`/core`, `/react`, `/data`,\n * `/typed-table`) are bundled separately and each carries its own copy of the client, so a module-level\n * Map here would be FOUR maps: the host primes `/core`'s and the `RecordsProvider` (`/react`) never\n * sees it (measured on /data/<table>, 2026-10-07: the bundle was asked again). The registry lives\n * on `globalThis` under one well-known symbol, so every copy reads the same one.\n */\nconst REGISTRY = Symbol.for(\"@ai-matrx/records/primed-table-page-bundles\");\ntype Registry = Map<string, { answer: Promise<PrimedBundleAnswer>; at: number }>;\nfunction registry(): Registry {\n  const g = globalThis as unknown as Record<symbol, Registry | undefined>;\n  return (g[REGISTRY] ??= new Map());\n}\n\nconst primedKey = (organizationId: string, tableId: string, viewId: string | null | undefined): string =>\n  `${organizationId}|${tableId}|${viewId ?? \"\"}`;\n\n/**\n * Hand the records client a table page's bundle that was asked elsewhere (the server render, as the\n * same person). The next records client that opens this Table in this organization uses it instead of\n * asking — once, within PRIMED_TTL_MS.\n */\nexport function primeTablePageBundle(input: {\n  organizationId: string;\n  tableId: string;\n  viewId?: string | null;\n  answer: Promise<PrimedBundleAnswer> | PrimedBundleAnswer;\n}): void {\n  const answer = Promise.resolve(input.answer).catch((thrown: unknown) => ({ data: null, error: thrown }));\n  registry().set(primedKey(input.organizationId, input.tableId, input.viewId), { answer, at: Date.now() });\n}\n\n/** The primed answer for this page, once — or null (none, or stale). */\nexport function takePrimedTablePageBundle(\n  organizationId: string | null | undefined,\n  tableId: string,\n  viewId: string | null | undefined,\n): Promise<PrimedBundleAnswer> | null {\n  if (!organizationId) return null;\n  const key = primedKey(organizationId, tableId, viewId);\n  const primed = registry();\n  const held = primed.get(key);\n  if (!held) return null;\n  primed.delete(key);\n  return Date.now() - held.at < PRIMED_TTL_MS ? held.answer : null;\n}\n\n/**\n * A WRITE HAPPENED ON THIS TABLE: its primed page bundle (asked by the server before the write, never\n * used because the page opened from the seed) would answer the next read with the table as it WAS.\n * Forget the Table's (`tableId`), or every one when the write did not name a Table (`null`).\n */\nexport function forgetPrimedTablePageBundlesOf(tableId: string | null): void {\n  const primed = registry();\n  for (const key of [...primed.keys()]) if (tableId === null || key.split(\"|\")[1] === tableId) primed.delete(key);\n}\n\n/** Tests only: forget every primed answer. */\nexport function forgetPrimedTablePageBundles(): void {\n  registry().clear();\n}\n\n/**\n * A RECORD PAGE'S BUNDLE (`custom.record_page_bundle`), asked elsewhere as the same person — the\n * record-page twin of `primeTablePageBundle`, held in the same registry, used once, while fresh.\n */\nexport function primeRecordPageBundle(input: {\n  organizationId: string;\n  recordId: string;\n  answer: Promise<PrimedBundleAnswer> | PrimedBundleAnswer;\n}): void {\n  primeTablePageBundle({ organizationId: input.organizationId, tableId: `record:${input.recordId}`, answer: input.answer });\n}\n\n// ─────────────────────────────────────────────────────────────────────────────────────────────\n// ANY DOOR'S ANSWER, ASKED ON THE SERVER, SERVED TO THE BROWSER'S OWN CALL, WHILE IT IS YOUNG (lane SEED-ENTITY)\n//\n// THE USE CASE: a grouped Visits table. Its group counts and its link labels are read by the grid in\n// effects, after the first paint — not in a first pass a seed can suspend. The server asked them too\n// (`askTablePageSeed`), so the provider hands every seeded answer here; the records client's own\n// `callDoor` finds the exact call (door name and every argument) and answers it while it is\n// young (10 s). A call that differs by any argument is asked of the store as always. A write (any door that\n// is not a read) empties the registry, so nothing stale is ever served after a change.\n// ─────────────────────────────────────────────────────────────────────────────────────────────\n\nconst DOOR_REGISTRY = Symbol.for(\"@ai-matrx/records/primed-door-answers\");\ntype DoorRegistry = Map<string, { data: unknown; at: number }>;\nfunction doorRegistry(): DoorRegistry {\n  const g = globalThis as unknown as Record<symbol, DoorRegistry | undefined>;\n  return (g[DOOR_REGISTRY] ??= new Map());\n}\n\n/** How long a primed door answer stays servable, counted from when the server asked. */\nexport const PRIMED_DOOR_TTL_MS = 10_000;\n\n/** Keep one door's answer (`key` = door name + canonical arguments, as `seedKey` builds it). */\nexport function primeDoorAnswer(key: string, data: unknown, at: number): void {\n  doorRegistry().set(key, { data, at });\n}\n\n/**\n * The primed answer to this exact call — or null (none, or older than the window). Served for the whole\n * window, not once: a grid's effect runs again when its rows land (same call, same answer). A write drops it.\n */\nexport function takePrimedDoorAnswer(key: string): { data: unknown } | null {\n  const registry = doorRegistry();\n  const held = registry.get(key);\n  if (!held) return null;\n  if (Date.now() - held.at < PRIMED_DOOR_TTL_MS) return { data: held.data };\n  registry.delete(key);\n  return null;\n}\n\n/**\n * A write happened: nothing primed is trusted any more — or, with `doors`, only what those doors answered\n * (a saved view changes the views and the layout, never a record's value or a count of records).\n */\nexport function dropPrimedDoorAnswers(doors?: readonly string[]): void {\n  const registry = doorRegistry();\n  if (!doors) {\n    registry.clear();\n    return;\n  }\n  for (const key of [...registry.keys()]) if (doors.some((door) => key.startsWith(`${door}|`))) registry.delete(key);\n}\n\n/** Writes that change only how a table is LOOKED AT: they drop these reads, and no others. */\nexport const LOOK_WRITES: Record<string, readonly string[]> = {\n  view_declare: [\"views\", \"view_look_read\", \"grid_layout\", \"table_page_bundle\"],\n  view_designate: [\"views\", \"view_look_read\", \"grid_layout\", \"table_page_bundle\"],\n  view_look_set: [\"views\", \"view_look_read\", \"grid_layout\", \"table_page_bundle\"],\n  view_record_order_set: [\"views\", \"view_look_read\", \"grid_layout\", \"table_page_bundle\"],\n};\n\n/**\n * A door that WRITES, by the verbs the store names its writers with. Anything this matches drops the\n * registry; a read that merely looks like a writer only costs a primed answer, never a stale one.\n */\nexport function isWritingDoor(door: string): boolean {\n  return /(_declare|_set(_|$)|_update|_write|_delete|_restore|_archive|_upsert|_reparent|_change|_duplicate|_move|_decide|_run$|_submit|_publish|_import_|_start$|_complete|_sign$|_add$|_retire|_propose|_promote|_land$|_pin$|_mute|_snooze|_unsnooze|_clear|_unclear|_revoke|_issue|_bind|_unbind|_apply|_backfill|_sync$|_decorate|_designate|_ensure|^migrate_|^set_table_|^home_add|^capture_|^claim_|^record_stage|^anon_|^io_import_|^io_comment_resolve|^enrich_(declare|land|pin)|^field_(declare|duplicate|propose|restore|retire|update)|^table_(declare|ensure|from_example|move|sync)|^value_restore|^relation_own)/.test(door);\n}\n","// src/results.ts — @ai-matrx/records\n//\n// THE NEVER-THROW RESULT ENVELOPE, and the refusal vocabulary behind it.\n//\n// This package's whole posture toward the store is in one sentence: THE CLIENT\n// MIRRORS THE STORE'S CONTRACT AND NEVER RE-IMPLEMENTS A RULE THE STORE\n// ENFORCES. When the store refuses, the client hands back the store's OWN\n// message, the store's OWN hint and the store's OWN SQLSTATE, under a code a\n// screen can branch on. It never rewrites the sentence, never swallows it, and\n// never invents a friendlier one — the store's refusals were written to be read\n// by a person, and a client that paraphrases them is lying about what happened.\n\nimport type { PerValueAccessWord } from \"./vocabulary\";\nimport type { Uuid } from \"./record\";\n\n/**\n * What KIND of refusal it was. The mapping from SQLSTATE to code lives in\n * `/core`, and it is checked against `STORE_REFUSAL_CODES` — the list of every\n * SQLSTATE the store's own bodies raise, generated from the live catalog. A\n * code the store can raise and this union cannot name is a hole, and the\n * real-door suite fails on it.\n */\nexport type RecordsErrorCode =\n  /** `PT409` — somebody else's write won. The record clock moved under you. */\n  | \"stale_write\"\n  /**\n   * The call needs an organization and none was carried (the platform's `organization_required`; the entity\n   * doors' MX002). Never resolved by guessing one: the person is shown their memberships and picks.\n   */\n  | \"organization_required\"\n  /** `42501` — a door. Either the schema is revoked, or the store is switched off, or this principal may not pass. */\n  | \"door\"\n  /** `23514` — a Rule, a shape guard, or a validation the store enforces refused it. */\n  | \"refused_by_rule\"\n  /**\n   * `22004` / `22023` / `22P02` — the call itself was malformed: a missing id, a\n   * patch that is not an object, or a value that does not fit the type the\n   * store holds for that Field. The store's own message names the value and the\n   * type it could not be read as.\n   */\n  | \"invalid_argument\"\n  /** `02000` — the record is not here (deleted, never existed, or another organization's). */\n  | \"not_found\"\n  /** `23503` — something it points at is not there. */\n  | \"missing_reference\"\n  /** `23505` — that thing is already here. */\n  | \"already_exists\"\n  /** `0A000` — the store does not do this yet, and says which part. */\n  | \"not_supported\"\n  /** `53400` / `22012` — the store ran out of something, or the arithmetic could not be done. */\n  | \"store_limit\"\n  /**\n   * `40001` — the read-access snapshot this connection carries is older than a\n   * write the reader has already observed, so the store refused to answer at\n   * all rather than hand back something they just lost. Retry on a fresh\n   * connection; it is the one refusal in this list that is worth repeating.\n   */\n  | \"stale_read\"\n  /**\n   * `57014` — the store cancelled the statement at its own timeout. Nothing was\n   * refused on its merits and nothing was written; the same call can succeed on\n   * a smaller page or a quieter moment. With `stale_read`, one of the only two\n   * refusals in this list worth repeating.\n   */\n  | \"timed_out\"\n  /**\n   * THE DOOR THAT DOES NOT EXIST YET. Not an error condition in the database —\n   * this package asked for a door that is not in the live catalogue, so it\n   * refused to guess. `door_absent` always names the door and the lane that\n   * owns it; it is never a silent no-op and never an empty list.\n   */\n  | \"door_absent\"\n  /**\n   * `PGRST202` / `PGRST205` — PostgREST could not find the function or the\n   * schema. The database this client is pointed at is not serving the record\n   * store: the schema is not exposed, or the grants are not there.\n   */\n  | \"store_not_served\"\n  /**\n   * `PT428` — the move was not refused and it did not happen: a stage gate whose\n   * `on_fail` is `require_approval` filed a request with the people who can\n   * answer it, and left the record exactly where it was. The store's own\n   * sentence is the gate's own sentence, and the DETAIL carries the approval.\n   *\n   * It is the one code in this list that is not a failure. A screen that drew it\n   * as one would tell somebody their work was rejected when it is being\n   * considered; a screen that drew it as success would move the card while\n   * somebody is still deciding. `custom.pipeline_move` answers an object on this\n   * path rather than raising, so a caller only meets PT428 when the move went\n   * through the ORDINARY write door — which is most of them.\n   */\n  | \"needs_approval\"\n  /**\n   * THE CALL NEVER REACHED THE STORE. Not a refusal — a transport failure: the\n   * browser lost the network, the gateway answered with an HTTP status and no\n   * body, the request was cancelled. supabase-js hands these back with an EMPTY\n   * `code` (a `FetchError`) or with the HTTP status in it (`\"404\"`, `\"502\"`),\n   * neither of which is a SQLSTATE, and until 2026-09-22 they all landed in\n   * `internal` — which is the one classification that tells a screen nothing,\n   * and which made the package print a sentence about ITSELF to the person\n   * (lane TAILS-6). Nothing was written, and the same call can simply be made\n   * again, which is what separates it from `internal`.\n   */\n  | \"unreachable\"\n  /** Anything the mapper could not place. It still carries the store's own words. */\n  | \"internal\";\n\n/** A refusal, in the store's own words. */\nexport interface RecordsError {\n  code: RecordsErrorCode;\n  /** THE STORE'S message, verbatim. Never paraphrased. */\n  message: string;\n  /** THE STORE'S hint, verbatim — this is where the remedy is written. */\n  hint?: string;\n  /** The SQLSTATE, so a caller can be exact when a code is not exact enough. */\n  sqlstate?: string;\n  /** Whatever the store put in DETAIL, parsed when it was json. */\n  detail?: unknown;\n  /**\n   * TRUE when this package did not recognize the class it was handed, so a\n   * caller can say so instead of reading the silence as \"handled\".\n   *\n   * 🚨 IT IS A FLAG AND A SEPARATE SENTENCE, NEVER AN APPENDIX TO `hint`\n   * (lane TAILS-6, 2026-09-22). `mapPgError` used to append \"@ai-matrx/records\n   * did not recognize SQLSTATE … from checklistTemplates\" ONTO `hint`, and\n   * `hint` is the field every screen treats as THE REMEDY — the sentence a\n   * person is told to act on. So a dropped connection on the Checklists tab\n   * showed a plumbing company \"Something went wrong at our end\" over a line\n   * about a TypeScript package and a SQLSTATE. A note this package writes about\n   * ITSELF is for whoever debugs it and belongs nowhere a person reads.\n   */\n  unmapped?: boolean;\n  /**\n   * THIS PACKAGE'S OWN NOTE, for an engineer. Never the store's words and never\n   * a person's: screens render it out of sight (a `title` attribute, a\n   * screen-reader line) or not at all.\n   */\n  diagnostic?: string;\n}\n\nexport type RecordsResult<T> = { ok: true; data: T } | { ok: false; error: RecordsError };\n\n/** Narrowing helper for hosts compiled without `strictNullChecks`. */\nexport function isRecordsErr<T>(\n  result: RecordsResult<T>,\n): result is { ok: false; error: RecordsError } {\n  return result.ok === false;\n}\n\n/**\n * A result's data, or THROW its refusal as an `Error` carrying the store's sentence — for the places\n * a throw is the contract (a `createAsyncThunk` body, a loader whose caller catches and shows it).\n */\nexport function unwrapRecords<T>(result: RecordsResult<T>): T {\n  if (result.ok) return result.data;\n  throw new Error(result.error.message);\n}\n\nexport const ok = <T>(data: T): RecordsResult<T> => ({ ok: true, data });\nexport const err = <T>(error: RecordsError): RecordsResult<T> => ({ ok: false, error });\n\n/**\n * A `stale_write` carries everything the screen needs to show the conflict\n * rather than a toast: which version you wrote against, which one won, and the\n * value of every field you touched as it stands now. The store builds this and\n * this type is its shape — nothing is reconstructed on the client.\n */\nexport interface StaleWriteDetail {\n  expected_version: number;\n  current_version: number;\n  contested_fields: Record<string, unknown>;\n}\n\n/** The parsed form of a `stale_write`, for `useRecordMutation`'s conflict state. */\nexport interface WriteConflict extends StaleWriteDetail {\n  record_id: Uuid;\n  /** The store's own sentence — what the screen shows. */\n  message: string;\n  /** The store's own remedy. */\n  hint: string;\n}\n\n/**\n * The structural shape of a PostgREST failure as supabase-js resolves it: a\n * PLAIN OBJECT parsed from the response body, NOT an `Error`. Reading\n * `.message` off `instanceof Error` discards the real database message on every\n * genuine failure.\n */\nexport interface PgError {\n  code?: string | null;\n  message: string;\n  details?: string | null;\n  hint?: string | null;\n}\n\n/** What the validation mirror answers: the same sentence the trigger would raise. */\nexport interface PredictedRefusal {\n  /** The field key the store would name, when it names one. */\n  field_key?: string;\n  /** The message the store's own body would raise, word for word. */\n  message: string;\n  hint?: string;\n  /** The store's structured detail, when its refusal carries one (e.g. `{ example }`). */\n  detail?: Record<string, unknown>;\n  sqlstate: string;\n  /**\n   * Which of the store's bodies would raise it, so a reader can go and check\n   * that this mirror still tells the truth.\n   */\n  predicted_by: string;\n}\n\n/** VAL-5 / VAL-6, named so a caller can say which word was the problem. */\nexport interface ForbiddenEnvelopeWord {\n  field_key: string;\n  word: PerValueAccessWord;\n}\n","// src/core/pgError.ts — @ai-matrx/records\n//\n// THE ONE FUNNEL from what the database said to what a caller reads. Every\n// method in this package's client goes through it, and it does exactly three\n// things: it classifies the SQLSTATE, it carries the store's message and hint\n// VERBATIM, and it parses the DETAIL when the store put json there.\n//\n// It never writes a sentence of its own about a refusal the store already\n// explained. The store's messages were written to be read by the person who hit\n// them — \"Someone else changed this record while you were working on it\" is the\n// screen's text, not a code the screen has to translate.\n\nimport type { PgError, RecordsError, RecordsErrorCode, StaleWriteDetail } from \"../results\";\n\n/**\n * SQLSTATE -> code. Every entry here answers one of the codes\n * `STORE_REFUSAL_CODES` reports the store raising; the real-door suite asserts\n * that this map covers all of them, so a new refusal class in the store shows\n * up as a red test rather than an `internal` in somebody's console.\n */\nconst BY_SQLSTATE: Record<string, RecordsErrorCode> = {\n  // Also what custom.has_visibility_at / table_move / whole_value_complete raise since 2026-10-21 (they\n  // raised 40001, which PostgREST retries without limit — the outage that day).\n  PT409: \"stale_write\",\n  \"42501\": \"door\",\n  \"23514\": \"refused_by_rule\",\n  \"22004\": \"invalid_argument\",\n  \"22023\": \"invalid_argument\",\n  // MX005 — a value the store cannot take as asked: since 2026-10-06 (AP-3 U3) a word that names more than one\n  // choice or linked record raises it (it used to borrow PT409 and read as somebody else's write winning).\n  MX005: \"invalid_argument\",\n  // MXD01 — the held-change door tried the proposed values before filing an\n  // approval request and the store refused them. Nothing is waiting for a\n  // person to decide; correct the value before asking again, which is the same\n  // caller-side condition as the other invalid-argument refusals.\n  MXD01: \"invalid_argument\",\n  // 22P02 — a value does not fit the type the store holds for it. The class is\n  // real and was hit live: an organization whose copy of a package table grew\n  // `status` as a uuid-valued Field was sent the text \"open\", and the store\n  // answered `invalid input syntax for type uuid: \"open\"`. It is the CALL that\n  // is wrong for the shape the store holds, which is what `invalid_argument`\n  // already means — the store's own sentence names the value and the type.\n  \"22P02\": \"invalid_argument\",\n  // 42703 — a column that is not there. The store raises it from\n  // `custom.entity_table`, which is asked for a column by NAME, so the class is\n  // exactly \"the call named something the shape does not have\": the same thing\n  // `invalid_argument` already means, and the store's own sentence names the\n  // column. Added 2026-09-20 (lane FORMS) because the package's live-door suite\n  // caught it raised by a door this package did not know about — which is the\n  // suite working, and is why the map is a census rather than a guess.\n  \"42703\": \"invalid_argument\",\n  // 22007 — a date or a time the store could not read as one. It is raised by\n  // `custom.dashboard_window_sql`, which is handed a window a caller wrote\n  // (\"last 30 days\", a literal date), so the class is again \"the call named\n  // something the shape does not accept\" and the store's own sentence names the\n  // text it could not read. Added 2026-09-20 (lane SCREEN-BREAK) after the\n  // live-door census caught it — the same way 42703 arrived, which is the\n  // census working rather than a guess.\n  \"22007\": \"invalid_argument\",\n  // 22003 — a number the store could not hold at the size it was handed. It is\n  // raised by `custom.context_resolve`, which is given a window or a depth a\n  // caller wrote, so the class is the same one 22P02, 42703 and 22007 already\n  // are: the CALL named a value the shape does not accept, and the store's own\n  // sentence names the number and the range. Added 2026-09-20 (lane GRID-TWO)\n  // when the live-door census caught the release gate red on it — which is the\n  // census working, and the fourth time it has been the thing that found a new\n  // refusal class rather than a person guessing one.\n  \"22003\": \"invalid_argument\",\n  // 42883 — `custom._template_call` (the template family, 2026-10-03) was handed a step that\n  // names a door the store does not have, or an argument that door does not take. The TEMPLATE\n  // named something the shape does not have — the same class 42703 is — and the store's own\n  // sentence names the door or the argument. Caught by the live-door census on records 0.68.1's\n  // tag, the eighth time the census found a class before a person did. (A bare 42883 on a door\n  // this package itself asks for is still `door_absent`, mapped before this funnel in\n  // `owedDoor`.)\n  \"42883\": \"invalid_argument\",\n  \"02000\": \"not_found\",\n  // P0002 — `custom.inbox_snooze` / `custom.inbox_clear` (lane S5-PRIME-2, 2026-09-24): \"There is\n  // nothing in your inbox with that id\". An invented id, another person's item and another\n  // organization's all answer it alike, so it reads exactly as 02000 does: not found.\n  \"P0002\": \"not_found\",\n  // 23502 — `custom.synced_source_save` (the synced-source registry, 2026-10-16) refuses a source\n  // saved without a value it cannot do without (its door, its table), in its own sentence naming\n  // the value. The CALL left out something the shape requires: the same class as 22004.\n  \"23502\": \"invalid_argument\",\n  \"23503\": \"missing_reference\",\n  \"23505\": \"already_exists\",\n  \"0A000\": \"not_supported\",\n  \"53400\": \"store_limit\",\n  \"22012\": \"store_limit\",\n  // 54001 — `custom.record_delete` stops a cascade that nests past sixty-four\n  // levels of containment, because that is a loop somebody built rather than a\n  // hierarchy, and saying so beats recursing until the server runs out of\n  // stack. It is a LIMIT of the store, and the store's own sentence names what\n  // to do about it, so it reads as one.\n  \"54001\": \"store_limit\",\n  // 54000 — the grid primitives' organization ceilings (GRID-PRIMITIVES, 2026-09-23):\n  // `custom.action_run` on a selection past its knob, `custom.table_decorate` past the\n  // rule count, `custom.table_from_example` past `custom/example_rows_max`,\n  // `custom.table_webhook_declare` past `custom/table_webhooks_max`, and\n  // `custom.hub_changed_by`. Each names its knob in the hint and writes nothing, so it\n  // reads exactly like 54001: a limit of the store, in the store's own sentence.\n  \"54000\": \"store_limit\",\n  // VIS: `custom.has_visibility_at` refuses to answer from a snapshot older\n  // than a write this reader has already seen, rather than returning something\n  // they just lost access to. It is retryable on a fresher connection, which is\n  // a different instruction from every other refusal here.\n  // 55000 — `custom.table_move` (SC-1', 2026-09-24) refuses a move the table's present state\n  // does not allow: a destination that cannot take it, a table something else holds, contents\n  // that point at themselves in a circle. The store's own sentence names the reason and nothing\n  // moves, so it reads as a refusal on the merits. Caught by the live-door census on records\n  // 0.58.3's tag, the seventh time the census found a class before a person did.\n  \"55000\": \"refused_by_rule\",\n  // 42P17 — a worked-out column that would read itself round a circle (STORE-TAILS-3,\n  // 2026-09-25): `custom._field_reads_what_it_reads` refuses the declaration or edit that would\n  // close the circle, naming every column in it, and `custom.far_value` refuses a circle stored\n  // before that rule when a lookup or rollup is worked out. Refused on its merits, in the store's\n  // own sentence, nothing written — so it reads as 55000 does.\n  \"42P17\": \"refused_by_rule\",\n  // P0001 — `custom.context_scope_write` (2026-10-03) refuses a scope whose parent breaks the\n  // parent rule in the old trigger's own class and words (manager ruling H6). Refused on its\n  // merits, nothing written. Caught by the live-door census on records 0.65.0's tag.\n  P0001: \"refused_by_rule\",\n  \"40001\": \"stale_read\",\n  // 57014 — the store canceled the statement at its own timeout. Like\n  // `stale_read` and unlike every other refusal here, the call was never\n  // refused on its merits: the same call on a smaller page, or once the\n  // organization's kernel is not being rewritten, can succeed. It gets its own\n  // code so a screen can offer \"try again\" honestly instead of showing a\n  // failure sentence the caller cannot act on.\n  \"57014\": \"timed_out\",\n  // PostgREST's own two: the store is not being SERVED, which is a different\n  // thing from the store refusing. `custom` absent from `pgrst.db_schemas`, or\n  // the grants not copied, land here.\n  PGRST202: \"store_not_served\",\n  PGRST205: \"store_not_served\",\n  PGRST301: \"door\",\n  // PT428 — NOT A FAILURE, and the release gate's live census is what found it\n  // missing: the store raises it and this package answered `internal`, which is\n  // the one classification that tells a screen nothing. A stage gate whose\n  // `on_fail` is `require_approval` files the request and leaves the record\n  // where it was; the transaction is rolled back to the pipeline's own block, so\n  // \"nothing was written\" is a fact rather than a promise. Landed by lane\n  // STAGE-RULES; mapped here by STAGE-RULES-2 the day after, when the census\n  // caught it — the sixth time that census has been the thing that found a\n  // refusal class rather than a person guessing one.\n  PT428: \"needs_approval\",\n};\n\n/** The SQLSTATEs this package claims to understand. Exported for the guard. */\nexport const MAPPED_SQLSTATES = Object.keys(BY_SQLSTATE);\n\nfunction parseDetail(details: string | null | undefined): unknown {\n  if (!details) return undefined;\n  const trimmed = details.trim();\n  if (!trimmed.startsWith(\"{\") && !trimmed.startsWith(\"[\")) return details;\n  try {\n    return JSON.parse(trimmed) as unknown;\n  } catch {\n    return details;\n  }\n}\n\n/**\n * A CODE THAT IS NOT A SQLSTATE AT ALL — so it is not read as one.\n *\n * A SQLSTATE is five characters. supabase-js puts something else in `code` in\n * exactly two situations, and BOTH of them mean the call never reached the\n * store rather than the store refusing it:\n *\n *   `\"\"`        a `FetchError` — no network, a canceled request, CORS.\n *   `\"404\"`…    an HTTP status, when the gateway answered with no JSON body.\n *\n * Lane TAILS-6 (2026-09-22) found both landing in `internal`, which is the one\n * classification that tells a screen nothing: a person on the Checklists tab of\n * a plumbing company's jobs table was shown \"Something went wrong at our end\"\n * with nothing to do about it, over a sentence naming this package. They are\n * `unreachable`, which a screen can honestly offer \"try again\" for.\n */\nfunction isNotASqlstate(code: string | undefined): boolean {\n  if (!code) return true;\n  return /^[0-9]{3}$/.test(code);\n}\n\n/** What a person reads when the store cancelled a call at its statement timeout (57014, code `timed_out`). */\nexport const TIMED_OUT_MESSAGE = \"That took too long. Nothing was lost; try again.\";\n\n/** Map a PostgREST/supabase-js failure into the package's refusal shape. */\n/**\n * THE DOOR'S NAME NEVER REACHES A PERSON (lane AT-REVIEW-3). The store's refusals are written for the\n * engineer and name the door that refused (\"…and custom.doc_template_save needs Full access\", \"…so\n * custom.read_record has nothing to do there\"). A person reads plain words; the store's own sentence goes\n * to the diagnostic. One place, so every door and every screen inherits it.\n */\nexport function plainDoorWords(text: string, where: string): string {\n  const bare = where.replace(/^custom\\./, \"\");\n  const names = [where, bare].filter((n, i, all) => n && /^[A-Za-z0-9_.]+$/.test(n) && all.indexOf(n) === i);\n  const door = `(?:custom\\\\.[a-z0-9_]+${names.map((n) => `|${n.replace(/\\./g, \"\\\\.\")}`).join(\"\")})`;\n  const rules: Array<[RegExp, string]> = [\n    [new RegExp(`, so ${door} has nothing to do there( until an owner restores it)?\\\\.`, \"g\"), \", so there is nothing for you to do there$1.\"],\n    [new RegExp(`, so ${door} has nothing to show you\\\\.`, \"g\"), \", so there is nothing to show you.\"],\n    [new RegExp(`, so ${door} may not write to it\\\\.`, \"g\"), \", so you cannot change it.\"],\n    [new RegExp(`, and ${door} needs `, \"g\"), \", and changing it needs \"],\n    [new RegExp(`, so ${door} is not taking writes\\\\.`, \"g\"), \", so it is not taking changes.\"],\n    // The store now names the ACTION here (\"Changing a record\", or \"Making this change\" for a door outside its\n    // map), not the door — so the sentence is matched by its shape, whatever words lead it.\n    [/^custom: .+? was called without an organization, and the store is keyed \\(organization_id, id\\)\\./, \"Say which organization you are working in.\"],\n    [new RegExp(`\\\\b${door} needs `, \"g\"), \"That needs \"],\n    [new RegExp(`\\\\b${door}\\\\b`, \"g\"), \"that\"],\n  ];\n  let out = text;\n  for (const [re, to] of rules) out = out.replace(re, to);\n  return out;\n}\n\nexport function mapPgError(error: PgError, where: string): RecordsError {\n  // `code: \"\"` is supabase-js's own value for a transport failure, and `\"\"` is\n  // not nullish — so it has to be emptied deliberately or it becomes a SQLSTATE\n  // nobody can look up.\n  const raw = error.code ?? undefined;\n  const sqlstate = raw && raw !== \"\" ? raw : undefined;\n  const mapped: RecordsError = {\n    code: \"internal\",\n    message: error.message,\n    ...(error.hint ? { hint: error.hint } : {}),\n    ...(sqlstate ? { sqlstate } : {}),\n  };\n  // TEMPLATE-INSTALL-3: PGRST001/PGRST002 (\"Could not query the database for the schema cache\") are the API being away, the same\n  // thing a 503 is: never raw text on a screen, and never \"internal\".\n  if (isNotASqlstate(sqlstate) || sqlstate === \"PGRST001\" || sqlstate === \"PGRST002\") {\n    mapped.code = \"unreachable\";\n  } else {\n    mapped.code = BY_SQLSTATE[sqlstate!] ?? \"internal\";\n  }\n  const detail = parseDetail(error.details);\n  if (detail !== undefined) mapped.detail = detail;\n  if (mapped.code === \"internal\") {\n    // 🚨 THE NOTE GOES IN ITS OWN FIELD, NEVER ONTO `hint` (lane TAILS-6).\n    // `hint` is THE REMEDY — the sentence screens hand a person to act on — so\n    // a note this package writes about ITSELF being surprised belonged nowhere\n    // near it. It is still said out loud, so nobody reads the silence as\n    // \"handled\"; it is said to whoever debugs this and to nobody else.\n    mapped.unmapped = true;\n    mapped.diagnostic =\n      `@ai-matrx/records did not recognize SQLSTATE ${sqlstate ?? \"(none)\"} from ${where}; ` +\n      `the store's own message is the thing to act on.`;\n  } else if (mapped.code === \"unreachable\") {\n    mapped.unmapped = true;\n    mapped.diagnostic =\n      `@ai-matrx/records never reached the store from ${where}: ` +\n      `${raw ? `the transport answered ${raw}` : \"no response\"} — ${error.message}`;\n    // 🚨 THE ONE PLACE THIS PACKAGE WRITES A MESSAGE OF ITS OWN, and it is the\n    // one place where there is no store message to carry: the store never\n    // answered. `TypeError: Failed to fetch` is the browser talking to itself,\n    // not a sentence anybody should read, so it goes to the engineer's line\n    // above and the person gets what actually happened.\n    mapped.message = \"We could not reach your data.\";\n    // Whatever the transport said was never a remedy either; the remedy is to ask again (the one-line message plus Try again).\n    mapped.hint = \"Try again.\";\n  } else if (mapped.code === \"door\") {\n    const said = plainDoorWords(error.message, where);\n    if (said !== error.message) {\n      mapped.diagnostic = `${where} refused: ${error.message}`;\n      mapped.message = said;\n    }\n    if (mapped.hint) mapped.hint = plainDoorWords(mapped.hint, where);\n  } else if (mapped.code === \"timed_out\") {\n    // 🚨 THE SECOND PLACE THIS PACKAGE WRITES ITS OWN SENTENCE (lane AT-SLOW, 2026-10-19). 57014 is\n    // Postgres talking about itself — \"canceling statement due to statement timeout\" — not a refusal\n    // the store wrote for a person, and it reached people raw on base move, Kanban \"Make it work\" and\n    // base rename. The cancelled statement rolled back, so nothing was written. The store's words go\n    // to the engineer's line; the person gets what happened and what to do.\n    mapped.diagnostic = `${where} was cancelled at the store's statement timeout: ${error.message}`;\n    mapped.message = TIMED_OUT_MESSAGE;\n    delete mapped.hint;\n  }\n  return mapped;\n}\n\n/**\n * Anything a host caught (a supabase-js error object, a thrown `Error`, a string) as the package's\n * refusal, through `mapPgError` — so a host service's `catch` speaks the same words as its doors.\n */\nexport function mapThrownError(thrown: unknown, where: string): RecordsError {\n  const o = thrown && typeof thrown === \"object\" ? (thrown as { code?: unknown; message?: unknown; details?: unknown; hint?: unknown }) : {};\n  const message = typeof o.message === \"string\" && o.message ? o.message : thrown == null ? \"Unknown error\" : String(thrown);\n  const code = typeof o.code === \"string\" ? o.code : null;\n  // A supabase-js answer (it carries a code) and a transport failure are the store's / the\n  // network's; anything else a host threw is its own sentence and is kept as said.\n  if (code !== null || (thrown instanceof TypeError && /fetch|network/i.test(message))) {\n    return mapPgError(\n      { code, message, details: typeof o.details === \"string\" ? o.details : null, hint: typeof o.hint === \"string\" ? o.hint : null },\n      where,\n    );\n  }\n  return {\n    code: \"internal\",\n    message,\n    unmapped: true,\n    diagnostic: `@ai-matrx/records: ${where} threw outside the store.`,\n  };\n}\n\n/** Pull the conflict out of a `stale_write`, when the store sent one. */\nexport function staleWriteDetail(error: RecordsError): StaleWriteDetail | null {\n  if (error.code !== \"stale_write\") return null;\n  const detail = error.detail as Partial<StaleWriteDetail> | undefined;\n  if (\n    !detail ||\n    typeof detail.expected_version !== \"number\" ||\n    typeof detail.current_version !== \"number\"\n  ) {\n    return null;\n  }\n  return {\n    expected_version: detail.expected_version,\n    current_version: detail.current_version,\n    contested_fields: detail.contested_fields ?? {},\n  };\n}\n\n/**\n * HONEST-REFUSALS 1 — a member of an ARCHIVED organization is refused with the store's own sentence\n * (\"This organization is archived, …\") and DETAIL `organization_archived:<organization id>`. The sentence\n * and the restore hint ride `message` and `hint` verbatim like every refusal; this reads the organization out\n * so a screen can offer \"Restore\" (the owner's `iam.organization_restore` door) instead of a dead end.\n * Null for every other refusal, including the non-member's \"You are not a member of that organization\".\n */\nexport function archivedOrganizationId(error: RecordsError): string | null {\n  if (error.code !== \"door\" || typeof error.detail !== \"string\") return null;\n  const m = /^organization_archived:([0-9a-f-]{36})$/i.exec(error.detail.trim());\n  return m ? m[1]! : null;\n}\n","// src/core/transient.ts — @ai-matrx/records · WHAT IS TRANSIENT, AND HOW TO ASK AGAIN (HEADLESS)\n//\n// The store's API goes away for a few seconds now and then (a PostgREST restart answers PGRST002 \"Could not\n// query the database for the schema cache\", PGRST001, or a bare 502/503/504; a deploy or a proxy resets the\n// connection; a statement is cancelled or loses a lock race). None of those is the store REFUSING anything, and\n// a person who pressed a button should not be handed the weather.\n//\n// ONE PLACE (TEMPLATE-INSTALL-3). The classification and the backoff live here and are read by the one door\n// call (`createDoorCall`, so every method of the records client and every light door client inherits them) and\n// by the template door runners. Before this, `runTemplateDoor` retried lock and timeout errors but not PGRST002,\n// and every other door did not retry at all: during a PostgREST outage 4 of 5 fresh installs stopped on raw text.\n//\n// WHICH CALLS MAY BE ASKED AGAIN. A read always may. A write only when asking twice is the same as asking once:\n// its door is idempotent, or the call carries a caller-chosen id (`p_install_id`) the store answers the same way\n// however many times it is asked. Every other write is NOT retried blindly: a 503 or a reset can arrive after the\n// store did the work, and a second ask would do it again. It is refused once, in one plain sentence with \"Try\n// again\" (`mapPgError`), and the person decides.\n\nimport type { PgError } from \"../results\";\nimport { isWritingDoor } from \"./primedBundle\";\n\n/** SQLSTATEs and PostgREST codes that mean \"the same call may succeed in a moment\". */\nexport const TRANSIENT_CODES: ReadonlySet<string> = new Set([\n  \"PGRST001\", // PostgREST cannot reach the database\n  \"PGRST002\", // PostgREST cannot build its schema cache (a restart, a reload)\n  \"57014\", // statement cancelled at its timeout\n  \"55P03\", // lock not available\n  \"40001\", // serialization failure\n  \"40P01\", // deadlock detected\n]);\n\n/** HTTP statuses a gateway answers while the API is down or restarting (supabase-js puts them in `code` when the body is not JSON). */\nconst TRANSIENT_STATUS = /^(502|503|504)$/;\n\n/** A dropped connection, in whatever words the runtime used (node, undici, a browser's fetch). */\nconst TRANSIENT_WORDS = /connection reset|econnreset|socket hang up|schema cache|bad gateway|service unavailable|gateway time-?out/i;\n\n/** True when `error` is the store's weather, not an answer about the call. */\nexport function isTransientStoreError(error: { code?: string | null; message?: string | null } | null | undefined): boolean {\n  if (!error) return false;\n  const code = error.code ?? \"\";\n  if (TRANSIENT_CODES.has(code) || TRANSIENT_STATUS.test(code)) return true;\n  return TRANSIENT_WORDS.test(error.message ?? \"\");\n}\n\n/** Codes whose cause is the API being away (said \"We could not reach your data.\" to a person), as opposed to a busy statement. */\nexport function isStoreAwayError(error: { code?: string | null; message?: string | null } | null | undefined): boolean {\n  if (!error) return false;\n  const code = error.code ?? \"\";\n  if (code === \"PGRST001\" || code === \"PGRST002\" || TRANSIENT_STATUS.test(code)) return true;\n  return code !== \"57014\" && code !== \"55P03\" && code !== \"40001\" && code !== \"40P01\" && TRANSIENT_WORDS.test(error.message ?? \"\");\n}\n\n/** The waits between asks, before jitter: 0.5, 1, 2 and 4 seconds (7.5 s in all). */\nexport const RETRY_DELAYS_MS: readonly number[] = [500, 1000, 2000, 4000];\n\n/**\n * A statement cancelled at its timeout already spent its whole budget; asking it four more times is a\n * half-minute of hanging. It gets ONE more ask (the common case is a cold cache that the first ask warmed).\n */\nconst TIMEOUT_RETRIES = 1;\n\n/** One wait: the base delay with +/-25 % jitter, so a crowd of callers does not come back in the same instant. */\nexport function backoffDelay(attempt: number, random: () => number = Math.random, delays: readonly number[] = RETRY_DELAYS_MS): number {\n  const base = delays[Math.min(attempt, delays.length - 1)] ?? 0;\n  return Math.round(base * (0.75 + random() * 0.5));\n}\n\n/** Doors whose second ask is the same as their first (they resume from the store's own record of the work). */\nconst IDEMPOTENT_DOORS: ReadonlySet<string> = new Set([\n  \"template_install_fresh\",\n  \"template_uninstall\",\n  \"template_restore\",\n  \"template_upgrade\",\n  \"template_install_note\",\n]);\n\n/** A door the name-based writing test does not recognise, but that makes something new on every ask. */\nconst ALWAYS_NEW = /^template_install$/;\n\n/** May this call be asked again after a transient answer? Reads: yes. Writes: only an idempotent door or a call with a caller-chosen id. */\nexport function isRetrySafe(door: string, args: Record<string, unknown>): boolean {\n  if (IDEMPOTENT_DOORS.has(door)) return true;\n  if (typeof args[\"p_install_id\"] === \"string\" && args[\"p_install_id\"] !== \"\") return true;\n  if (ALWAYS_NEW.test(door)) return false;\n  return !isWritingDoor(door);\n}\n\nexport interface RetryOptions {\n  /** False: ask once and hand back whatever came. */\n  safe: boolean;\n  /** Tests pass a fake. */\n  sleep?: (ms: number) => Promise<void>;\n  /** Tests pass a fixed source. */\n  random?: () => number;\n  delays?: readonly number[];\n  /** Told before each wait (attempt counts from 1), so a screen can say it is still trying. */\n  onRetry?: (info: { attempt: number; waitMs: number; error: PgError }) => void;\n}\n\nconst nap = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/** The answer a thrown ask (a rejected fetch) is read as. */\nfunction thrownAsError(thrown: unknown): PgError {\n  const o = thrown && typeof thrown === \"object\" ? (thrown as { code?: unknown; message?: unknown }) : {};\n  return {\n    code: typeof o.code === \"string\" ? o.code : \"\",\n    message: typeof o.message === \"string\" && o.message ? o.message : String(thrown),\n  };\n}\n\n/**\n * Ask `call` until it answers without a transient error, or the waits run out. Never throws: a rejected ask\n * becomes an `error` answer. Returns the LAST answer, so the caller maps it exactly as it mapped a first one.\n */\nexport async function retryTransient<T extends { data: unknown; error: PgError | null }>(\n  call: () => PromiseLike<T>,\n  options: RetryOptions,\n): Promise<T> {\n  const sleep = options.sleep ?? nap;\n  const delays = options.delays ?? RETRY_DELAYS_MS;\n  let attempt = 0;\n  for (;;) {\n    let answer: T;\n    try {\n      answer = await call();\n    } catch (thrown) {\n      answer = { data: null, error: thrownAsError(thrown) } as T;\n    }\n    const error = answer.error;\n    if (!error || !options.safe || !isTransientStoreError(error)) return answer;\n    const limit = error.code === \"57014\" ? Math.min(TIMEOUT_RETRIES, delays.length) : delays.length;\n    if (attempt >= limit) return answer;\n    const waitMs = backoffDelay(attempt, options.random, delays);\n    attempt++;\n    options.onRetry?.({ attempt, waitMs, error });\n    await sleep(waitMs);\n  }\n}\n","// src/core/doorCall.ts — @ai-matrx/records · THE ONE DOOR CALL (HEADLESS, LIGHT)\n//\n// Every typed method of the records client, and the light door clients a host's shell uses\n// (`@ai-matrx/records/door-call`: the scope doors, the pick-list doors, `storeDoors`), ask the store\n// through THIS function. It holds the door-call semantics once:\n//\n//   - a primed answer (the server render asked the same door as the same person) is served first;\n//   - a write empties what was primed (all of it, or only a look write's reads);\n//   - ONE READ IN FLIGHT, ONE ANSWER FOR EVERY ASKER (lane DEDUPE-READS): two askers of the same\n//     door with the same arguments in the same moment share one request; a writing door always goes\n//     out on its own, and a flight is forgotten the moment it lands;\n//   - the schema is said out loud (`custom`), never PostgREST's `public` default;\n//   - a door the store lacks is refused `door_absent` (never an empty answer), and every other\n//     refusal is the store's own words (`mapPgError`), said once through the error sink.\n//\n// What only the full client has (the table/record page bundle, the generated door catalog) is\n// handed in as hooks, so this file imports no table registry, no field-kind vocabulary and no UI:\n// a shell that only reads scopes or a pick list never carries the store client.\n\nimport type { RecordsDataSource, RecordsErrorSink } from \"../ports\";\nimport type { RecordsError, RecordsErrorCode, RecordsResult } from \"../results\";\nimport { err, ok } from \"../results\";\nimport { mapPgError } from \"./pgError\";\nimport { isRetrySafe, retryTransient, type RetryOptions } from \"./transient\";\nimport { LOOK_WRITES, dropPrimedDoorAnswers, forgetPrimedTablePageBundlesOf, isWritingDoor, takePrimedDoorAnswer } from \"./primedBundle\";\n\n/** The schema every door of the record store lives in, unless the host's config says otherwise. */\nexport const DEFAULT_DOOR_SCHEMA = \"custom\";\n\n/** An argument object as one stable string: keys sorted at every depth (PAGE-BUNDLE's match key). */\nexport function canonicalArgs(value: unknown): string {\n  return JSON.stringify(value, (_key, held) =>\n    held && typeof held === \"object\" && !Array.isArray(held)\n      ? Object.fromEntries(Object.keys(held as object).sort().map((k) => [k, (held as Record<string, unknown>)[k]]))\n      : held,\n  );\n}\n\n/**\n * 🚨 A REFUSAL IS NOT AN APP ERROR (lane RECORDS-UI-FIX, guide re-walk 2026-09-23).\n *\n * A person typing `-3` into a column that takes \"at least 0\" is the store WORKING: the\n * rule said no, the screen said so in the one notice, and the person fixed it. The default\n * sink printed every one of those through `console.error`, and the app's error capture\n * (matrx-frontend `lib/diagnostics/globalErrorCapture.ts`) counts every `console.error` —\n * so one refused value lit a red \"2 errors\" pill in the corner, telling an admin the\n * product had failed when a person had simply been told no.\n *\n * These are the codes a PERSON causes by what they typed or when they typed it; each one\n * is already drawn on the screen that asked. They are still said (`console.info`), never\n * silenced. Everything else — a door, the store switched off, a timeout, a class this\n * package did not recognize — is a failure of the system and stays `console.error`.\n */\nexport const A_PERSONS_REFUSAL: ReadonlySet<RecordsErrorCode> = new Set<RecordsErrorCode>([\n  \"refused_by_rule\",\n  \"stale_write\",\n  \"invalid_argument\",\n  \"already_exists\",\n  \"missing_reference\",\n]);\n\nexport function isAPersonsRefusal(code: RecordsErrorCode | string): boolean {\n  return A_PERSONS_REFUSAL.has(code as RecordsErrorCode);\n}\n\n/** The host's error sink, or the default one: the store's own words, naming where it happened. */\nexport function recordsErrorSink(onError: RecordsErrorSink | undefined): RecordsErrorSink {\n  return (\n    onError ??\n    ((e) => {\n      // The defined degradation, stated: with the store's own words, and naming where it\n      // happened. Never silence — but a person's refusal is information, not an error.\n      const line = `[@ai-matrx/records] ${e.where}: ${e.code} — ${e.message}${e.hint ? ` (${e.hint})` : \"\"}`;\n      if (isAPersonsRefusal(e.code)) console.info(line);\n      else console.error(line);\n    })\n  );\n}\n\n/** The refusal a missing door gets. It always says who owes it (`owedBy`, when a lane claims it). */\nexport function doorAbsentRefusal(name: string, owedBy?: string): RecordsError {\n  return {\n    code: \"door_absent\",\n    message:\n      `The record store has no door \\`custom.${name}\\` yet, so this call was not made. ` +\n      `Nothing was read and nothing was written.`,\n    hint: owedBy\n      ? `That door is ${owedBy}. Until it lands, this call refuses rather than guessing: ` +\n        `an empty answer here would read like \"there is nothing\", which is a different sentence.`\n      : `No lane in the build book claims this door. Either the name is wrong, or the door was ` +\n        `removed from the store and this package has not been regenerated — run \\`pnpm records:generate\\`.`,\n  };\n}\n\n/**\n * What the server render already asked as this person, for this exact door and arguments — or null.\n * A write (or a look write) empties what is primed instead, and is never answered from it.\n */\nexport function primedDoorAnswer(door: string, args: Record<string, unknown>): { data: unknown } | null {\n  const look = LOOK_WRITES[door];\n  if (look) {\n    dropPrimedDoorAnswers(look);\n    return null;\n  }\n  if (isWritingDoor(door)) {\n    dropPrimedDoorAnswers();\n    return null;\n  }\n  return takePrimedDoorAnswer(`${door}|${canonicalArgs(args)}`);\n}\n\n/** One door call: the door's name, its arguments, and where the caller is (for the refusal). */\nexport type DoorCall = <T>(\n  door: string,\n  args: Record<string, unknown>,\n  where: string,\n  /**\n   * `quiet`: this refusal is an ANSWER the caller already draws (a door that says \"not yours\" to a\n   * person who only has table-level access), not a failure of the system. It is returned to the\n   * caller and said once with `console.info` - never through the error sink, which lights the\n   * error badge. Everything else about the call is unchanged.\n   */\n  opts?: { quiet?: boolean },\n) => Promise<RecordsResult<T>>;\n\nexport interface DoorCallOptions {\n  /** The store's data seam (`asRecordsDataSource(supabase)`). */\n  dataSource: RecordsDataSource;\n  /** Defaults to `custom`. */\n  schema?: string;\n  /** The host's error sink (defaults to `recordsErrorSink(undefined)`). */\n  onError?: RecordsErrorSink;\n  /**\n   * MAY THIS DOOR BE ASKED AT ALL (the full client's generated catalog). False refuses with\n   * `absent(door)` and asks nobody. Absent ⇒ every door is asked, and a store that answers \"no such\n   * function\" (PostgREST's PGRST202 or Postgres's 42883) is refused `door_absent` all the same.\n   */\n  doorReady?: (door: string) => boolean;\n  /** The refusal a missing door gets (defaults to `doorAbsentRefusal(door)`). */\n  absent?: (door: string) => RecordsError;\n  /** An answer this page already holds for the exact call (the full client's page bundle), else null. */\n  held?: (door: string, args: Record<string, unknown>) => Promise<{ data: unknown } | null | undefined>;\n  /** A write landed: drop what this page still holds of it (the full client's page bundle). */\n  wrote?: (door: string, args: Record<string, unknown>) => void;\n  /**\n   * TRANSIENT STORE ERRORS ARE ASKED AGAIN, HERE, FOR EVERY DOOR (TEMPLATE-INSTALL-3). PGRST001/PGRST002, a 502/503/504, a\n   * reset connection, a cancelled statement, a lock wait, a serialization failure and a deadlock are the store's weather, not an\n   * answer: a read (or a write that is safe to repeat: an idempotent door, or a call carrying `p_install_id`) waits 0.5, 1, 2\n   * and 4 s with jitter and asks again. Any other write is asked once and refused in one plain sentence. Tests inject the waits;\n   * `false` turns it off.\n   */\n  retry?: false | Pick<RetryOptions, \"sleep\" | \"random\" | \"delays\" | \"onRetry\">;\n}\n\n/** Build the one door call over a data source. Every records client, light or full, asks through this. */\nexport function createDoorCall(options: DoorCallOptions): DoorCall {\n  const { dataSource, doorReady, held, wrote } = options;\n  const schema = options.schema ?? DEFAULT_DOOR_SCHEMA;\n  const scream = recordsErrorSink(options.onError);\n  const absent = options.absent ?? ((door: string) => doorAbsentRefusal(door));\n  const retryOptions = options.retry === false ? null : (options.retry ?? {});\n  const readsInFlight = new Map<string, Promise<Awaited<ReturnType<RecordsDataSource[\"rpc\"]>>>>();\n\n  const say = (refusal: RecordsError, where: string): void =>\n    scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where });\n\n  return async function callDoor<T>(\n    door: string,\n    args: Record<string, unknown>,\n    where: string,\n    opts?: { quiet?: boolean },\n  ): Promise<RecordsResult<T>> {\n    // A WRITE EMPTIES WHAT THE SERVER ASKED; A READ FINDS ITS EXACT ANSWER THERE FIRST (lane SEED-ENTITY).\n    const primed = primedDoorAnswer(door, args);\n    if (primed) return ok(primed.data as T);\n    if (held) {\n      const bundled = await held(door, args);\n      if (bundled) return ok(bundled.data as T);\n    }\n    // The generated catalog, or a store the host says already has the door (`knownDoors`) —\n    // the bridge between a chair's production apply and the next `pnpm records:generate`.\n    if (doorReady && !doorReady(door)) {\n      const refusal = absent(door);\n      say(refusal, where);\n      return err(refusal);\n    }\n    // THE SCHEMA IS SAID OUT LOUD. A door of the store is `custom.<name>`, and\n    // a host's supabase client resolves an unqualified `rpc()` against its own\n    // default PostgREST profile — `public` in every client we ship. Leaving it\n    // off therefore asked `public.store_is_open`, which the browser extension\n    // found for us on its first real turn (2026-09-18, W6-EXT): \"Could not find\n    // the function public.store_is_open(p_organization_id) in the schema cache\".\n    // The package knows which schema it lives in, so it is the package that\n    // says so, once, here — never every host remembering to.\n    // ONE READ IN FLIGHT, ONE ANSWER FOR EVERY ASKER (lane DEDUPE-READS). Two hooks asking the same\n    // door with the same arguments in the same moment (`custom.enrich_cells` fired twice in one\n    // millisecond) share ONE request. Only reads share; a writing door always goes out on its own.\n    // The flight is forgotten the moment it lands, so the next ask is a fresh read.\n    const flightKey = isWritingDoor(door) ? null : `${door}|${canonicalArgs(args)}`;\n    const flying = flightKey ? readsInFlight.get(flightKey) : undefined;\n    const response = await (flying ??\n      (() => {\n        const ask = () => Promise.resolve(dataSource.rpc(`${door}`, args, { schema }));\n        const call = retryOptions ? retryTransient(ask, { ...retryOptions, safe: isRetrySafe(door, args) }) : ask();\n        if (flightKey) {\n          readsInFlight.set(flightKey, call);\n          const forget = (): void => {\n            if (readsInFlight.get(flightKey) === call) readsInFlight.delete(flightKey);\n          };\n          call.then(forget, forget);\n        }\n        return call;\n      })());\n    if (response.error) {\n      const code = (response.error as { code?: string }).code;\n      // AN ARGUMENT LEFT UNDEFINED NEVER TRAVELS (JSON drops it), so PostgREST finds no function of that\n      // shape and says PGRST202 - which reads as \"the store is not served\". It is the CALLER's slip\n      // (AT-FIX-G1: a cleanup passed `d.id` for `dashboard_id`), so say that, naming the argument.\n      const missing = Object.keys(args).filter((k) => args[k] === undefined);\n      const refusal: RecordsError =\n        (code === \"PGRST202\" || code === \"42883\") && missing.length > 0\n          ? {\n              code: \"invalid_argument\",\n              message: `${door} was asked without ${missing.join(\", \")}, so it was not run.`,\n              hint: \"Name what it should act on and ask again.\",\n              sqlstate: code,\n            }\n          : // Without a catalog, \"no such function\" is the store saying it lacks the door.\n            !doorReady && (code === \"PGRST202\" || code === \"42883\")\n            ? absent(door)\n            : mapPgError(response.error, where);\n      if (opts?.quiet) console.info(`[@ai-matrx/records] ${where}: ${refusal.code} - ${refusal.message}`);\n      else say(refusal, where);\n      return err(refusal);\n    }\n    // A WRITE THAT LANDED EMPTIES WHAT THE PAGE STILL HOLDS OF THE TABLE (lane COPY-VIEW): \"Copy\n    // settings from…\" saved the view and the bar's re-read of the views was answered from the bundle, as\n    // of before the write — no request left the page and the grid kept the old filter until a reload.\n    if (isWritingDoor(door) || LOOK_WRITES[door]) {\n      const tableId = args[\"p_table_id\"];\n      wrote?.(door, args);\n      forgetPrimedTablePageBundlesOf(typeof tableId === \"string\" ? tableId : null);\n      dropPrimedDoorAnswers(LOOK_WRITES[door]);\n    }\n    return ok(response.data as T);\n  };\n}\n","// src/core/recordChanges.ts — @ai-matrx/records · lane RECORDS-UI-FIX (2026-09-23)\n//\n// EVERY SCREEN SHOWING A RECORD HEARS EVERY WRITE TO IT MADE THROUGH THIS PACKAGE.\n//\n// 🚨 WHAT A PERSON MET (VERIFIER-16 LOW, guide re-walk 2026-09-23): the record panel read\n// \"History 3 versions\" after its fourth write, while the store held four. The history\n// panel read the chain once, when it opened, and nothing told it the grid cell or the\n// form beside it had just written a new version. It is not the no-op-version class (the\n// store's history had the row; the screen never asked again) — it is a screen that\n// cannot hear the writes made on the same page.\n//\n// So every successful write door of the client announces the record it wrote, and any\n// screen showing that record re-reads on the announcement. Page-local and synchronous;\n// a write from another tab or person is realtime's job, not this one's.\n\n//\n// ONE BUS PER REALM, IN GLOBAL SLOTS: every section of the built package carries its own copy of\n// this module (and ESM/CJS are two graphs), so a module-level Set split the bus — the core client\n// announced into one copy while records/react listened on another (2026-10-08). Guarded on the\n// packed tarball by scripts/check-shared-state.mjs.\n\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\ntype Listener = (recordId: string) => void;\n\nconst listeners = globalSlot(\"ai-matrx.records.record-change-listeners\", () => new Set<Listener>());\n\n/** Called by the client after a write door answered yes. */\nexport function announceRecordChanged(recordId: string): void {\n  for (const listener of [...listeners]) {\n    try {\n      listener(recordId);\n    } catch (thrown) {\n      // A listener that throws must not take the write's answer with it.\n      console.error(\"[@ai-matrx/records] a record-change listener threw\", thrown);\n    }\n  }\n}\n\n// ── A RECORD THE PAGE ARCHIVED IS NOT READ AGAIN (Spaces r39) ───────────────────────────────\n//\n// `custom.read_record` refuses an archived record (400), and a screen that showed the record keeps\n// its entry live after it closes (a peek opened on a new row, then closed) — so the archive's own\n// change announcement, and the realtime echo of it, re-read a record nobody can open: two failing\n// requests per archive. `recordDelete` marks the record removed here; the live entry skips its\n// re-read while the mark stands; `recordRestore` lifts it.\n\nconst removed = globalSlot(\"ai-matrx.records.removed-records\", () => new Set<string>());\n\n/** Called by the client after `record_delete` answered yes (before it announces the change). */\nexport function markRecordRemoved(recordId: string): void {\n  removed.add(recordId);\n}\n\n/** Called by the client after `record_restore` answered yes (before it announces the change). */\nexport function markRecordRestored(recordId: string): void {\n  removed.delete(recordId);\n}\n\n/** Whether this page archived the record and has not brought it back. */\nexport function isRecordRemoved(recordId: string): boolean {\n  return removed.has(recordId);\n}\n\n/** Hear every record this page writes. Returns the unsubscribe. */\nexport function onRecordChanged(listener: Listener): () => void {\n  listeners.add(listener);\n  return () => listeners.delete(listener);\n}\n\n// ── A TABLE'S SHAPE MOVED (KINDS-GLUE wave 3 §1.4) ──────────────────────────────────────\n//\n// A record drawn as `table:<uuid>` in a chat, a note or a canvas draws through the Table's\n// Fields. When a Field is renamed, added, retired, brought back or retyped on this page, every\n// such card must re-read the Table's kind facts — so every structure door of the client\n// announces the Table here, the same page-local way record writes announce their record.\n// `null` means \"a Table changed and the door did not name which\" (a Field door is addressed by\n// the Field id alone): a listener then refreshes every Table it holds. Another tab's or\n// person's change is realtime's job (the `custom:table:<id>` notice with `kind: \"field\"`).\n\ntype TableListener = (tableId: string | null) => void;\n\nconst tableListeners = globalSlot(\"ai-matrx.records.table-structure-listeners\", () => new Set<TableListener>());\n\n/** Called by the client after a structure door (a Field or choice change) answered yes. */\nexport function announceTableStructureChanged(tableId: string | null): void {\n  for (const listener of [...tableListeners]) {\n    try {\n      listener(tableId);\n    } catch (thrown) {\n      console.error(\"[@ai-matrx/records] a table-structure listener threw\", thrown);\n    }\n  }\n}\n\n/** Hear every Table whose shape this page changes. Returns the unsubscribe. */\nexport function onTableStructureChanged(listener: TableListener): () => void {\n  tableListeners.add(listener);\n  return () => tableListeners.delete(listener);\n}\n","// src/archive.ts — @ai-matrx/records · THE ARCHIVE, HEADLESS\n//\n// 🚨 THE DEFECT THIS EXISTS FOR (VERIFIER-10 F4, measured 2026-09-22 on Rincon\n// Plumbing Co's \"Truck 1 dispatch backlog\" as admin@admin.com):\n//\n//   \"The grid's row action is Delete… Pressing it soft-deletes correctly:\n//    deleted_at set, version 1 → 2, nothing removed, and the row leaves the\n//    grid. Then it is gone for good as far as any screen is concerned. The\n//    store's own custom.record_restore exists and does exactly the right thing.\n//    The door is there; nothing reaches it.\"\n//\n// It could not have been reached. Every read door this store had answered LIVE\n// ROWS ONLY — `custom.read_records`, `read_records_by_ids` and\n// `read_records_matching` each hard-code `and r.deleted_at is null` — so no\n// screen could list an archived record however it was written. The store grew\n// `custom.read_records_archived` (migration\n// `fix10a_the_archive_has_a_read_door.sql`) and this module is its client half:\n// the vocabulary, the row shape, and the sentences a screen says about it.\n//\n// WHY THE SENTENCES LIVE HERE AND NOT IN THE UI. \"Archived by Maria Delgado on\n// 22 September\" is an answer about STORED FACTS, not a layout, and the desktop\n// app, the extension, an agent's reply and the web grid must all say it the\n// same way. A screen that composed its own would be a second answer to one\n// question, reached by knowing which client you are using.\n\nimport type { RecordDocument, ReadRow, Timestamp, Uuid } from \"./record\";\n\n/**\n * THE TWO LANES THE ARCHIVED-ITEMS LAW NAMES (Arman, 2026-09-09) — the same\n * split every other list in the platform makes between what is mine and what\n * is the organization's.\n *\n *   · `mine` — what I archived.\n *   · `org`  — what anybody in this organization archived.\n *\n * `mine` is by construction a SUBSET of `org`: the store applies it as a\n * narrowing conjunct beside the read-access ladder, so a lane can never show a\n * record the ladder would have refused.\n */\nexport const ARCHIVE_LANES = [\"mine\", \"org\"] as const;\nexport type ArchiveLane = (typeof ARCHIVE_LANES)[number];\n\n/** THE DEFAULT LANE. The organization's archive, because \"where did that job go?\" is almost never a question about yourself. */\nexport const DEFAULT_ARCHIVE_LANE: ArchiveLane = \"org\";\n\n/** What each lane is called on a screen, and what it actually answers. */\nexport const ARCHIVE_LANE_LABEL: Record<ArchiveLane, string> = {\n  mine: \"Archived by me\",\n  org: \"Archived by anyone\",\n};\n\nexport const ARCHIVE_LANE_MEANS: Record<ArchiveLane, string> = {\n  mine: \"The records you archived yourself.\",\n  org: \"Everything anybody in this organization archived, including you.\",\n};\n\n/** A word that is not a lane is not silently answered as one. */\nexport function isArchiveLane(word: unknown): word is ArchiveLane {\n  return typeof word === \"string\" && (ARCHIVE_LANES as readonly string[]).includes(word);\n}\n\n/**\n * One archived record, as `custom.read_records_archived` answers it: an\n * ordinary `ReadRow` — same id, same masked document, same level, same hidden\n * notices as it had while it was live — plus the two facts that only an archive\n * needs.\n *\n * `archivedBy` is null when the archiver is not a member of this organization\n * any more (their name is not this screen's to learn) or when the history\n * partition that held the SOFT_DELETE has rolled away. Null is an ANSWER and\n * gets its own sentence; it is never printed as an empty space.\n */\nexport interface ArchivedRow extends ReadRow {\n  archivedAt: Timestamp;\n  archivedBy: Uuid | null;\n  archivedByName: string | null;\n}\n\n/** The row shape the door returns over the wire, before it is folded. */\nexport interface ArchivedDoorRow {\n  id: Uuid;\n  document: unknown;\n  level: string;\n  archived_at: Timestamp;\n  archived_by: Uuid | null;\n  archived_by_name: string | null;\n}\n\n/**\n * WHEN IT WAS ARCHIVED, THE WAY A PERSON SAYS IT — \"22 September 2026 at 01:53\".\n * Not an ISO string, and never a bare relative word like \"yesterday\" on its\n * own: somebody deciding whether to bring a record back is deciding about a\n * particular day's work.\n */\nexport function archivedWhen(at: Timestamp, locale = \"en-GB\"): string {\n  const when = new Date(at);\n  if (Number.isNaN(when.getTime())) return \"a moment nobody recorded\";\n  return new Intl.DateTimeFormat(locale, {\n    day: \"numeric\",\n    month: \"long\",\n    year: \"numeric\",\n    hour: \"2-digit\",\n    minute: \"2-digit\",\n  }).format(when);\n}\n\n/**\n * THE WHOLE SENTENCE A ROW IN THE ARCHIVE CARRIES. Both halves of the question\n * the archived-items law asks — who, and when — and an honest sentence when the\n * store could not answer the first half, rather than a blank where a name goes.\n */\nexport function archivedByLine(row: Pick<ArchivedRow, \"archivedAt\" | \"archivedByName\">, locale = \"en-GB\"): string {\n  const when = archivedWhen(row.archivedAt, locale);\n  const who = (row.archivedByName ?? \"\").trim();\n  if (who === \"\") {\n    return `Archived on ${when}. The store does not know who archived it — whoever did is no longer in this organization, or it happened before this table kept that.`;\n  }\n  return `Archived by ${who} on ${when}.`;\n}\n\n/**\n * WHAT AN EMPTY ARCHIVE SAYS, PER LANE. An empty list is an answer and it names\n * the lane it is empty for, so \"nothing here\" can never be read as \"nothing was\n * ever archived\" while the other lane holds twenty records.\n */\nexport function emptyArchiveLine(lane: ArchiveLane): string {\n  return lane === \"mine\"\n    ? \"You have not archived anything in this table. Switch to “Archived by anyone” to see what the rest of the organization has.\"\n    : \"Nothing in this table has been archived. Records you remove from the grid arrive here, and nothing is ever destroyed.\";\n}\n\n/** A document that survived the round trip is the same document — used by the guard. */\nexport function sameDocument(a: RecordDocument, b: RecordDocument): boolean {\n  return JSON.stringify(a) === JSON.stringify(b);\n}\n","// src/aggregate.ts — @ai-matrx/records\n//\n// THE EIGHTH VERB (AGT-N-8). `custom.record_aggregate` groups, buckets, filters\n// and measures INSIDE the read door's own query: the aggregate node sits above\n// the join to `custom.query_visible_ids`, so a chart is computed over the rows\n// this principal may see and the rest are never fetched at all.\n//\n// That is why a chart in this platform is not \"read everything, then sum in the\n// browser\". Summing in the browser would either read rows a person may not see\n// or quietly under-count them, and both of those are a screen telling a lie.\n\nimport type { HiddenFieldNotice } from \"./record\";\nimport type { RuleExpression } from \"./rule\";\n\n/** The measures the store offers. Asked of `custom.agg_operations()` at run time too. */\nexport type AggregateOperation =\n  | \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\"\n  /** GRID-PRIMITIVES G1: the summary bar's other four. Blank = no value, JSON null or \"\". */\n  | \"median\" | \"filled\" | \"empty\" | \"unique\"\n  /**\n   * Notion's calculation row (Spaces N6): the share of the rows asked with no value / a value, as a\n   * percent 0..100 (NULL over no rows); and the RANGE, largest minus smallest (a date column: the days\n   * between its earliest and latest moment).\n   */\n  | \"percent_empty\" | \"percent_filled\" | \"range\";\n\n/** The periods a date Field can be bucketed into (`custom.agg_buckets()`). */\nexport type AggregateBucket = \"day\" | \"week\" | \"month\" | \"quarter\" | \"year\";\n\n/**\n * A HALF-OPEN MOMENT WINDOW: `from` is inclusive, `to` is exclusive. Half-open\n * is the only shape that makes \"September\" and \"October\" meet exactly once —\n * an inclusive `to` either double-counts the boundary moment or drops it,\n * depending on the reader, and both of those are a chart telling a lie.\n */\nexport interface AggregateWindow {\n  from?: string | null;\n  to?: string | null;\n}\n\n/**\n * ONE FILTER VALUE, as `custom.record_aggregate` and `custom.dashboard_run`\n * both read it: a SCALAR is an equality, and an OBJECT is a window. It is not\n * `unknown` on purpose — a filter value the store cannot read is a refusal a\n * caller should get from the compiler, not from the database.\n */\nexport type AggregateFilter = string | number | boolean | null | AggregateWindow;\n\n/**\n * 🚨 THE STORE'S ONE FILTER SHAPE, AND THE ONLY NAME FOR IT.\n *\n * An object of Field key -> value. A scalar is an equality, `null` is UNSET\n * (the third state of a tick box), an object is a half-open time window.\n *\n * It is not the aggregate's private shape and never was. `platform.saved_view`\n * has carried exactly this as `definition -> 'filters'` across five live\n * surface keys since DOOR-18; `custom.view_declare` writes it;\n * `custom.agg_view_admits` reads it to decide whether a change belongs to a\n * saved view; `custom.record_aggregate` takes it as `p_filter` to COMPUTE a\n * dashboard number; and `custom.read_records_matching` takes it to OPEN the\n * rows behind that number. One `custom.record_filter_sql` in the database turns\n * it into SQL for the last two, so the number and the rows cannot disagree.\n *\n * Invent a second one and a chart can compute a total whose drill-through\n * lands somewhere else, which is the only way a drill-through can lie.\n */\nexport type RecordFilter = Record<string, AggregateFilter>;\n\n/**\n * S2-PRIME FILTER-GROUPS — A READ DOOR'S QUESTION, IN EITHER OF ITS TWO SHAPES.\n *\n * The flat `RecordFilter` above (field key → scalar / `null` / window, AND only) is what\n * dashboards, drill-throughs and the notifier carry. A `RuleExpression` — `{op, args}`, ALL / ANY /\n * NOT groups nested to any depth, fields by id — is what the condition builder, a view's own\n * filter and every membership Rule speak. `custom.record_filter_sql(org, table, filter)` turns\n * EITHER into the one WHERE clause the grid (`list`), the aggregate and the board all use, so the\n * three can never disagree about which records a view holds.\n */\nexport type StoreFilter = RecordFilter | RuleExpression;\n\n/**\n * Is this filter a Rule expression? The store's own test (`custom.filter_is_rule`): an object\n * whose `op` is a word and which carries `args`.\n */\nexport function isRuleFilter(filter: unknown): filter is RuleExpression {\n  if (!filter || typeof filter !== \"object\" || Array.isArray(filter)) return false;\n  const node = filter as { op?: unknown; args?: unknown };\n  return typeof node.op === \"string\" && Array.isArray(node.args);\n}\n\n/** One measure. `count` counts rows and needs no Field; the rest read one. */\nexport interface AggregateMeasure {\n  op: AggregateOperation;\n  /** The Field's key. Required for every operation except `count`. */\n  key?: string;\n}\n\n/**\n * One row of an aggregate: which group it is, what each measure came to, and\n * how many records it was worked out from. The measure keys are the store's\n * own (`count`, `sum_amount`, `avg_amount`, …), never renamed on the way out.\n */\n/**\n * One group's key, as the column holds it (CHAIR-SHEET-STORE b): a number column's key is a number, a\n * yes/no column's true/false, a date its ISO text, a date period its first moment, everything else text.\n */\nexport type AggregateGroupValue = string | number | boolean | null;\n\nexport interface AggregateRow {\n  groups: Record<string, AggregateGroupValue>;\n  measures: Record<string, number | null>;\n  /**\n   * AGG-WITHHELD — a measure over a column this reader may not read is `null` in `measures` (the\n   * \"no value\" every number reader already handles) and its reason rides HERE by measure name: the\n   * same notice a withheld cell carries (`reason`, `needs`, `or`) plus the store's own sentence in\n   * `says`. The store never errors a read for a withheld column; it says so. A question that\n   * GROUPS or FILTERS by such a column answers one row with every measure null and `row_count` 0.\n   * Absent when nothing was withheld.\n   */\n  withheld?: Record<string, HiddenFieldNotice & { says?: string; label?: string; field_key?: string }>;\n  row_count: number;\n  /**\n   * S3 — present only when the question carried a comparison. The same group\n   * in the PRIOR window: a bucket is matched by its position in its own window\n   * (week 1 of September beside week 1 of August), so `prior_groups` names the\n   * prior bucket's own date. `null` when the prior window had no such group.\n   */\n  prior_groups?: Record<string, string | null> | null;\n  /** The prior window's measures, keyed exactly like `measures`. */\n  prior_measures?: Record<string, number | null> | null;\n  prior_row_count?: number | null;\n  /** Every measure now and before, the change, and the change as a percent of before. */\n  delta?: Record<string, AggregateDelta> | null;\n  /** The two windows this row was worked out over, and the calendar that cut them. */\n  compare?: AggregateCompareWindows | null;\n  /**\n   * S3 — a compared, bucketed row's POSITION in its window (0 = the first\n   * bucket). A row the current window has not reached yet has a position and\n   * no current bucket, so a chart names it \"Week 6\" rather than inventing a date.\n   */\n  position?: number | null;\n}\n\n/**\n * S3 — WHAT A PERIOD IS COMPARED AGAINST (`custom.agg_compare_kinds()`).\n * `previous_period` is the period before, of the same length (August before\n * September; an explicit window shifted back by its own length);\n * `same_period_last_year`; `range` is a fixed `baseline`.\n */\nexport type AggregateCompareKind = \"previous_period\" | \"same_period_last_year\" | \"range\";\n\n/**\n * S3 — ONE COMPARISON, as `custom.record_aggregate(p_compare)` and a\n * dashboard block's `compare` both take it. The current window is either the\n * calendar `period` holding `at` (default: now, in the organization's time\n * zone) or an explicit `from`/`to`. A date alone (\"2026-09-01\") is that local\n * day in the organization's time zone.\n */\nexport interface AggregateCompare {\n  against?: AggregateCompareKind;\n  /** The date Field the period runs along. Defaults to the bucket's key. */\n  key?: string;\n  period?: AggregateBucket;\n  at?: string;\n  from?: string;\n  to?: string;\n  /** Compare the part of the period that has happened (\"month to date\"). */\n  to_date?: boolean;\n  /** The fixed period `range` compares against. Half-open: `to` is excluded. */\n  baseline?: { from: string; to: string };\n}\n\n/** One measure now and before. `change_pct` is null when before was nothing or zero. */\nexport interface AggregateDelta {\n  current: number | null;\n  prior: number | null;\n  change: number | null;\n  change_pct: number | null;\n}\n\n/**\n * S3 — THE TWO WINDOWS the store actually ran, as local ISO moments with the\n * organization's offset (\"2026-09-01T00:00:00-07:00\"), and the calendar that\n * cut them. A screen labels the comparison from THIS, never from its own clock.\n */\nexport interface AggregateCompareWindows {\n  key: string;\n  against: AggregateCompareKind;\n  period: AggregateBucket | null;\n  to_date: boolean;\n  time_zone: string;\n  week_start: string;\n  /** The bucket grain the windows were counted in, when the question had a bucket. */\n  grain: AggregateBucket | null;\n  /** How many buckets the current window holds — what a target's pace is shared over. */\n  bucket_count: number | null;\n  window: { from: string; to: string };\n  prior_window: { from: string; to: string };\n  /** On a row from `recordAggregate`: that row's bucket position (see `AggregateRow.position`). */\n  position?: number | null;\n}\n\n/** The measure key the store answers with, so a chart can find its own series. */\nexport function measureKey(measure: AggregateMeasure): string {\n  return measure.op === \"count\" ? \"count\" : `${measure.op}_${measure.key ?? \"\"}`;\n}\n\n/**\n * THE QUESTION, AS A STABLE STRING — key-sorted JSON of a `RecordFilter`.\n *\n * A React parent that rebuilds `{ status: \"Cancelled\" }` on every render hands\n * a NEW object every time, and a hook that depends on the object re-reads the\n * whole page on every render forever. Depending on this instead means the page\n * is re-read exactly when the QUESTION changed, which is what a person means.\n *\n * Nested window objects are sorted too, so `{from, to}` and `{to, from}` are\n * one question. `undefined` and an empty filter are both `\"{}\"` — the caller\n * asked nothing, and there is only one way to ask nothing.\n */\nexport function stableFilterKey(filter: StoreFilter | null | undefined): string {\n  if (!filter) return \"{}\";\n  // A Rule expression is ORDERED — the evaluator asks its arguments in order — so its own JSON is\n  // already the question; only a flat map's keys need sorting.\n  if (isRuleFilter(filter)) return JSON.stringify(filter);\n  const keys = Object.keys(filter).sort();\n  if (keys.length === 0) return \"{}\";\n  const parts = keys.map((key) => {\n    const value = filter[key];\n    if (value !== null && typeof value === \"object\") {\n      const window = value as AggregateWindow;\n      return `${JSON.stringify(key)}:{\"from\":${JSON.stringify(window.from ?? null)},\"to\":${JSON.stringify(window.to ?? null)}}`;\n    }\n    return `${JSON.stringify(key)}:${JSON.stringify(value ?? null)}`;\n  });\n  return `{${parts.join(\",\")}}`;\n}\n\n/**\n * AGG-WITHHELD — the store's answer, with the withheld state lifted out of `measures`.\n * `custom.record_aggregate` puts a withheld measure's notice under `measures._withheld`\n * (null beside it); no consumer should ever meet that key among the numbers, so the one door\n * that reads the answer moves it to `row.withheld` and zeroes a count the store left out.\n */\nexport function liftWithheld(rows: AggregateRow[]): AggregateRow[] {\n  // HONEST-REFUSALS 2 — the store says the withheld explanation ONCE, on the first row's `measures._withheld`\n  // (older answers repeated it on every row). Whichever row carries it, every row of the answer gets the same\n  // `withheld`, so a total or a chart reads `row.withheld` exactly as before.\n  let shared: unknown;\n  for (const row of rows) {\n    const m = ((row.measures ?? {}) as Record<string, unknown>)[\"_withheld\"];\n    if (m !== undefined && m !== null && typeof m === \"object\") {\n      shared = m;\n      break;\n    }\n  }\n  return rows.map((row) => {\n    const measures = (row.measures ?? {}) as Record<string, unknown>;\n    const own = measures[\"_withheld\"];\n    const marker = own !== undefined && own !== null && typeof own === \"object\" ? own : shared;\n    const rowCount = (row.row_count as number | null) ?? 0;\n    if (marker === undefined || marker === null || typeof marker !== \"object\") {\n      return rowCount === row.row_count ? row : { ...row, row_count: rowCount };\n    }\n    const { _withheld: _drop, ...rest } = measures;\n    const withheld: NonNullable<AggregateRow[\"withheld\"]> = {};\n    for (const [name, raw] of Object.entries(marker as Record<string, unknown>)) {\n      const m = (raw ?? {}) as { withheld?: Partial<HiddenFieldNotice>; says?: string; label?: string; field_key?: string };\n      withheld[name] = {\n        reason: m.withheld?.reason ?? null,\n        needs: m.withheld?.needs ?? null,\n        or: m.withheld?.or ?? null,\n        ...(m.says ? { says: m.says } : {}),\n        ...(m.label ? { label: m.label } : {}),\n        ...(m.field_key ? { field_key: m.field_key } : {}),\n      };\n    }\n    return { ...row, measures: rest as Record<string, number | null>, withheld, row_count: rowCount };\n  });\n}\n\n/**\n * ROLLUP-FILTER (2026-10-18) — SEVERAL VALUES FOR ONE COLUMN, IN A FLAT FILTER.\n *\n * Beside a single value (`{status: \"Paid\"}`) and a window (`{paid_on: {relative: \"this_month\"}}`), a\n * column of a flat filter (a roll-up's `config.filter`, a saved view's filters) takes\n *   - an any-of list   `{status: [\"Sent\", \"Overdue\"]}`              (the store's list branch, has_any)\n *   - a not-in form    `{status: {not: [\"Draft\", \"Cancelled\"]}}`    (one word works too; list question is_not)\n * Each word is a choice's key or label, any case. This is the ONE reading of that grammar for the TypeScript\n * twins of `custom.record_filter_sql` (the memory world, the template checker); the store's own is the SQL.\n * A blank cell is none of the words, so a not-in form keeps it.\n */\nexport type FilterWords = { mode: \"any\" | \"none\"; words: string[] };\n\n/** `{not: ...}` / a list as the words it asks about, or `null` when the value is neither (a scalar, a window, null). */\nexport function filterWordsOf(want: unknown): FilterWords | null {\n  const strings = (v: unknown): string[] | null => {\n    if (typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\") return [String(v)];\n    if (Array.isArray(v) && v.every((x) => typeof x === \"string\" || typeof x === \"number\" || typeof x === \"boolean\")) return v.map(String);\n    return null;\n  };\n  if (Array.isArray(want)) {\n    const words = strings(want);\n    return words ? { mode: \"any\", words } : null;\n  }\n  if (want && typeof want === \"object\") {\n    const o = want as Record<string, unknown>;\n    const keys = Object.keys(o);\n    if (keys.length === 1 && keys[0] === \"not\") {\n      const words = strings(o[\"not\"]);\n      return words ? { mode: \"none\", words } : null;\n    }\n  }\n  return null;\n}\n\n/**\n * Does a cell (one value, a list, or nothing) satisfy an any-of / not-in question? `aliases` maps a word to the other\n * words that name the same choice (its key and label), so a filter written with the key reads a cell kept as the label.\n */\nexport function cellMatchesWords(cell: unknown, q: FilterWords, aliases?: (word: string) => readonly string[]): boolean {\n  const cellWords = (Array.isArray(cell) ? cell : [cell])\n    .filter((x) => x !== null && x !== undefined && String(x).trim() !== \"\")\n    .map((x) => String(x).trim().toLowerCase());\n  const asked = new Set(q.words.flatMap((w) => [w, ...(aliases?.(w) ?? [])]).map((w) => w.trim().toLowerCase()));\n  const hit = cellWords.some((w) => asked.has(w));\n  return q.mode === \"any\" ? hit : !hit;\n}\n","// src/record.ts — @ai-matrx/records\n//\n// THE RECORD, AND THE ONE DOCUMENT IT IS. REC-36: a record is one jsonb\n// document, never one row per value. Everything a record knows about a value —\n// what it is, where it came from, why it is missing, what else was a candidate,\n// which version of it this is — lives inside that one document, in the value\n// envelope the store writes and validates.\n//\n// Nothing in this module is a convenience re-description of the store. Each\n// shape is the store's own shape: the envelope keys are\n// `custom.value_envelope_keys()`, the absence words are\n// `custom.absence_reasons()`, and `custom.value_envelope_refusal` refuses by\n// name anything this file would let through.\n\nimport type { Actor, AbsenceReason } from \"./vocabulary\";\nimport type { RecordsError } from \"./results\";\n\n/** A `uuid` as the store writes it. */\nexport type Uuid = string;\n\n/** An ISO-8601 timestamp, as jsonb carries it. */\nexport type Timestamp = string;\n\n/**\n * VAL-1. WHERE a value came from, addressed by a pointer the STORE interns —\n * `s1`, `s2`, `s3`. A writer supplies the source itself and the store interns\n * it; a writer that invents a pointer is refused by name. Interned once per\n * save: two pointers holding the same description is the defect the word\n * \"interned\" exists to prevent, and the store refuses that too.\n */\nexport type ProvenancePointer = string;\n\n/** The description a pointer resolves to. Free-shaped by design: the store checks that it is an object, and the organization decides what it says. */\nexport type ValueSource = Record<string, unknown>;\n\n/**\n * VAL-3 / VAL-4. Another candidate for the same value, with the source it came\n * from and the RANK — the order an organization trusts its sources in, never a\n * score or a confidence a machine invented. Ranks are whole, start at 1, and\n * two alternates never claim the same one. They live INSIDE this record's\n * document; there is never a row per value.\n */\nexport interface ValueAlternate {\n  value: unknown;\n  /** A pointer this record's `_sources` block resolves. */\n  src?: ProvenancePointer | null;\n  rank: number;\n}\n\n/**\n * The value envelope. One per field key, in the record's `_values` block, with\n * the value itself sitting at the top level under the same key.\n *\n * The key set is CLOSED (`custom.value_envelope_keys()`). In particular it can\n * never carry any of the per-value access words (`PER_VALUE_ACCESS_WORDS`): VAL-5 puts those on the Field and on the Record, and VAL-6 says a\n * value that must be secret goes in a contained record with its own access.\n * The store refuses each of those words by name.\n */\nexport interface ValueEnvelope {\n  /** The per-value version, 1 or more. THE STORE WRITES IT — no caller sets it. */\n  ver: number;\n  /** A provenance pointer this record's `_sources` block resolves. */\n  src?: ProvenancePointer | null;\n  /** VAL-8. Who wrote it. */\n  actor: Actor;\n  /** Only an agent acts on behalf of a person; a person's id. */\n  on_behalf_of?: Uuid | null;\n  at?: Timestamp | null;\n  /** VAL-2. Why it is missing. A value either holds something or says this. */\n  absent?: AbsenceReason | null;\n  alternates?: ValueAlternate[] | null;\n  /**\n   * FLD-2's `dated` modifier: the WORLD clock for this value — when it was true\n   * of the world, which is a different question from when it was written. Added\n   * to the store's closed key set after this package's first generation, and\n   * caught by `pnpm check:store-registry` rather than by anybody noticing.\n   */\n  dated?: string | null;\n}\n\n/**\n * The one jsonb document. Field keys sit at the top level; the store's own\n * blocks are underscore-prefixed and are never a writer's value.\n */\nexport interface RecordDocument {\n  /** The store's interned provenance table: pointer -> source. */\n  _sources?: Record<ProvenancePointer, ValueSource>;\n  /** The envelopes, keyed by field key. */\n  _values?: Record<string, ValueEnvelope>;\n  /** FLD-10. Which type of record this is, selecting the Fields and Rules that apply. */\n  _type?: string;\n  /** REC-7. Zero or one parent. Never two. */\n  _parent?: Uuid | null;\n  [fieldKey: string]: unknown;\n}\n\n/** `custom.record` as the store holds it — the row around the document. */\n/**\n * What `custom.record_write_graph` wrote — a parent, the rows that belong to it, and the\n * edges it stands on, all in one transaction.\n *\n * `edges` counts BOTH writers: the edges written through `public.assoc_add` (whose ids are\n * in `edge_ids`) and the relation targets written through `platform.relation_set`, which\n * answers a count rather than ids because a relation is one field's worth of targets and\n * not a list of independent edges. `relations` is that second number on its own, so a\n * caller can tell them apart instead of subtracting.\n */\nexport interface RecordGraphWritten {\n  parent_id: Uuid;\n  table_id: Uuid | null;\n  child_ids: Uuid[];\n  edge_ids: Uuid[];\n  children: number;\n  edges: number;\n  relations: number;\n  /** The door's own sentence about what it did. Shown, never re-worded. */\n  how: string;\n}\n\nexport interface StoredRecord {\n  id: Uuid;\n  organization_id: Uuid;\n  table_id: Uuid | null;\n  /** `record` for ordinary rows, `kernel` for the nine kernel Tables (REC-27). */\n  data_class: string;\n  data: RecordDocument;\n  created_by: Uuid | null;\n  updated_by: Uuid | null;\n  created_at: Timestamp;\n  updated_at: Timestamp;\n  /** REC-23: soft, and reversible within `retention`. */\n  deleted_at: Timestamp | null;\n  /** The RECORD clock. `recordUpdate` writes against it (optimistic concurrency). */\n  version: number;\n  metadata: Record<string, unknown>;\n  custom_fields: Record<string, unknown>;\n  visibility: string;\n}\n\n/**\n * One value read back with everything the store knows about it — the shape\n * `custom.record_values_versioned` and `custom.value_read` answer in. This is\n * what a screen needs to explain a value (DYN-24) without a second query.\n */\nexport interface ReadValue {\n  field_key: string;\n  field_id: Uuid | null;\n  value: unknown;\n  value_version: number | null;\n  source: ValueSource | null;\n  absent_reason: AbsenceReason | null;\n  actor: Actor | null;\n  on_behalf_of: Uuid | null;\n  written_at: Timestamp | null;\n  alternates: ValueAlternate[] | null;\n}\n\n/**\n * Why one field of a record came back empty — `custom.hidden_field_notice`, as\n * the read door attaches it under `_hidden`. It is the store's own sentence, so\n * a screen says \"you need X to see this\" instead of drawing a blank cell.\n */\nexport interface HiddenFieldNotice {\n  /** The field's sensitivity word. */\n  reason: string | null;\n  /** The level this person would need. */\n  needs: string | null;\n  /** The other way in — \"a share of this one field with you\". */\n  or: string | null;\n}\n\n/**\n * One row as the read door `custom.read_records` answers it: the id, the\n * document the store decided this reader may see, and the reader's level on the\n * Table. A field this reader may not see is PRESENT and null, with its reason\n * in `hidden` — the masking is the store's, never this client's.\n */\nexport interface ReadRow {\n  id: Uuid;\n  document: RecordDocument;\n  /** `public.permission_level` — the caller's level on the Table. */\n  level: string;\n  hidden: Record<string, HiddenFieldNotice>;\n  /**\n   * A kept table's device copy holds a change to this row that has not reached the store yet (made\n   * offline, or not sent so far). Only the offline data source sets it; a read from the store never does.\n   */\n  waiting?: true;\n}\n\n/**\n * A ROW THE PERSON CANNOT OPEN (CHAIR-ACCESS b, by design): a row of a Confidential Table that the\n * reader is not named on comes back from the list doors as a bare header `{id, exists: true,\n * submitted_at}`, no values and no level. It is a fact (\"it exists\"), never a record to draw: a\n * screen that drew it painted a blank row. The client splits these out of `rows` and counts them in\n * `locked`; this is the one test for \"is this the header\".\n */\nexport function isLockedStub(row: { document?: unknown; level?: unknown } | null | undefined): boolean {\n  if (!row) return false;\n  if (row.level !== null && row.level !== undefined) return false;\n  const doc = row.document;\n  if (!doc || typeof doc !== \"object\") return false;\n  const keys = Object.keys(doc as Record<string, unknown>);\n  if (keys.length === 0 || keys.length > 3) return false;\n  const d = doc as Record<string, unknown>;\n  return d[\"exists\"] === true && keys.every((k) => k === \"id\" || k === \"exists\" || k === \"submitted_at\");\n}\n\n/** Split a read page into the rows a person can open and the count of header-only stubs. */\nexport function splitLockedRows<R extends { document?: unknown; level?: unknown }>(rows: readonly R[]): { rows: R[]; locked: number } {\n  const open: R[] = [];\n  let locked = 0;\n  for (const row of rows) {\n    if (isLockedStub(row)) locked += 1;\n    else open.push(row);\n  }\n  return { rows: open, locked };\n}\n\n/**\n * DOOR-SPEED. One key of a page's order, as `custom.read_records_page` takes it. `as` is the\n * column's own type — `number` sorts numerically (text that is not a number sorts last),\n * `date` sorts ISO dates and instants, `text` (the default) sorts by lower-cased text. A choice\n * column always sorts by the WORD a person sees; the store knows which columns are choices.\n * NULLS LAST both ways, record id as the tie-breaker.\n */\nexport interface RecordPageSort {\n  field: string;\n  direction?: \"asc\" | \"desc\";\n  as?: \"text\" | \"number\" | \"date\";\n}\n\n/** One page the store sorted, searched and counted: `total` is the matching set this reader may see. */\nexport interface RecordPage {\n  /** The rows this person can open. Header-only stubs of rows they cannot open are never in here. */\n  rows: ReadRow[];\n  /**\n   * The matching set this reader can OPEN (stubs left out). Absent `locked` and `total` agree with\n   * the old meaning.\n   */\n  total: number;\n  /** Rows the store listed only as a header (a Confidential row this person is not named on), across the whole table. */\n  locked?: number;\n  limit: number;\n  offset: number;\n  /**\n   * Sort keys the store SKIPPED because this reader cannot see that column (removed, or masked\n   * from their seat). The page is still read; the screen says the sort was not applied.\n   */\n  sort_ignored: string[];\n  /**\n   * Columns of a SAVED VIEW's own filter the store SKIPPED because this reader cannot see them (WITHHELD-HONEST-2).\n   * Only a filter marked `skip_withheld` is skipped; an explicit filter on such a column is refused by name.\n   */\n  filter_ignored?: string[];\n}\n\n/**\n * A row as the keyset door answers it: the read row plus the `version` and `organization_id` the\n * store read it at, in the same statement as its values (so a document and its version never\n * disagree). `version` is null only on a Confidential header row, which says nothing but \"it exists\".\n */\nexport type KeysetRow = ReadRow & { version: number | null; organization_id: Uuid };\n\n/**\n * AP3-KEYSET-DOOR. One page of `custom.read_records_keyset`: the same rows and order as `RecordPage`,\n * paged by an opaque `cursor` (null on the last page) instead of an offset, so nothing is skipped or\n * repeated while others write. Re-reading named rows (`ids`) answers `total: null` and no cursor.\n */\nexport interface RecordKeysetPage {\n  rows: KeysetRow[];\n  total: number | null;\n  /** Header-only stubs this page carried (rows this person cannot open); never in `rows`. */\n  locked?: number;\n  limit: number;\n  cursor: string | null;\n  /** As on `RecordPage`: sort keys skipped because this reader cannot see that column. */\n  sort_ignored: string[];\n  /** As on `RecordPage`: filter columns of a saved view skipped because this reader cannot see them. */\n  filter_ignored?: string[];\n}\n\n/** DOOR-SPEED. One change in a `recordChangeMany` batch. */\nexport type RecordChange =\n  | { op: \"insert\"; data: RecordDocument }\n  | { op: \"update\"; record_id: Uuid; patch: RecordDocument; expected_version?: number | null }\n  | { op: \"archive\"; record_id: Uuid };\n\n/** What one change did, in the order the changes were handed in. */\nexport type RecordChangeResult =\n  | { op: \"insert\"; id: Uuid }\n  | { op: \"update\"; id: Uuid; version: number }\n  | { op: \"archive\"; id: Uuid; archived_at: string };\n\n/**\n * One revision of one record, as `custom.io_revisions` answers it, newest\n * first. `version` is the record's own version at that point — the number a\n * screen hands back as `expectedVersion` so the store, not the screen, decides\n * whether someone else got there first.\n */\nexport interface RecordRevision {\n  version: number;\n  changed_at: string;\n  changed_by: Uuid | null;\n  summary: string | null;\n}\n\n/** A whole record as `recordRead` answers it, through `custom.read_record`. */\nexport interface RecordRead {\n  record_id: Uuid;\n  /** The masked document. A hidden field is present and null. */\n  document: RecordDocument;\n  /** Why each masked field is masked, in the store's words. */\n  hidden: Record<string, HiddenFieldNotice>;\n  /**\n   * FLD-9 / REC-19. Which Rule version produced each computed value. Present\n   * only where the store has computed provenance for this record.\n   */\n  computed: Array<{\n    field_key: string;\n    field_id: Uuid;\n    value: unknown;\n    rule_id: Uuid;\n    rule_version: number;\n    computed_at: Timestamp;\n  }>;\n  /**\n   * WHY `computed` IS EMPTY, when it is empty because nobody could read it.\n   *\n   * `custom.computed_provenance` is a footnote beside the record and its door is not\n   * open to a person's seat (no EXECUTE for `authenticated`, measured 2026-09-21). It\n   * used to fail the WHOLE read, so an organization's own owner was told \"You do not\n   * have access to this\" about a record he could read — see `core/client.ts`. The\n   * record comes back now, and this carries what the footnote's door said, so a screen\n   * that draws rule provenance can say it could not read it rather than draw nothing\n   * and mean two different things by it. `null` means the footnote was read fine (or\n   * was never asked for).\n   */\n  computedUnavailable?: RecordsError | null;\n  /**\n   * Asked with `withVersion: true`: the version this read saw, so a safe edit (`recordUpdate` with `expected_version`) needs no\n   * second call. Read beside the document in the same round of requests; `null` when the store\n   * could not answer it (a write then refuses as \"version unread\", never as last-write-wins).\n   */\n  version?: number | null;\n}\n","// src/subscription.ts — @ai-matrx/records\n//\n// DOOR-18. A SUBSCRIPTION IS A RULE RECORD, NOT A TABLE.\n//\n// \"Tell me when something in this view changes\" is a Rule carrying a\n// `subscription` block that names a saved view, a cadence, a channel and a\n// recipient. There is no subscriptions table and no second notifier: the store\n// answers `custom.agg_subscriptions`, fires through `custom.agg_subscription_fire`\n// and delivers through `communication.notification`.\n//\n// AND THE ADMISSION TEST RUNS AS THE SUBSCRIBER, not as the writer\n// (`custom.agg_view_admits`): a change to a record the subscriber may not see\n// is not a notification they are entitled to, because the notification's mere\n// existence would leak the record.\n\nimport type { RecordFilter } from \"./aggregate\";\nimport type { Uuid } from \"./record\";\n\n/**\n * HOW OFTEN. `instant` fires the moment a record ENTERS the view; the other three\n * are summaries, assembled by the store at that cadence and sent as ONE message\n * naming what entered, left and changed since the last one.\n *\n * `immediate` and `digest` — the two words this store wrote before 2026-09-20 —\n * are still accepted everywhere and normalized by `custom.agg_cadence_normalize`\n * to `instant` and `daily`, so a Rule written then and a Rule written by the\n * picker now mean the same thing to the same runner.\n */\nexport type SubscriptionCadence = \"instant\" | \"hourly\" | \"daily\" | \"weekly\";\n\n/**\n * THE HOURS NOT TO BE TOLD IN. A send inside them is not dropped — the store moves\n * it to the moment they end through the notification system's own `next_attempt_at`,\n * so there is still one sender and one retry policy and nothing disappears because\n * of the clock.\n */\nexport interface QuietHours {\n  /** \"22:00\". Left out (with `end`), the block names no night — only the clock. */\n  start?: string;\n  /** \"07:00\" — earlier than `start` means the block crosses midnight, which is the ordinary case. */\n  end?: string;\n  /**\n   * An IANA zone name, e.g. \"America/Chicago\". Left out, UTC. THIS IS ALSO THE CLOCK THE\n   * SCHEDULE IS READ IN: `custom.agg_digest_due_at` reads \"monday 08:00\" in this zone, so a\n   * block carrying only `tz` means \"no quiet hours, and 08:00 is my 08:00\".\n   */\n  tz?: string;\n}\n\n/** True when the block names a night (both ends), not only the clock the schedule is read in. */\nexport function hasQuietHours(\n  quiet: QuietHours | null | undefined,\n): quiet is QuietHours & { start: string; end: string } {\n  return Boolean(quiet?.start && quiet?.end);\n}\n\n/** The zone of the person at the keyboard, or null where the runtime cannot say. */\nexport function callersTimeZone(): string | null {\n  try {\n    return Intl.DateTimeFormat().resolvedOptions().timeZone || null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * A SUBSCRIPTION IS READ IN ITS OWNER'S CLOCK (lane HANDOVER, 2026-09-28).\n *\n * The store reads a schedule's \"08:00\" in `quiet_hours.tz` and falls back to UTC. Every caller\n * that set no quiet hours sent no zone, so Cedar Ridge Physical Therapy's \"every Monday at 8\"\n * went at 1 AM in California. `subscriptionDeclare` passes every spec through this: a spec that\n * names a zone is kept as it is; one that names none gets the caller's own.\n */\nexport function withCallersClock<T extends { quiet_hours?: QuietHours | null }>(\n  spec: T,\n  zone: string | null = callersTimeZone(),\n): T {\n  if (!zone || spec.quiet_hours?.tz) return spec;\n  return { ...spec, quiet_hours: { ...(spec.quiet_hours ?? {}), tz: zone } };\n}\n\n/** One subscription, exactly as `custom.agg_subscriptions` reports it. */\nexport interface Subscription {\n  rule_id: Uuid;\n  saved_view_id: Uuid | null;\n  cadence: string;\n  /** The digest's schedule. Null for `immediate`. */\n  schedule: string | null;\n  channel: string;\n  /** Null means this subscription fires at nobody, and the store says so. */\n  recipient_user_id: Uuid | null;\n  event_key: string;\n  name: string;\n}\n\n/**\n * ONE SUBSCRIPTION AS ITS OWNER SEES IT — `custom.subscriptions`.\n *\n * `custom.agg_subscriptions` is the NOTIFIER's reader: it answers the whole\n * organization's firing subscriptions so the delivery path can run, and it is\n * not callable by a client. This is the other side of the same rows — narrowed\n * to Tables the caller can already open, so the list never reveals a Table —\n * and it carries the two things a screen needs and the notifier does not: is it\n * switched off, and may I switch it off.\n */\nexport interface MySubscription extends Subscription {\n  table_id: Uuid | null;\n  /** Off. `custom.agg_subscriptions` already excludes a muted one, so this is the truth. */\n  muted: boolean;\n  /** It is addressed to me. */\n  mine: boolean;\n  /** I may switch it off: mine, or I hold admin on the Table it watches. */\n  i_may_mute: boolean;\n  /** The hours it will not tell me in. Null means any time. */\n  quiet_hours: QuietHours | null;\n  /** When this last told me anything at all. Null means it never has. */\n  last_sent_at: string | null;\n  /**\n   * When the next summary is due — computed by the SAME store functions the runner\n   * uses, so this and the moment it actually fires cannot drift. Null for `instant`,\n   * which has no due time, and null for a muted one, because saying \"next Monday\"\n   * beside a switch that is off is a screen that lies.\n   */\n  next_digest_at: string | null;\n}\n\n/**\n * THE SUMMARY THIS SUBSCRIPTION WOULD SEND RIGHT NOW — `custom.subscription_preview`.\n *\n * It assembles and returns: nothing is delivered, nothing is recorded and the\n * watermark does not move, so \"show me one now\" never costs somebody a text and\n * never robs the real Monday summary of a week of news.\n */\nexport interface DigestPreview {\n  rule_id: Uuid;\n  name: string;\n  cadence: string;\n  schedule: string | null;\n  quiet_hours: QuietHours | null;\n  channel: string;\n  recipient_user_id: Uuid | null;\n  muted: boolean;\n  table_id: Uuid | null;\n  saved_view_id: Uuid | null;\n  window_start: string;\n  window_end: string;\n  entered: Array<{ record_id: Uuid; name: string }>;\n  left: Array<{ record_id: Uuid; name: string }>;\n  changed: Array<{ record_id: Uuid; name: string }>;\n  counts: { entered: number; left: number; changed: number; in_view: number | null };\n  /** The grid, filtered by the very view this subscription is over. */\n  link: string | null;\n  subject: string;\n  body: string;\n  /**\n   * NOTHING FAILS SILENTLY. A subscription that cannot produce a summary — nobody to\n   * tell, no view, a view somebody deleted — says which piece is missing, in the\n   * sentence a person reads, instead of returning an empty summary that looks calm.\n   */\n  incomplete: string | null;\n}\n\n/**\n * ONE SAVED VIEW — `custom.views`. A subscription is written OVER one of these, so\n * a person with no saved view has nothing to be told about; `viewDeclare` is how a\n * screen gives them one without leaving the screen they are on.\n *\n * `filters` is written in the ONE shape `custom.agg_view_admits` reads, so a view\n * saved here needs no translation before the notifier can admit records to it.\n */\n/**\n * A ROW TEMPLATE (ROW-TEMPLATES, 2026-10-04) — Notion's database templates: a named preset of a\n * Table's values (\"New Instagram post\": Status=Idea, Platform=[Instagram], Page content = a\n * Hook/Script/Hashtags skeleton) that \"New from template\" starts a row from. Kept beside the\n * Table's views in `platform.saved_view` (surface `custom/records/template`); `values` by Field key.\n */\nexport interface RowTemplateRow {\n  template_id: Uuid;\n  name: string;\n  table_id: Uuid;\n  values: Record<string, unknown>;\n  created_at: string;\n  updated_at: string;\n}\n\nexport interface SavedViewRow {\n  view_id: Uuid;\n  name: string;\n  table_id: Uuid | null;\n  filters: RecordFilter;\n  /**\n   * THE WHOLE VIEW (S0 ONE-SAVED-VIEW, 2026-09-23): `platform.saved_view` is the ONE saved-view\n   * store, so this is what the view bar, the board, the calendar and the gallery draw from —\n   * `layout` (the kind), `group_field`, `measure`, `date_field`, `start_field`, `end_field`,\n   * `image_field`, `sorts`, `rule_id`,\n   * `is_default`, `presentation`, G7's `grid`, G13's `order`, the mover's `moved_from`.\n   */\n  definition: SavedViewDefinition;\n  created_at: string;\n}\n\n/** Every kind of view the store keeps (`custom.view_keys()` row `layout`). */\nexport type SavedViewLayout = \"grid\" | \"kanban\" | \"calendar\" | \"gallery\" | \"sheet\" | \"timeline\";\n\n/** `presentation.style.colorBy`: a choice or yes/no Field whose colors paint the cards, the calendar and the timeline. */\nexport interface SavedViewColorBy {\n  field: string;\n  target?: string;\n}\n\n/**\n * THE KEYS OF ONE SAVED VIEW, as `custom.view_keys()` declares them. Fields are named by key\n * (the store accepts an id and stores the key). Every key the store judges is listed here; the\n * index signature keeps the rest (`grid`, `order`, `moved_from`, the presentation details) open.\n */\nexport interface SavedViewDefinition {\n  layout?: SavedViewLayout;\n  /** The board's columns (kanban) or the timeline's rows: any Field. */\n  group_field?: string | null;\n  swimlane_field?: string | null;\n  measure?: string | null;\n  /** Calendar: the date Field that places a record. */\n  date_field?: string | null;\n  /** Timeline: the date Field where a record's bar starts. */\n  start_field?: string | null;\n  /** Calendar and timeline: the date Field where a record ends. Absent, a record is one day. */\n  end_field?: string | null;\n  /** Gallery: the Field drawn as the card's cover. */\n  image_field?: string | null;\n  presentation?: {\n    style?: { colorBy?: SavedViewColorBy | null; [key: string]: unknown } | null;\n    /** Gallery and grids: the Fields hidden from this view, by key. */\n    hiddenFields?: string[] | null;\n    [key: string]: unknown;\n  } | null;\n  [key: string]: unknown;\n}\n\n/**\n * What `custom.view_declare` is asked for. With `view_id` the door MERGES: `name` changes only\n * when sent, `filters` only when the key is sent, each `definition` key replaces that one key and\n * a key sent as `null` is removed — so a screen sends only what it changed.\n */\nexport interface SavedViewSpecIn {\n  name?: string;\n  filters?: RecordFilter | null;\n  definition?: SavedViewDefinition | Record<string, unknown> | null;\n  view_id?: Uuid | null;\n}\n\n/** What `custom.subscription_declare` is asked for. The store refuses the rest BY NAME. */\nexport interface SubscriptionSpec {\n  name: string;\n  saved_view_id: Uuid;\n  cadence: SubscriptionCadence;\n  /** \"monday 08:00\", \"09:30\". Meaningless for `instant`. */\n  schedule?: string | null;\n  channel?: \"in_app\" | \"email\" | \"sms\";\n  quiet_hours?: QuietHours | null;\n  /** Left out, the person setting it up — \"tell ME\". */\n  recipient_user_id?: Uuid | null;\n  event_key?: string;\n  /** Re-state an existing subscription rather than making a second one. */\n  rule_id?: Uuid | null;\n}\n\n/** The `subscription` block a Rule record carries. Written through `record_write`. */\nexport interface SubscriptionBlock {\n  saved_view_id: Uuid;\n  cadence: SubscriptionCadence;\n  schedule?: string | null;\n  channel?: string;\n  recipient_user_id?: Uuid | null;\n  event_key?: string;\n}\n","// src/rowLabel.ts — @ai-matrx/records\n//\n// A TABLE NAMES ITS RECORDS BY A FORMULA (ROW-LABEL-FORMULA, 2026-10-10).\n//\n// The older Sheet could name a row by several columns joined, `{First} & \" \" & {Last}`. The store keeps,\n// beside a table's single title column (`title_field`), an optional ROW-LABEL FORMULA over the table's own\n// columns. It is parsed by the formula field's own parser (`custom.formula_parse`) and worked out by the\n// formula field's own evaluator, so there is no second language. When it is set and returns words for a\n// record, those words are the record's name EVERYWHERE the store names a record - link chips, peeks,\n// pickers, back-links, search results, a notification's subject, the record page's title - because every\n// one of them reads the one resolver. A blank result, or a formula that cannot be worked out for one\n// record, names that record by the title column. Clearing the formula falls back to the title column.\n//\n// Nothing is copied: names are read live, so changing Last is the next read's name.\n\n/** What `tableRowLabel` / `tableRowLabelSet` answer. */\nexport interface TableRowLabel {\n  /** The formula as it was typed, or null when the table names its records by its title column. */\n  formula: string | null;\n  /** The single-column label the table falls back to (its `title_field` key). */\n  title_field: string | null;\n  /** Which of the two names records now: the formula, or the title column. */\n  effective: \"formula\" | \"column\";\n  /** The type the formula answers (text, number, ...), when it still reads. */\n  result_type: string | null;\n  /** False when the stored formula text no longer parses against the table's columns (a column was renamed or retired). */\n  valid: boolean;\n  /** The parser's sentence when `valid` is false. */\n  error: string | null;\n  /** Whether the caller may set or clear it (the table's maker, or someone with full access). */\n  can_change: boolean;\n}\n\n/** The longest formula the store keeps. */\nexport const ROW_LABEL_FORMULA_MAX_LENGTH = 2000;\n\n/** True when a value handed to `tableRowLabelSet` clears the formula (null, empty, or only spaces). */\nexport function clearsRowLabel(formula: string | null | undefined): boolean {\n  return formula == null || formula.trim() === \"\";\n}\n","// src/relation.ts — @ai-matrx/records\n//\n// THE RELATION. REL-1 … REL-16 and REL-N-1.\n//\n// A Relation is SEVEN independent properties, and the reason they are seven\n// separate fields rather than one enum is REL-1/REL-2: ownership and what\n// happens on delete are different questions, and a system that fuses them ends\n// up unable to say \"referenced, but cascade\".\n//\n// REL-10/REL-11: a relation is stored as an association with `role` = the field\n// key. NOTHING about a relation is stored in the value. REL-9: it is visible\n// from both ends and the reverse is not a second Field.\n\nimport type { Timestamp, Uuid } from \"./record\";\nimport type { RecordsDataSource } from \"./ports\";\nimport { err, ok, type RecordsResult } from \"./results\";\nimport { mapPgError } from \"./core/pgError\";\nimport type {\n  OnDelete,\n  RelationBinding,\n  RelationCardinality,\n  RelationFlavor,\n} from \"./vocabulary\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n/**\n * REL-6. Whether Visibility flows along this relation and the MAXIMUM access\n * level it carries. Default off on `referenced`, on for `owned`.\n */\nexport interface RelationCarries {\n  carries: boolean;\n  /** The ceiling — a relation never carries more access than this. */\n  max_access: string | null;\n}\n\n/** The seven properties, each its own question. */\nexport interface RelationProperties {\n  /** REL-1. Stored once on the contained table, read from the field's side. */\n  flavor: RelationFlavor;\n  /** REL-2. Separate from flavour. */\n  on_delete: OnDelete;\n  /** REL-3. A snapshot is a frozen copy in the relation's payload — never a pointer into History. */\n  binding: RelationBinding;\n  /** REL-4. */\n  ordered: boolean;\n  /** REL-5. */\n  loops: \"allowed\" | \"refused\";\n  /** REL-6. */\n  carries: RelationCarries;\n  /** REL-7. */\n  cardinality: RelationCardinality;\n}\n\n/**\n * REL-8 / REL-N-1. A target is a REFERENCE, written that way from the first\n * line of code, because it may name a row outside our database. One Table,\n * several, or any — polymorphic without restriction. External targets are\n * read-only in v1.\n */\nexport type RelationTarget =\n  | { kind: \"ours\"; entity_token: string; row_id: Uuid }\n  | {\n      kind: \"external\";\n      connection_token: string;\n      external_table: string;\n      external_key: string;\n    }\n  | { kind: \"any\" };\n\n/** One edge, as the store holds it in `platform.associations`. */\nexport interface Relation {\n  id: Uuid;\n  organization_id: Uuid;\n  /** REL-10. The field key, which is what `role` holds. */\n  role: string;\n  source: RelationTarget;\n  target: RelationTarget;\n  properties: RelationProperties;\n  /** REL-4. Meaningful only when `ordered`. */\n  position: number | null;\n  /** REL-3. The frozen copy, when `binding` is `snapshot`. */\n  payload: Record<string, unknown> | null;\n  /** REL-14. Hydrated from the target's title field AT READ — never stored. */\n  label: string | null;\n  created_at: Timestamp;\n  updated_at: Timestamp;\n  /** REL-13 / REL-16. Associations are versioned, so relation history exists. */\n  version: number;\n}\n\n/**\n * DOOR-6. A query coordinate: \"related to THIS, along THAT role, in that\n * direction\". Any combination, and any subset of them.\n */\nexport interface RelationCoordinate {\n  /** The record at the other end. */\n  record_id: Uuid;\n  /** The field key the edge carries as its role. Omit to mean any role. */\n  role?: string;\n  /** Which way to walk. `out` is this record's own relation fields. */\n  direction?: \"out\" | \"in\" | \"either\";\n}\n\n/**\n * The arguments of the ONE relation-words resolver: the FIELD, because that is where its display\n * spec is declared and judged (`custom._display_of_field` reads it server-side; the caller never\n * carries it), and the ids of a page of cells.\n */\n/** A linked record's icon, and its table's icon for a record that has none (`relationWordsMany`). */\nexport interface RelationIcons {\n  icon: string | null;\n  tableIcon: string | null;\n}\n\nexport interface RelationWordsManyArgs {\n  field_id: Uuid;\n  record_ids: Uuid[];\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// SC-R / P12 — A FIELD THAT POINTS AT A PLATFORM ENTITY\n// ───────────────────────────────────────────────────────────────────────────\n//\n// An ENTITY REFERENCE is a relation (FLD-1's five behaviors hold) whose target\n// mode is `any` (REL-8), restricted by `config.allowed_types` to the platform\n// kinds it may name — an agent, a note, a web site, a workbook, a dataset, a\n// conversation. Its value is REL-N-1's reference shape, `{token, id}`, a list\n// like every relation's (REL-7); the edge beside it is ONE\n// `platform.associations` row record → <token>, written by the store. Every\n// read door answers `{token, id, label}`, the label read — never stored\n// (REL-14) — from the thing's own title, WITHHELD for a reader who may not open\n// the thing. File and Person are not entity references: they are relations to\n// their kernel Tables (`attachment`, `member`).\n\n/** One reference as the store keeps it. */\nexport interface EntityRef {\n  /** The `platform.entity_types` token: `note`, `web_site`, `agent` … */\n  token: string;\n  id: Uuid;\n}\n\n/** One reference as a read door answers it. */\nexport interface EntityRefWithWords extends EntityRef {\n  /**\n   * The thing's own title — or the store's withheld sentence when the reader\n   * may not open it; `null` when the kind names no title.\n   */\n  label: string | null;\n}\n\n/** One kind of platform thing a record may point at (`custom.entity_reference_kinds`). */\nexport interface EntityReferenceKind {\n  token: string;\n  /** What a person reads: \"Note\", \"Site\", \"Agent\". */\n  label: string;\n  /** The picker's grouping: the admin-assigned reference category, else the schema. */\n  category: string;\n}\n\nfunction isRefLike(value: unknown): value is { token: unknown; id: unknown } {\n  return typeof value === \"object\" && value !== null && \"token\" in value && \"id\" in value;\n}\n\n/**\n * The references a cell holds, whichever shape it arrived in — one object, a\n * list, or what a read door rendered (with labels). Anything that is not a\n * reference is left out, never guessed at.\n */\nexport function entityRefsOf(value: unknown): EntityRefWithWords[] {\n  const items = Array.isArray(value) ? value : value == null ? [] : [value];\n  const out: EntityRefWithWords[] = [];\n  for (const item of items) {\n    if (!isRefLike(item)) continue;\n    const token = String(item.token ?? \"\").trim().toLowerCase();\n    const id = String(item.id ?? \"\").trim();\n    if (!token || !isUuidShape(id)) continue;\n    const label = (item as { label?: unknown }).label;\n    out.push({ token, id: id.toLowerCase(), label: typeof label === \"string\" ? label : null });\n  }\n  return out;\n}\n\n/**\n * What to WRITE for an entity-reference cell: `{token, id}` only, each thing\n * once, first mention first — the label a read door added is dropped, because\n * the store reads it and never keeps it (REL-14). A single-valued column gets\n * the one object (or `null`), a multi-valued one the list.\n */\nexport function entityRefsToWrite(value: unknown, multi: boolean): EntityRef | EntityRef[] | null {\n  const seen = new Set<string>();\n  const refs: EntityRef[] = [];\n  for (const ref of entityRefsOf(value)) {\n    const k = `${ref.token}:${ref.id}`;\n    if (seen.has(k)) continue;\n    seen.add(k);\n    refs.push({ token: ref.token, id: ref.id });\n  }\n  if (multi) return refs;\n  return refs[0] ?? null;\n}\n\n/**\n * The kinds of platform thing a record may point at — what the field editor's\n * kind picker lists. `custom.entity_reference_kinds()`.\n */\nexport async function entityReferenceKinds(\n  source: RecordsDataSource,\n): Promise<RecordsResult<EntityReferenceKind[]>> {\n  const { data, error } = await source.rpc(\"entity_reference_kinds\", {}, { schema: \"custom\" });\n  if (error) return err(mapPgError(error, \"entityReferenceKinds\"));\n  return ok(Array.isArray(data) ? (data as EntityReferenceKind[]) : []);\n}\n\n/**\n * THE SEARCH DOOR (lane REFERENCE-CARRY). The platform things of these kinds whose words hold\n * `search`, that THIS person may point a record at — each one a thing the store's own write check\n * (`custom._entity_reference_target_ok`) would accept, so a picked reference is never refused on\n * save. `custom.entity_reference_search`. An empty search lists the first things by name.\n */\nexport async function entityReferenceSearch(\n  source: RecordsDataSource,\n  organizationId: Uuid | null,\n  tokens: readonly string[],\n  search: string,\n  limit = 20,\n): Promise<RecordsResult<EntityRefWithWords[]>> {\n  if (tokens.length === 0) return ok([]);\n  const { data, error } = await source.rpc(\n    \"entity_reference_search\",\n    { p_organization_id: organizationId, p_tokens: [...tokens], p_search: search.trim() || null, p_limit: limit },\n    { schema: \"custom\" },\n  );\n  if (error) return err(mapPgError(error, \"entityReferenceSearch\"));\n  return ok(entityRefsOf(data));\n}\n\n/**\n * THE WORDS HELPER. The words of each `{token, id}` for a picker or a chip\n * before anything is saved — each label read by the store for THIS person and\n * withheld when they may not open the thing. `custom.entity_reference_words`.\n * A saved cell needs no call: every read door already answers its labels.\n */\nexport async function entityReferenceWords(\n  source: RecordsDataSource,\n  organizationId: Uuid | null,\n  refs: readonly EntityRef[],\n): Promise<RecordsResult<EntityRefWithWords[]>> {\n  if (refs.length === 0) return ok([]);\n  const { data, error } = await source.rpc(\n    \"entity_reference_words\",\n    { p_organization_id: organizationId, p_refs: refs.map((r) => ({ token: r.token, id: r.id })) },\n    { schema: \"custom\" },\n  );\n  if (error) return err(mapPgError(error, \"entityReferenceWords\"));\n  return ok(entityRefsOf(data));\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// VIEWS-AND-FIELDS BL — THE REVERSE COLUMN (REL-9, Airtable's back-link)\n// ───────────────────────────────────────────────────────────────────────────\n//\n// When a column of table A links to table B, B shows a column listing the A\n// records that point at each B record. REL-9: the reverse is NOT a second Field,\n// so it is never in `applicableFields(B)` — it is VIRTUAL, listed by\n// `custom.reverse_columns` and read a page at a time by\n// `custom.reverse_links_many`. Read-only: a link is made or broken from A's side.\n\n/** One reverse column of a Table, as `custom.reverse_columns` answers it. */\nexport interface ReverseColumn {\n  /** Stable key: the linking Field's `inverse_key`, else `linked_<field id>`. Never a Field key of B. */\n  key: string;\n  /** What the column is called on B: the linking table's name (plus the column's when ambiguous). */\n  label: string;\n  /** The relation Field on the linking table. */\n  source_field_id: Uuid;\n  source_field_key: string;\n  source_field_label: string;\n  /** The linking table. */\n  source_table_id: Uuid;\n  source_table_name: string;\n  /** Always `many`: any number of records may link to one. */\n  cardinality: \"many\";\n  /**\n   * True for a virtual back-link (written only from the linking table's side). False for a TWO-WAY\n   * LINK (NOTION-PROPS): the reverse end is a real Field on this table — `key` is its key, `label`\n   * its label — and `relationReverseSet` writes its links from here.\n   */\n  read_only: boolean;\n}\n\n/**\n * NOTION-PROPS. A two-way link's reverse Field: a relation whose `config.reverse_of` names the\n * forward relation it mirrors. It holds no value of its own — its links are the forward Field's.\n */\nexport function isReverseField(field: { type?: unknown; config?: unknown } | null | undefined): boolean {\n  if (!field || field.type !== \"relation\") return false;\n  const config = field.config as { reverse_of?: unknown } | null | undefined;\n  return typeof config?.reverse_of === \"string\" && config.reverse_of.length > 0;\n}\n\n/** One linking record, as a chip shows it. */\nexport interface ReverseLink {\n  id: Uuid;\n  /** The linking record's name, read by the store for this reader. */\n  words: string;\n}\n\n/** The links of one record through one reverse column: how many the reader may see, and one page. */\nexport interface ReverseLinks {\n  total: number;\n  links: ReverseLink[];\n}\n\nexport interface ReverseLinksManyArgs {\n  /** The Table whose records are being shown (B). */\n  table_id: Uuid;\n  /** `ReverseColumn.source_field_id`. */\n  source_field_id: Uuid;\n  /** A page of B's record ids — up to 200 a call; more are sent in groups by the client. */\n  record_ids: readonly Uuid[];\n  /** Links per record, 1–50 (the store holds it there). Default 10. */\n  limit?: number;\n  /** Skip this many links of each record — the next page of one hub record. Default 0. */\n  offset?: number;\n}\n\n/** `reverseLinksFields`: the links of a page through several reverse columns, in one call. */\nexport interface ReverseLinksFieldsArgs {\n  table_id: Uuid;\n  /** Each `ReverseColumn.source_field_id` — at most 20. */\n  source_field_ids: readonly Uuid[];\n  record_ids: readonly Uuid[];\n  limit?: number;\n  offset?: number;\n}\n\n/** The store's per-call ceiling on records for `custom.reverse_links_many`. */\nexport const REVERSE_LINKS_RECORDS_PER_CALL = 200;\n/** The store's ceiling on links a record per call. */\nexport const REVERSE_LINKS_PAGE_MAX = 50;\n\n// ── A WORKED-OUT COLUMN WHOSE SOURCE IS ARCHIVED (CHAIR-ROLLUP-HONEST) ─────────\n//\n// `custom.rollup_value` / `custom.lookup_value` answer this object, in the value's own place,\n// when the link a roll-up or lookup reads through (a forward link, or the linking column of a\n// back-link) or the far column it totals or borrows is archived — never a 0 or an empty that\n// looks like \"nothing linked\". `custom.field_source_archived` answers the same object for a\n// column with no record to read (Column settings). `custom.field_restore(field_id)` brings it back.\n\n/** The store's typed \"source archived\" answer for a lookup or roll-up. */\nexport interface SourceArchived {\n  __unavailable: \"source_archived\";\n  /** `link`: the relation it reads through is archived; `column`: the far column it reads is. */\n  reads: \"link\" | \"column\";\n  /** The archived Field. Absent when the reader may not know its Table. */\n  field_id?: Uuid;\n  /** Its label. Absent when the reader may not know its Table. */\n  label?: string;\n  table_id?: Uuid;\n  /** Its Table's name. Absent when the reader may not know that Table. */\n  table?: string;\n}\n\n/** The typed \"source archived\" answer, when `value` is one; null for any other value. */\nexport function sourceArchivedOf(value: unknown): SourceArchived | null {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n  const v = value as Record<string, unknown>;\n  if (v[\"__unavailable\"] !== \"source_archived\") return null;\n  const text = (k: string) => (typeof v[k] === \"string\" && v[k] ? (v[k] as string) : undefined);\n  const out: SourceArchived = { __unavailable: \"source_archived\", reads: v[\"reads\"] === \"column\" ? \"column\" : \"link\" };\n  const fieldId = text(\"field_id\");\n  const label = text(\"label\");\n  const tableId = text(\"table_id\");\n  const table = text(\"table\");\n  if (fieldId) out.field_id = fieldId as Uuid;\n  if (label) out.label = label;\n  if (tableId) out.table_id = tableId as Uuid;\n  if (table) out.table = table;\n  return out;\n}\n","// src/formulaLook.ts — THE ONE HOME of the number format a formula (or rollup / lookup) column shows.\n//\n// A formula column carries no look of its own unless one is DECLARED on the field (`display_format`, like any other\n// column's \"Shows as\"). This module answers what that look is when nobody declared it: the template preview, the\n// template installer (it writes the answer onto the field at install time) and the table display of an older or\n// hand-made formula (`withFormulaLooks`, applied where the client reads a table's fields) all call it. Never copy it.\n\ntype Json = Record<string, unknown>;\n\nconst NUMBER_LOOKS = new Set([\"number\", \"decimal\", \"currency\", \"percent\", \"progress\", \"integer\", \"duration\", \"file_size\"]);\nconst CURRENCY_CODES: Record<string, string> = { $: \"USD\", \"£\": \"GBP\", \"€\": \"EUR\", \"¥\": \"JPY\", \"₹\": \"INR\", R$: \"BRL\", C$: \"CAD\", A$: \"AUD\" };\n\n/**\n * THE NUMBER FORMAT A ROLLUP OR LOOKUP INHERITS from the column it reads (BUTTON-STAMPS; the store's\n * custom._picked_look twin): the column's own chosen number look whole, else money keeps its currency, a percent\n * stays a percent and a number keeps its unit as a suffix. `undefined` when the column has no number format worth\n * carrying.\n */\nexport function pickedLookOf(field: Json): { id: string; options?: Json } | undefined {\n  const df = field[\"display_format\"] as { id?: unknown; options?: Json } | undefined;\n  if (df && typeof df === \"object\" && typeof df.id === \"string\" && NUMBER_LOOKS.has(df.id)) return df as { id: string; options?: Json };\n  const unit = typeof field[\"unit\"] === \"string\" && field[\"unit\"].trim() ? field[\"unit\"].trim() : null;\n  const parity = String(field[\"parity_type\"] ?? \"\");\n  if (parity === \"currency\") return { id: \"currency\", options: { currency: CURRENCY_CODES[unit ?? \"$\"] ?? (unit ?? \"USD\").toUpperCase() } };\n  if (parity === \"percent\") return { id: \"percent\" };\n  if ((parity === \"number\" || parity === \"integer\" || parity === \"decimal\") && unit) return { id: \"number\", options: { suffix: ` ${unit}` } };\n  return undefined;\n}\n\n/** A label that says its column is a percent: \"Margin (%)\", \"Fee percent\", \"Win pct\". */\nconst PERCENT_LABEL = /\\(%\\)|%\\s*$|\\bpercent(age)?\\b|\\bpct\\b/i;\n\n/**\n * THE NUMBER FORMAT A FORMULA COLUMN SHOWS when the template declares none: a label that says percent is a\n * percent; otherwise a formula that does arithmetic with money columns (and never divides by one: a ratio is not\n * money) shows money in that currency — \"Net to client\" = offer − fee − costs − liens reads \"$18,247\", not\n * \"18,247\" (ADVERSARIAL-3 D8). `fields` are the table's columns as the store keeps them (their `display_format`\n * already inherited). `undefined` when nothing is worth carrying — a formula answering words stays words.\n */\nexport function formulaLookOf(formula: string, field: Json, fields: readonly Json[]): { id: string; options?: Json } | undefined {\n  const label = String(field[\"label\"] ?? field[\"key\"] ?? \"\");\n  const unit = typeof field[\"unit\"] === \"string\" ? field[\"unit\"].trim() : \"\";\n  if (unit === \"%\" || PERCENT_LABEL.test(label)) return { id: \"percent\" };\n  if (unit && CURRENCY_CODES[unit]) return { id: \"currency\", options: { currency: CURRENCY_CODES[unit] } };\n  if (/^[A-Z]{3}$/.test(unit)) return { id: \"currency\", options: { currency: unit } };\n  const lookOf = (f: Json) => {\n    const df = f[\"display_format\"] as { id?: unknown; options?: Json } | undefined;\n    return df && typeof df.id === \"string\" && NUMBER_LOOKS.has(df.id) ? (df as { id: string; options?: Json }) : pickedLookOf(f);\n  };\n  const escape = (x: string) => x.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n  let money: { id: string; options?: Json } | undefined;\n  for (const m of formula.matchAll(/\\{([^}]+)\\}/g)) {\n    const name = m[1]!;\n    const ref = fields.find((f) => f[\"label\"] === name || f[\"key\"] === name);\n    const look = ref ? lookOf(ref) : undefined;\n    if (look?.id !== \"currency\") continue;\n    const at = `\\\\{${escape(name)}\\\\}`;\n    // Dividing BY money is a ratio (margin / quote), never money.\n    if (new RegExp(`/\\\\s*${at}`).test(formula)) return undefined;\n    // Money is the answer only when the formula computes with it (or is it): a comparison inside IF is not.\n    if (new RegExp(`${at}\\\\s*[-+*/]|[-+*/]\\\\s*${at}`).test(formula) || formula.trim() === `{${name}}`) money ??= look;\n  }\n  return money;\n}\n\n/** The aggregates whose answer is in the unit of the column they read; count, countall, filled, unique… stay plain numbers. */\nconst UNIT_KEEPING_AGGS = new Set([\"sum\", \"min\", \"max\", \"avg\"]);\n\n/** Does this stored field read as a rollup or a lookup (a column that reads another table's column)? */\nexport function isDerivedField(f: Json): boolean {\n  const parity = String(f[\"parity_type\"] ?? \"\");\n  return parity === \"rollup\" || parity === \"lookup\";\n}\n\n/**\n * THE NUMBER FORMAT A ROLLUP OR LOOKUP SHOWS when it declares none (ROLLUP-FORMAT): that of the column it reads\n * (\"Material cost per unit (USD)\" = sum of the BOM lines' \"Line cost\" reads \"$56\", a lookup of a money column reads\n * \"$\"). sum / min / max / avg keep the source's look; count and the other measures stay plain numbers. `farFieldsOf`\n * answers the candidate far tables' columns (their own looks already worked out) for the field's `via` link; the\n * first candidate that holds the picked column and has a look worth carrying wins. `undefined` otherwise.\n */\nexport function derivedLookOf(field: Json, farFieldsOf: (via: string) => ReadonlyArray<readonly Json[]>): { id: string; options?: Json } | undefined {\n  const parity = String(field[\"parity_type\"] ?? \"\");\n  const cfg = (field[\"config\"] ?? {}) as Json;\n  if (parity !== \"rollup\" && parity !== \"lookup\") return undefined;\n  if (parity === \"rollup\" && !UNIT_KEEPING_AGGS.has(String(cfg[\"agg\"] ?? \"\"))) return undefined;\n  const via = String(cfg[\"via\"] ?? \"\");\n  const pick = String((parity === \"rollup\" ? cfg[\"of\"] : cfg[\"pick\"]) ?? \"\");\n  if (!via || !pick) return undefined;\n  for (const far of farFieldsOf(via)) {\n    const source = far.find((f) => f[\"key\"] === pick);\n    const look = source ? pickedLookOf(source) : undefined;\n    if (look) return look;\n  }\n  return undefined;\n}\n\n/** Does this stored field read as a formula column (a typed expression, not a rollup or lookup)? */\nfunction isPlainFormula(f: Json): boolean {\n  if (String(f[\"type\"] ?? \"\") !== \"formula\" && String(f[\"parity_type\"] ?? \"\") !== \"formula\") return false;\n  const cfg = (f[\"config\"] ?? {}) as Json;\n  return !cfg[\"agg\"] && !cfg[\"pick\"] && !cfg[\"via\"];\n}\n\n/**\n * THE DISPLAY FALLBACK: every formula column with no declared `display_format` gets the inferred one, so an older\n * install or a hand-made formula reads \"$18,247\" / \"42%\" like a new one. A declared format is never touched; a\n * formula with nothing worth carrying stays as it is. Returns the same array when nothing changed.\n */\nexport function withFormulaLooks<F extends object>(fields: readonly F[]): F[] {\n  const work = [...(fields as unknown as Json[])];\n  let changed = false;\n  work.forEach((f, i) => {\n    if (!isPlainFormula(f) || (f[\"display_format\"] && typeof f[\"display_format\"] === \"object\")) return;\n    const text = String(((f[\"config\"] ?? {}) as Json)[\"formula_text\"] ?? \"\");\n    const look = formulaLookOf(text, f, work);\n    if (!look) return;\n    work[i] = { ...f, display_format: look };\n    changed = true;\n  });\n  return (changed ? work : (fields as unknown as Json[])) as unknown as F[];\n}\n\n/**\n * THE DISPLAY FALLBACK FOR ROLLUPS AND LOOKUPS: every rollup / lookup with no declared `display_format` gets the\n * look of the column it reads (`derivedLookOf`). A formula that reads such a column is worked out again after, so\n * chains (lookup -> formula -> rollup) settle. Never touches a declared format.\n */\nexport function withDerivedLooks<F extends object>(fields: readonly F[], farFieldsOf: (via: string) => ReadonlyArray<readonly Json[]>): F[] {\n  let work = withFormulaLooks(fields) as unknown as Json[];\n  for (let pass = 0; pass < 3; pass++) {\n    let changed = false;\n    work = work.map((f) => {\n      if (!isDerivedField(f) || (f[\"display_format\"] && typeof f[\"display_format\"] === \"object\")) return f;\n      const look = derivedLookOf(f, farFieldsOf);\n      if (!look) return f;\n      changed = true;\n      return { ...f, display_format: look };\n    });\n    if (!changed) break;\n    work = withFormulaLooks(work) as unknown as Json[];\n  }\n  return work as unknown as F[];\n}\n","/**\n * THE CLIENT OPERATION LEDGER — how a browser recognizes the echo of its own write.\n *\n * Every private-channel notice the record store broadcasts reaches EVERY browser watching that\n * Table, including the one that caused it. Until now the writer had no way to tell its own\n * change from a colleague's: the notice carried ids and nothing about who moved them, so\n * `recordsRealtimePort.ts` declared `acceptEchoFromSelf: true` and the writer re-read a page it\n * had already updated. It was named honestly rather than faked, and this is the other half.\n *\n * THE SHAPE. Every write through `RecordsClient` mints a uuid, sends it to the store as the\n * platform envelope key `_op_id`, and remembers it here. The store lifts that key out before\n * storage — it is never written onto the record — carries it on the change-feed row, and puts\n * it in the notice as `op_id`. A notice whose `op_id` is in this ledger is this browser's own\n * echo and is dropped.\n *\n * WHY A TIME WINDOW RATHER THAN A DELETE-ON-MATCH. One write can produce MORE THAN ONE notice:\n * a record write that also moves a column produces a `record` notice and a `field` notice, and\n * a statement touching two Tables produces one per Table. Forgetting an op the first time it\n * came back would make the second notice look like somebody else's and cost the re-read this\n * exists to avoid. So an op is remembered for a window and expires on its own.\n *\n * 🚨 THE WINDOW IS A CORRECTNESS BOUNDARY, NOT A TUNING KNOB, AND IT FAILS IN THE SAFE\n * DIRECTION BY CONSTRUCTION. Too SHORT and a late echo is treated as a stranger's change: one\n * extra read of a page that is already correct — invisible. Too LONG and a stranger's change\n * that happened to reuse our uuid would be dropped — which cannot happen, because it is a v4\n * uuid nobody else has ever seen. The only real cost of a long window is memory, so it is\n * bounded by COUNT as well as by time.\n *\n * WHAT THIS IS NOT. It is not a replacement for the store's optimistic concurrency, and it\n * never decides what is true — a dropped echo means \"I already know about this\", and every\n * path that could be wrong about that (a reconnect, a tab wake, a notice with no `op_id` at\n * all) re-reads through the door as it always did.\n */\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\nimport type { Uuid } from \"./core/index\";\n\n/** How long an operation stays recognizable as ours. See the header: it fails safe both ways. */\nconst REMEMBER_MS = 30_000;\n\n/** A ceiling so a long-lived tab that writes constantly cannot grow this without bound. */\nconst REMEMBER_MAX = 500;\n\n/**\n * One client's memory of its own operations. `mint()` names a write and remembers it; `isOwn(opId)`\n * answers whether a notice is that write's echo.\n *\n * OWN-WRITE DETECTION IS PER CLIENT INSTANCE. Two setups in ONE process (a server holding two\n * identities, a worker beside a UI) must hear each other: a realm-wide ledger made A's write \"ours\" to\n * B as well, and B dropped it as an echo (2026-10-08, the README proof). `createRecords` gives every\n * setup its own ledger and hands it to its client, its entity port and its live-changes port.\n */\nexport interface OpLedger {\n  mint(): Uuid;\n  isOwn(opId: string | null | undefined): boolean;\n  /** Test seam: forget everything. */\n  clear(): void;\n  /** Test seam: how many operations are currently remembered. */\n  readonly size: number;\n}\n\nfunction ledgerOver(ours: Map<string, number>): OpLedger {\n  function trim(now: number): void {\n    // A Map iterates in insertion order and ids are minted in time order, so the first entry\n    // that is still inside the window means every entry after it is too.\n    for (const [id, at] of ours) {\n      if (now - at <= REMEMBER_MS) break;\n      ours.delete(id);\n    }\n    // Then the ceiling, oldest first, for a tab that writes faster than the window expires.\n    while (ours.size > REMEMBER_MAX) {\n      const oldest = ours.keys().next();\n      if (oldest.done === true) break;\n      ours.delete(oldest.value);\n    }\n  }\n  return {\n    mint() {\n      const id = crypto.randomUUID();\n      const now = Date.now();\n      ours.set(id, now);\n      trim(now);\n      return id as Uuid;\n    },\n    isOwn(opId) {\n      if (!opId) return false;\n      const at = ours.get(opId);\n      if (at === undefined) return false;\n      if (Date.now() - at > REMEMBER_MS) {\n        ours.delete(opId);\n        return false;\n      }\n      return true;\n    },\n    clear() {\n      ours.clear();\n    },\n    get size() {\n      return ours.size;\n    },\n  };\n}\n\n/** A ledger of one client's own: hand the SAME one to the client that writes and the port that listens. */\nexport function createOpLedger(): OpLedger {\n  return ledgerOver(new Map<string, number>());\n}\n\n/**\n * THE REALM'S DEFAULT LEDGER, IN A GLOBAL SLOT — for hosts that mount one client per realm (a browser\n * tab) and never name a ledger. Every section of the built package (root, core, react, realtime, data,\n * typed-table) carries its own copy of this module, and the ESM and CJS builds are two more graphs; a\n * module-level Map split it so `records/core` minted in one and `records/realtime` checked another — own\n * writes came back as strangers' changes (2026-10-08). Guarded on the packed tarball by\n * scripts/check-shared-state.mjs.\n */\nexport const defaultOpLedger: OpLedger = ledgerOver(globalSlot(\"ai-matrx.records.op-ledger\", () => new Map<string, number>()));\n\n/**\n * Mint the id for one client operation and remember it as ours (the realm's default ledger).\n *\n * ONE CALL IS ONE OPERATION. A fifty-row paste through `recordWriteMany` is ONE op id, because\n * the store announces one statement once — and it REFUSES a batch carrying two different ones\n * by name, for exactly that reason.\n */\nexport function mintOpId(): Uuid {\n  return defaultOpLedger.mint();\n}\n\n/**\n * Is this notice the echo of a write this realm's default ledger made?\n *\n * `undefined`/`null` is NOT ours and never has been: a notice with no `op_id` came from a\n * server-side write, an agent tool, another client, or a store older than this mechanism —\n * all of which are changes this browser has not seen and must read.\n */\nexport function isOwnOp(opId: string | null | undefined): boolean {\n  return defaultOpLedger.isOwn(opId);\n}\n\n/** Test seam: forget everything. Never called by product code. */\nexport function forgetAllOps(): void {\n  defaultOpLedger.clear();\n}\n\n/** Test seam: how many operations are currently remembered. */\nexport function rememberedOpCount(): number {\n  return defaultOpLedger.size;\n}\n","// src/scopes/types.ts — @ai-matrx/records/scopes\n//\n// SCOPES ARE CUSTOM DATA (Arman, 2026-10-09: \"Scopes are now nothing more than custom data… A scope\n// type is nothing more than a row [a custom Table flagged kept_for='context'], a context item is\n// nothing more than a column.\").\n//\n//   scope type      a Table of the store kept for context (`kept_for = 'context'`)\n//   scope           a Record of that Table\n//   context field   a Field (column) of that Table — what the old screens called a \"context item\"\n//   context value   the Record's cell under the Field's key\n//\n// These are the shapes the `custom.context_*` doors answer, in the store's words. Nothing here is a\n// row of the archived `context.*` tables, and nothing re-creates one: a value is the cell (`value`),\n// never a set of `value_text` / `value_number` / … columns; a field says `context_policy` and the\n// store's `sensitivity`, never the old `fetch_hint` words.\n\nimport type { Uuid } from \"../record\";\n\n/**\n * What a context field holds, as a person thinks of it — derived from the Field's behavior, `multi`,\n * `format`, display format and `config.kind` (`contextFieldKind`). The value is always `value`; the\n * kind says how to read and edit it.\n */\nexport type ContextFieldKind =\n  | \"string\"\n  | \"markdown\"\n  | \"email\"\n  | \"url\"\n  | \"phone\"\n  | \"color\"\n  | \"number\"\n  | \"percent\"\n  | \"currency\"\n  | \"boolean\"\n  | \"date\"\n  | \"datetime\"\n  | \"time\"\n  | \"object\"\n  | \"array\"\n  | \"reference\"\n  | \"document\";\n\nexport const CONTEXT_FIELD_KINDS: readonly ContextFieldKind[] = [\n  \"string\",\n  \"markdown\",\n  \"email\",\n  \"url\",\n  \"phone\",\n  \"color\",\n  \"number\",\n  \"percent\",\n  \"currency\",\n  \"boolean\",\n  \"date\",\n  \"datetime\",\n  \"time\",\n  \"object\",\n  \"array\",\n  \"reference\",\n  \"document\",\n];\n\n/** The store's context policy on a Field: whether an agent receives it every turn, on request, or never. */\nexport type ContextPolicy = \"include\" | \"on_request\" | \"exclude\";\n\n/** The store's sensitivity words on a Field. */\nexport type ContextSensitivity = \"public\" | \"internal\" | \"confidential\" | \"restricted\";\n\n/** A scope type: a Table kept for context. */\nexport interface ScopeType {\n  id: Uuid;\n  organization_id: Uuid;\n  label_singular: string;\n  label_plural: string;\n  icon: string;\n  color: string;\n  /** The Table's slug in the store's grammar (`practice_areas`). */\n  slug: string | null;\n  description: string;\n  sort_order: number;\n  max_assignments_per_entity: number | null;\n  default_variable_keys: string[];\n  /** Who made the type: with the organization's owners and admins, they shape it (`canShapeScopeType`). */\n  created_by: Uuid | null;\n  created_at: string;\n  updated_at: string;\n}\n\n/** A scope type with its live scopes, as the tree doors answer it. */\nexport interface ScopeTypeWithScopes extends ScopeType {\n  scopes: Scope[];\n}\n\n/** A scope: a Record of its type's Table. */\nexport interface Scope {\n  id: Uuid;\n  scope_type_id: Uuid;\n  organization_id: Uuid;\n  name: string;\n  description: string;\n  slug: string | null;\n  sort_order: number;\n  parent_scope_id: Uuid | null;\n  /** Free settings keys of the scope (each a Field of its Table the scope door derived). */\n  settings: Record<string, unknown>;\n  created_by: Uuid | null;\n  created_at: string;\n  updated_at: string;\n}\n\n/** A scope with its type's presentation (`custom.context_scopes`). */\nexport interface ScopeWithType extends Scope {\n  scope_type: ScopeTypeLabel | null;\n}\n\n/** The presentation of a scope type: what a chip or a breadcrumb shows. */\nexport interface ScopeTypeLabel {\n  id: Uuid;\n  /** The type's slug in the store's grammar (`practice_areas`), when it has one. */\n  slug: string | null;\n  label_singular: string;\n  label_plural: string;\n  icon: string | null;\n  color: string | null;\n}\n\n/** A scope type that was archived, with how many scopes went with it. */\nexport interface ArchivedScopeType {\n  id: Uuid;\n  organization_id: Uuid;\n  label_singular: string;\n  label_plural: string;\n  icon: string;\n  color: string;\n  archived_at: string;\n  created_by: Uuid | null;\n  archived_scope_count: number;\n}\n\n/** A scope that was archived (a Record in the archive of its type's Table). */\nexport interface ArchivedScope {\n  id: Uuid;\n  name: string | null;\n  slug: string | null;\n  archived_at: string | null;\n}\n\n/** A context field: a Field (column) of a scope type's Table. */\nexport interface ContextField {\n  id: Uuid;\n  scope_type_id: Uuid;\n  organization_id: Uuid;\n  key: string;\n  label: string;\n  description: string;\n  kind: ContextFieldKind;\n  /** The Field's own words, for a caller that needs them (`type` is the store's behavior word). */\n  type: string;\n  multi: boolean;\n  format: string | null;\n  config: Record<string, unknown>;\n  relation_target: Uuid | null;\n  /** Its place among the type's context fields, from 0. */\n  sort: number;\n  context_policy: ContextPolicy;\n  sensitivity: ContextSensitivity;\n  source: string;\n  status: string;\n  status_note: string | null;\n  category: string | null;\n  tags: string[];\n  max_items: number;\n  custom_component: unknown;\n  reference_source: unknown;\n  allowed_scope_type_ids: Uuid[] | null;\n  allowed_reference_types: string[] | null;\n  review_interval_days: number | null;\n  depends_on: string[];\n  /** The store's clock on this Field. */\n  version: number;\n  created_by: Uuid | null;\n  created_at: string;\n  updated_at: string;\n}\n\n/** One thing a reference cell points at. */\nexport interface ContextReference {\n  /** The record id (for a file: the File record's id). */\n  id: Uuid;\n  /** What it is: `scope`, `file`, `table`, or another entity token. */\n  type: string;\n  /** Its name, where the door named it to this caller. */\n  label?: string;\n  /** For a file: the `files.files` id a viewer opens. */\n  file_id?: Uuid;\n}\n\n/** The cell holds only the first words of a text kept as a file, and the whole could not be read. */\nexport interface IncompleteValue {\n  /** The cell's own first words. */\n  head: string;\n  /** The whole text's length in characters, when known. */\n  chars: number | null;\n  /** The file holding the whole text, when it has one yet. */\n  file_id: Uuid | null;\n  /** Why the whole text is not here, in one sentence. */\n  why: string;\n}\n\n/** A context value: one cell of a scope's Record. */\nexport interface ContextValue {\n  scope_id: Uuid;\n  field_id: Uuid;\n  key: string;\n  kind: ContextFieldKind;\n  /**\n   * THE CELL, as the store holds it (a text, a number, a boolean, an ISO date, a list, an object).\n   * A reference or document cell is its `references` (ids here). A text kept as a file is its whole\n   * text when the read could open the file (`completeWholeValues`), else the first words and `incomplete`.\n   */\n  value: unknown;\n  /** A reference / document cell, decoded: what it points at, with names the caller may see. */\n  references: ContextReference[];\n  /** The version a PERSON made (system rewrites never move it). */\n  version: number;\n  set_at: string | null;\n  source_type: string | null;\n  authored_by: Uuid | null;\n  /** The pointer to the file holding a text too big for one cell, when the cell holds only its start. */\n  whole_value: StoreWholeValue | null;\n  /** Present only when `value` is not the whole text — never save it back as the value. */\n  incomplete: IncompleteValue | null;\n}\n\n/** The file fields of a whole-value pointer, as `custom.context_values` answers them. */\nexport interface StoreWholeValue {\n  kind: string;\n  file_id?: Uuid | null;\n  file_record?: Uuid | null;\n  bytes?: number | null;\n  chars?: number | null;\n  sha256?: string | null;\n  shown_chars?: number | null;\n  mime?: string | null;\n  pending?: boolean | null;\n  in_value?: boolean | null;\n}\n\n/** The scope types of some organizations, without their scopes, and how many each holds. */\nexport interface ScopeTypeSkeleton {\n  types: ScopeType[];\n  /** type id → how many scopes the caller sees in it; null when asked without counts. */\n  counts: Record<Uuid, number> | null;\n}\n\n/** One page of one type's scopes. */\nexport interface ScopePage {\n  scopes: Scope[];\n  total: number;\n  next_offset: number | null;\n}\n\n/**\n * The pseudo scope-type id a System Context field carries. System Context (what is simply TRUE on the\n * platform) has no scope type; its fields share this sentinel so a holder can keep them beside a\n * type's fields. A client-side key only — a binding to one of these carries `scope_type_id: null`.\n */\nexport const SYSTEM_CONTEXT_TYPE_ID = \"__system__\";\n\n/** What a System Context item is: a curated fact, an ambient fact of the moment, or a dataset. */\nexport type SystemContextItemClass = \"curated\" | \"ambient\" | \"dataset\" | (string & {});\n\n/**\n * A System Context item (`custom.context_system_items`), as a `ContextField` of the\n * `SYSTEM_CONTEXT_TYPE_ID` pseudo-type, plus its class.\n */\nexport interface SystemContextField extends ContextField {\n  item_class: SystemContextItemClass | null;\n}\n\n/** One column of a table template. */\nexport interface TableTemplateField {\n  field_name: string;\n  display_name: string;\n  data_type: string;\n  field_order: number;\n  is_required: boolean;\n}\n\n/**\n * A table template (a `custom.template` of kind `table`) a scope's dataset field may lock its\n * table's columns to: the organization's own or a platform one, as `custom.table_templates` answers it.\n */\nexport interface TableTemplate {\n  id: Uuid;\n  organization_id: Uuid | null;\n  name: string;\n  description: string;\n  version: number;\n  is_platform: boolean;\n  fields: TableTemplateField[];\n}\n\n/** One scope template of the gallery, as `custom.context_templates` answers it. */\nexport interface ScopeTemplate {\n  [key: string]: unknown;\n}\n\n// ─── writes ──────────────────────────────────────────────────────────────────────────────────────\n\n/** A new scope type, or the parts of one to change (`undefined` = leave as it is). */\nexport interface ScopeTypeSpec {\n  label_singular?: string;\n  label_plural?: string;\n  icon?: string;\n  color?: string;\n  description?: string;\n  sort_order?: number;\n  max_assignments_per_entity?: number | null;\n  default_variable_keys?: string[];\n  /** Any spelling; the package writes it in the store's grammar. Absent on create = from the label. */\n  slug?: string;\n}\n\n/** A new scope, or the parts of one to change. */\nexport interface ScopeSpec {\n  name?: string;\n  description?: string;\n  settings?: Record<string, unknown>;\n  parent_scope_id?: Uuid | null;\n  slug?: string;\n  sort_order?: number;\n}\n\n/** A new context field, or the parts of one to change (`null` clears). */\nexport interface ContextFieldSpec {\n  key?: string;\n  label?: string;\n  kind?: ContextFieldKind;\n  description?: string;\n  category?: string | null;\n  context_policy?: ContextPolicy;\n  sensitivity?: ContextSensitivity;\n  tags?: string[];\n  sort?: number;\n  status?: string;\n  status_note?: string | null;\n  custom_component?: unknown;\n  review_interval_days?: number | null;\n  allowed_reference_types?: string[] | null;\n  max_items?: number | null;\n  allowed_scope_type_ids?: Uuid[] | null;\n  reference_source?: unknown;\n}\n\n/** One cell to write. `value` is the cell as `ContextValue.value` reads it; a reference cell takes `references`. */\nexport interface ContextValueWrite {\n  scope_id: Uuid;\n  field_id: Uuid;\n  kind: ContextFieldKind;\n  value?: unknown;\n  /** A reference / document cell: the things it points at (replaces the cell). */\n  references?: ContextReference[];\n  /** Who wrote it: `manual` from a person's own edit (the store's default is `ai_enriched`). */\n  source_type?: string;\n  change_summary?: string;\n}\n\n/** What a written cell answers. */\nexport interface ContextValueWritten {\n  scope_id: Uuid;\n  field_id: Uuid;\n  version: number;\n  source_type: string;\n}\n","// src/scopes/codec.ts — @ai-matrx/records/scopes\n//\n// THE ONE PLACE THE SCOPE DOORS' WORDS ARE READ AND WRITTEN.\n//\n// The `custom.context_*` doors answer the store's rows (a Table, a Record, a Field document, a\n// cell) and, for the write doors, still TAKE a few of the words the old screens wrote\n// (`display_name`, `value_type`, `fetch_hint`, `value_text`…) and answer the field they wrote in\n// those words. That grammar is the door's contract, so it is spoken here, once, and never by a\n// caller: everything above this file holds `ScopeType`, `Scope`, `ContextField` and `ContextValue`.\n// The server's reader (aidream `matrx_records/store/scopes.py`) reads the same doors.\n\nimport type { Uuid } from \"../record\";\nimport type {\n  ArchivedScopeType,\n  ContextField,\n  ContextFieldKind,\n  ContextFieldSpec,\n  ContextPolicy,\n  ContextReference,\n  ContextSensitivity,\n  ContextValue,\n  ContextValueWrite,\n  Scope,\n  ScopeType,\n  ScopeTypeLabel,\n  ScopeWithType,\n  StoreWholeValue,\n  SystemContextField,\n} from \"./types\";\nimport { SYSTEM_CONTEXT_TYPE_ID } from \"./types\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n// ─── the doors' answers ─────────────────────────────────────────────────────────────────────────\n\n/** A scope type as the tree doors answer it. */\nexport interface StoreTypeRow {\n  id: string;\n  organization_id: string;\n  label_singular?: string | null;\n  label_plural?: string | null;\n  name?: string | null;\n  icon?: string | null;\n  color?: string | null;\n  slug?: string | null;\n  description?: string | null;\n  sort_order?: number | null;\n  max_assignments_per_entity?: number | null;\n  default_variable_keys?: string[] | null;\n  created_by?: string | null;\n  created_at?: string | null;\n  updated_at?: string | null;\n  scope_count?: number | null;\n}\n\n/** A scope as the tree and scope doors answer it. */\nexport interface StoreScopeRow {\n  id: string;\n  scope_type_id: string;\n  organization_id: string;\n  name?: string | null;\n  description?: string | null;\n  slug?: string | null;\n  sort_order?: number | string | null;\n  parent_scope_id?: string | null;\n  settings?: Record<string, unknown> | null;\n  created_by?: string | null;\n  created_at?: string | null;\n  updated_at?: string | null;\n  scope_type?: (Partial<StoreTypeRow> & { id: string }) | null;\n}\n\n/** A Field document, as `custom.context_items` / `custom.context_values` answer it. */\nexport interface StoreFieldDoc {\n  key?: string;\n  label?: string;\n  type?: string;\n  multi?: boolean | null;\n  format?: string | null;\n  display_format?: { id?: string } | null;\n  config?: ({ kind?: string } & Record<string, unknown>) | null;\n  relation_target?: string | null;\n  sort?: number | string | null;\n  description?: string | null;\n  sensitivity?: string | null;\n  context_policy?: string | null;\n  source?: string | null;\n  status?: string | null;\n  status_note?: string | null;\n  category?: string | null;\n  tags?: string[] | null;\n  max_items?: number | null;\n  custom_component?: unknown;\n  reference_source?: unknown;\n  allowed_scope_type_ids?: string[] | null;\n  allowed_reference_types?: string[] | null;\n  review_interval_days?: number | null;\n  depends_on?: string[] | null;\n  [extra: string]: unknown;\n}\n\n/** What the store remembers about a field it moved from the old tables and could not type. */\nexport interface StoreCarried {\n  value_type?: string;\n  as_text?: boolean;\n  is_active?: boolean;\n}\n\n/** A context field as `custom.context_items` answers it. */\nexport interface StoreItemRow {\n  id: string;\n  scope_type_id: string;\n  organization_id: string;\n  data: StoreFieldDoc;\n  carried?: StoreCarried | null;\n  created_by?: string | null;\n  created_at?: string | null;\n  updated_at?: string | null;\n  version?: number | null;\n}\n\n/** A cell as `custom.context_values` answers it. */\nexport interface StoreValueRow {\n  scope_id: string;\n  context_item_id: string;\n  key: string;\n  value: unknown;\n  field?: (Pick<StoreFieldDoc, \"type\" | \"multi\" | \"format\" | \"display_format\" | \"config\" | \"relation_target\"> & {\n    carried?: StoreCarried | null;\n  }) | null;\n  version?: number | null;\n  store_version?: number | null;\n  set_at?: string | null;\n  source_type?: string | null;\n  value_id?: string | null;\n  authored_by?: string | null;\n  labels?: Record<string, string> | null;\n  files?: Record<string, string> | null;\n  whole_value?: StoreWholeValue | null;\n}\n\n/** An archived scope type as `custom.context_archived_types` answers it. */\nexport interface StoreArchivedTypeRow {\n  id: string;\n  organization_id: string;\n  label_singular?: string | null;\n  label_plural?: string | null;\n  icon?: string | null;\n  color?: string | null;\n  deleted_at?: string | null;\n  created_by?: string | null;\n  archived_scope_count?: number | null;\n}\n\n// ─── reading ────────────────────────────────────────────────────────────────────────────────────\n\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\nconst strOrNull = (v: unknown): string | null => (typeof v === \"string\" ? v : null);\nconst num = (v: unknown, fallback = 0): number => {\n  const n = typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : NaN;\n  return Number.isFinite(n) ? n : fallback;\n};\n\nexport function scopeTypeFromStore(row: StoreTypeRow): ScopeType {\n  const singular = row.label_singular ?? row.name ?? \"\";\n  return {\n    id: row.id,\n    organization_id: row.organization_id,\n    label_singular: singular,\n    label_plural: row.label_plural ?? singular,\n    icon: row.icon ?? \"folder\",\n    color: row.color ?? \"\",\n    slug: row.slug ?? null,\n    description: row.description ?? \"\",\n    sort_order: num(row.sort_order),\n    max_assignments_per_entity: row.max_assignments_per_entity ?? null,\n    default_variable_keys: Array.isArray(row.default_variable_keys) ? row.default_variable_keys : [],\n    created_by: row.created_by ?? null,\n    created_at: row.created_at ?? \"\",\n    updated_at: row.updated_at ?? \"\",\n  };\n}\n\nexport function scopeTypeLabelFromStore(t: Partial<StoreTypeRow> & { id: string }): ScopeTypeLabel {\n  const singular = t.label_singular ?? t.name ?? \"\";\n  return { id: t.id, slug: t.slug ?? null, label_singular: singular, label_plural: t.label_plural ?? singular, icon: t.icon ?? null, color: t.color ?? null };\n}\n\n/**\n * A settings value as it was written. The scope door keeps a list-of-objects setting (a class's exam\n * dates) as a list of their JSON texts (`custom._ctx_words`); read back, each is the object again.\n */\nexport function settingFromStore(value: unknown): unknown {\n  if (!Array.isArray(value)) return value;\n  return value.map((el) => {\n    if (typeof el !== \"string\") return el;\n    const t = el.trim();\n    if (!(t.startsWith(\"{\") && t.endsWith(\"}\")) && !(t.startsWith(\"[\") && t.endsWith(\"]\"))) return el;\n    try {\n      return JSON.parse(t) as unknown;\n    } catch {\n      return el;\n    }\n  });\n}\n\nexport function scopeFromStore(row: StoreScopeRow): Scope {\n  const settings: Record<string, unknown> = {};\n  for (const [k, v] of Object.entries(row.settings ?? {})) settings[k] = settingFromStore(v);\n  return {\n    id: row.id,\n    scope_type_id: row.scope_type_id,\n    organization_id: row.organization_id,\n    name: row.name ?? \"\",\n    description: row.description ?? \"\",\n    slug: row.slug ?? null,\n    sort_order: num(row.sort_order),\n    parent_scope_id: row.parent_scope_id ?? null,\n    settings,\n    created_by: row.created_by ?? null,\n    created_at: row.created_at ?? \"\",\n    updated_at: row.updated_at ?? \"\",\n  };\n}\n\nexport function scopeWithTypeFromStore(row: StoreScopeRow): ScopeWithType {\n  return { ...scopeFromStore(row), scope_type: row.scope_type ? scopeTypeLabelFromStore(row.scope_type) : null };\n}\n\nexport function archivedScopeTypeFromStore(row: StoreArchivedTypeRow): ArchivedScopeType {\n  const singular = row.label_singular ?? \"\";\n  return {\n    id: row.id,\n    organization_id: row.organization_id,\n    label_singular: singular,\n    label_plural: row.label_plural ?? singular,\n    icon: row.icon ?? \"folder\",\n    color: row.color ?? \"\",\n    archived_at: row.deleted_at ?? \"\",\n    created_by: row.created_by ?? null,\n    archived_scope_count: row.archived_scope_count ?? 0,\n  };\n}\n\n/** The file kernel: a relation at it is a document (a file), never a reference to a row. */\nexport const FILE_KERNEL_ID = \"11111111-0000-4000-8000-000000000006\";\n\nconst KINDS = new Set<string>([\n  \"string\", \"markdown\", \"email\", \"url\", \"phone\", \"color\", \"number\", \"percent\", \"currency\", \"boolean\",\n  \"date\", \"datetime\", \"time\", \"object\", \"array\", \"reference\", \"document\",\n]);\n\n/** What a Field holds, as a person thinks of it. */\nexport function contextFieldKind(\n  doc: Pick<StoreFieldDoc, \"type\" | \"multi\" | \"format\" | \"display_format\" | \"config\" | \"relation_target\">,\n  carried?: StoreCarried | null,\n): ContextFieldKind {\n  // A field the store landed as text keeps the word it had (custom._ctx_store_item carries it).\n  if (carried?.as_text && carried.value_type && KINDS.has(carried.value_type)) return carried.value_type as ContextFieldKind;\n  const behavior = String(doc.type ?? \"text\");\n  const fmt = doc.format ? String(doc.format) : \"\";\n  const shown = doc.display_format && typeof doc.display_format === \"object\" ? String(doc.display_format.id ?? \"\") : \"\";\n  const kind = String(doc.config?.kind ?? \"\");\n  const multi = Boolean(doc.multi);\n  if (behavior === \"boolean\") return \"boolean\";\n  if (behavior === \"relation\") return doc.relation_target === FILE_KERNEL_ID && !multi ? \"document\" : \"reference\";\n  if (behavior === \"range\") {\n    if (kind === \"date\") return \"date\";\n    if (kind === \"datetime\") return \"datetime\";\n    if (fmt === \"percent\" || fmt === \"currency\") return fmt;\n    return \"number\";\n  }\n  if (behavior === \"text\") {\n    if (multi) return \"array\";\n    if (fmt === \"json\") return \"object\";\n    for (const word of [fmt, shown]) {\n      if (word === \"time\" || word === \"email\" || word === \"url\" || word === \"phone\" || word === \"color\" || word === \"markdown\") return word;\n    }\n  }\n  return \"string\";\n}\n\nconst POLICIES = new Set<string>([\"include\", \"on_request\", \"exclude\"]);\nconst SENSITIVITIES = new Set<string>([\"public\", \"internal\", \"confidential\", \"restricted\"]);\n\nexport function contextFieldFromStore(row: StoreItemRow): ContextField {\n  const d = row.data ?? {};\n  const key = str(d.key);\n  const policy = str(d.context_policy, \"include\");\n  const sensitivity = str(d.sensitivity, \"internal\");\n  return {\n    id: row.id,\n    scope_type_id: row.scope_type_id,\n    organization_id: row.organization_id,\n    key,\n    label: str(d.label, key),\n    description: str(d.description),\n    kind: contextFieldKind(d, row.carried),\n    type: str(d.type, \"text\"),\n    multi: Boolean(d.multi),\n    format: strOrNull(d.format),\n    config: (d.config ?? {}) as Record<string, unknown>,\n    relation_target: strOrNull(d.relation_target),\n    // The store's sort counts the scope's own two columns first (custom._ctx_store_item: + 2).\n    sort: Math.max(0, num(d.sort) - 2),\n    context_policy: (POLICIES.has(policy) ? policy : \"include\") as ContextPolicy,\n    sensitivity: (SENSITIVITIES.has(sensitivity) ? sensitivity : \"internal\") as ContextSensitivity,\n    source: str(d.source, \"manual\"),\n    status: str(d.status, \"active\"),\n    status_note: strOrNull(d.status_note),\n    category: strOrNull(d.category),\n    tags: Array.isArray(d.tags) ? d.tags : [],\n    max_items: typeof d.max_items === \"number\" ? d.max_items : 1,\n    custom_component: d.custom_component ?? null,\n    reference_source: d.reference_source ?? null,\n    allowed_scope_type_ids: Array.isArray(d.allowed_scope_type_ids) ? d.allowed_scope_type_ids : null,\n    allowed_reference_types: Array.isArray(d.allowed_reference_types) ? d.allowed_reference_types : null,\n    review_interval_days: typeof d.review_interval_days === \"number\" ? d.review_interval_days : null,\n    depends_on: Array.isArray(d.depends_on) ? d.depends_on : [],\n    version: num(row.version, 1),\n    created_by: row.created_by ?? null,\n    created_at: row.created_at ?? \"\",\n    updated_at: row.updated_at ?? \"\",\n  };\n}\n\n// The write doors still speak three old words for a field; these are their meanings, both ways.\nconst POLICY_TO_DOOR: Record<ContextPolicy, string> = { include: \"always\", on_request: \"on_demand\", exclude: \"never\" };\nconst POLICY_FROM_DOOR: Record<string, ContextPolicy> = { always: \"include\", on_demand: \"on_request\", never: \"exclude\" };\nconst SENSITIVITY_TO_DOOR: Record<ContextSensitivity, string> = {\n  public: \"public\",\n  internal: \"internal\",\n  confidential: \"restricted\",\n  restricted: \"privileged\",\n};\nconst SENSITIVITY_FROM_DOOR: Record<string, ContextSensitivity> = {\n  public: \"public\",\n  internal: \"internal\",\n  restricted: \"confidential\",\n  privileged: \"restricted\",\n};\n\n/** The field a write door answered (`custom.context_item_row_of`), as a `ContextField`. */\nexport function contextFieldFromWriteAnswer(row: Record<string, unknown>, organizationId: Uuid): ContextField {\n  const key = str(row.key);\n  const kind = str(row.value_type, \"string\");\n  return {\n    id: str(row.id),\n    scope_type_id: str(row.scope_type_id),\n    organization_id: organizationId,\n    key,\n    label: str(row.display_name, key),\n    description: str(row.description),\n    kind: (KINDS.has(kind) ? kind : \"string\") as ContextFieldKind,\n    type: \"\",\n    multi: kind === \"array\",\n    format: null,\n    config: {},\n    relation_target: null,\n    sort: num(row.sort_order),\n    context_policy: POLICY_FROM_DOOR[str(row.fetch_hint)] ?? \"include\",\n    sensitivity: SENSITIVITY_FROM_DOOR[str(row.sensitivity)] ?? \"internal\",\n    source: \"manual\",\n    status: str(row.status, \"active\"),\n    status_note: strOrNull(row.status_note),\n    category: strOrNull(row.category),\n    tags: Array.isArray(row.tags) ? (row.tags as string[]) : [],\n    max_items: typeof row.max_items === \"number\" ? row.max_items : 1,\n    custom_component: row.custom_component ?? null,\n    reference_source: row.reference_source ?? null,\n    allowed_scope_type_ids: Array.isArray(row.allowed_scope_type_ids) ? (row.allowed_scope_type_ids as string[]) : null,\n    allowed_reference_types: Array.isArray(row.allowed_reference_types) ? (row.allowed_reference_types as string[]) : null,\n    review_interval_days: typeof row.review_interval_days === \"number\" ? row.review_interval_days : null,\n    depends_on: Array.isArray(row.depends_on) ? (row.depends_on as string[]) : [],\n    version: num(row.version, 1),\n    created_by: strOrNull(row.created_by),\n    created_at: str(row.created_at),\n    updated_at: str(row.updated_at),\n  };\n}\n\n/** A System Context item, as `custom.context_system_items` answers it (the door's own words). */\nexport interface StoreSystemItemRow {\n  id?: string | null;\n  key?: string | null;\n  display_name?: string | null;\n  description?: string | null;\n  item_class?: string | null;\n  value_type?: string | null;\n  sensitivity?: string | null;\n  sort_order?: number | null;\n}\n\n/** A System Context item as a field of the `SYSTEM_CONTEXT_TYPE_ID` pseudo-type, with its class. */\nexport function systemContextFieldFromStore(row: StoreSystemItemRow, index: number): SystemContextField {\n  const key = str(row.key);\n  const kind = str(row.value_type, \"string\");\n  return {\n    id: str(row.id),\n    scope_type_id: SYSTEM_CONTEXT_TYPE_ID,\n    organization_id: \"\",\n    key,\n    label: str(row.display_name, key),\n    description: str(row.description),\n    kind: (KINDS.has(kind) ? kind : \"string\") as ContextFieldKind,\n    type: \"system\",\n    multi: kind === \"array\",\n    format: null,\n    config: {},\n    relation_target: null,\n    sort: typeof row.sort_order === \"number\" ? row.sort_order : index,\n    context_policy: \"include\",\n    // The system table keeps the old sensitivity words (`restricted`/`privileged`), like the write doors.\n    sensitivity: SENSITIVITY_FROM_DOOR[str(row.sensitivity)] ?? \"public\",\n    source: \"system\",\n    status: \"active\",\n    status_note: null,\n    category: null,\n    tags: [],\n    max_items: 0,\n    custom_component: null,\n    reference_source: null,\n    allowed_scope_type_ids: null,\n    allowed_reference_types: null,\n    review_interval_days: null,\n    depends_on: [],\n    version: 0,\n    created_by: null,\n    created_at: \"\",\n    updated_at: \"\",\n    item_class: strOrNull(row.item_class),\n  };\n}\n\n\n/** A reference / document cell's targets, with the names and files the door gave this caller. */\nexport function referencesOf(row: Pick<StoreValueRow, \"value\" | \"field\" | \"labels\" | \"files\">): ContextReference[] {\n  const v = row.value;\n  const list = Array.isArray(v) ? v : v == null ? [] : [v];\n  const labels = row.labels ?? {};\n  const files = row.files ?? {};\n  const toFile = row.field?.relation_target === FILE_KERNEL_ID;\n  const out: ContextReference[] = [];\n  for (const el of list) {\n    let ref: ContextReference | null = null;\n    if (typeof el === \"string\" && isUuidShape(el)) ref = { id: el, type: toFile ? \"file\" : \"scope\" };\n    else if (el && typeof el === \"object\" && typeof (el as { id?: unknown }).id === \"string\") {\n      const token = String((el as { token?: unknown }).token ?? \"\");\n      const own = (el as { label?: unknown }).label;\n      ref = { id: (el as { id: string }).id, type: token === \"dataset\" ? \"table\" : token || (toFile ? \"file\" : \"scope\") };\n      // A reference outside the scope system carries its own label in the store; the door names scopes only.\n      if (typeof own === \"string\" && own) ref.label = own;\n    }\n    if (!ref) continue;\n    const label = labels[ref.id];\n    if (label) ref.label = label;\n    const fileId = files[ref.id];\n    if (fileId) ref.file_id = fileId;\n    out.push(ref);\n  }\n  return out;\n}\n\n/** One cell, as a `ContextValue` (its whole text not yet read — see `completeWholeValues`). */\nexport function contextValueFromStore(row: StoreValueRow): ContextValue {\n  const kind = contextFieldKind(row.field ?? {}, row.field?.carried);\n  const carriedText = Boolean(row.field?.carried?.as_text);\n  const isRef = !carriedText && (kind === \"reference\" || kind === \"document\");\n  return {\n    scope_id: row.scope_id,\n    field_id: row.context_item_id,\n    key: row.key,\n    kind,\n    value: row.value ?? null,\n    references: isRef ? referencesOf(row) : [],\n    version: num(row.version, 1),\n    set_at: row.set_at ?? null,\n    source_type: row.source_type ?? null,\n    authored_by: row.authored_by ?? null,\n    whole_value: row.whole_value ?? null,\n    incomplete: null,\n  };\n}\n\n// ─── whole texts kept as files ──────────────────────────────────────────────────────────────────\n\n/** Reads a file's whole text as the person (the host's one file reader). */\nexport type ReadContextFileText = (fileId: Uuid) => Promise<string>;\n\nasync function sha256Hex(text: string): Promise<string | null> {\n  const subtle = globalThis.crypto?.subtle;\n  if (!subtle) return null;\n  const digest = await subtle.digest(\"SHA-256\", new TextEncoder().encode(text));\n  return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * A CELL THAT HOLDS ONLY THE FIRST WORDS OF A TEXT KEPT AS A FILE GETS ITS WHOLE TEXT.\n *\n * The store keeps a value over its one-cell ceiling as a file and the cell holds its first words;\n * `custom.context_values` names the file (`whole_value`). Each such value is given the file's whole\n * text — read once per file through the host's reader, checked against the size and SHA-256 the\n * pointer names. A file that cannot be read, or does not match, leaves the first words AND sets\n * `incomplete` (with why) — never the first words passed off as the value. Mutates `values`.\n */\nexport async function completeWholeValues(values: ContextValue[], read: ReadContextFileText | null): Promise<void> {\n  const texts = new Map<string, Promise<string>>();\n  await Promise.all(\n    values.map(async (cell) => {\n      const w = cell.whole_value;\n      if (!w || w.in_value || typeof cell.value !== \"string\") return;\n      const head = cell.value;\n      const chars = typeof w.chars === \"number\" ? w.chars : null;\n      const incomplete = (fileId: string | null, why: string): void => {\n        cell.incomplete = { head, chars, file_id: fileId, why };\n      };\n      if (!w.file_id) return incomplete(null, \"The rest of this text is still being saved.\");\n      if (!read) return incomplete(w.file_id, \"This place cannot open the file that holds the whole text.\");\n      if (!texts.has(w.file_id)) texts.set(w.file_id, read(w.file_id));\n      try {\n        const text = await texts.get(w.file_id)!;\n        if (chars !== null && [...text].length !== chars) {\n          return incomplete(w.file_id, `The file holds ${[...text].length} characters, not ${chars}.`);\n        }\n        if (w.sha256) {\n          const sha = await sha256Hex(text);\n          if (sha === null) return incomplete(w.file_id, \"This browser cannot check the file.\");\n          if (sha !== w.sha256) return incomplete(w.file_id, \"The file's content is not the text the cell points at.\");\n        }\n        cell.value = text;\n      } catch (thrown) {\n        incomplete(w.file_id, thrown instanceof Error ? thrown.message : String(thrown));\n      }\n    }),\n  );\n}\n\n/** The refusal a person sees when saving would cut a value that was not read whole. */\nexport const INCOMPLETE_SAVE_REFUSAL = \"Only the start of this value loaded. Paste the whole text to replace it.\";\n\n/**\n * The refusal sentence when saving `draft` over a cell that was not read whole would cut the real\n * value — else `null`. Refused: the first words unchanged, and a draft built on them that is shorter\n * than the whole. Allowed: a draft that replaces the text, an explicit clear.\n */\nexport function incompleteSaveRefusal(cell: Pick<ContextValue, \"incomplete\"> | undefined, draft: unknown): string | null {\n  const incomplete = cell?.incomplete;\n  if (!incomplete || typeof draft !== \"string\" || draft === \"\") return null;\n  if (draft === incomplete.head) return INCOMPLETE_SAVE_REFUSAL;\n  if (incomplete.head && draft.startsWith(incomplete.head)) {\n    const whole = incomplete.chars ?? Number.POSITIVE_INFINITY;\n    if ([...draft].length < whole) return INCOMPLETE_SAVE_REFUSAL;\n  }\n  return null;\n}\n\n// ─── writing ────────────────────────────────────────────────────────────────────────────────────\n\n/** Drop keys whose value is `undefined`, keep `null` (a clear). */\nexport function definedOnly(fields: Record<string, unknown>): Record<string, unknown> {\n  const out: Record<string, unknown> = {};\n  for (const [k, v] of Object.entries(fields)) if (v !== undefined) out[k] = v;\n  return out;\n}\n\n/** A field spec in the words `custom.context_item_write` takes. */\nexport function fieldSpecForDoor(spec: ContextFieldSpec): Record<string, unknown> {\n  return definedOnly({\n    key: spec.key,\n    display_name: spec.label,\n    value_type: spec.kind,\n    description: spec.description,\n    category: spec.category,\n    fetch_hint: spec.context_policy ? POLICY_TO_DOOR[spec.context_policy] : undefined,\n    sensitivity: spec.sensitivity ? SENSITIVITY_TO_DOOR[spec.sensitivity] : undefined,\n    tags: spec.tags,\n    sort_order: spec.sort,\n    status: spec.status,\n    status_note: spec.status_note,\n    custom_component: spec.custom_component,\n    review_interval_days: spec.review_interval_days,\n    allowed_reference_types: spec.allowed_reference_types,\n    max_items: spec.max_items,\n    allowed_scope_type_ids: spec.allowed_scope_type_ids,\n    reference_source: spec.reference_source,\n  });\n}\n\n/** The canonical reference fence (the same grammar `@ai-matrx/agents/envelope` builds). */\nexport function referenceFence(references: readonly ContextReference[]): string {\n  const kinds = [...new Set(references.map((r) => r.type))];\n  const type = kinds.length === 1 ? kinds[0]! : \"mixed\";\n  const items = references.map((r) => {\n    if (r.type === \"file\" && r.file_id) return r.label ? { file_id: r.file_id, label: r.label } : { file_id: r.file_id };\n    const item: { id: string; label?: string; type?: string } = { id: r.id };\n    if (r.label) item.label = r.label;\n    if (kinds.length > 1) item.type = r.type;\n    return item;\n  });\n  return \"```matrx\\n\" + JSON.stringify({ matrx_version: 1, kind: \"reference\", type, items }, null, 2) + \"\\n```\";\n}\n\nconst FENCE_BODY = /```matrx[^\\n]*\\n([\\s\\S]*?)\\n?```/;\n\n/**\n * The things a reference fence points at (the inverse of `referenceFence`). Reads the canonical\n * grammar `{ kind: \"reference\", type, items }`, with or without the ```matrx wrapper; anything that\n * is not a reference fence answers `[]`.\n */\nexport function referencesFromFence(text: string | null | undefined): ContextReference[] {\n  if (typeof text !== \"string\" || text.trim() === \"\") return [];\n  const body = FENCE_BODY.exec(text)?.[1] ?? text;\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(body.trim());\n  } catch {\n    return [];\n  }\n  if (!parsed || typeof parsed !== \"object\") return [];\n  const fence = parsed as { kind?: unknown; type?: unknown; items?: unknown };\n  if (fence.kind !== \"reference\" || !Array.isArray(fence.items)) return [];\n  const noun = typeof fence.type === \"string\" ? fence.type : \"\";\n  return fence.items.flatMap((raw): ContextReference[] => {\n    if (!raw || typeof raw !== \"object\") return [];\n    const item = raw as { id?: unknown; file_id?: unknown; label?: unknown; type?: unknown };\n    const label = typeof item.label === \"string\" && item.label ? { label: item.label } : {};\n    if (typeof item.file_id === \"string\" && item.file_id) {\n      return [{ id: typeof item.id === \"string\" ? item.id : item.file_id, type: \"file\", file_id: item.file_id, ...label }];\n    }\n    if (typeof item.id !== \"string\" || !item.id) return [];\n    const type = typeof item.type === \"string\" && item.type ? item.type : noun || \"scope\";\n    return [{ id: item.id, type, ...label }];\n  });\n}\n\nconst isContextReference = (v: unknown): v is ContextReference =>\n  !!v && typeof v === \"object\" && typeof (v as { id?: unknown }).id === \"string\" && typeof (v as { type?: unknown }).type === \"string\";\n\n/**\n * THE ONE WRITE AN EDIT BECOMES: an editor's raw value for `field` on `scopeId`, as a\n * `ContextValueWrite`. A reference / document field takes a fence (what the reference picker edits)\n * or a list of `ContextReference`s and writes `references`; a clear (`null`, `undefined`, `\"\"`)\n * writes no references. Any other field writes `value`, with `\"\"` and `undefined` a clear (`null`).\n * Written by a person (`source_type: \"manual\"`) unless `options` says otherwise.\n */\nexport function contextValueWrite(\n  field: Pick<ContextField, \"id\" | \"kind\">,\n  scopeId: Uuid,\n  raw: unknown,\n  options: { source_type?: string; change_summary?: string } = {},\n): ContextValueWrite {\n  const base: ContextValueWrite = {\n    scope_id: scopeId,\n    field_id: field.id,\n    kind: field.kind,\n    source_type: options.source_type ?? \"manual\",\n    ...(options.change_summary ? { change_summary: options.change_summary } : {}),\n  };\n  if (field.kind === \"reference\" || field.kind === \"document\") {\n    if (typeof raw === \"string\") return { ...base, references: referencesFromFence(raw) };\n    if (Array.isArray(raw)) {\n      return {\n        ...base,\n        references: raw.flatMap((el): ContextReference[] =>\n          isContextReference(el) ? [el] : typeof el === \"string\" ? referencesFromFence(el) : [],\n        ),\n      };\n    }\n    return { ...base, references: [] };\n  }\n  return { ...base, value: raw === \"\" || raw === undefined ? null : raw };\n}\n\n/**\n * One cell in the payload `custom.context_value_write` takes: the value lands in the slot the door\n * reads for the field's kind; a reference cell is the canonical fence the door's reference rule reads.\n */\nexport function valuePayloadForDoor(write: ContextValueWrite): Record<string, unknown> {\n  const base: Record<string, unknown> = definedOnly({\n    scope_id: write.scope_id,\n    context_item_id: write.field_id,\n    source_type: write.source_type,\n    change_summary: write.change_summary,\n  });\n  const v = write.value;\n  if (write.kind === \"reference\" || write.kind === \"document\") {\n    if (write.references) return { ...base, value_text: write.references.length ? referenceFence(write.references) : null };\n    // A document cell may also be written as a url.\n    if (write.kind === \"document\" && typeof v === \"string\") return { ...base, value_document_url: v || null };\n    return { ...base, value_text: typeof v === \"string\" ? v || null : null };\n  }\n  if (v === null || v === undefined || v === \"\") {\n    return { ...base, value_text: null };\n  }\n  switch (write.kind) {\n    case \"number\":\n    case \"percent\":\n      return typeof v === \"number\" ? { ...base, value_number: v } : { ...base, value_text: String(v) };\n    case \"currency\":\n      return typeof v === \"object\" ? { ...base, value_json: v } : typeof v === \"number\" ? { ...base, value_number: v } : { ...base, value_text: String(v) };\n    case \"boolean\":\n      return typeof v === \"boolean\" ? { ...base, value_boolean: v } : { ...base, value_text: String(v) };\n    case \"date\":\n      return { ...base, value_date: String(v) };\n    case \"datetime\":\n      return { ...base, value_timestamp: String(v) };\n    case \"time\":\n      return { ...base, value_time: String(v) };\n    case \"object\":\n    case \"array\":\n      return typeof v === \"object\" ? { ...base, value_json: v } : { ...base, value_text: String(v) };\n    default:\n      return typeof v === \"object\" ? { ...base, value_json: v } : { ...base, value_text: String(v) };\n  }\n}\n","// src/scopes/rules.ts — @ai-matrx/records/scopes\n//\n// The few rules a screen needs BEFORE it asks a door, each a mirror of what the door itself decides\n// (the door is the authority; this only spares a person a button that would be refused).\n\nimport type { RecordsResult } from \"../results\";\nimport type { Uuid } from \"../record\";\n\n/** An organization role, as `iam.organization_member` holds it. */\nexport type ScopeSeatRole = \"owner\" | \"admin\" | \"member\" | string;\n\n/**\n * WHO MAY CHANGE A SCOPE TYPE'S STRUCTURE — rename it, add/edit/archive its fields, archive or restore\n * it: an organization owner or admin, or the person who made the type. Every member works the DATA\n * (adds, renames, archives and restores scopes, writes values). Arman 2026-10-07: \"structure is the\n * org admins' and the creator's\". Mirrors `custom.context_type_write` / `_archive` / `_restore` and\n * `custom.context_item_write` / `_archive` / `_restore`.\n */\nexport function canShapeScopeType(\n  role: ScopeSeatRole | null | undefined,\n  userId: Uuid | null | undefined,\n  type: { created_by?: Uuid | null } | null | undefined,\n): boolean {\n  if (role === \"owner\" || role === \"admin\") return true;\n  return !!userId && !!type?.created_by && type.created_by === userId;\n}\n\n/** Display name → kebab URL slug. */\nexport function toSlug(name: string): string {\n  return name\n    .toLowerCase()\n    .trim()\n    .replace(/[^a-z0-9]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n}\n\n/** Display name → snake_case field key. */\nexport function toFieldKey(name: string): string {\n  return name\n    .toLowerCase()\n    .trim()\n    .replace(/[\\s-]+/g, \"_\")\n    .replace(/[^a-z0-9_]/g, \"\")\n    .replace(/_+/g, \"_\")\n    .replace(/^_|_$/g, \"\");\n}\n\n/** True when `s` is a clean slug: a-z, 0-9, single hyphens or underscores between words. */\nexport function isValidSlug(s: string): boolean {\n  return /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s);\n}\n\n/** Route segments that are literal pages of the scope screens; no slug may equal one. */\nexport const RESERVED_SCOPE_SLUGS: ReadonlySet<string> = new Set([\"context-items\", \"scopes\", \"edit\", \"manage\", \"new\", \"settings\"]);\n\nexport function isReservedSlug(s: string): boolean {\n  return RESERVED_SCOPE_SLUGS.has(s.toLowerCase().replace(/_/g, \"-\"));\n}\n\n/**\n * Two slugs name the same thing when they differ only by `-` ↔ `_` (the store's Table grammar is\n * `practice_areas`; a link a person typed may say `practice-areas`).\n */\nexport function sameSlug(a: string | null | undefined, b: string | null | undefined): boolean {\n  if (!a || !b) return false;\n  return a.toLowerCase().replace(/_/g, \"-\") === b.toLowerCase().replace(/_/g, \"-\");\n}\n\n/** The slug a write sends: the one supplied, else one made from the name; refused when unusable. */\nexport function resolveSlug(supplied: string | undefined, fallbackName: string): RecordsResult<string> {\n  const slug = supplied?.trim() || toSlug(fallbackName);\n  if (!slug || !isValidSlug(slug)) {\n    return {\n      ok: false,\n      error: { code: \"invalid_argument\", message: \"Use letters, numbers and single hyphens for the short name.\" },\n    };\n  }\n  if (isReservedSlug(slug)) {\n    return { ok: false, error: { code: \"invalid_argument\", message: `\"${slug}\" is a page name here. Pick another short name.` } };\n  }\n  return { ok: true, data: slug };\n}\n","// src/scopes/doors.ts — @ai-matrx/records/scopes\n//\n// THE SCOPE DOORS, ONE CALL EACH, THROUGH THE RECORDS CLIENT'S OWN DOOR PATH.\n//\n// `client.scopes` is built from the same `callDoor` every other method of the client uses, so a scope\n// read gets what every store read gets: the schema said out loud, one request in flight per question,\n// a door the store lacks refused as `door_absent` (never an empty list), and every refusal in the\n// store's own words (`RecordsError`). Nothing here talks to Supabase itself.\n//\n// The doors take explicit organizations (a scope read spans every organization the person belongs\n// to; a write names its own), so the client's `organizationId` is never used here.\n\nimport type { RecordsErrorCode, RecordsResult } from \"../results\";\nimport type { Uuid } from \"../record\";\nimport {\n  archivedScopeTypeFromStore,\n  completeWholeValues,\n  contextFieldFromStore,\n  contextValueFromStore,\n  definedOnly,\n  fieldSpecForDoor,\n  scopeFromStore,\n  scopeTypeFromStore,\n  scopeWithTypeFromStore,\n  systemContextFieldFromStore,\n  valuePayloadForDoor,\n  type ReadContextFileText,\n  type StoreArchivedTypeRow,\n  type StoreItemRow,\n  type StoreScopeRow,\n  type StoreSystemItemRow,\n  type StoreTypeRow,\n  type StoreValueRow,\n} from \"./codec\";\nimport { resolveSlug } from \"./rules\";\nimport type {\n  ArchivedScope,\n  ArchivedScopeType,\n  ContextField,\n  ContextFieldSpec,\n  ContextValue,\n  ContextValueWrite,\n  ContextValueWritten,\n  Scope,\n  ScopePage,\n  ScopeSpec,\n  ScopeTemplate,\n  ScopeType,\n  ScopeTypeSkeleton,\n  ScopeTypeSpec,\n  ScopeTypeWithScopes,\n  ScopeWithType,\n  SystemContextField,\n  TableTemplate,\n} from \"./types\";\n\n/** The client's one door call (`callDoor` in core/client.ts). */\nexport type ScopeDoorCall = <T>(door: string, args: Record<string, unknown>, where: string) => Promise<RecordsResult<T>>;\n\n/** The kernel Table every Field is a record of. */\nexport const FIELD_KERNEL_ID = \"11111111-0000-4000-8000-000000000002\";\n\n/** How many ids one call of each batched door takes. */\nexport const SCOPES_PER_CALL = 500;\nexport const SCOPE_TYPES_PER_FIELDS_CALL = 100;\n/** `custom.context_values` refuses more than this many scopes in one call. */\nexport const SCOPES_PER_VALUES_CALL = 200;\n/** One page of a type's scopes (the door's default; it answers at most 1000). */\nexport const TYPE_SCOPES_PAGE = 200;\n/** The archive answers at most this many rows a call (`custom.page_size` ceiling). */\nexport const ARCHIVED_SCOPES_PAGE = 200;\n\nexport interface ScopeDoors {\n  // ── reads ──────────────────────────────────────────────────────────────────────────────────\n  /** Every live scope type of these organizations, each with its live scopes. */\n  tree(organizationIds: readonly Uuid[]): Promise<RecordsResult<ScopeTypeWithScopes[]>>;\n  /** The scope types of these organizations without their scopes (the first paint), with or without counts. */\n  types(organizationIds: readonly Uuid[], options?: { withCounts?: boolean }): Promise<RecordsResult<ScopeTypeSkeleton>>;\n  /** One page of one type's scopes, in the tree's order. */\n  typeScopesPage(scopeTypeId: Uuid, offset?: number, limit?: number): Promise<RecordsResult<ScopePage>>;\n  /** The scopes whose name holds `query` (case-insensitive), across these organizations. */\n  search(organizationIds: readonly Uuid[], query: string, limit?: number): Promise<RecordsResult<{ scopes: Scope[]; total: number }>>;\n  /** Scopes by id, each with its type's label, in whichever organization each lives. */\n  scopes(ids: readonly Uuid[]): Promise<RecordsResult<ScopeWithType[]>>;\n  /**\n   * The context fields (columns) of these scope types, each type's fields in their order (`sort`,\n   * then label) as the door answers them.\n   */\n  fields(scopeTypeIds: readonly Uuid[]): Promise<RecordsResult<ContextField[]>>;\n  /**\n   * One context field by its id, read in whichever of these organizations holds it (a Field is a\n   * record of the field kernel; its scope type is the Table it is defined on). Refused `not_found`\n   * when no organization answers it.\n   */\n  field(fieldId: Uuid, organizationIds: readonly Uuid[]): Promise<RecordsResult<ContextField>>;\n  /**\n   * The cells of these scopes. A text kept as a file is read whole through `readFileText`; without\n   * one (or when the file cannot be read) the cell keeps its first words and says so (`incomplete`).\n   */\n  values(scopeIds: readonly Uuid[], options?: { readFileText?: ReadContextFileText | null }): Promise<RecordsResult<ContextValue[]>>;\n  /** The archived scope types of one organization. */\n  archivedTypes(organizationId: Uuid): Promise<RecordsResult<ArchivedScopeType[]>>;\n  /** Of these scope ids, the ones that are ARCHIVED scopes of this type. */\n  archivedScopesOfType(organizationId: Uuid, scopeTypeId: Uuid, wanted: ReadonlySet<Uuid>): Promise<RecordsResult<ArchivedScope[]>>;\n  /** The System Context items (not scopes: the platform's own ambient context). */\n  systemItems(): Promise<RecordsResult<SystemContextField[]>>;\n  /** The table templates an organization's scope dataset fields may use (its own and the platform's). */\n  tableTemplates(organizationId: Uuid): Promise<RecordsResult<TableTemplate[]>>;\n  /** The scope templates of the gallery. */\n  templates(): Promise<RecordsResult<ScopeTemplate[]>>;\n\n  // ── writes ─────────────────────────────────────────────────────────────────────────────────\n  /** A new scope type in `organizationId`. */\n  createType(organizationId: Uuid, spec: ScopeTypeSpec): Promise<RecordsResult<ScopeType>>;\n  /** Change a scope type (only the keys given). */\n  updateType(typeId: Uuid, spec: ScopeTypeSpec): Promise<RecordsResult<ScopeType>>;\n  /** Archive a scope type; its scopes and fields come back with a restore. */\n  archiveType(typeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n  restoreType(typeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n  /** A new scope of `typeId` in `organizationId`. */\n  createScope(organizationId: Uuid, typeId: Uuid, spec: ScopeSpec): Promise<RecordsResult<Scope>>;\n  updateScope(scopeId: Uuid, spec: ScopeSpec): Promise<RecordsResult<Scope>>;\n  archiveScope(scopeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n  restoreScope(scopeId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n  /** A new context field (column) on a scope type. Answers the field as the read door does. */\n  createField(scopeTypeId: Uuid, spec: ContextFieldSpec): Promise<RecordsResult<ContextField>>;\n  /** Change a context field (`null` clears a key). Answers the field as the read door does. */\n  updateField(fieldId: Uuid, scopeTypeId: Uuid, spec: ContextFieldSpec): Promise<RecordsResult<ContextField>>;\n  archiveField(fieldId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n  restoreField(fieldId: Uuid): Promise<RecordsResult<{ id: Uuid }>>;\n  /** Write one cell. */\n  writeValue(write: ContextValueWrite): Promise<RecordsResult<ContextValueWritten>>;\n  /**\n   * G11. The record-store Table a context scope's template-bound item provisions — one per item and\n   * scope (`custom.scope_table_provision`). A scope provisioned before the move answers with its moved\n   * Table (same id); the Home defaults to the organization's own. `organization_id` null lets the door\n   * read the scope's own organization.\n   */\n  tableProvision(args: { organization_id: Uuid | null; item_id: Uuid; scope_id: Uuid; home_id?: Uuid | null }): Promise<RecordsResult<Uuid>>;\n}\n\nconst uniq = (ids: readonly string[]): string[] => [...new Set(ids.filter(Boolean))];\n\n/** The ids in batches of `size`, each batch one call, answers concatenated in order. */\nasync function inBatches<T>(\n  ids: readonly string[],\n  size: number,\n  call: (batch: string[]) => Promise<RecordsResult<T[] | null>>,\n): Promise<RecordsResult<T[]>> {\n  const unique = uniq(ids);\n  const batches: string[][] = [];\n  for (let i = 0; i < unique.length; i += size) batches.push(unique.slice(i, i + size));\n  const answers = await Promise.all(batches.map(call));\n  const out: T[] = [];\n  for (const a of answers) {\n    if (!a.ok) return a;\n    out.push(...(a.data ?? []));\n  }\n  return { ok: true, data: out };\n}\n\n/** A write door's answer: `{ ok, writer, row, store }`. */\ninterface WriteAnswer {\n  ok?: boolean;\n  row?: Record<string, unknown> | null;\n}\n\nfunction noRow<T>(door: string): RecordsResult<T> {\n  return { ok: false, error: { code: \"internal\", message: `${door} answered without the row it wrote.`, diagnostic: `@ai-matrx/records/scopes: ${door}` } };\n}\n\n/** The value door answers its own envelope; its codes, as the package's. */\nconst VALUE_DOOR_CODES: Record<string, RecordsErrorCode> = {\n  unauthorized: \"door\",\n  forbidden: \"door\",\n  forbidden_org: \"door\",\n  not_found: \"not_found\",\n  invalid_argument: \"invalid_argument\",\n  conflict: \"stale_write\",\n  unavailable: \"not_supported\",\n};\n\nexport function createScopeDoors(call: ScopeDoorCall): ScopeDoors {\n  async function write(door: string, args: Record<string, unknown>): Promise<RecordsResult<Record<string, unknown>>> {\n    const res = await call<WriteAnswer>(door, args, `scopes.${door}`);\n    if (!res.ok) return res;\n    const row = res.data?.row;\n    if (!row || typeof row !== \"object\") return noRow(door);\n    return { ok: true, data: row };\n  }\n\n  async function archiveOrRestore(door: string, args: Record<string, unknown>, id: Uuid): Promise<RecordsResult<{ id: Uuid }>> {\n    const res = await call<unknown>(door, args, `scopes.${door}`);\n    return res.ok ? { ok: true, data: { id } } : res;\n  }\n\n  async function fieldById(scopeTypeId: Uuid, fieldId: Uuid, door: string): Promise<RecordsResult<ContextField>> {\n    const fields = await doors.fields([scopeTypeId]);\n    if (!fields.ok) return fields;\n    const field = fields.data.find((f) => f.id === fieldId);\n    return field ? { ok: true, data: field } : noRow(door);\n  }\n\n  const doors: ScopeDoors = {\n    async tree(organizationIds) {\n      const ids = uniq(organizationIds);\n      if (ids.length === 0) return { ok: true, data: [] };\n      const res = await call<{ types?: StoreTypeRow[]; scopes?: StoreScopeRow[] } | null>(\"context_tree\", { p_organization_ids: ids }, \"scopes.tree\");\n      if (!res.ok) return res;\n      const byType = new Map<string, Scope[]>();\n      for (const s of res.data?.scopes ?? []) {\n        const scope = scopeFromStore(s);\n        const list = byType.get(scope.scope_type_id) ?? [];\n        list.push(scope);\n        byType.set(scope.scope_type_id, list);\n      }\n      return { ok: true, data: (res.data?.types ?? []).map((t) => ({ ...scopeTypeFromStore(t), scopes: byType.get(t.id) ?? [] })) };\n    },\n\n    async types(organizationIds, options) {\n      const withCounts = options?.withCounts ?? true;\n      const ids = uniq(organizationIds);\n      if (ids.length === 0) return { ok: true, data: { types: [], counts: withCounts ? {} : null } };\n      const res = await call<{ types?: StoreTypeRow[] } | null>(\"context_tree_types\", { p_organization_ids: ids, p_with_counts: withCounts }, \"scopes.types\");\n      if (!res.ok) return res;\n      const rows = res.data?.types ?? [];\n      const counts: Record<string, number> | null = withCounts ? {} : null;\n      if (counts) for (const r of rows) counts[r.id] = Number(r.scope_count ?? 0);\n      return { ok: true, data: { types: rows.map(scopeTypeFromStore), counts } };\n    },\n\n    async typeScopesPage(scopeTypeId, offset = 0, limit = TYPE_SCOPES_PAGE) {\n      const res = await call<{ scopes?: StoreScopeRow[]; total?: number; next_offset?: number | null } | null>(\n        \"context_tree_type_scopes\",\n        { p_scope_type_id: scopeTypeId, p_offset: offset, p_limit: limit },\n        \"scopes.typeScopesPage\",\n      );\n      if (!res.ok) return res;\n      return {\n        ok: true,\n        data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0), next_offset: res.data?.next_offset ?? null },\n      };\n    },\n\n    async search(organizationIds, query, limit = 100) {\n      const ids = uniq(organizationIds);\n      const q = query.trim();\n      if (ids.length === 0 || q === \"\") return { ok: true, data: { scopes: [], total: 0 } };\n      const res = await call<{ scopes?: StoreScopeRow[]; total?: number } | null>(\n        \"context_tree_search\",\n        { p_organization_ids: ids, p_query: q, p_limit: limit },\n        \"scopes.search\",\n      );\n      if (!res.ok) return res;\n      return { ok: true, data: { scopes: (res.data?.scopes ?? []).map(scopeFromStore), total: Number(res.data?.total ?? 0) } };\n    },\n\n    async scopes(ids) {\n      const res = await inBatches(ids, SCOPES_PER_CALL, (batch) => call<StoreScopeRow[]>(\"context_scopes\", { p_scope_ids: batch }, \"scopes.scopes\"));\n      return res.ok ? { ok: true, data: res.data.map(scopeWithTypeFromStore) } : res;\n    },\n\n    async fields(scopeTypeIds) {\n      const res = await inBatches(scopeTypeIds, SCOPE_TYPES_PER_FIELDS_CALL, (batch) =>\n        call<StoreItemRow[]>(\"context_items\", { p_scope_type_ids: batch }, \"scopes.fields\"),\n      );\n      return res.ok ? { ok: true, data: res.data.map(contextFieldFromStore) } : res;\n    },\n\n    async field(fieldId, organizationIds) {\n      const orgs = uniq(organizationIds);\n      const answers = await Promise.all(\n        orgs.map((org) =>\n          call<Array<{ id: string; document?: { entity_definition_id?: unknown } | null }> | null>(\n            \"read_records_by_ids\",\n            { p_organization_id: org, p_table_id: FIELD_KERNEL_ID, p_record_ids: [fieldId], p_by_id: false },\n            \"scopes.field\",\n          ),\n        ),\n      );\n      let refusal: RecordsResult<ContextField> | null = null;\n      for (const answer of answers) {\n        if (!answer.ok) {\n          refusal ??= answer;\n          continue;\n        }\n        const typeId = answer.data?.find((r) => r.id === fieldId)?.document?.entity_definition_id;\n        if (typeof typeId !== \"string\") continue;\n        const fields = await doors.fields([typeId]);\n        if (!fields.ok) return fields;\n        const field = fields.data.find((f) => f.id === fieldId);\n        if (field) return { ok: true, data: field };\n      }\n      return (\n        refusal ?? {\n          ok: false,\n          error: { code: \"not_found\", message: \"This context field could not be found.\", diagnostic: `@ai-matrx/records/scopes: field ${fieldId}` },\n        }\n      );\n    },\n\n    async values(scopeIds, options) {\n      const res = await inBatches(scopeIds, SCOPES_PER_VALUES_CALL, (batch) =>\n        call<StoreValueRow[]>(\"context_values\", { p_scope_ids: batch }, \"scopes.values\"),\n      );\n      if (!res.ok) return res;\n      const cells = res.data.map(contextValueFromStore);\n      await completeWholeValues(cells, options?.readFileText ?? null);\n      return { ok: true, data: cells };\n    },\n\n    async archivedTypes(organizationId) {\n      const res = await call<StoreArchivedTypeRow[] | null>(\"context_archived_types\", { p_organization_id: organizationId }, \"scopes.archivedTypes\");\n      return res.ok ? { ok: true, data: (res.data ?? []).map(archivedScopeTypeFromStore) } : res;\n    },\n\n    async archivedScopesOfType(organizationId, scopeTypeId, wanted) {\n      const out: ArchivedScope[] = [];\n      for (let offset = 0; out.length < wanted.size; offset += ARCHIVED_SCOPES_PAGE) {\n        const res = await call<Array<{ id: string; document?: { name?: unknown; slug?: unknown } | null; archived_at?: string | null }> | null>(\n          \"read_records_archived\",\n          { p_organization_id: organizationId, p_table_id: scopeTypeId, p_lane: \"org\", p_by_id: false, p_limit: ARCHIVED_SCOPES_PAGE, p_offset: offset },\n          \"scopes.archivedScopesOfType\",\n        );\n        if (!res.ok) return res;\n        const rows = res.data ?? [];\n        for (const r of rows) {\n          if (!wanted.has(r.id)) continue;\n          out.push({\n            id: r.id,\n            name: typeof r.document?.name === \"string\" ? r.document.name : null,\n            slug: typeof r.document?.slug === \"string\" ? r.document.slug : null,\n            archived_at: r.archived_at ?? null,\n          });\n        }\n        if (rows.length < ARCHIVED_SCOPES_PAGE) break;\n      }\n      return { ok: true, data: out };\n    },\n\n    async systemItems() {\n      const res = await call<StoreSystemItemRow[] | null>(\"context_system_items\", {}, \"scopes.systemItems\");\n      return res.ok ? { ok: true, data: (res.data ?? []).map(systemContextFieldFromStore) } : res;\n    },\n\n    async tableTemplates(organizationId) {\n      const res = await call<TableTemplate[] | null>(\"table_templates\", { p_org_id: organizationId }, \"scopes.tableTemplates\");\n      return res.ok ? { ok: true, data: Array.isArray(res.data) ? res.data : [] } : res;\n    },\n\n    async templates() {\n      const res = await call<ScopeTemplate[] | null>(\"context_templates\", {}, \"scopes.templates\");\n      return res.ok ? { ok: true, data: res.data ?? [] } : res;\n    },\n\n    async createType(organizationId, spec) {\n      const slug = resolveSlug(spec.slug, spec.label_plural || spec.label_singular || \"\");\n      if (!slug.ok) return slug;\n      const res = await write(\"context_type_write\", {\n        p_organization_id: organizationId,\n        p_type_id: null,\n        p_spec: definedOnly({\n          label_singular: spec.label_singular,\n          label_plural: spec.label_plural,\n          icon: spec.icon ?? \"folder\",\n          description: spec.description ?? \"\",\n          sort_order: spec.sort_order ?? 0,\n          max_assignments: spec.max_assignments_per_entity ?? undefined,\n          default_variable_keys: spec.default_variable_keys ?? [],\n          color: spec.color,\n          slug: slug.data,\n        }),\n      });\n      return res.ok ? { ok: true, data: scopeTypeFromStore(res.data as unknown as StoreTypeRow) } : res;\n    },\n\n    async updateType(typeId, spec) {\n      let slug: string | undefined;\n      if (spec.slug !== undefined) {\n        const resolved = resolveSlug(spec.slug, spec.label_plural ?? spec.label_singular ?? \"\");\n        if (!resolved.ok) return resolved;\n        slug = resolved.data;\n      }\n      const res = await write(\"context_type_write\", {\n        p_organization_id: null,\n        p_type_id: typeId,\n        p_spec: definedOnly({\n          label_singular: spec.label_singular,\n          label_plural: spec.label_plural,\n          icon: spec.icon,\n          description: spec.description,\n          sort_order: spec.sort_order,\n          max_assignments: spec.max_assignments_per_entity,\n          color: spec.color,\n          slug,\n        }),\n      });\n      return res.ok ? { ok: true, data: scopeTypeFromStore(res.data as unknown as StoreTypeRow) } : res;\n    },\n\n    archiveType: (typeId) => archiveOrRestore(\"context_type_archive\", { p_type_id: typeId }, typeId),\n    restoreType: (typeId) => archiveOrRestore(\"context_type_restore\", { p_type_id: typeId }, typeId),\n\n    async createScope(organizationId, typeId, spec) {\n      const slug = resolveSlug(spec.slug, spec.name ?? \"\");\n      if (!slug.ok) return slug;\n      const res = await write(\"context_scope_write\", {\n        p_organization_id: organizationId,\n        p_scope_id: null,\n        p_type_id: typeId,\n        p_spec: definedOnly({\n          name: spec.name,\n          parent_scope_id: spec.parent_scope_id,\n          description: spec.description ?? \"\",\n          settings: spec.settings ?? {},\n          slug: slug.data,\n          sort_order: spec.sort_order,\n        }),\n      });\n      return res.ok ? { ok: true, data: scopeFromStore(res.data as unknown as StoreScopeRow) } : res;\n    },\n\n    async updateScope(scopeId, spec) {\n      let slug: string | undefined;\n      if (spec.slug !== undefined) {\n        const resolved = resolveSlug(spec.slug, spec.name ?? \"\");\n        if (!resolved.ok) return resolved;\n        slug = resolved.data;\n      }\n      const res = await write(\"context_scope_write\", {\n        p_organization_id: null,\n        p_scope_id: scopeId,\n        p_type_id: null,\n        p_spec: definedOnly({ name: spec.name, description: spec.description, settings: spec.settings, slug, sort_order: spec.sort_order }),\n      });\n      return res.ok ? { ok: true, data: scopeFromStore(res.data as unknown as StoreScopeRow) } : res;\n    },\n\n    archiveScope: (scopeId) => archiveOrRestore(\"context_scope_archive\", { p_scope_id: scopeId }, scopeId),\n    restoreScope: (scopeId) => archiveOrRestore(\"context_scope_restore\", { p_scope_id: scopeId }, scopeId),\n\n    async createField(scopeTypeId, spec) {\n      const res = await write(\"context_item_write\", {\n        p_item_id: null,\n        p_scope_type_id: scopeTypeId,\n        p_spec: fieldSpecForDoor({ kind: \"string\", description: \"\", context_policy: \"on_request\", sensitivity: \"internal\", tags: [], ...spec }),\n      });\n      if (!res.ok) return res;\n      return fieldById(scopeTypeId, String(res.data.id), \"context_item_write\");\n    },\n\n    async updateField(fieldId, scopeTypeId, spec) {\n      const res = await write(\"context_item_write\", { p_item_id: fieldId, p_scope_type_id: null, p_spec: fieldSpecForDoor(spec) });\n      if (!res.ok) return res;\n      return fieldById(scopeTypeId, fieldId, \"context_item_write\");\n    },\n\n    archiveField: (fieldId) => archiveOrRestore(\"context_item_archive\", { p_item_id: fieldId }, fieldId),\n    restoreField: (fieldId) => archiveOrRestore(\"context_item_restore\", { p_item_id: fieldId }, fieldId),\n\n    async writeValue(cell) {\n      const res = await call<{ ok?: boolean; data?: { version?: number; source_type?: string }; error?: { code?: string; message?: string } } | null>(\n        \"context_value_write\",\n        { p_payload: { source_type: \"ai_enriched\", ...valuePayloadForDoor(cell) } },\n        \"scopes.writeValue\",\n      );\n      if (!res.ok) return res;\n      const envelope = res.data ?? {};\n      if (!envelope.ok) {\n        const code = VALUE_DOOR_CODES[envelope.error?.code ?? \"\"] ?? \"internal\";\n        return { ok: false, error: { code, message: envelope.error?.message ?? \"The value was not saved.\" } };\n      }\n      return {\n        ok: true,\n        data: {\n          scope_id: cell.scope_id,\n          field_id: cell.field_id,\n          version: Number(envelope.data?.version ?? 1),\n          source_type: String(envelope.data?.source_type ?? cell.source_type ?? \"ai_enriched\"),\n        },\n      };\n    },\n\n    tableProvision({ organization_id, item_id, scope_id, home_id }) {\n      return call<Uuid>(\n        \"scope_table_provision\",\n        { p_organization_id: organization_id, p_item_id: item_id, p_scope_id: scope_id, p_home_id: home_id ?? null },\n        \"scopeTableProvision\",\n      );\n    },\n  };\n  return doors;\n}\n","// src/core/pickListDoors.ts — @ai-matrx/records · THE PICK-LIST DOORS (HEADLESS, LIGHT)\n//\n// One call each, through the one door call (./doorCall). The records client spreads these into\n// itself; `@ai-matrx/records/door-call` hands them to a shell that only reads or rewrites a pick\n// list, so it never carries the store client. The list is read by its own id; its organization is\n// the list's own, never the client's.\n\nimport type { Uuid } from \"../record\";\nimport type { RecordsResult } from \"../results\";\nimport type { PickListDocument, PickListIndexDocument, PickListItemInput } from \"../pick-list\";\nimport type { DoorCall } from \"./doorCall\";\n\nexport interface PickListDoors {\n  /**\n   * PICK-LISTS: every pick list a person may open in ONE organization (`custom.pick_list_index`): id, name and\n   * choice count, nothing else. Read only when a picker opens (the load law), never with the screen.\n   */\n  pickListIndex(args: { organization_id: Uuid }): Promise<RecordsResult<PickListIndexDocument | null>>;\n  /**\n   * PICK-LISTS: a pick list with its choices, grouped (`custom.pick_list_get`; viewer access on the list).\n   * The list is read by its own id; its organization is the list's own, never the client's.\n   */\n  pickListGet(args: { list_id: Uuid }): Promise<RecordsResult<PickListDocument | null>>;\n  /** PICK-LISTS: a pick list for a selection control (`custom.pick_list_for_selection`): labels, help, groups, icons, NEVER the secret description. */\n  pickListForSelection(args: { list_id: Uuid }): Promise<RecordsResult<PickListDocument | null>>;\n  /**\n   * PICK-LISTS: rename / describe a pick list and, with `items`, REPLACE its choices\n   * (`custom.pick_list_update`; editor access). The replaced choices are archived, soft and restorable.\n   */\n  pickListUpdate(args: {\n    list_id: Uuid;\n    list_name?: string | null;\n    description?: string | null;\n    items?: readonly PickListItemInput[] | null;\n  }): Promise<RecordsResult<PickListDocument | null>>;\n}\n\n/** The door names (guard: each is in the generated catalog — `door-call-entry.test.ts`). */\nexport const PICK_LIST_DOORS = {\n  pickListIndex: \"pick_list_index\",\n  pickListGet: \"pick_list_get\",\n  pickListForSelection: \"pick_list_for_selection\",\n  pickListUpdate: \"pick_list_update\",\n} as const;\n\nexport function createPickListDoors(callDoor: DoorCall): PickListDoors {\n  return {\n    async pickListIndex({ organization_id }) {\n      return callDoor<PickListIndexDocument | null>(\n        PICK_LIST_DOORS.pickListIndex,\n        { p_organization_id: organization_id },\n        \"pickListIndex\",\n      );\n    },\n\n    async pickListGet({ list_id }) {\n      return callDoor<PickListDocument | null>(PICK_LIST_DOORS.pickListGet, { p_list_id: list_id }, \"pickListGet\");\n    },\n\n    async pickListForSelection({ list_id }) {\n      return callDoor<PickListDocument | null>(\n        PICK_LIST_DOORS.pickListForSelection,\n        { p_list_id: list_id },\n        \"pickListForSelection\",\n      );\n    },\n\n    async pickListUpdate({ list_id, list_name, description, items }) {\n      return callDoor<PickListDocument | null>(\n        PICK_LIST_DOORS.pickListUpdate,\n        {\n          p_list_id: list_id,\n          p_list_name: list_name ?? null,\n          p_description: description ?? null,\n          p_items: items ? [...items] : null,\n        },\n        \"pickListUpdate\",\n      );\n    },\n  };\n}\n","// src/choice.ts — @ai-matrx/records\n//\n// WHAT A CHOICE VALUE IS, in one place, for every screen and every caller.\n//\n// A pick-list is a Table and an option is a Record of it (FLD-5 / FLD-6) — that part is\n// unchanged and is the store being right. What a CELL holds is not the option record's id: it\n// is the option's own stable key, a short word derived from its title when the option is born,\n// unique within its list and never rewritten. So renaming \"Circle\" to \"Round\" rewrites no row,\n// and nothing — no person, no agent, no import — is ever asked to know a uuid for a word the\n// product showed them.\n//\n// The read doors hand back the LABEL in the cell and name the key beside it in `_choices`:\n//\n//   { \"kind\": \"Circle\",\n//     \"_choices\": { \"kind\": { \"key\": \"circle\", \"label\": \"Circle\", \"id\": \"…\",\n//                             \"retired\": false, \"reason\": null } } }\n//\n// A multi-choice cell reads as an array of labels and its `_choices` entry is an array in the\n// same order. A RETIRED option is in there too, with `retired: true` and the reason — a value\n// whose choice was retired reads as its label and says what happened rather than vanishing.\n//\n// WRITING takes the label, the key, or (so nothing that worked yesterday breaks) the option\n// record's id. The store normalizes all three to the key on the way in and refuses a word that\n// names no choice, naming the choices themselves.\n\nimport type { RecordDocument, StoredRecord } from \"./record\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n/** One option, as `_choices` names it and as `optionsOf` returns it. */\nexport interface ChoiceOption {\n  /** The stable key the cell actually holds. */\n  key: string;\n  /** What a person reads. */\n  label: string;\n  /** The option RECORD's id, for a caller that needs the row itself. */\n  id?: string;\n  /** True when the option was retired: still readable, no longer pickable. */\n  retired?: boolean;\n  /** Why it is no longer offered, in a sentence, when it is retired. */\n  reason?: string | null;\n}\n\n/**\n * The stable key of an option RECORD as `custom.field_options` returns it.\n *\n * It lives in `metadata.option_key`, not in the document: FLD-5 keeps a category to one title\n * field, and the key is the store's own bookkeeping rather than a column anybody declared.\n * The fallback is the same slug the store derives, so an option written by something that has\n * not caught up still answers.\n */\nexport function optionKey(option: StoredRecord): string {\n  const stored = option.metadata?.[\"option_key\"];\n  if (typeof stored === \"string\" && stored.trim() !== \"\") return stored;\n  return choiceSlug(optionLabel(option));\n}\n\n/** What a person reads on an option record. */\nexport function optionLabel(option: StoredRecord): string {\n  const doc = option.data as RecordDocument | undefined;\n  const title = doc?.[\"title\"] ?? doc?.[\"name\"];\n  if (typeof title === \"string\" && title.trim() !== \"\") return title;\n  return \"Unnamed choice\";\n}\n\n/**\n * The store's own slug, mirrored so a client can predict a key without a round trip.\n * `custom.choice_slug` is the original; a title with nothing a-z0-9 in it gets a short hash of\n * itself there, and this returns the empty-ish fallback rather than guessing a hash — a caller\n * that needs the real key for such a title reads it off the option.\n */\nexport function choiceSlug(word: string): string {\n  const slug = word\n    .trim()\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, \"_\")\n    .replace(/^_+|_+$/g, \"\")\n    .slice(0, 55);\n  return slug === \"\" ? \"choice\" : slug;\n}\n\n/**\n * Does this stored (or typed) value name this option? The key, the label and the option's own\n * id all name the same choice, and a control has to recognize every one of them: what the read\n * door hands it is the LABEL, what the store holds is the KEY, and what a screen written before\n * this contract sends is the ID.\n */\nexport function isTheChosen(option: StoredRecord, value: unknown): boolean {\n  if (typeof value !== \"string\") return false;\n  const asked = value.trim().toLowerCase();\n  if (asked === \"\") return false;\n  return (\n    asked === optionKey(option).toLowerCase() ||\n    asked === optionLabel(option).toLowerCase() ||\n    asked === option.id.toLowerCase()\n  );\n}\n\n/** Every value of one cell, as strings, whether the Field is multi or not. */\nexport function choiceValuesOf(value: unknown): string[] {\n  if (Array.isArray(value)) return value.filter((v): v is string => typeof v === \"string\");\n  if (typeof value === \"string\" && value !== \"\") return [value];\n  return [];\n}\n\n/**\n * What the read door said about one column's choices: the key behind the label, and whether the\n * option was retired and why. Returns an empty array when the document carries no `_choices`\n * entry for that column, which is also what a document written before this contract looks like.\n */\nexport function choicesOf(document: RecordDocument | undefined, fieldKeyOrId: string): ChoiceOption[] {\n  const block = document?.[\"_choices\"];\n  if (!block || typeof block !== \"object\") return [];\n  const entry = (block as Record<string, unknown>)[fieldKeyOrId];\n  if (!entry) return [];\n  const list = Array.isArray(entry) ? entry : [entry];\n  return list.filter((x): x is ChoiceOption => !!x && typeof x === \"object\" && typeof (x as ChoiceOption).key === \"string\");\n}\n\n/** True when this cell's value points at a choice that has since been retired. */\nexport function holdsARetiredChoice(document: RecordDocument | undefined, fieldKeyOrId: string): boolean {\n  return choicesOf(document, fieldKeyOrId).some((c) => c.retired === true);\n}\n\n/** True when a token looks like a uuid — which a choice value is no longer allowed to be. */\nexport function looksLikeAnId(value: unknown): boolean {\n  return typeof value === \"string\" && isUuidShape(value);\n}\n\n/* ═══ WORDS TYPED INTO A CHOICE CELL THAT ARE NOT A CHOICE (lane CHOICE-COLUMN-EDIT) ═══════════\n *\n * A software team's \"Account Type\" column offers Cursor · Claude · Codex, and somebody types\n * \"Gemini\". Three answers are possible and the store has a door for each: add it to the choices\n * and the cell takes it (`recordUpdateAddingChoices`), keep it as typed on a column that takes\n * other values (`config.allow_other` — an ordinary `recordUpdate`), or refuse it. Which one is\n * the Feature Knob `custom/choice_nudge` (`choiceNudge()`), and this is the ONE place that\n * reads it, so the grid, the record form and every other surface answer the same way.\n */\n\n/** The Feature Knob `custom/choice_nudge`: ask (the default), always add, or never add. */\nexport type ChoiceNudge = \"ask\" | \"always_add\" | \"never_add\";\n\nexport const CHOICE_NUDGES: readonly ChoiceNudge[] = [\"ask\", \"always_add\", \"never_add\"];\n\n/** Any answer the knob door gives, as one of the three; anything unknown is the default, `ask`. */\nexport function asChoiceNudge(value: unknown): ChoiceNudge {\n  return typeof value === \"string\" && (CHOICE_NUDGES as readonly string[]).includes(value) ? (value as ChoiceNudge) : \"ask\";\n}\n\n/** What `decideTypedChoice` answers. */\nexport type TypedChoiceDecision =\n  /** Nothing was typed. */\n  | { decision: \"empty\" }\n  /** The words name a live choice (by its words or its key, any case): write `key`. */\n  | { decision: \"chosen\"; key: string; label: string }\n  /** Ask the person. `keepOffered` is true only when the column takes other values. */\n  | { decision: \"ask\"; words: string; keepOffered: boolean }\n  /** Add the words to the choices and the cell takes them — without asking (`always_add`). */\n  | { decision: \"add\"; words: string }\n  /** Keep the words as typed, an \"other\" value (`never_add` on a column that takes other values). */\n  | { decision: \"keep_as_typed\"; words: string }\n  /** The words are not one of the choices and nothing may add them (`never_add`, closed column). */\n  | { decision: \"not_a_choice\"; words: string };\n\n/** A choice as either door hands it: an option record (`fieldOptions`) or a `_choices` entry. */\nexport type ChoiceLike = StoredRecord | ChoiceOption;\n\nfunction choiceKeyAndLabel(option: ChoiceLike): { key: string; label: string; retired: boolean } {\n  if (typeof (option as ChoiceOption).key === \"string\" && typeof (option as ChoiceOption).label === \"string\") {\n    const o = option as ChoiceOption;\n    return { key: o.key, label: o.label, retired: o.retired === true };\n  }\n  // `custom.field_options` answers LIVE options only, so an option record is never retired.\n  const record = option as StoredRecord;\n  return { key: optionKey(record), label: optionLabel(record), retired: false };\n}\n\n/**\n * THE ONE DECISION for words typed into a choice cell.\n *\n * `options` are the column's choices; a retired one is not pickable, so words naming only a\n * retired choice are treated as new (adding them brings the retired choice back, which is what\n * the store does). `nudge` absent or unknown is `ask`.\n */\nexport function decideTypedChoice(args: {\n  words: string;\n  options: readonly ChoiceLike[];\n  allowOther: boolean;\n  nudge?: ChoiceNudge | string | null | undefined;\n}): TypedChoiceDecision {\n  const words = args.words.trim();\n  if (words === \"\") return { decision: \"empty\" };\n  const asked = words.toLowerCase();\n  for (const option of args.options) {\n    const { key, label, retired } = choiceKeyAndLabel(option);\n    if (retired) continue;\n    if (label.toLowerCase() === asked || key.toLowerCase() === asked) return { decision: \"chosen\", key, label };\n  }\n  const nudge = asChoiceNudge(args.nudge);\n  if (nudge === \"always_add\") return { decision: \"add\", words };\n  if (nudge === \"never_add\") return args.allowOther ? { decision: \"keep_as_typed\", words } : { decision: \"not_a_choice\", words };\n  return { decision: \"ask\", words, keepOffered: args.allowOther };\n}\n\n/* ═══ REMOVING A CHOICE THAT RECORDS STILL HOLD (lane CHOICE-TAILS, 2026-09-27) ════════════════\n *\n * A dental front desk's \"Visit Type\" offers Cleaning · Exam · X-ray · Whitening, and the office\n * stops booking X-rays as their own visit. Removing X-ray used to leave every record that held it\n * holding a retired choice, with nobody asked. Now the column editor asks, Notion-style:\n * \"3 records use “X-ray”.\" — move them to another choice, keep the words as other values (only\n * where the column takes other values), or clear them. The answer goes in the SAME save as the\n * list (`fieldUpdateRehomingChoices`), and that save answers its own undo.\n */\n\n/** How many records hold one choice (`custom.field_choice_usage`), keyed by the option's id. */\nexport interface ChoiceUsage {\n  key: string;\n  words: string;\n  retired: boolean;\n  /** Live records the caller may see whose cell holds the choice. */\n  records: number;\n}\n\n/** Where the records of a removed choice go. */\nexport type ChoiceRehome =\n  | { then: \"move\"; to: string }\n  | { then: \"keep\" }\n  | { then: \"clear\" };\n\n/** One cell as it was before a rehoming save — what its undo writes back. */\nexport interface ChoiceCellBack {\n  record_id: string;\n  value: unknown;\n}\n\n/** What `fieldUpdateRehomingChoices` answers. */\nexport interface ChoicesRehomed {\n  field_id: string;\n  rehomed: Array<{ choice_id: string; words: string; then: ChoiceRehome[\"then\"]; to: string | null; records: number }>;\n  cells_back: number;\n  /** Send `{ patch: { options: undo.options }, cells_back: undo.cells_back }` to put it all back. */\n  undo: { options: Array<{ id: string; words: string }>; cells_back: ChoiceCellBack[] };\n}\n\n/**\n * THE CHOICES A LIST NO LONGER NAMES THAT RECORDS STILL HOLD — the ones the editor must ask about.\n * `beforeIds` is the list as the store answered it, `afterIds` the list as the person has it now.\n */\nexport function removedChoicesInUse(\n  beforeIds: readonly string[],\n  afterIds: readonly string[],\n  usage: Readonly<Record<string, ChoiceUsage>> | null | undefined,\n): Array<{ id: string; words: string; records: number }> {\n  if (!usage) return [];\n  const kept = new Set(afterIds);\n  return beforeIds\n    .filter((id) => !kept.has(id))\n    .map((id) => ({ id, words: usage[id]?.words ?? \"\", records: usage[id]?.records ?? 0 }))\n    .filter((c) => c.records > 0);\n}\n\n/** “1 record uses “X-ray”.” · “3 records use “X-ray”.” — the question's first line. */\nexport function recordsUseSentence(records: number, words: string): string {\n  return `${records} ${records === 1 ? \"record uses\" : \"records use\"} “${words}”.`;\n}\n\n/** What the answer will do, said before Save: “3 records move to “Exam”.” */\nexport function rehomeSentence(records: number, words: string, rehome: ChoiceRehome, toWords?: string): string {\n  const n = `${records} ${records === 1 ? \"record\" : \"records\"}`;\n  if (rehome.then === \"move\") return `${n} that ${records === 1 ? \"holds\" : \"hold\"} “${words}” ${records === 1 ? \"moves\" : \"move\"} to “${toWords ?? \"another choice\"}”.`;\n  if (rehome.then === \"keep\") return `${n} ${records === 1 ? \"keeps\" : \"keep\"} “${words}” as another value.`;\n  return `${n} that ${records === 1 ? \"holds\" : \"hold\"} “${words}” ${records === 1 ? \"is\" : \"are\"} cleared.`;\n}\n","// src/placement.ts — @ai-matrx/records\n//\n// WHO KEEPS A TABLE, AND WHETHER THE CONTEXT PICKER OFFERS IT (lane SC-1 PLACEMENT,\n// SCOPES-CONTEXT-TRANSITION.md §2.3 P1/P2 as amended by the plan attack, H5).\n//\n// The store answers these facts; this file only carries their shape and the two questions\n// every screen asks of them. It re-derives nothing — which tables a feature keeps is decided\n// ONCE, by `custom.table_placement` in the database, from the Table document's own keys and\n// the facts the door that made it already wrote (a column's choices, a scope's own table, a\n// checklist's steps, a booking page's holds, a workflow's states, the app's own tables).\n//\n//   platform_owned     the store's one flag. true = the app or one of its features keeps it,\n//                       and a person's list of tables shows it only behind \"Show everything\".\n//   kept_for            WHICH feature: context · choices · checklists · bookings · workflow ·\n//                       app · store, or whatever word the next feature brings. Null when the\n//                       organization keeps the table.\n//   offered_as_context  whether the context picker offers the Table. Only a Table somebody\n//                       marked (a scope type the scopes mover lands) is offered.\n//   foundation          lane 10 FD: part of the business's day-one data (Patients, Therapists,\n//                       Services). Independent of who keeps the table. Absent is false.\n//\n// Import-inert: types and pure functions, nothing else.\n\nimport type { Uuid } from \"./record\";\n\n/** The placement facts, as the Table document or `custom.table` carries them. */\nexport interface TablePlacement {\n  platform_owned?: boolean | null;\n  kept_for?: string | null;\n  offered_as_context?: boolean | null;\n  foundation?: boolean | null;\n}\n\n/**\n * One row of `custom.table_facts` since SC-1 — the two lane facts it always answered\n * (`visibility`, `mine`) and the placement, with the sentence a person reads and where the\n * table is used. A store without the SC-1 door answers the first three columns only; every\n * placement column is then `undefined`, and the readers below treat the table as the\n * organization's own — exactly what that store's older screens did.\n */\nexport interface TablePlacementFact extends TablePlacement {\n  table_id: Uuid;\n  visibility: string;\n  mine: boolean;\n  /** The heading a kept table is listed under: \"The context system\", \"The choices behind your columns\", … */\n  keeper_group?: string | null;\n  /** One plain sentence: who keeps it and where it opens from. Null for the organization's own. */\n  keeper_says?: string | null;\n  /** Where the table is used: `table` (another Table, or itself) or `scope` (a context scope). */\n  used_in_kind?: \"table\" | \"scope\" | null;\n  used_in_id?: Uuid | null;\n  /** The Table that page belongs to, when `used_in_kind` is `table`. */\n  used_in_table_id?: Uuid | null;\n}\n\n/** Whether a person's list of tables keeps this one out of sight until \"Show everything\". */\nexport function keptOutOfSight(placement: TablePlacement | null | undefined): boolean {\n  return placement?.platform_owned === true;\n}\n\n/** Whether the Table is part of the business's day-one data (lane 10 FD). Absent is no. */\nexport function isFoundation(placement: TablePlacement | null | undefined): boolean {\n  return placement?.foundation === true;\n}\n\n/** Whether the context picker may offer this Table. Absent is no. */\nexport function offeredAsContext(placement: TablePlacement | null | undefined): boolean {\n  return placement?.offered_as_context === true;\n}\n\n/**\n * The placement facts folded onto a table list, by id. Pure — returns new objects and leaves\n * the list it was given alone. A table the facts do not name is returned unchanged.\n */\nexport function withTablePlacement<T extends { id: Uuid }>(\n  tables: readonly T[],\n  facts: readonly TablePlacementFact[] | null | undefined,\n): Array<T & Partial<TablePlacementFact>> {\n  if (!facts) return [...tables];\n  const byId = new Map(facts.map((f) => [f.table_id, f]));\n  return tables.map((table) => {\n    const fact = byId.get(table.id);\n    if (!fact || fact.platform_owned === undefined) return table;\n    return {\n      ...table,\n      platform_owned: fact.platform_owned,\n      kept_for: fact.kept_for ?? null,\n      offered_as_context: fact.offered_as_context ?? false,\n      foundation: fact.foundation ?? false,\n      keeper_group: fact.keeper_group ?? null,\n      keeper_says: fact.keeper_says ?? null,\n      used_in_kind: fact.used_in_kind ?? null,\n      used_in_id: fact.used_in_id ?? null,\n      used_in_table_id: fact.used_in_table_id ?? null,\n    };\n  });\n}\n\n/**\n * THE KEPT TABLES, GROUPED UNDER THEIR KEEPER, in the order each group first appears. A kept\n * table the store gave no heading goes under \"Platform tables\" — never dropped.\n */\nexport function keptGroups<T extends TablePlacement & Partial<TablePlacementFact>>(\n  tables: readonly T[],\n): Array<{ group: string; tables: T[] }> {\n  const out: Array<{ group: string; tables: T[] }> = [];\n  const at = new Map<string, number>();\n  for (const table of tables) {\n    if (!keptOutOfSight(table)) continue;\n    const group = table.keeper_group?.trim() || \"Platform tables\";\n    let i = at.get(group);\n    if (i === undefined) {\n      i = out.length;\n      at.set(group, i);\n      out.push({ group, tables: [] });\n    }\n    out[i]!.tables.push(table);\n  }\n  return out;\n}\n\n/**\n * WHERE A KEPT TABLE OPENS FROM (THE DOOR LAW): the host's own addresses for a table and for a\n * context scope, chosen by what the store said the table is used in. With nothing said, the\n * table's own page — a kept table is never a row with nowhere to go.\n */\nexport function keptTableHref(\n  fact: { table_id: Uuid } & Partial<TablePlacementFact>,\n  hrefs: { table: (tableId: Uuid) => string; scope: (scopeId: Uuid) => string },\n): string {\n  if (fact.used_in_kind === \"scope\" && fact.used_in_id) return hrefs.scope(fact.used_in_id);\n  if (fact.used_in_kind === \"table\" && (fact.used_in_table_id || fact.used_in_id)) {\n    return hrefs.table((fact.used_in_table_id || fact.used_in_id)!);\n  }\n  return hrefs.table(fact.table_id);\n}\n\n// ── WHERE A TABLE LIVES, AND MOVING IT (lane SC-1-TAILS; the owner, 2026-09-23: \"I am not seeing\n// how I can see what org this data is in … make it easy to see and set the org for something\") ──\n//\n// `custom.table_home` says which organization a Table lives in — read FROM THE TABLE, never from\n// the organization the person is working in — whether this person may move it and where to, and\n// what holds it in place; `custom.table_move` moves it (with every Table inside it or its rows)\n// or refuses with one sentence. These are the shapes and the two pure readers every screen uses:\n// `parseTableHome` reads the store's answer strictly (an answer it cannot read is \"could not\n// ask\", never a guess) and `moveConsequence` says what a move does before it happens (the\n// destructive-and-expensive-actions law). The client's `tableHome` / `tableMove` are the calls.\n\n/** One of the person's other organizations, and whether the Table can go there. */\nexport interface TableHomeDestination {\n  id: Uuid;\n  name: string;\n  /**\n   * The organization's web address (UI-FIX-19). A screen draws it beside a name another\n   * destination also carries, so two organizations with one name can be told apart. `null` when\n   * the store's answer predates it.\n   */\n  slug: string | null;\n  /** The person's role there: owner · admin · member. */\n  role: string;\n  /** False when the store says the Table cannot go there; `why` says why, in its words. */\n  ok: boolean;\n  why: string | null;\n}\n\n/** `custom.table_home`'s answer, read. */\nexport interface TableHome {\n  table: { id: Uuid; name: string; version: number };\n  /** Where it lives, from the Table itself. */\n  organization: { id: Uuid; name: string };\n  /** The Table's maker, or an owner/admin of its organization. */\n  mayMove: boolean;\n  /** When `mayMove` is false: the sentence that says who can. */\n  whyNot: string | null;\n  /** Sentences for what holds it where it is. Empty when nothing does. */\n  heldBy: string[];\n  /** Every other organization this person belongs to. */\n  destinations: TableHomeDestination[];\n  carries: {\n    fields: number;\n    records: number;\n    inTrash: number;\n    choiceLists: number;\n    withIt: number;\n    /** Tables that ride along because they live inside it or inside its rows. */\n    tablesInside: number;\n    /** Links between its rows and rows that stay, which will reach back across the wall. */\n    linksAcross: number;\n  };\n}\n\n/** What `custom.table_move` answered when the move landed. */\nexport interface TableMoved {\n  to: { id: Uuid; name: string };\n  from: { id: Uuid; name: string };\n  tableName: string;\n}\n\nfunction countOf(value: unknown): number {\n  return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction wordsOf(value: unknown): string | null {\n  return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n/** Read the store's answer strictly: an answer this cannot read is `null`, never a guess. */\nexport function parseTableHome(raw: unknown): TableHome | null {\n  if (!raw || typeof raw !== \"object\") return null;\n  const row = raw as Record<string, unknown>;\n  const table = row.table as Record<string, unknown> | undefined;\n  const org = row.organization as Record<string, unknown> | undefined;\n  if (!table || !org || !wordsOf(table.id) || !wordsOf(org.id) || !wordsOf(org.name)) return null;\n  const carries = (row.carries ?? {}) as Record<string, unknown>;\n  const destinations = Array.isArray(row.destinations) ? row.destinations : [];\n  return {\n    table: { id: String(table.id), name: wordsOf(table.name) ?? \"This table\", version: countOf(table.version) },\n    organization: { id: String(org.id), name: String(org.name) },\n    mayMove: row.may_move === true,\n    whyNot: wordsOf(row.why_not),\n    heldBy: Array.isArray(row.held_by) ? row.held_by.filter((s): s is string => typeof s === \"string\") : [],\n    destinations: destinations\n      .filter((d): d is Record<string, unknown> => !!d && typeof d === \"object\" && !!wordsOf((d as Record<string, unknown>).id))\n      .map((d) => ({\n        id: String(d.id),\n        name: wordsOf(d.name) ?? \"An organization\",\n        slug: wordsOf(d.slug),\n        role: wordsOf(d.role) ?? \"member\",\n        ok: d.ok === true,\n        why: wordsOf(d.why),\n      })),\n    carries: {\n      fields: countOf(carries.fields),\n      records: countOf(carries.records),\n      inTrash: countOf(carries.in_trash),\n      choiceLists: countOf(carries.choice_lists),\n      withIt: countOf(carries.with_it),\n      tablesInside: countOf(carries.tables_inside),\n      linksAcross: countOf(carries.links_across),\n    },\n  };\n}\n\n/** Read `custom.table_move`'s answer; `null` when it is not a landed move. */\nexport function parseTableMoved(raw: unknown): TableMoved | null {\n  const row = (raw ?? {}) as Record<string, unknown>;\n  const to = (row.to ?? {}) as Record<string, unknown>;\n  const from = (row.from ?? {}) as Record<string, unknown>;\n  const table = (row.table ?? {}) as Record<string, unknown>;\n  if (row.moved !== true || !wordsOf(to.id)) return null;\n  return {\n    to: { id: String(to.id), name: wordsOf(to.name) ?? \"the new organization\" },\n    from: { id: wordsOf(from.id) ?? \"\", name: wordsOf(from.name) ?? \"its old organization\" },\n    tableName: wordsOf(table.name) ?? \"The table\",\n  };\n}\n\n/**\n * What `custom.table_duplicate` answered when the copy landed (lane TABLE-ACTIONS). The copy is a\n * NEW Table in `organization`; `copied` counts what came with it and `notCopied` names, in the\n * store's own words, what a copy never carries (history, forms, portals, dashboards, rules, …).\n */\nexport interface TableDuplicated {\n  table: { id: Uuid; name: string };\n  from: { id: Uuid; name: string; organizationId: Uuid };\n  /**\n   * Where the copy lives. `null` only for a copy carried on by its id (`tableDuplicateContinue`\n   * after a reload): the carry-on door's answer names the copy, not its organization, and the\n   * first answer that did is gone. `tableDuplicate` always fills it from its first answer.\n   */\n  organization: { id: Uuid; name: string } | null;\n  copied: {\n    fields: number;\n    choiceLists: number;\n    choices: number;\n    views: number;\n    records: number;\n    withRecords: boolean;\n  };\n  /** Archived columns of the source, which stay behind with it. */\n  archivedFieldsLeft: number;\n  /** Archived (or quarantined) records left behind; `null` when records were not copied. */\n  archivedRecordsLeft: number | null;\n  /** Records this person is not handed (the ladder, then \"Shown to\"); `null` when records were not copied. */\n  recordsNotYoursLeft: number | null;\n  /** Columns this person may not read: copied as columns, values left empty — column name → values left behind. */\n  hiddenColumns: Record<string, number>;\n  /** Another person's \"only me\" views of the source, which stay theirs. */\n  privateViewsLeft: number;\n  /** Where a reference to a row that was not copied was taken out (\"view …\", \"column …\", the table's look). */\n  rowReferencesDropped: string[];\n  /** Views whose source was \"only me\": copied as new views are made, still \"Shown to: only me\". */\n  viewsSharedAsNewViews: string[];\n  /** Views the house door for a new view refused, each with its sentence. */\n  viewsNotCopied: string[];\n  /** What moved in the source while it was copied (the copy keeps what was fixed when it started). */\n  changedDuringCopy: {\n    columnsArchivedSince: string[];\n    rowsChangedAfterCopied: number;\n    rowsArchivedSince: number | null;\n    rowsAddedSince: number | null;\n  };\n  notCopied: string[];\n  path: string;\n}\n\n/** One pass of a paged copy (`custom.table_duplicate` / `custom.table_duplicate_continue`). */\nexport interface TableDuplicateProgress {\n  tableId: Uuid;\n  tableName: string;\n  /** \"busy\": another pass of this copy is running (wait, then carry on). \"failed\": the source was\n   *  archived while it was copied — not handed over; discard it. \"discarded\": its half table was archived. */\n  status: \"copying\" | \"done\" | \"busy\" | \"failed\" | \"discarded\";\n  /** What the pass stopped on: \"choices\" | \"fields\" | \"views\" | \"records\" | \"links\" | \"done\". */\n  step: string;\n  /** The store's sentence for busy / failed / discarded. */\n  sentence: string | null;\n  /** This pass: how long before its first unit, how many units, how long in all (ms). */\n  pass: { setupMs: number; units: number; ms: number } | null;\n  choiceLists: { done: number; total: number };\n  fields: { done: number; total: number };\n  views: { done: number; total: number };\n  /** `null` when records are not being copied. */\n  records: { done: number; total: number } | null;\n}\n\nfunction doneTotal(value: unknown): { done: number; total: number } {\n  const v = (value ?? {}) as Record<string, unknown>;\n  return { done: countOf(v.done), total: countOf(v.total) };\n}\n\n/** Read one pass's answer strictly; `null` when the shape is not a copy's progress. */\nexport function parseTableDuplicateProgress(raw: unknown): TableDuplicateProgress | null {\n  if (!raw || typeof raw !== \"object\") return null;\n  const row = raw as Record<string, unknown>;\n  const table = (row.table ?? {}) as Record<string, unknown>;\n  const progress = (row.progress ?? {}) as Record<string, unknown>;\n  const statuses = [\"copying\", \"done\", \"busy\", \"failed\", \"discarded\"] as const;\n  const status = statuses.find((s) => s === row.status);\n  if (row.duplicated !== true || !wordsOf(table.id) || !status) return null;\n  const pass = (row.pass ?? null) as Record<string, unknown> | null;\n  return {\n    tableId: String(table.id),\n    tableName: wordsOf(table.name) ?? \"The copy\",\n    status,\n    step: wordsOf(row.step) ?? \"\",\n    sentence: wordsOf(row.sentence),\n    pass: pass ? { setupMs: countOf(pass.setup_ms), units: countOf(pass.units), ms: countOf(pass.ms) } : null,\n    choiceLists: doneTotal(progress.choice_lists),\n    fields: doneTotal(progress.fields),\n    views: doneTotal(progress.views),\n    records: progress.records && typeof progress.records === \"object\" ? doneTotal(progress.records) : null,\n  };\n}\n\n/** One of the caller's unfinished copies (`custom.table_copies_in_progress`). */\nexport interface TableCopyInProgress {\n  tableId: Uuid;\n  tableName: string;\n  organization: { id: Uuid; name: string };\n  from: { id: Uuid; name: string };\n  /** \"copying\" (carry it on) or \"failed\" (the source was archived meanwhile — discard it). */\n  status: \"copying\" | \"failed\";\n  sentence: string | null;\n  startedAt: string | null;\n  records: { done: number; total: number } | null;\n}\n\nexport function parseTableCopiesInProgress(raw: unknown): TableCopyInProgress[] {\n  if (!Array.isArray(raw)) return [];\n  return raw\n    .filter((x): x is Record<string, unknown> => !!x && typeof x === \"object\")\n    .map((x) => {\n      const t = (x.table ?? {}) as Record<string, unknown>;\n      const o = (x.organization ?? {}) as Record<string, unknown>;\n      const f = (x.from ?? {}) as Record<string, unknown>;\n      return {\n        tableId: String(t.id ?? \"\"),\n        tableName: wordsOf(t.name) ?? \"A copy\",\n        organization: { id: String(o.id ?? \"\"), name: wordsOf(o.name) ?? \"its organization\" },\n        from: { id: String(f.id ?? \"\"), name: wordsOf(f.name) ?? \"the table it was copied from\" },\n        status: x.status === \"failed\" ? (\"failed\" as const) : (\"copying\" as const),\n        sentence: wordsOf(x.sentence),\n        startedAt: wordsOf(x.started_at),\n        records: x.records && typeof x.records === \"object\" ? doneTotal(x.records) : null,\n      };\n    })\n    .filter((x) => x.tableId.length > 0);\n}\n\n/** Read `custom.table_duplicate`'s answer strictly; `null` when it is not a landed copy. */\nexport function parseTableDuplicated(raw: unknown): TableDuplicated | null {\n  if (!raw || typeof raw !== \"object\") return null;\n  const row = raw as Record<string, unknown>;\n  const table = (row.table ?? {}) as Record<string, unknown>;\n  const from = (row.from ?? {}) as Record<string, unknown>;\n  const organization = (row.organization ?? {}) as Record<string, unknown>;\n  const copied = (row.copied ?? {}) as Record<string, unknown>;\n  const left = (row.left_behind ?? {}) as Record<string, unknown>;\n  // THE CARRY-ON DOOR'S \"done\" (W4 snapshot defect, 2026-10-18): `custom.table_duplicate_continue`\n  // answers {duplicated, table, path, status, progress, copied, left_behind, changed_during_copy}\n  // and never `from` / `organization` — only the first door says those. Requiring\n  // `organization.id` here refused EVERY copy that took more than one pass (any table past a few\n  // hundred rows) after the store had finished and handed it over, so a snapshot left a visible\n  // table and said nothing was left. `tableDuplicate` merges its first answer's header in;\n  // a resumed copy reads `organization: null`.\n  if (row.duplicated !== true || row.status !== \"done\" || !wordsOf(table.id)) return null;\n  return {\n    table: { id: String(table.id), name: wordsOf(table.name) ?? \"The copy\" },\n    from: {\n      id: wordsOf(from.id) ?? \"\",\n      name: wordsOf(from.name) ?? \"the table it was copied from\",\n      organizationId: wordsOf(from.organization_id) ?? \"\",\n    },\n    organization: wordsOf(organization.id)\n      ? { id: String(organization.id), name: wordsOf(organization.name) ?? \"its organization\" }\n      : null,\n    copied: {\n      fields: countOf(copied.fields),\n      choiceLists: countOf(copied.choice_lists),\n      choices: countOf(copied.choices),\n      views: countOf(copied.views),\n      records: countOf(copied.records),\n      withRecords: copied.with_records === true,\n    },\n    archivedFieldsLeft: countOf(left.archived_fields),\n    archivedRecordsLeft: typeof left.archived_records === \"number\" ? left.archived_records : null,\n    recordsNotYoursLeft: typeof left.records_not_yours_to_open === \"number\" ? left.records_not_yours_to_open : null,\n    hiddenColumns: Object.fromEntries(\n      Object.entries((left.hidden_columns ?? {}) as Record<string, unknown>).map(([name, n]) => [name, countOf(n)]),\n    ),\n    privateViewsLeft: countOf(left.private_views),\n    rowReferencesDropped: Array.isArray(left.row_references_dropped)\n      ? left.row_references_dropped.filter((s): s is string => typeof s === \"string\")\n      : [],\n    viewsSharedAsNewViews: Array.isArray(left.views_shared_as_new_views)\n      ? left.views_shared_as_new_views.filter((s): s is string => typeof s === \"string\")\n      : [],\n    changedDuringCopy: (() => {\n      const ch = (row.changed_during_copy ?? {}) as Record<string, unknown>;\n      return {\n        columnsArchivedSince: Array.isArray(ch.columns_archived_since)\n          ? ch.columns_archived_since.filter((s): s is string => typeof s === \"string\")\n          : [],\n        rowsChangedAfterCopied: countOf(ch.rows_changed_after_copied),\n        rowsArchivedSince: typeof ch.rows_archived_since === \"number\" ? ch.rows_archived_since : null,\n        rowsAddedSince: typeof ch.rows_added_since === \"number\" ? ch.rows_added_since : null,\n      };\n    })(),\n    viewsNotCopied: Array.isArray(left.views_not_copied)\n      ? left.views_not_copied.filter((s): s is string => typeof s === \"string\")\n      : [],\n    notCopied: Array.isArray(left.not_copied) ? left.not_copied.filter((s): s is string => typeof s === \"string\") : [],\n    path: wordsOf(row.path) ?? `/data/${String(table.id)}`,\n  };\n}\n\nfunction plural(n: number, one: string, many: string): string {\n  return `${n} ${n === 1 ? one : many}`;\n}\n\n/** The consequence of a move, said before it happens (destructive-and-expensive-actions law). */\nexport function moveConsequence(home: TableHome, to: Pick<TableHomeDestination, \"name\">): string {\n  const c = home.carries;\n  const parts = [plural(c.fields, \"column\", \"columns\"), plural(c.records, \"row\", \"rows\")];\n  if (c.inTrash > 0) parts.push(`${c.inTrash} in the trash`);\n  const extra = c.choiceLists + c.withIt;\n  return (\n    `${home.table.name} moves to ${to.name} with its ${parts.join(\", \")}` +\n    (c.tablesInside > 0\n      ? `, the ${plural(c.tablesInside, \"table\", \"tables\")} that live${c.tablesInside === 1 ? \"s\" : \"\"} inside it or its rows (with their own rows)`\n      : \"\") +\n    (extra > 0\n      ? `, and ${plural(extra, \"thing\", \"things\")} built only on it (choice lists, rules, dashboards, templates)`\n      : \"\") +\n    `, its comments, forms, saved views and history. ` +\n    (c.linksAcross > 0\n      ? `${plural(c.linksAcross, \"link\", \"links\")} to rows that stay in ${home.organization.name} keep${c.linksAcross === 1 ? \"s\" : \"\"} pointing there, across the two organizations. `\n      : \"\") +\n    `People who see it only because they are in ${home.organization.name} stop seeing it; people it ` +\n    `was shared with by name keep it. You can move it back from the same place.`\n  );\n}\n","// src/level.ts — @ai-matrx/records\n//\n// THE FOUR WORDS, AND THEIR ORDER. `public.permission_level` is a closed enum —\n// viewer < commenter < edit_content < editor < admin — and the store says so in its own\n// refusals (\"This needs the admin level (viewer < commenter < editor < admin)\").\n//\n// It lives here, in the headless package, for one reason: a screen that has to\n// decide whether to DRAW a control needs the same ordering the door uses to\n// decide whether to accept the call. Two orderings is two answers to one\n// question, and the second one is always the wrong one.\n//\n// Nothing here decides policy. `atLeast` compares two words the store defined;\n// which word a door requires is the door's business and is never restated here.\n\nimport { PERMISSION_LEVELS } from \"@ai-matrx/data/access/levels\";\n\n/** `public.permission_level`, in the store's own order. */\n/**\n * `edit_content` (Notion's \"Can edit content\") sits between `commenter` and `editor`: it may change\n * the rows and page content of a thing, never its structure (columns, views, settings) or its\n * sharing — those stay with `editor` and `admin`.\n */\nexport type PermissionLevel = \"viewer\" | \"commenter\" | \"edit_content\" | \"editor\" | \"admin\";\n\n// The ladder is `@ai-matrx/data/access/levels` (viewer < commenter < editor < admin), a subpath that imports\n// nothing, so this headless package never needs auth or supabase-js (the whole `/access` section would: the\n// packed-consumer canary failed with ERR_MODULE_NOT_FOUND). The store's enum adds the retired `edit_content`\n// rung directly above `commenter` (it normalizes to `editor`, so it sits below it); that one insertion is the\n// only thing this file adds to the ladder.\nconst RETIRED_RUNG_ABOVE: PermissionLevel = \"commenter\";\n\n/** The order the store writes them in, lowest first — `public.permission_level` itself, retired `edit_content` included (the code ladder that labels and offers levels is `@ai-matrx/data/access` PERMISSION_LEVELS). */\nexport const STORE_PERMISSION_LEVELS: readonly PermissionLevel[] = PERMISSION_LEVELS.flatMap(\n  (level): PermissionLevel[] => (level === RETIRED_RUNG_ABOVE ? [level, \"edit_content\"] : [level]),\n);\n\n/** 1-based rank of each store word (viewer 1 … admin 5). A plain object on purpose: `asPermissionLevel` reads it with `in`. */\nconst ORDINAL: Record<PermissionLevel, number> = Object.fromEntries(\n  STORE_PERMISSION_LEVELS.map((level, index) => [level, index + 1]),\n) as Record<PermissionLevel, number>;\n\n/** Whether `held` is the same rung as `needed` or a higher one. Nothing held is never enough. */\nexport function atLeast(held: PermissionLevel | null | undefined, needed: PermissionLevel): boolean {\n  if (!held) return false;\n  const have = ORDINAL[held];\n  return have !== undefined && have >= ORDINAL[needed];\n}\n\n/** A level word the store sent, or null when it sent something this package does not know. */\nexport function asPermissionLevel(word: unknown): PermissionLevel | null {\n  return typeof word === \"string\" && word in ORDINAL ? (word as PermissionLevel) : null;\n}\n\n/** The higher of two levels — what a person holds when two ways in both let them through. */\nexport function highestLevel(\n  left: PermissionLevel | null | undefined,\n  right: PermissionLevel | null | undefined,\n): PermissionLevel | null {\n  if (!left) return right ?? null;\n  if (!right) return left;\n  return ORDINAL[left] >= ORDINAL[right] ? left : right;\n}\n\n/**\n * What one subject's level is, as `custom.my_levels` answers it. `null` is an\n * ANSWER — \"you hold nothing on this\" — and never a missing row: a screen that\n * could not tell \"no access\" from \"not asked yet\" would draw one of them as the\n * other.\n */\nexport interface MyLevel {\n  id: string;\n  level: PermissionLevel | null;\n}\n","// src/core/keysetCursor.ts — @ai-matrx/records\n//\n// THE KEYSET CURSOR AT THE CLIENT EDGE (AP3-KEYSET-DOOR, 2026-10-06). `custom.read_records_keyset`\n// answers its cursor as a small JSON object (the last row's sort values, its id, and a fingerprint of\n// the question it was made under). Screens never read it: it travels as one opaque base64url string\n// and is handed back unchanged. It carries nothing secret — the store re-applies the row predicate on\n// every page and refuses, by name, a cursor made under a different sort, filter or search.\n\nfunction utf8ToBinary(text: string): string {\n  let out = \"\";\n  for (const byte of new TextEncoder().encode(text)) out += String.fromCharCode(byte);\n  return out;\n}\n\nfunction binaryToUtf8(binary: string): string {\n  const bytes = new Uint8Array(binary.length);\n  for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n  return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n}\n\n/** The store's cursor object as one opaque base64url string. */\nexport function encodeKeysetCursor(cursor: unknown): string {\n  return btoa(utf8ToBinary(JSON.stringify(cursor))).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * The string back into the object the store made, or `null` when it is not one of its cursors (not\n * base64url, not JSON, or not an object). A null is refused at the edge; it is never sent as \"page 1\".\n */\nexport function decodeKeysetCursor(cursor: string): Record<string, unknown> | null {\n  if (!/^[A-Za-z0-9_-]+$/.test(cursor)) return null;\n  try {\n    const padded = cursor.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (cursor.length % 4)) % 4);\n    const value: unknown = JSON.parse(binaryToUtf8(atob(padded)));\n    return value !== null && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n  } catch {\n    return null;\n  }\n}\n","// src/table.ts — @ai-matrx/records\n//\n// THE TABLE AND THE HOME. REC-1, REC-3, REC-14, REC-26, REC-32, REC-33.\n// A Table is a Record (REC-25), which is why every shape here carries the\n// record contract as well as its own columns: `custom.table` is a VIEW over\n// `custom.record`, and this is that view's shape.\n\nimport type { Timestamp, Uuid } from \"./record\";\nimport type {\n  StorageMode,\n  TableDisplay,\n  TableOrigin,\n  TableType,\n} from \"./vocabulary\";\n\n/**\n * REC-1. A Table declares its fields, exactly one Home, and the properties\n * `display`, `ordered`, `heavy` | `light`, `retention` and `detail`.\n */\nexport interface Table {\n  id: Uuid;\n  organization_id: Uuid;\n  /**\n   * The access ladder's Table \"Level\": organization · public · confidential · private. Absent is\n   * the organization's own. Confidential and Private records have no \"Shown to\".\n   */\n  level?: string | null;\n  /** The token this Table is addressed by. */\n  slug: string;\n  name: string;\n  label_singular: string | null;\n  label_plural: string | null;\n  icon: string | null;\n  color: string | null;\n  /** REC-32. One of the seven, closed. */\n  type: TableType;\n  /** REC-11. A detail Table inherits only: no direct shares, never a Home. */\n  detail: boolean;\n  parent_token: string | null;\n  /** AGT-1 / AGT-2. On by default for a custom table; an organization turns it off. */\n  agent_writable: boolean;\n  display: TableDisplay | null;\n  ordered: boolean;\n  /** REC-4. `heavy` is indexed with Rules on write; `light` is the whole document with Rules on read. */\n  weight: StorageMode;\n  /** REC-23. How long a soft delete stays reversible. */\n  retention_days: number | null;\n  /** REC-2. Every Table has one; without it a record cannot be a chip. */\n  title_field: string | null;\n  /**\n   * T8 / CD-CORE-15. The Field KEY whose value is each record's type (a Shape's Kind); which columns a record\n   * has follows it (`applies_to_types` on a Field). Absent or null: every record has every column.\n   */\n  type_field?: string | null;\n  /** The field ids this Table declares, in declaration order. */\n  fields: Uuid[];\n  default_sort: string | null;\n  row_order: string | null;\n  /** REC-14. Where this Table lives. Exactly one primary Home. */\n  home_id: Uuid | null;\n  /** The feature that keeps this Table out of the person's lists (`snapshot`, `copying`, …); absent for a person's own table. */\n  kept_for?: string | null;\n  /** REC-27. One of the nine, defined in code and not editable by Migration. */\n  is_kernel: boolean;\n  created_by: Uuid | null;\n  updated_by: Uuid | null;\n  created_at: Timestamp;\n  updated_at: Timestamp;\n  version: number;\n  metadata: Record<string, unknown>;\n  /** The old lane word; read `shown_to` and `published_to_web` (access ladder), which the store answers now. */\n  visibility: string;\n  /** Access ladder \"Shown to\" (which lists show it; never a lock). Absent on a store that does not answer it. */\n  shown_to?: string | null;\n  /** Access ladder \"Published to the web\". Absent on a store that does not answer it. */\n  published_to_web?: boolean;\n  /**\n   * Lane 10 FD. Part of the business's day-one data (Patients, Therapists, Services) — a mark, not\n   * storage. Absent is false. Only admin on the Table changes it (custom._table_shape_guard).\n   */\n  foundation?: boolean;\n  /**\n   * Present only on what `tableFind({ …, keptFor })` answers for an ARCHIVED table of that slug and\n   * kept_for (the store's `archived_at`); such an answer carries only `id`, `organization_id` and this.\n   */\n  archived_at?: Timestamp | null;\n}\n\n/**\n * REC-33. `origin` is `standard` or `custom`, and it is orthogonal to `type`.\n * A Table we ship in schema `custom` is `standard` — the schema name is not the\n * origin.\n */\nexport interface RegisteredTable {\n  token: string;\n  type: TableType;\n  origin: TableOrigin;\n  /** REC-34. Carried per table type: true for Entity and Detail, false for the other five. */\n  custom_fields_enabled: boolean;\n}\n\n/**\n * REC-3 / REC-26. A Home is where a Table appears. The declared organization\n * Home is the tree's root; every additional Home is a referenced carrying\n * relation from the Home record to the Table record, which is why this shape\n * names a relation id rather than a second placement column.\n */\nexport interface Home {\n  table_id: Uuid;\n  home_record_id: Uuid;\n  organization_id: Uuid;\n  /** `declared` for the Table's own Home, `carried` for an additional one. */\n  kind: string;\n  relation_id: Uuid | null;\n}\n\n/** What `tablePropose` / `tableList` hands back about how full a Table is (REC-N-5). */\nexport interface TableCapacity {\n  records: number;\n  ceiling: number;\n  full: boolean;\n  /** The knob that decides the ceiling, named so a person can act on it. */\n  knob: string;\n}\n\n/**\n * WHAT ONE PASS OF `custom.table_archive` ANSWERS WITH — the numbers a screen\n * needs to draw a bar and write a sentence, instead of a spinner and an\n * SQLSTATE (VERIFIER-10 F3, VERIFIER-11 F3).\n *\n * Archiving a table is a JOB, NOT A STATEMENT. `custom.record_delete` on a\n * Table recurses through everything the Table contains inside one transaction,\n * which is unbounded by construction: at 1,430 records it dies on `57014`,\n * \"canceling statement due to statement timeout\", and nothing is changed. The\n * remedy for a thing that cannot finish in one statement is more statements,\n * never a longer one — so the caller loops, passing its own `chunk`, until\n * `done`.\n *\n * IT IS RESUMABLE BECAUSE IT IS STATELESS. There is no job row to lose:\n * `remaining` is read off the records themselves on every call, so a browser\n * closed halfway, a failed pass or a deploy mid-run all leave a table that is\n * half archived and a next call that picks up exactly where the last stopped.\n * Which is why a screen driving this may NEVER say \"nothing was changed\" after\n * a pass that moved rows — `archived_total` is what really landed.\n *\n * NOTHING IS DELETED. Every row goes through `custom.record_delete`, so every\n * guard, history capture and outbox row still happens and `recordRestore`\n * still brings any of them back.\n */\nexport interface TableArchiveProgress {\n  table_id: Uuid;\n  /** The table's own name, so a sentence can use it rather than an id. */\n  table_name: string;\n  /** What THIS pass archived. */\n  archived: number;\n  /** Records of this table still live. Zero is the end of the row work. */\n  remaining: number;\n  /** Records this table has ever held: `remaining` + `archived_total`. */\n  total: number;\n  /** Records of this table already archived, across every pass ever made. */\n  archived_total: number;\n  /** Whether the Table record itself has been archived. */\n  table_archived: boolean;\n  /** Nothing live is left to do. The caller's loop ends here. */\n  done: boolean;\n  /** The chunk the door actually took on — it clamps what it is handed. */\n  chunk: number;\n  /** The store's own sentence about this pass, in the product's voice. */\n  message: string;\n  /**\n   * An earlier run of this archive was started and has not finished (an open archive event). A\n   * screen reading this after a reload offers to carry on, never a fresh button (BREAKER-1 B-F13).\n   * Absent from a store that predates it.\n   */\n  in_progress?: boolean;\n  /**\n   * THE REVERSIBLE ACTION'S SIZE LINE (knob `custom/archive_confirm_over`, organization-overridable):\n   * a table with at most this many live records is archived at once and announced with Undo; one\n   * with more is asked about first, with the count. Absent from a store that predates it — a screen\n   * then asks first, as it always did.\n   */\n  confirm_over?: number;\n}\n\n/**\n * BRINGING A WHOLE TABLE BACK — ONE PASS OF IT (`custom.table_restore`, lane TABLE-ACTIONS).\n *\n * The mirror of {@link TableArchiveProgress}: the Table and its structure come back in the first\n * pass, then its records in the order they went, then what was built on it, all from the one\n * archive event. The CALLER LOOPS until `done` (`client.tableRestoreWhole` does it).\n */\nexport interface TableRestoreProgress {\n  table_id: Uuid;\n  table_name: string;\n  /** Records THIS pass brought back. */\n  restored: number;\n  /** The Table, its Fields, rules and views THIS pass brought back (the first pass). */\n  structure_restored: number;\n  /** Forms, views, portals, child Tables… built on the Table THIS pass brought back. */\n  built_on_restored: number;\n  /** Rows the archive took that are still waiting. */\n  remaining: number;\n  built_on_remaining: number;\n  /** Rows refused on their own now (a value another row took since): left archived and named. */\n  left: number;\n  left_ids?: Uuid[];\n  /** Each row left archived, with the store's own reason for it. */\n  left_reasons?: Record<Uuid, string>;\n  /** Restoring events of this table still open (a re-archive mid-restore leaves two). */\n  events_open?: number;\n  /** Whether the Table record itself is live. */\n  table_restored: boolean;\n  /** Nothing the archive took is still waiting. The caller's loop ends here. */\n  done: boolean;\n  chunk: number;\n  archive_event: Uuid | null;\n  message: string;\n}\n\n/**\n * WHAT A STORED COLUMN DIFFERS FROM THE SPEC THAT ASKED FOR IT IN (lane PLATFORM-APP-DATA).\n *\n * `custom.table_ensure` never retypes, relabels or drops a column a table already has — a retype is\n * a conversion a person decides. It used to ignore the difference without a word; now it names\n * each one, aspect by aspect, and still changes nothing. This shape is the contract a release-time\n * drift check will read, so it stays this small:\n *\n * - `type`     the column's kind: its parity type when it has one, else its behavior (`text`, `range`, …)\n * - `format`   how it is shown (`long`, `phone`, `currency`, …); `null` when it has none\n * - `label`    the column's name\n * - `multi` / `required`   booleans (absent = `false`)\n * - `unique`   whether it holds a `unique` rule\n * - `spec`     the spec for that column could not be read at all; `declared` is the store's sentence\n *\n * The declared side is the spec as the store WOULD store it, so `long_text` compares as the\n * `text` + `long` it is stored as — never a false difference.\n */\n/** `extra`: a column the table holds that the spec no longer declares (kept, never removed). */\nexport type FieldDriftAspect = \"type\" | \"format\" | \"label\" | \"multi\" | \"required\" | \"unique\" | \"spec\" | \"extra\";\n\nexport interface FieldDrift {\n  /** The column's key. */\n  field: string;\n  aspect: FieldDriftAspect;\n  /** What the column holds now. */\n  stored: string | boolean | null;\n  /** What the spec asked for (for `spec`, the store's sentence about why it could not be read). */\n  declared: string | boolean | null;\n}\n\nconst DRIFT_ASPECTS: readonly FieldDriftAspect[] = [\"type\", \"format\", \"label\", \"multi\", \"required\", \"unique\", \"spec\", \"extra\"];\n\n/**\n * The store's `drift` answer, typed. `null` when the store did not send one — a `table_ensure`\n * body older than `lane12_c_an_ensured_table_says_what_differs_from_its_spec.sql` — which means\n * \"not compared\", never \"no difference\". An entry of an aspect this package does not know is kept\n * as `spec`, so a newer store is never silenced.\n */\nexport function parseFieldDrift(raw: unknown): FieldDrift[] | null {\n  if (!Array.isArray(raw)) return null;\n  const scalar = (v: unknown): string | boolean | null =>\n    typeof v === \"string\" || typeof v === \"boolean\" ? v : v === null || v === undefined ? null : JSON.stringify(v);\n  return raw\n    .filter((d): d is Record<string, unknown> => Boolean(d) && typeof d === \"object\")\n    .map((d) => ({\n      field: String(d.field ?? \"\"),\n      aspect: DRIFT_ASPECTS.includes(d.aspect as FieldDriftAspect) ? (d.aspect as FieldDriftAspect) : \"spec\",\n      stored: scalar(d.stored),\n      declared: scalar(d.declared),\n    }));\n}\n","// src/grid.ts — @ai-matrx/records\n//\n// THE GRID'S STORE PRIMITIVES (lane GRID-PRIMITIVES, 2026-09-22).\n//\n// The /data grid is being rebuilt on the record store with its UI and behavior unchanged. The\n// older grid kept five things the store could not say; each is now a door, and these are the\n// shapes those doors answer:\n//\n//   G1  a Table's colors (row color by a choice column, ordered color rules, hand highlights),\n//       its layout (organization default + per-view override) and the summary bar's nine\n//       measures                           → custom.table_decorate / table_decorations,\n//                                             custom.grid_layout, custom.record_aggregate\n//   G2  row actions, run on a whole selection in one transaction\n//                                          → custom.action_declare / row_actions / action_run\n//   G3  the formula language a person types, worked out by the store\n//                                          → custom.formula_parse (+ formula_text on a Field)\n//   G4  every record change out to a signed webhook\n//                                          → custom.table_webhook_declare / table_webhooks /\n//                                             table_webhook_archive\n//   G5  autonumber / created / modified time columns, display formats, example tables, Excel\n//                                          → field kinds, custom.autonumber_backfill,\n//                                             custom.io_export\n//\n// Fields and records are named BY ID everywhere here (REC-17): a column renamed keeps its\n// color, its width and its place in a formula.\n\nimport type { WorkbookJson } from \"@ai-matrx/print/xlsx\";\nimport type { Uuid } from \"./record\";\nimport type { RecordsError } from \"./results\";\n\n// ── G1: colors ──────────────────────────────────────────────────────────────────────────\n\n/** `custom.decoration_colors()` — the palette, in the order an uncolored choice takes. */\nexport type DecorationColor = \"slate\" | \"green\" | \"amber\" | \"red\" | \"blue\" | \"violet\" | \"teal\" | \"orange\" | \"yellow\" | \"pink\" | \"brown\" | \"gray\";\n\n/** `custom.decoration_rule_ops()` — the tests a color rule may ask. */\nexport type DecorationRuleOp =\n  | \"is\" | \"is_not\" | \"contains\" | \"is_empty\" | \"not_empty\" | \"is_true\" | \"is_false\"\n  | \"gt\" | \"gte\" | \"lt\" | \"lte\";\n\nexport type DecorationTarget = \"row\" | \"cell\";\n\nexport interface DecorationRule {\n  /** Given by the store when omitted; keep it to edit the rule in place. */\n  id?: string;\n  /** The Field id the rule reads. */\n  field: Uuid;\n  op: DecorationRuleOp;\n  /** Compared as text for is / is_not / contains, as a number for gt / gte / lt / lte. */\n  value?: string | number;\n  color: DecorationColor;\n  target: DecorationTarget;\n}\n\nexport interface TableDecorations {\n  version: 1;\n  colors: DecorationColor[];\n  rule_ops: Array<{ op: DecorationRuleOp; takes_value: boolean; label: string }>;\n  color_by?: { field: Uuid; target: DecorationTarget };\n  rules: DecorationRule[];\n  /** Hand highlights: record id → color. */\n  rows: Record<Uuid, DecorationColor>;\n  /** Hand highlights: Field id → color. */\n  columns: Record<Uuid, DecorationColor>;\n  /** Hand highlights: record id → Field id → color. */\n  cells: Record<Uuid, Record<Uuid, DecorationColor>>;\n  /** What stopped painting because its column is gone — said, never silently dropped. */\n  stale: Array<{ part: string; field?: Uuid; rule_id?: string; record_id?: Uuid; says: string }>;\n}\n\n/**\n * ONE LEAF of a Table's colors — the older door's own path shape\n * (`public.udt_set_table_style`), so two people highlighting two rows never overwrite each other.\n */\nexport type DecorationPath =\n  | [\"color_by\"]\n  | [\"rules\"]\n  | [\"rows\", Uuid]\n  | [\"columns\", Uuid]\n  | [\"cells\", Uuid, Uuid];\n\n// ── G1: layout ──────────────────────────────────────────────────────────────────────────\n\nexport type GridLayoutMode = \"auto\" | \"fit\" | \"scroll\";\n/**\n * Airtable's four heights are short (1 line), medium (2), tall (4), extra_tall (6). `compact` and `normal`\n * are the older words and still read: both are a one-line row.\n */\nexport type GridRowHeight = \"compact\" | \"short\" | \"normal\" | \"medium\" | \"tall\" | \"extra_tall\";\n\n/** A saved view's own grid choices, kept at `definition.grid` (custom.view_declare judges them). `definition.layout` is the view's KIND (grid / kanban / calendar / gallery), never these. */\nexport interface ViewLayout {\n  mode?: GridLayoutMode;\n  row_height?: GridRowHeight;\n  freeze_first_column?: boolean;\n  wrap?: boolean;\n  /** Field id → pixels, 60–1200. */\n  widths?: Record<Uuid, number>;\n}\n\nexport interface GridLayout {\n  layout: Required<Omit<ViewLayout, \"widths\">> & { fit_max_columns: number; widths?: Record<Uuid, number> };\n  /** Where each choice came from. */\n  source: Record<string, \"platform\" | \"organization\" | \"view\">;\n  view_id: Uuid | null;\n  /** A stored choice the grid cannot honor, named. */\n  refused: Array<{ from: \"organization\" | \"view\"; choice: string; value: unknown; says: string }>;\n}\n\n// ── G2: row actions ─────────────────────────────────────────────────────────────────────\n\nexport type RowActionStep =\n  | { field: Uuid; set: \"value\"; value: unknown }\n  | { field: Uuid; set: \"clear\" }\n  /** Worked out by the store on each record: the older grid's formula text, or an expression. */\n  | { field: Uuid; set: \"compute\"; formula_text?: string; expr?: Record<string, unknown> };\n\nexport interface RowAction {\n  /** Given by the store when omitted. */\n  id?: Uuid;\n  name: string;\n  kind?: \"update\" | \"agent\";\n  color?: DecorationColor | null;\n  icon?: string;\n  /** Ask before running. */\n  confirm?: boolean;\n  steps?: RowActionStep[];\n  /** `agent` only: what the record chat opens with. */\n  prompt?: string;\n  /** On read: whether custom.action_run can run it. */\n  runnable?: boolean;\n}\n\nexport interface ActionRunResult {\n  action_id: Uuid;\n  action: string;\n  table_id: Uuid;\n  ran: number;\n  records: Array<{ record_id: Uuid; version: number }>;\n}\n\n/** One record (and, when it can be named, one field) that refused a row action. */\nexport interface ActionRefusal {\n  record_id: Uuid;\n  record: string | null;\n  field_id: Uuid | null;\n  field: string | null;\n  code?: string;\n  says: string;\n}\n\n/**\n * Every refusal of an action run, read off the store's refusal. A run that any record refused\n * changed NOTHING; this is the list a screen shows so the person can fix those and run again.\n */\nexport function actionRefusals(error: RecordsError): ActionRefusal[] {\n  return Array.isArray(error.detail) ? (error.detail as ActionRefusal[]) : [];\n}\n\n// ── G3: formulas ────────────────────────────────────────────────────────────────────────\n\nexport type FormulaParse =\n  | {\n      ok: true;\n      text: string;\n      /** The store's expression shape — what `config.expr` holds. */\n      expr: Record<string, unknown>;\n      references: Array<{ name: string; field_id: Uuid }>;\n      result_type: \"number\" | \"text\" | \"boolean\" | \"date\" | \"unknown\";\n    }\n  | { ok: false; text: string; error: string; position: number };\n\n/** NOTION-PROPS: `formulaPreview` — the parse, and what it works out to on one record. */\nexport type FormulaPreview = FormulaParse & {\n  /** The answer on `record_id`, as the formula column would show it; null when nothing was sampled. */\n  value?: unknown;\n  record_id?: Uuid | null;\n  /** It parses, and could not be worked out on that record (a division by zero, a bad date …). */\n  error?: string;\n};\n\n// ── G4: webhooks ────────────────────────────────────────────────────────────────────────\n\nexport type RecordEvent = \"record.created\" | \"record.updated\" | \"record.archived\" | \"record.restored\" | \"record.purged\";\n\nexport interface TableWebhookDeclared {\n  webhook_id: Uuid;\n  table_id: Uuid;\n  target_url: string;\n  events: RecordEvent[];\n  /** Shown this once: X-Matrx-Signature is sha256=HMAC-SHA256(secret, body). */\n  secret: string;\n  says: string;\n}\n\nexport interface TableWebhook {\n  webhook_id: Uuid;\n  target_url: string;\n  description: string | null;\n  events: RecordEvent[] | null;\n  is_active: boolean;\n  last_attempt_at: string | null;\n  last_success_at: string | null;\n  consecutive_failures: number;\n  owner_id: Uuid;\n  created_at: string;\n}\n\n// ── G5: export ──────────────────────────────────────────────────────────────────────────\n\n/** One page of `custom.io_export`: exactly what the read door serves this person. */\nexport interface IoExportPage {\n  table_id: Uuid;\n  token: string;\n  columns: string[];\n  rows: Array<Record<string, unknown>>;\n  /** A column the store withheld from this reader, with the store's reason. */\n  withheld: Record<string, unknown>;\n  page: { requested: number; returned: number; ceiling: number; next: number | null };\n  choices: unknown;\n}\n\nfunction exportCellText(value: unknown): string | number | boolean {\n  if (value === null || value === undefined) return \"\";\n  if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") return value;\n  return JSON.stringify(value);\n}\n\n/**\n * THE .XLSX OF AN EXPORT PAGE. Numbers stay numbers and booleans stay booleans in the sheet; a\n * column the store withheld is NAMED on a second sheet with the store's reason, so a person\n * never mistakes a withheld column for an empty one. `labels` maps a column key to its header\n * (the Field's label); a key with no label is its own header.\n */\nexport async function exportPageXlsx(\n  page: IoExportPage,\n  labels: Record<string, string> = {},\n  sheetLabel = \"Records\",\n): Promise<Uint8Array> {\n  // Alchemy's one workbook engine (SheetJS behind it), loaded on first export.\n  const { writeWorkbookBytes } = await import(\"@ai-matrx/print/xlsx\");\n  const header = page.columns.map((c) => labels[c] ?? c);\n  const body = page.rows.map((row) => page.columns.map((c) => exportCellText(row[c])));\n  const name = sheetLabel.replace(/[\\\\/?*[\\]:]/g, \" \").trim().slice(0, 31) || \"Records\";\n  const sheets: WorkbookJson[\"sheets\"] = [{ name, rows: [header, ...body] }];\n  const withheld = Object.entries(page.withheld ?? {});\n  if (withheld.length > 0) {\n    sheets.push({\n      name: \"Withheld columns\",\n      rows: [\n        [\"Column\", \"Why it is empty in this export\"],\n        ...withheld.map(([k, v]) => [labels[k] ?? k, typeof v === \"string\" ? v : JSON.stringify(v)]),\n      ],\n    });\n  }\n  if (page.page?.next !== null && page.page?.next !== undefined) {\n    sheets.push({\n      name: \"More rows\",\n      rows: [[\n        `This file holds the first ${page.page.returned} rows. The table has more; export again from row ${page.page.next + 1}.`,\n      ]],\n    });\n  }\n  return writeWorkbookBytes({ sheets });\n}\n\n// ── G8: \"when a row changes, run an agent\" on a record-store table ──────────────────────\n\n/**\n * THE EVENT-SOURCE KEY of a record-store table: `record:<table id>` — what its changes carry on the\n * activity spine, what a webhook's `resource_types` names and what a schedule's `event` trigger\n * listens for (`custom.record_source_key` in the store). The store's token is `record`; the older\n * key `custom_record:<table id>` named the retired tier-2 table and is never written.\n */\nexport function recordSourceKey(tableId: Uuid): string {\n  return `record:${tableId}`;\n}\n\nconst SOURCE_KEY = /^(record|custom_record):([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n\n/**\n * The table a stored event-source key names, or `null` when the key is not a record-store key.\n * Reads the older `custom_record:<table id>` too, for rows saved before the key moved (the store\n * reads both for one release: `custom.record_source_table`).\n */\nexport function recordSourceTable(key: string | null | undefined): Uuid | null {\n  const m = key ? SOURCE_KEY.exec(key) : null;\n  return m ? (m[2] as Uuid) : null;\n}\n\n/** A record-store row event, as the activity spine carries it (and a schedule matches it). */\nexport type RecordChangeAction = RecordEvent;\n\n/**\n * THE SCHEDULE TRIGGER for \"when a row of this record-store table changes, run …\" — the same\n * `event` trigger the older store's tables use, pointed at this store's events:\n * `entity_type` `record:<table id>` ({@link recordSourceKey}), actions `record.*`, `changed_fields`\n * by column KEY.\n * `scheduler.sch_match_event` matches it against the event\n * `custom._record_events_to_activity` writes (GRID-PRIMITIVES G8), so one matcher serves both\n * stores. Omit `actions` to hear every change; omit `changedFields` to hear every column.\n */\nexport function recordChangeTrigger(\n  tableId: Uuid,\n  options: { actions?: RecordChangeAction[]; changedFields?: string[] } = {},\n): {\n  type: \"event\";\n  entity_type: string;\n  table_id: Uuid;\n  actions?: RecordChangeAction[];\n  changed_fields?: string[];\n} {\n  return {\n    type: \"event\",\n    entity_type: recordSourceKey(tableId),\n    table_id: tableId,\n    ...(options.actions && options.actions.length > 0 ? { actions: options.actions } : {}),\n    ...(options.changedFields && options.changedFields.length > 0 ? { changed_fields: options.changedFields } : {}),\n  };\n}\n\n// ── G9: every table picker lists both stores ───────────────────────────────────────────\n\n/**\n * One entry of `custom.table_list_everywhere` — `public.get_user_tables`' own shape plus\n * `store`, so a picker swaps one call and keeps its code. `store` says which home opens it.\n */\nexport interface TableListEntry {\n  id: Uuid;\n  table_name: string;\n  description: string | null;\n  version: number | null;\n  user_id: Uuid | null;\n  is_public: boolean | null;\n  visibility: string | null;\n  organization_id: Uuid;\n  created_at: string;\n  updated_at: string | null;\n  last_activity_at: string | null;\n  row_count: number;\n  field_count: number;\n  store: \"older\" | \"records\";\n}\n\n/**\n * One row of `custom.data_home_tables` — every table the person reaches, with the store's own\n * answers for the organization's name, who made it, and whether the app keeps it. `system` is a\n * system organization's table (reached on the admin lane only).\n */\nexport interface DataHomeTable {\n  table_id: Uuid;\n  table_name: string;\n  organization_id: Uuid;\n  organization_name: string;\n  member: boolean;\n  visibility: string | null;\n  updated_at: string | null;\n  mine: boolean;\n  shared_with_me: boolean;\n  platform_owned: boolean;\n  kind: string | null;\n  team?: boolean;\n  system?: boolean;\n  created_by?: Uuid | null;\n}\n\n/**\n * One row of `custom.admin_all_tables` — a table in ANY organization, for the admin section only\n * (the store's walls admit a platform admin to system organizations alone, so `DataHomeTable` cannot\n * list the rest). Answered only on the admin lane for a platform admin; any other caller is refused.\n */\nexport interface AdminTable {\n  table_id: Uuid;\n  table_name: string;\n  organization_id: Uuid;\n  organization_name: string | null;\n  updated_at: string | null;\n  platform_owned: boolean;\n  system: boolean;\n}\n\n// ── G10: a synced sheet is one table that refreshes ────────────────────────────────────\n\n/** Where a synced table comes from. `external_id` is the source's own id (a spreadsheet id). */\nexport interface TableSyncSource {\n  provider: string;\n  external_id: string;\n  tab_id?: string | null;\n  synced_at?: string | null;\n}\n\n/** What `custom.table_sync` takes: the source, its columns, and every row it has NOW. */\nexport interface TableSyncSpec {\n  source: TableSyncSource;\n  table_name: string;\n  columns: string[];\n  rows: { ref: string; values: Record<string, string | number | boolean | null> }[];\n}\n\nexport interface TableSyncResult {\n  table_id: Uuid;\n  created: boolean;\n  fields_added: number;\n  rows_inserted: number;\n  rows_updated: number;\n  rows_archived: number;\n  source_system: string;\n}\n\n/**\n * A sheet tab's cells (header row first) → the spec `custom.table_sync` takes. Every row is\n * named by its sheet row number (`row-2` is the first row under the header) unless\n * `refColumn` names a column holding a stable id; a blank or repeated ref is refused here, so\n * the store never sees two rows claiming to be the same source row. Wholly blank rows are\n * skipped. Pure.\n */\nexport function sheetSyncSpec(args: {\n  source: TableSyncSource;\n  tableName: string;\n  cells: readonly (readonly (string | number | boolean | null | undefined)[])[];\n  refColumn?: string;\n}): TableSyncSpec {\n  const [header = [], ...body] = args.cells;\n  const columns = header.map((c, i) => {\n    const name = c == null ? \"\" : String(c).trim();\n    return name === \"\" ? `Column ${i + 1}` : name;\n  });\n  if (columns.length === 0) {\n    throw new Error(\"The sheet has no header row, so there are no columns to sync. Nothing was sent.\");\n  }\n  const seenCol = new Set<string>();\n  for (const c of columns) {\n    if (seenCol.has(c)) throw new Error(`The sheet has two columns named \"${c}\". Rename one and sync again.`);\n    seenCol.add(c);\n  }\n  const refIdx = args.refColumn == null ? -1 : columns.indexOf(args.refColumn);\n  if (args.refColumn != null && refIdx < 0) {\n    throw new Error(`The id column \"${args.refColumn}\" is not in the sheet's header. Nothing was sent.`);\n  }\n  const seen = new Set<string>();\n  const rows: TableSyncSpec[\"rows\"] = [];\n  body.forEach((cells, i) => {\n    if (cells.every((v) => v == null || String(v).trim() === \"\")) return;\n    const ref = refIdx >= 0 ? String(cells[refIdx] ?? \"\").trim() : `row-${i + 2}`;\n    if (ref === \"\") throw new Error(`Sheet row ${i + 2} has no value in the id column \"${args.refColumn}\".`);\n    if (seen.has(ref)) throw new Error(`Two sheet rows share the id \"${ref}\"; each row needs its own.`);\n    seen.add(ref);\n    const values: Record<string, string | number | boolean | null> = {};\n    columns.forEach((c, j) => {\n      const v = cells[j];\n      values[c] = v === undefined || v === \"\" ? null : v;\n    });\n    rows.push({ ref, values });\n  });\n  return { source: args.source, table_name: args.tableName, columns, rows };\n}\n\n/**\n * What `custom.table_copy_sync` takes (lane SYNC-AIRTABLE): a table synced from another table's\n * view — read as the caller, so the copy holds only what that view shows them. Lands through\n * `custom.table_sync` in the caller's active organization (`home_id` defaults to its data home).\n */\nexport interface TableCopySpec {\n  source_organization_id: Uuid;\n  source_table_id: Uuid;\n  view_id?: Uuid | null;\n  table_name?: string | null;\n  home_id?: Uuid | null;\n  /** `on_change` (default): the store's time tick refreshes the copy when the source changes. */\n  auto_refresh?: \"on_change\" | \"off\";\n}\n\n/** Every `custom.table_sync` answer also says when the sync happened and what it could not do. */\nexport interface TableSyncAnswer extends TableSyncResult {\n  rows_restored?: number;\n  rows_kept_archived?: number;\n  rows_total?: number;\n  warnings?: string[];\n  synced_at?: string;\n}\n\n/** How often a synced table refreshes on its own (`sync_source.auto_refresh`). */\nexport type SyncAutoRefresh = \"off\" | \"hourly\" | \"daily\" | \"on_change\";\n\n/** What `custom.table_sync_settings_set` changes on one synced table. */\nexport interface TableSyncSettings {\n  auto_refresh?: SyncAutoRefresh;\n  /** Google Sheets through a connected account only: edits go back to the sheet. */\n  write_back?: boolean;\n}\n\n/** The `sync_source` a synced Table carries (what the store wrote, read back). */\nexport interface TableSyncSourceDocument extends TableSyncSource {\n  label?: string | null;\n  url?: string | null;\n  access?: \"link\" | null;\n  header_row?: number | null;\n  set_by?: Uuid | null;\n  auto_refresh?: SyncAutoRefresh | null;\n  write_back?: boolean | null;\n  source_organization_id?: Uuid | null;\n  due_at?: string | null;\n}\n\n// ── G12: every table counts its rows, every row shows its header ───────────────────────\n\n/** One row of `custom.table_row_counts`: the rows of that Table this reader may see. */\nexport interface TableRowCount {\n  table_id: Uuid;\n  visible_rows: number;\n}\n\n/**\n * One row of `custom.record_headers`: the row's own columns the document door does not answer.\n * `created_by` is the caller's own id on rows the caller made and null on every other; `mine`\n * says which.\n */\nexport interface RecordHeader {\n  id: Uuid;\n  table_id: Uuid;\n  created_at: string;\n  updated_at: string;\n  version: number;\n  deleted_at: string | null;\n  mine: boolean;\n  created_by: Uuid | null;\n}\n\n/**\n * Fold `table_row_counts` onto a table list: `row_count` set on every Table the counts name.\n * A Table the counts do not name keeps what it had — the store answers no row for a Table this\n * reader may not know, and that is never turned into a zero. Pure.\n */\nexport function withRowCounts<T extends { id: Uuid; row_count?: number | null }>(\n  tables: readonly T[],\n  counts: readonly TableRowCount[] | null | undefined,\n): T[] {\n  if (!counts) return [...tables];\n  const byId = new Map(counts.map((c) => [c.table_id, Number(c.visible_rows)]));\n  return tables.map((t) => (byId.has(t.id) ? { ...t, row_count: byId.get(t.id) as number } : t));\n}\n\n// ── G13: a view keeps the order a person dragged ───────────────────────────────────────\n\n/** What `custom.view_record_order_set` answers. */\nexport interface ViewOrderSet {\n  view_id: Uuid;\n  table_id: Uuid;\n  order: \"manual\";\n  named: number;\n  positioned: number;\n}\n\n/**\n * The order to send after a drag: `order` with `moved` taken out and put at `toIndex` (clamped).\n * The store keeps every row the call does not name in its old place after the named ones, so a\n * screen may send only the rows it shows. Pure.\n */\nexport function moveInOrder(order: readonly Uuid[], moved: Uuid, toIndex: number): Uuid[] {\n  const rest = order.filter((id) => id !== moved);\n  const at = Math.max(0, Math.min(Math.trunc(toIndex), rest.length));\n  return [...rest.slice(0, at), moved, ...rest.slice(at)];\n}\n\n// ── G14: a known outsider is granted at once ───────────────────────────────────────────\n\n/**\n * What `custom.table_share_outside_grant` answers. `person` says which path ran:\n * `outside_account` (granted at once and notified — never made a member), `member` (a plain\n * share), `no_account` (the invitation door's own answer, with its link and delivery).\n */\nexport interface OutsideShareAnswer {\n  granted: boolean;\n  invited: boolean;\n  joined: boolean;\n  person: \"outside_account\" | \"member\" | \"no_account\";\n  email: string;\n  table: string;\n  level: string;\n  level_label: string;\n  say: string;\n  user_id?: Uuid;\n  permission_id?: Uuid;\n  invitation_id?: Uuid | null;\n  accept_path?: string | null;\n  delivery_say?: string | null;\n}\n","// src/store.generated.ts — @ai-matrx/records\n//\n// GENERATED. Do not edit by hand: `pnpm records:generate` rewrites it from the\n// live record store, and `pnpm check:store-registry` fails the build when this\n// file and the store disagree. Every literal below was read from the database's\n// own catalog — the vocabularies from the store's vocabulary functions, the\n// parity types from `custom.parity_field_types()`, the doors from `pg_proc`,\n// the kernel ids from the kernel rows themselves, the tokens from\n// `platform.entity_types`.\n//\n// Counts at generation: 3 actor words, 4 absence\n// reasons, 14 parity field types, 32 declarable field kinds,\n// 158 rule node kinds,\n// 9 kernel Tables, 1065 doors, 78 knobs,\n// 1303 entity tokens.\n\nexport const ACTOR_VOCABULARY = [\"user\", \"agent\", \"system\"] as const;\n\n/** The three words the store still accepts and rewrites, and what each becomes. */\nexport const RETIRED_ACTOR_WORDS = {\"ai\": \"agent\", \"code\": \"system\", \"human\": \"user\"} as const;\n\nexport const ABSENCE_REASONS = [\"never asked\", \"none\", \"refused\", \"conflicting\"] as const;\n\nexport const VALUE_ENVELOPE_KEYS = [\"ver\", \"src\", \"actor\", \"on_behalf_of\", \"at\", \"absent\", \"alternates\", \"dated\", \"pinned\"] as const;\n\nexport const VALUE_ALTERNATE_KEYS = [\"value\", \"src\", \"rank\"] as const;\n\nexport const STORAGE_MODES = [\"light\", \"heavy\"] as const;\n\nexport const RULE_USES = [\"validate\", \"compute\", \"membership\", \"applicability\"] as const;\n\nexport const PER_VALUE_ACCESS_WORDS = [\"visibility\", \"access\", \"share\", \"acl\", \"permission\", \"permissions\", \"secret\"] as const;\n\n/** FLD-11's parity floor, each with the behavior it is MADE OF (FLD-1). */\nexport const PARITY_FIELD_TYPES = [\n  { parity_type: \"attachment\", behavior: \"relation\", made_of: \"REC-31: a File record reached through a relation, target the kernel `File` Table\" },\n  { parity_type: \"checkbox\", behavior: \"boolean\", made_of: \"a ticked or unticked answer, stored as a REAL boolean — and a record that never answered holds neither, so filters and group-by see three states, not two\" },\n  { parity_type: \"currency\", behavior: \"range\", made_of: \"FLD-N-1: a number whose UNIT is the currency and whose format is currency — on the Field, never in presentation\" },\n  { parity_type: \"datetime\", behavior: \"range\", made_of: \"a range of kind date or datetime — the dated modifier says the VALUES are dated, which is a different question\" },\n  { parity_type: \"email\", behavior: \"text\", made_of: \"text whose format is email\" },\n  { parity_type: \"formula\", behavior: \"formula\", made_of: \"FLD-9: a declared computation, on read or on write, evaluated by custom.rule_eval\" },\n  { parity_type: \"lookup\", behavior: \"formula\", made_of: \"a Value read THROUGH a relation — config.via names the relation field, config.pick the Value on the far side\" },\n  { parity_type: \"member\", behavior: \"relation\", made_of: \"a person: a relation whose target is the kernel `Person` Table\" },\n  { parity_type: \"multi_select\", behavior: \"list\", made_of: \"many choices from the same Table — the multi modifier, never a second behaviour\" },\n  { parity_type: \"percent\", behavior: \"range\", made_of: \"a number whose unit is % and whose format is percent\" },\n  { parity_type: \"phone\", behavior: \"text\", made_of: \"text whose format is phone\" },\n  { parity_type: \"rollup\", behavior: \"formula\", made_of: \"an aggregate ALONG a relation — config.via, config.of, config.agg; far-side ids are taken DISTINCT, so nothing is counted twice\" },\n  { parity_type: \"select\", behavior: \"list\", made_of: \"one choice from a Table shown as a list (FLD-5/FLD-6)\" },\n  { parity_type: \"url\", behavior: \"text\", made_of: \"text whose format is url, with the pattern Rule that makes the format enforceable\" },\n] as const;\n\n/**\n * THE ONE REGISTRY: every kind a column can be DECLARED as, from\n * `custom.field_kinds()`. `parity` says whether the kind is one of FLD-11's parity\n * floor; the rest are the behaviors and formats the declaration door answers to and\n * nothing else enumerated — which is how `signature` came to be a shape\n * `custom.doc_sign` accepted and no screen could offer.\n */\nexport const DECLARABLE_FIELD_KINDS = [\n  { kind: \"address\", behavior: \"text\", parity: false, made_of: \"P4: behaviour text, format address; the value is {street, city, region, postal_code, country}, every part optional, at least one filled\" },\n  { kind: \"attachment\", behavior: \"relation\", parity: true, made_of: \"REC-31: a File record reached through a relation, target the kernel `File` Table\" },\n  { kind: \"barcode\", behavior: \"text\", parity: false, made_of: \"P4: behaviour text, format barcode; one printable line a scanner reads, config.symbology optional (custom.barcode_symbologies()), EAN/UPC digits and check digit enforced\" },\n  { kind: \"button\", behavior: \"text\", parity: false, made_of: \"NOTION-PROPS-2: behaviour text, format button; holds no value. config.button says what a press does through custom.button_press: open_url (url, {{field id}} filled from the row), run_automation (one of the table's automations, on this row) or run_action (one of its row actions, which sets fields), or add_row (a new row in this table or table_id's, prefilled from this row by prefill, opened); a button with no do yet is a label only\" },\n  { kind: \"checkbox\", behavior: \"boolean\", parity: true, made_of: \"a ticked or unticked answer, stored as a REAL boolean — and a record that never answered holds neither, so filters and group-by see three states, not two\" },\n  { kind: \"count\", behavior: \"formula\", parity: false, made_of: \"P4: a roll-up whose config.agg is count, with format count: how many records a many-relation points at, as a number of its own\" },\n  { kind: \"created_by\", behavior: \"formula\", parity: false, made_of: \"P4: a formula Field whose config.system is created_by: who made the record, {id, name}, filled by the store from the record's writer on read and never typed\" },\n  { kind: \"currency\", behavior: \"range\", parity: true, made_of: \"FLD-N-1: a number whose UNIT is the currency and whose format is currency — on the Field, never in presentation\" },\n  { kind: \"datetime\", behavior: \"range\", parity: true, made_of: \"a range of kind date or datetime — the dated modifier says the VALUES are dated, which is a different question\" },\n  { kind: \"duration\", behavior: \"range\", parity: false, made_of: \"P4: behaviour range, format duration, unit seconds; a length of time kept as seconds, never below zero\" },\n  { kind: \"email\", behavior: \"text\", parity: true, made_of: \"text whose format is email\" },\n  { kind: \"entity_reference\", behavior: \"relation\", parity: false, made_of: \"SC-R / P12: a relation whose target mode is any (REL-8), restricted by config.allowed_types to the platform kinds it may name (custom.entity_reference_kinds() — agents, notes, web sites, workbooks, datasets, conversations …); each value is {token, id}, the edge a platform.associations row record → <token>. File and Person stay relations to their kernel Tables\" },\n  { kind: \"formula\", behavior: \"formula\", parity: true, made_of: \"FLD-9: a declared computation, on read or on write, evaluated by custom.rule_eval\" },\n  { kind: \"json\", behavior: \"text\", parity: false, made_of: \"W2-A: behaviour text, format json; any JSON value (object, list, number, words, yes/no) kept as jsonb, shown collapsed\" },\n  { kind: \"long_text\", behavior: \"text\", parity: false, made_of: \"behaviour text with format long and config.multiline, for several lines rather than one\" },\n  { kind: \"lookup\", behavior: \"formula\", parity: true, made_of: \"a Value read THROUGH a relation — config.via names the relation field, config.pick the Value on the far side\" },\n  { kind: \"member\", behavior: \"relation\", parity: true, made_of: \"a person: a relation whose target is the kernel `Person` Table\" },\n  { kind: \"modified_by\", behavior: \"formula\", parity: false, made_of: \"P4: a formula Field whose config.system is modified_by: who last changed the record, {id, name}, filled by the store on read and never typed\" },\n  { kind: \"multi_select\", behavior: \"list\", parity: true, made_of: \"many choices from the same Table — the multi modifier, never a second behaviour\" },\n  { kind: \"number\", behavior: \"range\", parity: false, made_of: \"a plain number: behaviour range with no date kind and neither the currency nor the percent format\" },\n  { kind: \"percent\", behavior: \"range\", parity: true, made_of: \"a number whose unit is % and whose format is percent\" },\n  { kind: \"phone\", behavior: \"text\", parity: true, made_of: \"text whose format is phone\" },\n  { kind: \"rating\", behavior: \"range\", parity: false, made_of: \"P4: behaviour range, format rating; a whole number of stars from 0 to its max Rule (1 to 10, default 5), shown as stars\" },\n  { kind: \"relation\", behavior: \"relation\", parity: false, made_of: \"REL / FLD-11: a relation a person aims themselves — relation_target names a Table of this organization, and it is a BEHAVIOUR, never a parity type of its own\" },\n  { kind: \"rich_text\", behavior: \"text\", parity: false, made_of: \"P4: behaviour text, format rich_text; Markdown with no raw HTML and no script links, shown formatted\" },\n  { kind: \"rollup\", behavior: \"formula\", parity: true, made_of: \"an aggregate ALONG a relation — config.via, config.of, config.agg; far-side ids are taken DISTINCT, so nothing is counted twice\" },\n  { kind: \"select\", behavior: \"list\", parity: true, made_of: \"one choice from a Table shown as a list (FLD-5/FLD-6)\" },\n  { kind: \"signature\", behavior: \"text\", parity: false, made_of: \"VAL-10: behaviour text whose format is signature — the one shape custom.doc_sign accepts, sealed by custom.doc_signature_write and checked by custom.doc_signature_intact\" },\n  { kind: \"status\", behavior: \"list\", parity: false, made_of: \"P4: a single-choice list with format status; config.status_groups puts each choice key in todo, in_progress or done (Notion's Status)\" },\n  { kind: \"text\", behavior: \"text\", parity: false, made_of: \"plain text: behaviour text with no format — it carries no parity type, which is exactly what custom.parity_type answers for it\" },\n  { kind: \"time\", behavior: \"text\", parity: false, made_of: \"W2-A: behaviour text, format time; a time of day with no date kept as 24-hour HH:MM or HH:MM:SS (zero-padded, so its text order is its time order); HOUR, MINUTE and SECOND read it\" },\n  { kind: \"url\", behavior: \"text\", parity: true, made_of: \"text whose format is url, with the pattern Rule that makes the format enforceable\" },\n] as const;\n\n/** The node kinds `custom.rule_eval` evaluates, and the lane that owns each. */\nexport const RULE_NODE_KINDS = [\n  { node: \"actor_at_least\", evaluated_by: \"PIPELINES\" },\n  { node: \"add\", evaluated_by: \"W1-RULE\" },\n  { node: \"and\", evaluated_by: \"W1-RULE\" },\n  { node: \"concat\", evaluated_by: \"W1-RULE\" },\n  { node: \"const\", evaluated_by: \"W1-RULE\" },\n  { node: \"contains\", evaluated_by: \"NOTION-Q\" },\n  { node: \"div\", evaluated_by: \"W1-RULE\" },\n  { node: \"eq\", evaluated_by: \"W1-RULE\" },\n  { node: \"field\", evaluated_by: \"W1-RULE\" },\n  { node: \"fx.abs\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.add\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.and\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.arraycompact\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.arrayflatten\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.arrayjoin\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.arrayslice\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.arrayunique\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.at\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.autonumber\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.average\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.blank\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.ceiling\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.concatenate\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.contains\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.count\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.counta\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.countall\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.created_time\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.current\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.current1\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.current2\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.dateadd\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.datediff\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.datestr\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.datetime_diff\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.datetime_format\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.datetime_parse\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.day\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.div\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.encode_url_component\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.eq\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.error\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.even\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.every\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.exp\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.false\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.filter\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.find\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.findfirst\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.first\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.floor\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.fromnow\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.gt\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.gte\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.hour\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.if\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.includes\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.index\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.int\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.is_after\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.is_before\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.is_same\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.isblank\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.iserror\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.join\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.last\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.last_modified_time\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.left\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.len\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.length\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.log\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.lower\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.lt\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.lte\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.map\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.max\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.median\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.mid\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.min\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.minute\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.mod\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.modified_time\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.month\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.mul\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.ne\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.neg\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.not\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.now\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.odd\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.or\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.power\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.record_id\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.recprop\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.regex_extract\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.regex_match\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.regex_replace\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.regexreplace\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.replace\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.rept\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.reverse\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.right\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.round\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.rounddown\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.roundup\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.search\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.second\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.set_locale\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.set_timezone\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.slice\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.some\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.sort\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.split\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.sqrt\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.sub\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.substitute\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.sum\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.switch\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.t\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.timestr\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.today\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.tonow\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.trim\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.true\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.unique\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.upper\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.value\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.weekday\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.weeknum\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.workday\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.workday_diff\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.xor\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"fx.year\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n  { node: \"gt\", evaluated_by: \"W1-RULE\" },\n  { node: \"gte\", evaluated_by: \"W1-RULE\" },\n  { node: \"has_all\", evaluated_by: \"NOTION-Q\" },\n  { node: \"has_any\", evaluated_by: \"NOTION-Q\" },\n  { node: \"has_none\", evaluated_by: \"NOTION-Q\" },\n  { node: \"is_empty\", evaluated_by: \"NOTION-Q\" },\n  { node: \"is_exactly\", evaluated_by: \"NOTION-Q\" },\n  { node: \"is_not_empty\", evaluated_by: \"NOTION-Q\" },\n  { node: \"length\", evaluated_by: \"W1-RULE\" },\n  { node: \"linked\", evaluated_by: \"NOTION-Q\" },\n  { node: \"lt\", evaluated_by: \"W1-RULE\" },\n  { node: \"lte\", evaluated_by: \"W1-RULE\" },\n  { node: \"matches\", evaluated_by: \"W1-RULE\" },\n  { node: \"merge_field\", evaluated_by: \"W5-MERGE-B\" },\n  { node: \"mul\", evaluated_by: \"W1-RULE\" },\n  { node: \"ne\", evaluated_by: \"W1-RULE\" },\n  { node: \"not\", evaluated_by: \"W1-RULE\" },\n  { node: \"not_contains\", evaluated_by: \"NOTION-Q\" },\n  { node: \"or\", evaluated_by: \"W1-RULE\" },\n  { node: \"parent_field\", evaluated_by: \"W1-RULE-APPLY\" },\n  { node: \"present\", evaluated_by: \"W1-RULE\" },\n  { node: \"previous\", evaluated_by: \"PIPELINES\" },\n  { node: \"sibling_count\", evaluated_by: \"STAGE-RULES\" },\n  { node: \"stage_count\", evaluated_by: \"PIPELINES\" },\n  { node: \"sub\", evaluated_by: \"W1-RULE\" },\n  { node: \"within\", evaluated_by: \"CHAIR-FILTER\" },\n] as const;\n\n/**\n * What each formula node answers (`custom.formula_node_kinds()`): number, text, boolean, date or unknown.\n * Generated, so a function the store adds can never be missing from a screen that types a formula.\n */\nexport const FORMULA_NODE_RESULTS: Readonly<Record<string, string>> = {\n  \"fx.abs\": \"number\",\n  \"fx.add\": \"number\",\n  \"fx.and\": \"boolean\",\n  \"fx.arraycompact\": \"unknown\",\n  \"fx.arrayflatten\": \"unknown\",\n  \"fx.arrayjoin\": \"text\",\n  \"fx.arrayslice\": \"unknown\",\n  \"fx.arrayunique\": \"unknown\",\n  \"fx.at\": \"unknown\",\n  \"fx.autonumber\": \"number\",\n  \"fx.average\": \"number\",\n  \"fx.blank\": \"unknown\",\n  \"fx.ceiling\": \"number\",\n  \"fx.concatenate\": \"text\",\n  \"fx.contains\": \"boolean\",\n  \"fx.count\": \"number\",\n  \"fx.counta\": \"number\",\n  \"fx.countall\": \"number\",\n  \"fx.created_time\": \"date\",\n  \"fx.current\": \"unknown\",\n  \"fx.current1\": \"unknown\",\n  \"fx.current2\": \"unknown\",\n  \"fx.dateadd\": \"date\",\n  \"fx.datediff\": \"number\",\n  \"fx.datestr\": \"text\",\n  \"fx.datetime_diff\": \"number\",\n  \"fx.datetime_format\": \"text\",\n  \"fx.datetime_parse\": \"date\",\n  \"fx.day\": \"number\",\n  \"fx.div\": \"number\",\n  \"fx.encode_url_component\": \"text\",\n  \"fx.eq\": \"boolean\",\n  \"fx.error\": \"unknown\",\n  \"fx.even\": \"number\",\n  \"fx.every\": \"boolean\",\n  \"fx.exp\": \"number\",\n  \"fx.false\": \"boolean\",\n  \"fx.filter\": \"unknown\",\n  \"fx.find\": \"number\",\n  \"fx.findfirst\": \"unknown\",\n  \"fx.first\": \"unknown\",\n  \"fx.floor\": \"number\",\n  \"fx.fromnow\": \"number\",\n  \"fx.gt\": \"boolean\",\n  \"fx.gte\": \"boolean\",\n  \"fx.hour\": \"number\",\n  \"fx.if\": \"unknown\",\n  \"fx.includes\": \"boolean\",\n  \"fx.index\": \"number\",\n  \"fx.int\": \"number\",\n  \"fx.is_after\": \"boolean\",\n  \"fx.is_before\": \"boolean\",\n  \"fx.is_same\": \"boolean\",\n  \"fx.isblank\": \"boolean\",\n  \"fx.iserror\": \"boolean\",\n  \"fx.join\": \"text\",\n  \"fx.last\": \"unknown\",\n  \"fx.last_modified_time\": \"date\",\n  \"fx.left\": \"text\",\n  \"fx.len\": \"number\",\n  \"fx.length\": \"number\",\n  \"fx.log\": \"number\",\n  \"fx.lower\": \"text\",\n  \"fx.lt\": \"boolean\",\n  \"fx.lte\": \"boolean\",\n  \"fx.map\": \"unknown\",\n  \"fx.max\": \"number\",\n  \"fx.median\": \"number\",\n  \"fx.mid\": \"text\",\n  \"fx.min\": \"number\",\n  \"fx.minute\": \"number\",\n  \"fx.mod\": \"number\",\n  \"fx.modified_time\": \"date\",\n  \"fx.month\": \"number\",\n  \"fx.mul\": \"number\",\n  \"fx.ne\": \"boolean\",\n  \"fx.neg\": \"number\",\n  \"fx.not\": \"boolean\",\n  \"fx.now\": \"date\",\n  \"fx.odd\": \"number\",\n  \"fx.or\": \"boolean\",\n  \"fx.power\": \"number\",\n  \"fx.record_id\": \"text\",\n  \"fx.recprop\": \"unknown\",\n  \"fx.regex_extract\": \"text\",\n  \"fx.regex_match\": \"boolean\",\n  \"fx.regex_replace\": \"text\",\n  \"fx.regexreplace\": \"text\",\n  \"fx.replace\": \"text\",\n  \"fx.rept\": \"text\",\n  \"fx.reverse\": \"unknown\",\n  \"fx.right\": \"text\",\n  \"fx.round\": \"number\",\n  \"fx.rounddown\": \"number\",\n  \"fx.roundup\": \"number\",\n  \"fx.search\": \"number\",\n  \"fx.second\": \"number\",\n  \"fx.set_locale\": \"date\",\n  \"fx.set_timezone\": \"date\",\n  \"fx.slice\": \"unknown\",\n  \"fx.some\": \"boolean\",\n  \"fx.sort\": \"unknown\",\n  \"fx.split\": \"unknown\",\n  \"fx.sqrt\": \"number\",\n  \"fx.sub\": \"number\",\n  \"fx.substitute\": \"text\",\n  \"fx.sum\": \"number\",\n  \"fx.switch\": \"unknown\",\n  \"fx.t\": \"text\",\n  \"fx.timestr\": \"text\",\n  \"fx.today\": \"date\",\n  \"fx.tonow\": \"number\",\n  \"fx.trim\": \"text\",\n  \"fx.true\": \"boolean\",\n  \"fx.unique\": \"unknown\",\n  \"fx.upper\": \"text\",\n  \"fx.value\": \"number\",\n  \"fx.weekday\": \"number\",\n  \"fx.weeknum\": \"number\",\n  \"fx.workday\": \"date\",\n  \"fx.workday_diff\": \"number\",\n  \"fx.xor\": \"boolean\",\n  \"fx.year\": \"number\",\n};\n\n/** REC-27. The kernel, by name and by id, as the store holds it. */\nexport const KERNEL_TABLES = [\n  { id: \"11111111-0000-4000-8000-000000000002\", name: \"Field\" },\n  { id: \"11111111-0000-4000-8000-000000000006\", name: \"File\" },\n  { id: \"11111111-0000-4000-8000-000000000009\", name: \"Merge Field\" },\n  { id: \"11111111-0000-4000-8000-000000000004\", name: \"Organization\" },\n  { id: \"11111111-0000-4000-8000-000000000005\", name: \"Person\" },\n  { id: \"11111111-0000-4000-8000-000000000007\", name: \"Presentation\" },\n  { id: \"11111111-0000-4000-8000-000000000003\", name: \"Rule\" },\n  { id: \"11111111-0000-4000-8000-000000000001\", name: \"Table\" },\n  { id: \"11111111-0000-4000-8000-000000000008\", name: \"Widget\" },\n] as const;\n\n/**\n * Every door the store actually has, with the argument list and the result the\n * catalog reports. A client call whose door is not in this list is answered\n * `door_absent` by name — never a guess, never a silent no-op.\n */\nexport const STORE_DOORS = [\n  { name: \"absence_reasons\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"action_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_actions jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"action_run\", args: \"p_organization_id uuid, p_action_id uuid, p_record_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"actor_vocabulary\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"actor_word\", args: \"p_declared text\", returns: \"text\", security: \"invoker\" },\n  { name: \"addressed_cap\", args: \"p_user_id uuid, p_type text, p_id uuid, p_organization_id uuid DEFAULT NULL::uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"permission_level\", security: \"definer\" },\n  { name: \"addressed_cap_specific\", args: \"p_user_id uuid, p_type text, p_id uuid, p_organization_id uuid DEFAULT NULL::uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"permission_level\", security: \"definer\" },\n  { name: \"admin_all_tables\", args: \"\", returns: \"TABLE(table_id uuid, table_name text, organization_id uuid, organization_name text, updated_at timestamp with time zone, platform_owned boolean, system boolean)\", security: \"definer\" },\n  { name: \"agent_change_approval\", args: \"p_organization uuid, p_conversation uuid DEFAULT NULL::uuid, p_table uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"agent_change_trust\", args: \"p_organization_id uuid, p_approval_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"agent_context\", args: \"p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 50\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agent_context_value\", args: \"p_doc jsonb, p_key text, p_type text, p_organization_id uuid, p_record_id uuid, p_cap bigint\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agent_context_value_cap\", args: \"p_organization_id uuid\", returns: \"bigint\", security: \"invoker\" },\n  { name: \"agent_table_claim\", args: \"p_organization uuid, p_table uuid, p_conversation uuid DEFAULT NULL::uuid\", returns: \"void\", security: \"definer\" },\n  { name: \"agg_assert_key\", args: \"p_key text\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_bucket_ordinal\", args: \"p_by text, p_window_from timestamp without time zone, p_at timestamp without time zone, p_week_start text\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_buckets\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"agg_cadence_normalize\", args: \"p_cadence text\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_calendar\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agg_compare_kinds\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"agg_compare_windows\", args: \"p_organization_id uuid, p_compare jsonb, p_bucket jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agg_deliver\", args: \"p_organization_id uuid, p_rule_id uuid, p_record_id uuid, p_channel text, p_recipient_user_id uuid, p_event_key text, p_subject text, p_body text, p_payload jsonb DEFAULT '{}'::jsonb, p_dedupe_suffix text DEFAULT NULL::text\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"agg_deliver_quietly\", args: \"p_organization_id uuid, p_rule_id uuid, p_subject_id uuid, p_channel text, p_recipient_user_id uuid, p_event_key text, p_subject text, p_body text, p_payload jsonb, p_quiet_hours jsonb, p_link text, p_dedupe_suffix text DEFAULT NULL::text\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"agg_delta\", args: \"p_current jsonb, p_prior jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agg_digest_assemble\", args: \"p_organization_id uuid, p_rule_id uuid, p_since timestamp with time zone DEFAULT NULL::timestamp with time zone, p_until timestamp with time zone DEFAULT NULL::timestamp with time zone\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agg_digest_due_at\", args: \"p_cadence text, p_schedule text, p_quiet jsonb, p_after timestamp with time zone\", returns: \"timestamp with time zone\", security: \"invoker\" },\n  { name: \"agg_digest_judged_at\", args: \"p_organization_id uuid, p_rule_id uuid\", returns: \"timestamp with time zone\", security: \"invoker\" },\n  { name: \"agg_digest_run\", args: \"p_organization_id uuid, p_rule_id uuid DEFAULT NULL::uuid, p_since timestamp with time zone DEFAULT NULL::timestamp with time zone\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_digest_run_at\", args: \"p_organization_id uuid, p_rule_id uuid, p_since timestamp with time zone, p_now timestamp with time zone\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_digest_tick\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_digest_tick_at\", args: \"p_now timestamp with time zone, p_organization_id uuid DEFAULT NULL::uuid\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_explain\", args: \"p_organization_id uuid, p_table_id uuid, p_group_by jsonb DEFAULT '[]'::jsonb, p_measures jsonb DEFAULT '[]'::jsonb, p_bucket jsonb DEFAULT NULL::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_required text DEFAULT 'viewer'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"agg_field_kind\", args: \"p_organization_id uuid, p_table_id uuid, p_key text\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_field_value_sql\", args: \"p_organization_id uuid, p_table_id uuid, p_key text\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_fields_readable_assert\", args: \"p_organization_id uuid, p_table_id uuid, p_keys text[], p_required text DEFAULT 'viewer'::text\", returns: \"void\", security: \"invoker\" },\n  { name: \"agg_group_value\", args: \"p_value text, p_kind text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agg_last_digest_at\", args: \"p_organization_id uuid, p_rule_id uuid\", returns: \"timestamp with time zone\", security: \"invoker\" },\n  { name: \"agg_local_label\", args: \"p_local timestamp without time zone, p_tz text\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_moment_sql\", args: \"p_key text, p_tz text\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_operations\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"agg_parse_moment\", args: \"p_raw text, p_tz text, p_what text\", returns: \"timestamp with time zone\", security: \"invoker\" },\n  { name: \"agg_period_start\", args: \"p_local timestamp without time zone, p_by text, p_week_start text DEFAULT 'monday'::text\", returns: \"timestamp without time zone\", security: \"invoker\" },\n  { name: \"agg_period_step\", args: \"p_by text\", returns: \"interval\", security: \"invoker\" },\n  { name: \"agg_quiet_until\", args: \"p_quiet jsonb, p_at timestamp with time zone\", returns: \"timestamp with time zone\", security: \"invoker\" },\n  { name: \"agg_record_name\", args: \"p_organization_id uuid, p_record_id uuid, p_state jsonb DEFAULT NULL::jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_split_parts\", args: \"p_organization_id uuid, p_table_id uuid, p_key text, p_alias text\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"agg_sql\", args: \"p_organization_id uuid, p_table_id uuid, p_group_by jsonb DEFAULT '[]'::jsonb, p_measures jsonb DEFAULT '[]'::jsonb, p_bucket jsonb DEFAULT NULL::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_limit integer DEFAULT 200, p_required text DEFAULT 'viewer'::text, p_window jsonb DEFAULT NULL::jsonb, p_search text DEFAULT NULL::text, p_time_zone text DEFAULT NULL::text, p_split_multi boolean DEFAULT false\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_subscription_cadences\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"agg_subscription_fire\", args: \"p_organization_id uuid, p_record_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_changed_field_ids jsonb DEFAULT '[]'::jsonb\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_subscription_fire_entered\", args: \"p_organization_id uuid, p_record_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_since timestamp with time zone DEFAULT NULL::timestamp with time zone\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_subscription_tick\", args: \"p_window interval DEFAULT '00:15:00'::interval\", returns: \"integer\", security: \"invoker\" },\n  { name: \"agg_subscriptions\", args: \"p_organization_id uuid, p_saved_view_id uuid DEFAULT NULL::uuid, p_cadence text DEFAULT NULL::text\", returns: \"TABLE(rule_id uuid, saved_view_id uuid, table_id uuid, cadence text, schedule text, quiet_hours jsonb, channel text, recipient_user_id uuid, event_key text, name text)\", security: \"invoker\" },\n  { name: \"agg_value_sql\", args: \"p_key text\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_value_text\", args: \"p_value jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"agg_view_admits\", args: \"p_organization_id uuid, p_saved_view_id uuid, p_record_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"agg_view_admits_state\", args: \"p_definition jsonb, p_state jsonb\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"agg_withheld_marker\", args: \"p_organization_id uuid, p_table_id uuid, p_key text, p_required text DEFAULT 'viewer'::text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"agg_zero\", args: \"p_measures jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"anon_capture\", args: \"p_organization_id uuid, p_client_key text, p_table_id uuid, p_payload jsonb, p_device text DEFAULT NULL::text, p_captured_at timestamp with time zone DEFAULT NULL::timestamp with time zone\", returns: \"uuid\", security: \"definer\" },\n  { name: \"anon_clear\", args: \"p_organization_id uuid, p_submission_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"anon_inbound_land\", args: \"p_address text, p_secret text, p_payload jsonb, p_raw_payload jsonb DEFAULT '{}'::jsonb, p_client_key text DEFAULT NULL::text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"anon_publish\", args: \"p_organization_id uuid, p_form_id uuid, p_published boolean DEFAULT true\", returns: \"timestamp with time zone\", security: \"definer\" },\n  { name: \"anon_rate_take\", args: \"p_organization_id uuid, p_form_id uuid, p_bucket text, p_token_id uuid DEFAULT NULL::uuid\", returns: \"integer\", security: \"definer\" },\n  { name: \"anon_submissions\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_state text DEFAULT NULL::text, p_limit integer DEFAULT 100, p_offset integer DEFAULT 0\", returns: \"TABLE(id uuid, form_id uuid, inbound_id uuid, table_id uuid, source text, state text, payload jsonb, raw_payload jsonb, client_key text, record_id uuid, remote_origin text, rejection_reason text, created_at timestamp with time zone, cleared_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"anon_token_issue\", args: \"p_organization_id uuid, p_mode text, p_allowed_origins jsonb, p_form_id uuid DEFAULT NULL::uuid, p_saved_view_id uuid DEFAULT NULL::uuid, p_record_id uuid DEFAULT NULL::uuid, p_expires_at timestamp with time zone DEFAULT NULL::timestamp with time zone\", returns: \"TABLE(token_id uuid, secret text)\", security: \"definer\" },\n  { name: \"anon_token_revoke\", args: \"p_organization_id uuid, p_token_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"anon_token_verify\", args: \"p_secret text, p_origin text, p_required_mode text\", returns: \"TABLE(token_id uuid, organization_id uuid, form_id uuid, saved_view_id uuid, record_id uuid, mode text)\", security: \"definer\" },\n  { name: \"anon_write\", args: \"p_secret text, p_origin text, p_payload jsonb, p_client_key text DEFAULT NULL::text, p_raw_payload jsonb DEFAULT '{}'::jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"applicable_fields\", args: \"p_organization_id uuid, p_table_id uuid, p_record_type text DEFAULT NULL::text\", returns: \"SETOF custom.record\", security: \"definer\" },\n  { name: \"archive_event_of\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"history.migration_log\", security: \"definer\" },\n  { name: \"archive_guard_count\", args: \"p_value jsonb\", returns: \"integer\", security: \"invoker\" },\n  { name: \"archive_guard_decide\", args: \"p_organization_id uuid, p_scope text, p_live_before integer, p_ids text[], p_confirm text, p_log jsonb, p_now timestamp with time zone DEFAULT now(), p_share numeric DEFAULT NULL::numeric, p_hours numeric DEFAULT NULL::numeric\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"archive_guard_knob\", args: \"p_key text, p_organization_id uuid\", returns: \"numeric\", security: \"invoker\" },\n  { name: \"archive_guard_log_add\", args: \"p_log jsonb, p_entry jsonb, p_organization_id uuid, p_now timestamp with time zone DEFAULT now()\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"archive_guard_when\", args: \"p_value jsonb\", returns: \"timestamp with time zone\", security: \"invoker\" },\n  { name: \"archive_hold_answer\", args: \"p_organization_id uuid, p_table_id uuid, p_answer text, p_token text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"archived_tables_everywhere\", args: \"p_lane text DEFAULT 'org'::text, p_limit integer DEFAULT 100, p_offset integer DEFAULT 0, p_sort text DEFAULT 'archived_at'::text, p_desc boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"assert_client_may_change\", args: \"p_organization_id uuid, p_subject_id uuid, p_door text, p_required permission_level DEFAULT 'editor'::permission_level, p_subject_word text DEFAULT 'record'::text\", returns: \"void\", security: \"invoker\" },\n  { name: \"assert_client_may_open\", args: \"p_organization_id uuid, p_subject_id uuid, p_door text, p_required permission_level DEFAULT 'viewer'::permission_level, p_subject_word text DEFAULT 'record'::text\", returns: \"void\", security: \"invoker\" },\n  { name: \"assert_client_may_reach\", args: \"p_organization_id uuid, p_door text\", returns: \"void\", security: \"invoker\" },\n  { name: \"assert_columns_are_defined\", args: \"p_organization_id uuid, p_record_id uuid, p_patch jsonb\", returns: \"void\", security: \"definer\" },\n  { name: \"assert_entity_door\", args: \"p_organization_id uuid, p_door text\", returns: \"void\", security: \"definer\" },\n  { name: \"assert_entity_is_organization_scoped\", args: \"p_token text, p_label text, p_scoped boolean\", returns: \"void\", security: \"invoker\" },\n  { name: \"assert_may_know_table\", args: \"p_organization_id uuid, p_table_id uuid, p_door text\", returns: \"void\", security: \"invoker\" },\n  { name: \"assert_organization_admin\", args: \"p_organization_id uuid, p_door text, p_what text\", returns: \"void\", security: \"invoker\" },\n  { name: \"assert_organization_wall\", args: \"p_kind text, p_organization_id uuid, p_row jsonb\", returns: \"void\", security: \"invoker\" },\n  { name: \"assert_public_reader_names_a_public_table\", args: \"p_organization_id uuid, p_table_id uuid, p_door text\", returns: \"void\", security: \"definer\" },\n  { name: \"assert_scope_door\", args: \"p_organization_id uuid, p_door text\", returns: \"void\", security: \"definer\" },\n  { name: \"assert_store_door\", args: \"p_organization_id uuid, p_door text\", returns: \"void\", security: \"invoker\" },\n  { name: \"automation_app_event\", args: \"p_automation_id uuid, p_items jsonb, p_cursor jsonb, p_expected_owner text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_app_may_edit\", args: \"p_automation_id uuid, p_user_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"automation_app_note\", args: \"p_automation_id uuid, p_says text, p_cursor jsonb, p_expected_owner text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_app_stop\", args: \"p_automation_id uuid, p_says text, p_expected_owner text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_app_watch\", args: \"p_automation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_archive\", args: \"p_organization_id uuid, p_automation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_claim_pending\", args: \"p_worker text, p_limit integer DEFAULT 5, p_lease_seconds integer DEFAULT 180\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_spec jsonb, p_automation_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_delivery_tick\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"automation_note\", args: \"p_run_id uuid, p_says text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_restore\", args: \"p_organization_id uuid, p_automation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_resume\", args: \"p_run_id uuid, p_output jsonb, p_error text DEFAULT NULL::text, p_logs jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_revision_restore\", args: \"p_organization_id uuid, p_automation_id uuid, p_revision_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_revisions\", args: \"p_organization_id uuid, p_automation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_runs\", args: \"p_automation_id uuid, p_limit integer DEFAULT 50, p_cursor timestamp with time zone DEFAULT NULL::timestamp with time zone, p_organization_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_set_enabled\", args: \"p_organization_id uuid, p_automation_id uuid, p_enabled boolean\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_step_mark\", args: \"p_run_id uuid, p_n integer, p_state text, p_output jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_test\", args: \"p_organization_id uuid, p_automation_id uuid, p_record_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automation_time_tick\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"automation_webhook_receive\", args: \"p_automation_id uuid, p_secret text, p_body jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"automations\", args: \"p_table_id uuid, p_organization_id uuid DEFAULT NULL::uuid, p_include_archived boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"autonumber_backfill\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"barcode_symbologies\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"base_activity\", args: \"p_organization_id uuid, p_subject_id uuid, p_limit integer DEFAULT 50, p_before bigint DEFAULT NULL::bigint\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"base_copy_finish\", args: \"p_organization_id uuid, p_pairs jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"base_move\", args: \"p_home_id uuid, p_to_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"base_move_access_kept\", args: \"p_home_id uuid, p_to_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"base_move_remove_access\", args: \"p_home_id uuid, p_user_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"booking_busy_due\", args: \"p_form_id uuid\", returns: \"TABLE(feed text, due boolean, timezone text, days integer, read_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"booking_busy_set\", args: \"p_form_id uuid, p_busy jsonb, p_problem text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"booking_cancel\", args: \"p_booking_ref text, p_origin text DEFAULT NULL::text\", returns: \"TABLE(booking_ref text, record_id uuid, slot_key text, state text, message text)\", security: \"definer\" },\n  { name: \"booking_confirm\", args: \"p_form_id uuid, p_hold_id uuid, p_origin text, p_payload jsonb, p_bucket text, p_honeypot text DEFAULT NULL::text, p_client_key text DEFAULT NULL::text\", returns: \"TABLE(booking_ref text, record_id uuid, submission_id uuid, slot_key text, slot_at timestamp with time zone, state text, message text)\", security: \"definer\" },\n  { name: \"booking_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_title text, p_questions jsonb, p_availability jsonb DEFAULT '{}'::jsonb, p_presentation jsonb DEFAULT '{}'::jsonb, p_submission_cap integer DEFAULT NULL::integer, p_quarantine_rule_id uuid DEFAULT NULL::uuid, p_notify_rule_id uuid DEFAULT NULL::uuid, p_form_id uuid DEFAULT NULL::uuid, p_slug text DEFAULT NULL::text, p_home_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"booking_hold\", args: \"p_form_id uuid, p_slot_key text, p_origin text, p_bucket text, p_client_key text DEFAULT NULL::text\", returns: \"TABLE(hold_id uuid, slot_key text, expires_at timestamp with time zone, member_user_id uuid, state text, message text)\", security: \"definer\" },\n  { name: \"booking_manage\", args: \"p_booking_ref text, p_days integer DEFAULT NULL::integer\", returns: \"TABLE(booking_ref text, form_id uuid, title text, slot_key text, slot_at timestamp with time zone, status text, slots jsonb, availability jsonb, state text, message text)\", security: \"definer\" },\n  { name: \"booking_messages\", args: \"p_organization_id uuid, p_form_id uuid, p_record_id uuid, p_submission_id uuid, p_event text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"booking_notify\", args: \"p_organization_id uuid, p_form_id uuid, p_record_id uuid, p_submission_id uuid, p_event text, p_when text\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"booking_public\", args: \"p_form_id uuid, p_days integer DEFAULT NULL::integer\", returns: \"TABLE(form_id uuid, organization_id uuid, table_id uuid, title text, presentation jsonb, fields jsonb, honeypot_key text, availability jsonb, slots jsonb, state text, message text)\", security: \"definer\" },\n  { name: \"booking_reschedule\", args: \"p_booking_ref text, p_slot_key text, p_origin text, p_bucket text DEFAULT NULL::text\", returns: \"TABLE(booking_ref text, record_id uuid, slot_key text, slot_at timestamp with time zone, state text, message text)\", security: \"definer\" },\n  { name: \"booking_sms_consent\", args: \"p_booking_ref text, p_phone text, p_text_shown text, p_origin text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"bookings\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(form_id uuid, table_id uuid, title text, slug text, published_at timestamp with time zone, closed_at timestamp with time zone, slot_minutes integer, timezone text, slot_table_id uuid, booked bigint, cancelled bigint, upcoming bigint, held bigint, next_at timestamp with time zone, state text)\", security: \"definer\" },\n  { name: \"bump_epoch\", args: \"p_entity_type text, p_entity_id uuid, p_organization_id uuid DEFAULT NULL::uuid\", returns: \"bigint\", security: \"definer\" },\n  { name: \"button_press\", args: \"p_organization_id uuid, p_record_id uuid, p_field_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"cache_lookup\", args: \"p_container_type text, p_container_id uuid, p_item_type text, p_item_id uuid\", returns: \"permission_level\", security: \"definer\" },\n  { name: \"caller_role\", args: \"\", returns: \"name\", security: \"invoker\" },\n  { name: \"capture_open\", args: \"p_organization_id uuid, p_sheet_id uuid\", returns: \"TABLE(sheet_id uuid, organization_id uuid, table_id uuid, title text, presentation jsonb, fields jsonb, state text, may_capture boolean, message text)\", security: \"definer\" },\n  { name: \"capture_publish\", args: \"p_organization_id uuid, p_sheet_id uuid, p_open boolean DEFAULT true\", returns: \"timestamp with time zone\", security: \"definer\" },\n  { name: \"capture_sheet_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_title text, p_questions jsonb, p_presentation jsonb DEFAULT '{}'::jsonb, p_sheet_id uuid DEFAULT NULL::uuid, p_notify_rule_id uuid DEFAULT NULL::uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"capture_sheets\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(sheet_id uuid, table_id uuid, title text, slug text, state text, opened_at timestamp with time zone, captures bigint, replays bigint, last_capture_at timestamp with time zone, presentation jsonb)\", security: \"definer\" },\n  { name: \"capture_submit\", args: \"p_organization_id uuid, p_sheet_id uuid, p_client_key text, p_payload jsonb, p_files jsonb DEFAULT '[]'::jsonb, p_device text DEFAULT NULL::text, p_captured_at timestamp with time zone DEFAULT NULL::timestamp with time zone, p_location jsonb DEFAULT NULL::jsonb\", returns: \"TABLE(record_id uuid, state text, message text, replay boolean, file_ids uuid[])\", security: \"definer\" },\n  { name: \"carry_unchanged_value_stamps\", args: \"p_old jsonb, p_new jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"carrying_edges_in\", args: \"p_organization_id uuid\", returns: \"TABLE(container_type text, container_id uuid, item_type text, item_id uuid, conveys_max permission_level)\", security: \"definer\" },\n  { name: \"carrying_edges_of\", args: \"p_item_type text, p_item_id uuid\", returns: \"TABLE(container_type text, container_id uuid, conveys_max permission_level)\", security: \"definer\" },\n  { name: \"checklist_declare\", args: \"p_organization_id uuid, p_spec jsonb, p_template_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"checklist_refusal\", args: \"p_spec jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"checklist_run\", args: \"p_organization_id uuid, p_run_id uuid\", returns: \"TABLE(step_id uuid, step_order integer, ref text, title text, role text, assignee_name text, assignee_user_id uuid, due_on timestamp with time zone, due_state text, status text, finished boolean, requires text, requires_key text, requires_label text, requires_id uuid, evidence jsonb, blocked_by text[], may_complete boolean, refusal text)\", security: \"definer\" },\n  { name: \"checklist_runs\", args: \"p_organization_id uuid, p_about_table_id uuid DEFAULT NULL::uuid, p_about_record_id uuid DEFAULT NULL::uuid, p_include_closed boolean DEFAULT true, p_limit integer DEFAULT 100\", returns: \"TABLE(run_id uuid, name text, template_id uuid, template text, about_record_id uuid, about text, about_table_id uuid, started_at timestamp with time zone, started_by uuid, origin text, step_count integer, done integer, overdue integer, next_step text, next_due timestamp with time zone, closed_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"checklist_start\", args: \"p_organization_id uuid, p_template_id uuid, p_about_record_id uuid DEFAULT NULL::uuid, p_roles jsonb DEFAULT '{}'::jsonb, p_starting_at timestamp with time zone DEFAULT NULL::timestamp with time zone\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"checklist_step_complete\", args: \"p_organization_id uuid, p_step_id uuid, p_evidence jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"checklist_step_refusal\", args: \"p_organization_id uuid, p_step_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"checklist_steps_table\", args: \"p_organization_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"checklist_template_shape\", args: \"p_organization_id uuid, p_template_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"checklist_templates\", args: \"p_organization_id uuid, p_about_table_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 100\", returns: \"TABLE(template_id uuid, name text, about_table_id uuid, about_table text, steps integer, roles integer, trigger_kind text, trigger_status text, open_runs integer, total_runs integer, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"checklist_templates_archived\", args: \"p_organization_id uuid, p_about_table_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 100\", returns: \"TABLE(template_id uuid, name text, about_table_id uuid, about_table text, steps integer, archived_at timestamp with time zone, archived_by uuid, table_archived boolean)\", security: \"definer\" },\n  { name: \"choice_census\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"choice_field_map\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_filter_normalize\", args: \"p_map jsonb, p_filter jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_key_for\", args: \"p_organization_id uuid, p_options_table_id uuid, p_title text, p_exclude uuid DEFAULT NULL::uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"choice_key_of\", args: \"p_field jsonb, p_token text\", returns: \"text\", security: \"invoker\" },\n  { name: \"choice_nudge\", args: \"p_organization_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"choice_options\", args: \"p_organization_id uuid, p_options_table_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_render\", args: \"p_organization_id uuid, p_table_id uuid, p_doc jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_render_groups\", args: \"p_map jsonb, p_groups jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_render_note\", args: \"p_field jsonb, p_value jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_render_plan\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_render_value\", args: \"p_field jsonb, p_value jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_render_with\", args: \"p_organization_id uuid, p_table_id uuid, p_doc jsonb, p_plan jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"choice_slug\", args: \"p_word text\", returns: \"text\", security: \"invoker\" },\n  { name: \"choice_synonyms\", args: \"p_organization_id uuid, p_table_id uuid, p_token text\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"choice_synonyms_in\", args: \"p_map jsonb, p_token text\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"choice_value_keys\", args: \"p_field jsonb, p_value jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"choice_words\", args: \"p_field jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"choice_words_normalize\", args: \"p_field jsonb, p_const jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"client_write_grants\", args: \"\", returns: \"TABLE(role_name text, object_name text, privilege text)\", security: \"invoker\" },\n  { name: \"comment_counts\", args: \"p_organization_id uuid, p_record_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"comment_mention_deliver\", args: \"p_organization_id uuid, p_record_id uuid, p_table_id uuid, p_comment_id uuid, p_recipient uuid, p_author_name text, p_record_title text, p_body text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"comment_thread\", args: \"p_organization_id uuid, p_record_id uuid, p_include_resolved boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"comment_write\", args: \"p_organization_id uuid, p_record_id uuid, p_body text, p_anchor jsonb DEFAULT '{}'::jsonb, p_parent_comment_id uuid DEFAULT NULL::uuid, p_mentions uuid[] DEFAULT NULL::uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"computed_block\", args: \"p_block jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"computed_provenance\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(field_key text, field_id uuid, value jsonb, rule_id uuid, rule_version integer, computed_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"computed_refresh\", args: \"p_org uuid, p_table uuid, p_ids uuid[]\", returns: \"integer\", security: \"invoker\" },\n  { name: \"computed_refresh\", args: \"p_table_id uuid, p_max_rows integer DEFAULT 200\", returns: \"integer\", security: \"definer\" },\n  { name: \"computed_refresh_drain\", args: \"p_ms integer DEFAULT 8000\", returns: \"integer\", security: \"invoker\" },\n  { name: \"computed_refresh_progress\", args: \"p_org uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"computed_sort_ceiling\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"computed_warm\", args: \"p_table_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"confidential_anchor\", args: \"p_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"confidential_answer\", args: \"p_user uuid, p_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level\", returns: \"boolean\", security: \"definer\" },\n  { name: \"confidential_header\", args: \"p_user uuid, p_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"confidential_names\", args: \"p_organization_id uuid, p_value jsonb, p_user uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"containment_chain\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(ancestor_id uuid, depth integer)\", security: \"invoker\" },\n  { name: \"containment_depth_ceiling\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"integer\", security: \"invoker\" },\n  { name: \"containment_edges\", args: \"p_organization_id uuid\", returns: \"TABLE(parent_id uuid, child_id uuid, via text)\", security: \"invoker\" },\n  { name: \"containment_parent\", args: \"p_data jsonb\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"context_archived_types\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_class_for_checkout\", args: \"p_scope_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_compare_facts\", args: \"p_user_id uuid, p_record_ids uuid[], p_item_ids uuid[] DEFAULT NULL::uuid[], p_cells jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_item_archive\", args: \"p_item_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_item_restore\", args: \"p_item_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_item_row_of\", args: \"p_field custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"context_item_write\", args: \"p_item_id uuid, p_scope_type_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_items\", args: \"p_scope_type_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_policy_rank\", args: \"p_policy text\", returns: \"integer\", security: \"invoker\" },\n  { name: \"context_resolve\", args: \"p_bindings jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_scope_archive\", args: \"p_scope_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_scope_restore\", args: \"p_scope_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_scope_write\", args: \"p_organization_id uuid, p_scope_id uuid, p_type_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_scopes\", args: \"p_scope_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_system_items\", args: \"\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_tags_set\", args: \"p_entity_type text, p_entity_id uuid, p_scope_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_template_define\", args: \"p_organization_id uuid, p_definition jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"context_templates\", args: \"\", returns: \"SETOF jsonb\", security: \"invoker\" },\n  { name: \"context_tree\", args: \"p_organization_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_tree_search\", args: \"p_organization_ids uuid[], p_query text, p_limit integer DEFAULT 100\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_tree_type_scopes\", args: \"p_scope_type_id uuid, p_offset integer DEFAULT 0, p_limit integer DEFAULT 200\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_tree_types\", args: \"p_organization_ids uuid[], p_with_counts boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_type_archive\", args: \"p_type_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_type_restore\", args: \"p_type_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_type_write\", args: \"p_organization_id uuid, p_type_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"context_value_write\", args: \"p_payload jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"context_values\", args: \"p_scope_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"conversation_scope\", args: \"p_organization_id uuid, p_conversation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"conversation_scope_bind\", args: \"p_organization_id uuid, p_conversation_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"conversation_scope_context\", args: \"p_organization_id uuid, p_conversation_id uuid, p_relations integer DEFAULT 12, p_history integer DEFAULT 15, p_siblings integer DEFAULT 8\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"conversation_scope_unbind\", args: \"p_organization_id uuid, p_conversation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"copy_table_extras\", args: \"p_organization_id uuid, p_pairs jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"count_records_archived\", args: \"p_organization_id uuid, p_table_ids uuid[], p_lane text DEFAULT 'org'::text\", returns: \"TABLE(table_id uuid, n integer)\", security: \"definer\" },\n  { name: \"cross_organization_links_open\", args: \"p_source_organization_id uuid, p_target_organization_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"custom_fields_on\", args: \"p_organization_id uuid, p_table_token text\", returns: \"TABLE(field_id uuid, field_key text, field_label text, field_type text, field_source text, field_required boolean, field_sort numeric, table_label text)\", security: \"definer\" },\n  { name: \"custom_fields_tables\", args: \"\", returns: \"TABLE(token text, schema_name text, table_name text)\", security: \"invoker\" },\n  { name: \"dashboard_block_normalize\", args: \"p_organization_id uuid, p_subject_table_id uuid, p_block jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"dashboard_class\", args: \"\", returns: \"text\", security: \"invoker\" },\n  { name: \"dashboard_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_name text, p_blocks jsonb DEFAULT '[]'::jsonb, p_presentation jsonb DEFAULT '{}'::jsonb, p_dashboard_id uuid DEFAULT NULL::uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"dashboard_delete\", args: \"p_organization_id uuid, p_dashboard_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"dashboard_field_keys\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"text[]\", security: \"definer\" },\n  { name: \"dashboard_kinds\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"dashboard_moment_sql\", args: \"p_key text\", returns: \"text\", security: \"invoker\" },\n  { name: \"dashboard_restore\", args: \"p_organization_id uuid, p_dashboard_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"dashboard_run\", args: \"p_organization_id uuid, p_dashboard_id uuid, p_filter jsonb DEFAULT '{}'::jsonb, p_compare jsonb DEFAULT NULL::jsonb, p_grain text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"dashboard_stuck\", args: \"p_organization_id uuid, p_table_id uuid, p_state_key text, p_days integer DEFAULT 14, p_filter jsonb DEFAULT '{}'::jsonb, p_limit integer DEFAULT 50, p_required text DEFAULT 'viewer'::text\", returns: \"TABLE(record_id uuid, title text, state text, last_changed_at timestamp with time zone, days_unchanged numeric, measured_from text)\", security: \"definer\" },\n  { name: \"dashboard_target_field_assert\", args: \"p_organization_id uuid, p_table_id uuid, p_field_key text\", returns: \"void\", security: \"invoker\" },\n  { name: \"dashboard_window_sql\", args: \"p_key text, p_window jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"dashboards\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(dashboard_id uuid, table_id uuid, name text, blocks jsonb, presentation jsonb, block_count integer, version integer, created_at timestamp with time zone, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"data_home\", args: \"p_organization_id uuid DEFAULT NULL::uuid, p_search text DEFAULT NULL::text, p_include_platform_tables boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"data_home_changed_by\", args: \"p_asks jsonb\", returns: \"TABLE(organization_id uuid, id uuid, at timestamp with time zone, who text)\", security: \"definer\" },\n  { name: \"data_home_custom_fields\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(organization_id uuid, organization_name text, table_token text, table_label text, field_count integer, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"data_home_first\", args: \"p_organization_id uuid DEFAULT NULL::uuid, p_include_platform_tables boolean DEFAULT false, p_limit integer DEFAULT 100\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"data_home_items\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(kind text, organization_id uuid, organization_name text, item_id uuid, table_id uuid, table_name text, item_row jsonb)\", security: \"definer\" },\n  { name: \"data_home_slim\", args: \"p_organization_id uuid DEFAULT NULL::uuid, p_search text DEFAULT NULL::text, p_include_platform_tables boolean DEFAULT false\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"data_home_tables\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(table_id uuid, table_name text, organization_id uuid, organization_name text, member boolean, visibility text, updated_at timestamp with time zone, mine boolean, shared_with_me boolean, platform_owned boolean, kind text, team boolean, system boolean, created_by uuid)\", security: \"definer\" },\n  { name: \"data_home_tables\", args: \"p_organization_id uuid, p_include_platform_tables boolean\", returns: \"TABLE(table_id uuid, table_name text, organization_id uuid, organization_name text, member boolean, visibility text, updated_at timestamp with time zone, mine boolean, shared_with_me boolean, platform_owned boolean, kind text, team boolean, system boolean, created_by uuid)\", security: \"invoker\" },\n  { name: \"day_zone\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"declared_conversation\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"decoration_colors\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"decoration_rule_ops\", args: \"\", returns: \"TABLE(op text, takes_value boolean, label text)\", security: \"invoker\" },\n  { name: \"delete_cascade_closure\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"uuid[]\", security: \"invoker\" },\n  { name: \"delete_preview\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"delete_rule\", args: \"p_organization_id uuid, p_record_id uuid, p_apply boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"dependency_cycle\", args: \"p_organization_id uuid, p_row custom.record\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"dependency_label\", args: \"p_organization_id uuid, p_node text\", returns: \"text\", security: \"invoker\" },\n  { name: \"derive_visibility\", args: \"p_container_type text, p_container_id uuid\", returns: \"TABLE(item_type text, item_id uuid, depth integer, max_level permission_level)\", security: \"definer\" },\n  { name: \"derived_value\", args: \"p_organization_id uuid, p_record_id uuid, p_field_data jsonb, p_values jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"derived_values\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"derived_values_of\", args: \"v_rec custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"display_format_ids\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"doc_content_hash\", args: \"p_body text\", returns: \"text\", security: \"invoker\" },\n  { name: \"doc_format_value\", args: \"p_field_data jsonb, p_value jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"doc_letterhead\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"doc_name_token_pattern\", args: \"\", returns: \"text\", security: \"invoker\" },\n  { name: \"doc_name_tokens\", args: \"p_body text\", returns: \"TABLE(ordinal integer, raw text)\", security: \"invoker\" },\n  { name: \"doc_render_body\", args: \"p_organization_id uuid, p_template_id uuid, p_record_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"doc_render_delete\", args: \"p_organization_id uuid, p_render_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"doc_render_document\", args: \"p_organization_id uuid, p_template_id uuid, p_record_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"doc_render_read\", args: \"p_organization_id uuid, p_render_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"doc_render_restore\", args: \"p_organization_id uuid, p_render_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"doc_render_write\", args: \"p_organization_id uuid, p_template_id uuid, p_record_id uuid, p_table_id uuid, p_template_version integer, p_body text, p_content_hash text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"doc_renders\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(render_id uuid, template_id uuid, record_id uuid, table_id uuid, template_version integer, body text, content_hash text, rendered_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"doc_sign\", args: \"p_organization_id uuid, p_render_id uuid, p_field_key text, p_signer_name text, p_signer_user_id uuid DEFAULT NULL::uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"doc_signature_field_ok\", args: \"p_field_data jsonb\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"doc_signature_intact\", args: \"p_organization_id uuid, p_signature_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"doc_signature_read\", args: \"p_organization_id uuid, p_signature_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"doc_signature_write\", args: \"p_organization_id uuid, p_render_id uuid, p_record_id uuid, p_field_key text, p_signer_name text, p_signer_user_id uuid, p_document_hash text, p_document_version integer\", returns: \"uuid\", security: \"definer\" },\n  { name: \"doc_signatures\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(signature_id uuid, render_id uuid, record_id uuid, field_key text, signer_name text, signer_user_id uuid, signed_at timestamp with time zone, document_hash text, document_version integer)\", security: \"definer\" },\n  { name: \"doc_template_delete\", args: \"p_organization_id uuid, p_template_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"doc_template_read\", args: \"p_organization_id uuid, p_template_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"doc_template_restore\", args: \"p_organization_id uuid, p_template_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"doc_template_save\", args: \"p_organization_id uuid, p_table_id uuid, p_name text, p_body text, p_template_id uuid DEFAULT NULL::uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"doc_templates\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(template_id uuid, renders_table_id uuid, name text, body text, template_version integer, token_count bigint, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"doc_token_pattern\", args: \"\", returns: \"text\", security: \"invoker\" },\n  { name: \"doc_tokens\", args: \"p_body text\", returns: \"TABLE(ordinal integer, raw text, field_id uuid)\", security: \"invoker\" },\n  { name: \"doc_unresolved_tokens\", args: \"p_organization_id uuid, p_table_id uuid, p_body text\", returns: \"TABLE(raw text, field_id uuid, why text)\", security: \"invoker\" },\n  { name: \"door_reads_only\", args: \"p_door text\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"doors_not_deciding_the_caller\", args: \"\", returns: \"TABLE(function_name text, identity_args text)\", security: \"invoker\" },\n  { name: \"doors_not_deciding_the_record\", args: \"\", returns: \"TABLE(function_name text, identity_args text, why text)\", security: \"invoker\" },\n  { name: \"doors_not_masking_fields\", args: \"\", returns: \"TABLE(function_name text, identity_args text, why text)\", security: \"invoker\" },\n  { name: \"doors_not_on_one_ladder\", args: \"\", returns: \"TABLE(function_name text, identity_args text, why text)\", security: \"invoker\" },\n  { name: \"doors_refusing_in_another_doors_name\", args: \"\", returns: \"TABLE(function_name text, identity_args text, why text)\", security: \"invoker\" },\n  { name: \"drill_resolve\", args: \"p_organization_id uuid, p_table_id uuid, p_group_by jsonb, p_measures jsonb, p_bucket jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"effective_level\", args: \"p_user_id uuid, p_organization_id uuid, p_id uuid, p_type text DEFAULT 'record'::text\", returns: \"permission_level\", security: \"definer\" },\n  { name: \"effective_level_many\", args: \"p_user_id uuid, p_ids uuid[], p_type text DEFAULT 'record'::text\", returns: \"TABLE(id uuid, level permission_level)\", security: \"definer\" },\n  { name: \"enrich_cells\", args: \"p_organization_id uuid, p_table_id uuid, p_field_keys text[] DEFAULT NULL::text[], p_record_ids uuid[] DEFAULT NULL::uuid[]\", returns: \"TABLE(record_id uuid, field_key text, agent_owned boolean, value jsonb, value_version integer, actor text, on_behalf_of text, written_at timestamp with time zone, source jsonb, absent_reason text, alternates jsonb, pinned boolean, stale boolean, due_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"enrich_data_source\", args: \"p_ds jsonb, p_inputs jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"enrich_declare\", args: \"p_organization_id uuid, p_field_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"enrich_due\", args: \"p_organization_id uuid, p_field_id uuid, p_limit integer DEFAULT 50, p_include_fresh boolean DEFAULT false, p_record_ids uuid[] DEFAULT NULL::uuid[]\", returns: \"TABLE(record_id uuid, title text, inputs jsonb, current_value jsonb, written_at timestamp with time zone, reason text, trimmed_to integer)\", security: \"definer\" },\n  { name: \"enrich_land\", args: \"p_organization_id uuid, p_field_id uuid, p_results jsonb, p_run jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"enrich_normalize\", args: \"p_organization_id uuid, p_table_id uuid, p_field_key text, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"enrich_pin\", args: \"p_organization_id uuid, p_record_id uuid, p_field_key text, p_pinned boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"enrich_refill_due_tick\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"enrich_run_class\", args: \"\", returns: \"text\", security: \"invoker\" },\n  { name: \"enrich_runs\", args: \"p_organization_id uuid, p_field_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 50\", returns: \"TABLE(run_id uuid, field_id uuid, field_key text, model text, trigger_word text, rows_seen integer, rows_written integer, rows_absent integer, rows_below_floor integer, rows_pinned integer, rows_refused integer, cost_cents numeric, cost_per_row_cents numeric, ran_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"enrich_sensitivity_rank\", args: \"p_word text\", returns: \"integer\", security: \"invoker\" },\n  { name: \"enrich_triggers\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"enrichments\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(field_id uuid, table_id uuid, field_key text, label text, enrichment jsonb, enabled boolean, review_interval_days integer, rows_total integer, rows_filled integer, rows_stale integer, rows_pinned integer, rows_absent integer, runs integer, cost_cents numeric, cost_per_row_cents numeric, last_run_at timestamp with time zone, last_run jsonb)\", security: \"definer\" },\n  { name: \"entity_back_links\", args: \"p_organization_id uuid, p_token text, p_record_id uuid, p_limit integer DEFAULT 50, p_cursor text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_custom_value_apply\", args: \"p_organization_id uuid, p_token text, p_record_id uuid, p_clear text[], p_patch jsonb, p_expected_version integer DEFAULT NULL::integer\", returns: \"integer\", security: \"definer\" },\n  { name: \"entity_custom_values_lock\", args: \"p_token text\", returns: \"TABLE(locked boolean, reason text)\", security: \"definer\" },\n  { name: \"entity_field_declare\", args: \"p_organization_id uuid, p_token text, p_spec jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"entity_field_protect_arman_explicitly_approved\", args: \"p_field_id uuid, p_readers jsonb, p_arman_words text, p_approved_on date\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_field_retire\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"entity_field_rights\", args: \"p_organization_id uuid, p_token text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_field_update\", args: \"p_organization_id uuid, p_field_id uuid, p_patch jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"entity_fields\", args: \"p_organization_id uuid, p_token text, p_include_retired boolean DEFAULT false\", returns: \"SETOF custom.record\", security: \"definer\" },\n  { name: \"entity_fields_across\", args: \"p_token text, p_organization_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_read_mask\", args: \"p_organization_id uuid, p_token text, p_level permission_level, p_action text DEFAULT 'read'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_record_home\", args: \"p_token text, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_record_read\", args: \"p_organization_id uuid, p_token text, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_records_find\", args: \"p_organization_id uuid, p_token text, p_key text, p_value jsonb DEFAULT NULL::jsonb, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_reference_fields\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_reference_kinds\", args: \"\", returns: \"TABLE(token text, label text, category text)\", security: \"definer\" },\n  { name: \"entity_reference_render\", args: \"p_organization_id uuid, p_table_id uuid, p_doc jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_reference_render_with\", args: \"p_organization_id uuid, p_table_id uuid, p_doc jsonb, p_fields jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_reference_rows\", args: \"p_organization_id uuid, p_token text, p_ids uuid[]\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_reference_search\", args: \"p_organization_id uuid, p_tokens text[], p_search text DEFAULT NULL::text, p_limit integer DEFAULT 20\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_reference_target\", args: \"p_token text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_reference_words\", args: \"p_organization_id uuid, p_refs jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"entity_row_propose\", args: \"p_organization_id uuid, p_token text, p_record_id uuid, p_columns jsonb DEFAULT '{}'::jsonb, p_custom jsonb DEFAULT '{}'::jsonb, p_expected_version integer DEFAULT NULL::integer, p_archive boolean DEFAULT NULL::boolean, p_note text DEFAULT NULL::text, p_conversation_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_row_write\", args: \"p_organization_id uuid, p_token text, p_record_id uuid, p_columns jsonb DEFAULT '{}'::jsonb, p_custom jsonb DEFAULT '{}'::jsonb, p_expected_version integer DEFAULT NULL::integer, p_archive boolean DEFAULT NULL::boolean\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"entity_seat_level\", args: \"p_organization_id uuid, p_token text, p_record_id uuid\", returns: \"permission_level\", security: \"invoker\" },\n  { name: \"entity_table\", args: \"p_token text\", returns: \"TABLE(token text, schema_name text, table_name text, type text, title_column text, label text, has_organization boolean, has_deleted_at boolean)\", security: \"definer\" },\n  { name: \"entity_value_write\", args: \"p_organization_id uuid, p_token text, p_record_id uuid, p_patch jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"export_ceiling\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"integer\", security: \"invoker\" },\n  { name: \"export_records\", args: \"p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 1000\", returns: \"TABLE(id uuid, document jsonb)\", security: \"invoker\" },\n  { name: \"external_foreign_table_findings\", args: \"\", returns: \"SETOF text\", security: \"definer\" },\n  { name: \"external_history_event\", args: \"p_organization_id uuid, p_link_id uuid, p_operation text\", returns: \"bigint\", security: \"definer\" },\n  { name: \"external_rows\", args: \"p_organization_id uuid, p_source_id uuid\", returns: \"SETOF jsonb\", security: \"definer\" },\n  { name: \"external_source_declare\", args: \"p_organization_id uuid, p_tier text, p_connection_token text, p_external_schema text, p_external_table text, p_link_template text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"external_stub_upsert\", args: \"p_organization_id uuid, p_source_id uuid, p_table_id uuid, p_external_key text, p_link_url text, p_cached_title text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"external_tier_contract\", args: \"\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"external_write_through\", args: \"p_organization_id uuid, p_record_id uuid, p_patch jsonb\", returns: \"void\", security: \"definer\" },\n  { name: \"external_writes_set\", args: \"p_organization_id uuid, p_source_id uuid, p_enabled boolean\", returns: \"boolean\", security: \"definer\" },\n  { name: \"far_value\", args: \"p_organization_id uuid, p_record_id uuid, p_key text, p_reader jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"field_access\", args: \"p_user uuid, p_field_id uuid, p_token text, p_row_id uuid, p_action text, p_audit boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_access_set\", args: \"p_field_id uuid, p_part text, p_word text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_access_setup\", args: \"p_field_id uuid, p_proposed jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_add_rung\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"permission_level\", security: \"invoker\" },\n  { name: \"field_behaviour\", args: \"p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"field_choice_usage\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_context_policy_floor\", args: \"p_organization_id uuid, p_field_data jsonb, p_self uuid DEFAULT NULL::uuid\", returns: \"TABLE(context_policy text, reads jsonb)\", security: \"definer\" },\n  { name: \"field_cycle\", args: \"p_organization_id uuid, p_field_data jsonb, p_self uuid\", returns: \"text[]\", security: \"definer\" },\n  { name: \"field_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_spec jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"field_declare_many\", args: \"p_organization_id uuid, p_table_id uuid, p_specs jsonb\", returns: \"uuid[]\", security: \"invoker\" },\n  { name: \"field_dependants\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"TABLE(kind text, dependant_id uuid, label text, how text)\", security: \"definer\" },\n  { name: \"field_duplicate\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_history\", args: \"p_organization_id uuid, p_table_id uuid, p_field_key text, p_limit integer DEFAULT 100, p_offset integer DEFAULT 0, p_record_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(record_id uuid, record_title text, version integer, occurred_at timestamp with time zone, operation_label text, actor jsonb, before jsonb, after jsonb)\", security: \"definer\" },\n  { name: \"field_input_closure\", args: \"p_organization_id uuid, p_field_data jsonb, p_self uuid DEFAULT NULL::uuid\", returns: \"TABLE(input_id uuid, input_key text, input_label text, input_table uuid, sensitivity text, retired boolean, depth integer)\", security: \"definer\" },\n  { name: \"field_input_closure_many\", args: \"p_organization_id uuid, p_ids uuid[]\", returns: \"TABLE(root_id uuid, input_id uuid, retired boolean, depth integer)\", security: \"definer\" },\n  { name: \"field_inputs_of\", args: \"p_organization_id uuid, p_field_data jsonb\", returns: \"TABLE(input_id uuid, input_key text, input_label text, input_table uuid, sensitivity text, retired boolean, how text)\", security: \"definer\" },\n  { name: \"field_is_protected\", args: \"p_data jsonb\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"field_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"field_kind_of\", args: \"p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"field_kinds\", args: \"\", returns: \"TABLE(kind text, behavior text, parity boolean, made_of text)\", security: \"invoker\" },\n  { name: \"field_make_automatic\", args: \"p_organization_id uuid, p_field_id uuid, p_kind text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_notify_on_assign\", args: \"p_organization_id uuid, p_field_id uuid, p_on boolean\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_options\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"SETOF custom.record\", security: \"definer\" },\n  { name: \"field_protection_refusal\", args: \"p_op text, p_old jsonb, p_new jsonb, p_field_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"field_restore\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"field_retire\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"field_retype_preview\", args: \"p_organization_id uuid, p_field_id uuid, p_patch jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_rules\", args: \"p_field_data jsonb\", returns: \"TABLE(kind text, spec jsonb)\", security: \"invoker\" },\n  { name: \"field_sensitivity_floor\", args: \"p_organization_id uuid, p_field_data jsonb, p_self uuid DEFAULT NULL::uuid\", returns: \"TABLE(sensitivity text, reads jsonb)\", security: \"definer\" },\n  { name: \"field_source_archived\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_update\", args: \"p_organization_id uuid, p_field_id uuid, p_patch jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"field_update_rehoming_choices\", args: \"p_organization_id uuid, p_field_id uuid, p_patch jsonb, p_rehome jsonb DEFAULT NULL::jsonb, p_cells_back jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"field_value_convert\", args: \"p_to jsonb, p_value jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"field_value_kind\", args: \"p_organization_id uuid, p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"field_words\", args: \"p_organization_id uuid, p_field_id uuid, p_value jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"file_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"filter_is_rule\", args: \"p_filter jsonb\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"filter_list_op\", args: \"p_op text, p_a jsonb, p_b jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"filter_list_op_words\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"find_duplicates\", args: \"p_organization_id uuid, p_table_id uuid, p_fields text[], p_limit integer DEFAULT 50\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_archive\", args: \"p_organization_id uuid, p_form_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_title text, p_questions jsonb, p_presentation jsonb DEFAULT '{}'::jsonb, p_submission_cap integer DEFAULT NULL::integer, p_quarantine_rule_id uuid DEFAULT NULL::uuid, p_notify_rule_id uuid DEFAULT NULL::uuid, p_form_id uuid DEFAULT NULL::uuid, p_slug text DEFAULT NULL::text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"form_draft_read\", args: \"p_form_id uuid, p_secret text\", returns: \"TABLE(answers jsonb, saved_at timestamp with time zone, expires_at timestamp with time zone, state text, message text)\", security: \"definer\" },\n  { name: \"form_draft_save\", args: \"p_form_id uuid, p_answers jsonb, p_secret text DEFAULT NULL::text, p_bucket text DEFAULT NULL::text, p_origin text DEFAULT NULL::text\", returns: \"TABLE(draft_secret text, saved_at timestamp with time zone, expires_at timestamp with time zone, state text, message text)\", security: \"definer\" },\n  { name: \"form_knobs\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_look_options\", args: \"p_organization_id uuid, p_presentation jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_notify\", args: \"p_organization_id uuid, p_form_id uuid, p_record_id uuid, p_submission_id uuid\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"form_preview_asks\", args: \"p_organization_id uuid, p_table_id uuid, p_questions jsonb, p_values jsonb\", returns: \"TABLE(field_key text, asked boolean, decided boolean, said text)\", security: \"definer\" },\n  { name: \"form_preview_route\", args: \"p_organization_id uuid, p_table_id uuid, p_questions jsonb, p_endings jsonb, p_values jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_public\", args: \"p_form_id uuid\", returns: \"TABLE(form_id uuid, organization_id uuid, table_id uuid, title text, presentation jsonb, fields jsonb, honeypot_key text, state text, message text)\", security: \"definer\" },\n  { name: \"form_public_asks\", args: \"p_form_id uuid, p_values jsonb, p_secret text DEFAULT NULL::text, p_origin text DEFAULT NULL::text\", returns: \"TABLE(field_key text, asked boolean, decided boolean, said text)\", security: \"definer\" },\n  { name: \"form_public_options\", args: \"p_form_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_public_route\", args: \"p_form_id uuid, p_values jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_redirect_domains\", args: \"p_organization_id uuid\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"form_redirect_refusal\", args: \"p_organization_id uuid, p_url text\", returns: \"text\", security: \"invoker\" },\n  { name: \"form_respondent_copy\", args: \"p_organization_id uuid, p_form_id uuid, p_record_id uuid, p_submission_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_response_read\", args: \"p_form_id uuid, p_edit text, p_unlock text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_response_update\", args: \"p_form_id uuid, p_edit text, p_origin text, p_payload jsonb, p_bucket text\", returns: \"TABLE(submission_id uuid, record_id uuid, state text, message text)\", security: \"definer\" },\n  { name: \"form_restore\", args: \"p_organization_id uuid, p_form_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_results\", args: \"p_organization_id uuid, p_form_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_set_password\", args: \"p_organization_id uuid, p_form_id uuid, p_password text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_slug\", args: \"p_organization_id uuid, p_title text, p_form_id uuid DEFAULT NULL::uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"form_submit\", args: \"p_form_id uuid, p_origin text, p_payload jsonb, p_bucket text, p_honeypot text DEFAULT NULL::text, p_client_key text DEFAULT NULL::text\", returns: \"TABLE(submission_id uuid, record_id uuid, state text, message text)\", security: \"definer\" },\n  { name: \"form_theme_options\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"form_unlock\", args: \"p_form_id uuid, p_password text DEFAULT NULL::text, p_unlock text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"form_visit\", args: \"p_form_id uuid, p_visit text, p_event text, p_field text DEFAULT NULL::text\", returns: \"text\", security: \"definer\" },\n  { name: \"form_visit_admit\", args: \"p_form_id uuid, p_bucket text\", returns: \"boolean\", security: \"definer\" },\n  { name: \"forms\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(form_id uuid, table_id uuid, title text, slug text, published_at timestamp with time zone, closed_at timestamp with time zone, submission_cap integer, responses bigint, in_table bigint, held bigint, rejected bigint, state text, quarantine_rule_id uuid, notify_rule_id uuid, presentation jsonb)\", security: \"definer\" },\n  { name: \"forms_archived\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 100\", returns: \"TABLE(form_id uuid, table_id uuid, table_name text, kind text, title text, slug text, archived_at timestamp with time zone, archived_by uuid, table_archived boolean, can_restore boolean)\", security: \"definer\" },\n  { name: \"forms_archived_everywhere\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"formula_compile_sql\", args: \"p_organization_id uuid, p_expr jsonb, p_values_sql text\", returns: \"text\", security: \"invoker\" },\n  { name: \"formula_eval\", args: \"p_organization_id uuid, p_expr jsonb, p_values jsonb, p_context jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"formula_field_keys\", args: \"p_organization_id uuid, p_expr jsonb\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"formula_history\", args: \"p_organization_id uuid, p_record_id uuid, p_field_key text, p_limit integer DEFAULT 100\", returns: \"TABLE(occurred_at timestamp with time zone, cause text, record_version integer, formula_version integer, formula_text text, value jsonb, refused text, actor jsonb)\", security: \"definer\" },\n  { name: \"formula_node_kinds\", args: \"\", returns: \"TABLE(node text, min_args integer, max_args integer, result text, signature text, says text)\", security: \"invoker\" },\n  { name: \"formula_parse\", args: \"p_organization_id uuid, p_table_id uuid, p_text text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"formula_preview\", args: \"p_organization_id uuid, p_table_id uuid, p_record_id uuid, p_text text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"formula_result_kind\", args: \"p_organization_id uuid, p_expr jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"formula_translate_notion\", args: \"p_text text, p_types jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"formula_value\", args: \"p_organization_id uuid, p_record_id uuid, p_field_data jsonb, p_values jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"freshness_verdict\", args: \"p_written_at timestamp with time zone, p_ceiling_seconds numeric\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"grid_layout\", args: \"p_organization_id uuid, p_table_id uuid, p_view_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"grid_layout_check\", args: \"p_layout jsonb, p_scope text DEFAULT 'view'::text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"guard_refusals_are_complete\", args: \"\", returns: \"TABLE(guard text, said text)\", security: \"invoker\" },\n  { name: \"has_visibility\", args: \"p_user_id uuid, p_type text, p_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level\", returns: \"boolean\", security: \"definer\" },\n  { name: \"has_visibility_at\", args: \"p_user_id uuid, p_type text, p_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level, p_organization_id uuid DEFAULT NULL::uuid, p_min_version bigint DEFAULT NULL::bigint\", returns: \"boolean\", security: \"definer\" },\n  { name: \"hidden_field_notice\", args: \"p_field custom.record, p_action text DEFAULT 'read'::text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"history_actor\", args: \"p_tier text, p_document jsonb, p_actor_id uuid, p_people jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"history_changes\", args: \"p_organization_id uuid, p_table_id uuid, p_old jsonb, p_new jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"history_people\", args: \"p_organization_id uuid, p_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"history_prune\", args: \"p_organization_id uuid, p_scope text DEFAULT 'values'::text, p_table_id uuid DEFAULT NULL::uuid, p_dry_run boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"history_restore_body\", args: \"p_current jsonb, p_target jsonb, p_field_key text DEFAULT NULL::text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"history_restore_body\", args: \"p_current jsonb, p_target jsonb, p_field_key text, p_author jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"history_retention\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"history_retention_floor_raise\", args: \"p_organization_id uuid, p_days integer\", returns: \"integer\", security: \"definer\" },\n  { name: \"history_retention_set\", args: \"p_organization_id uuid, p_table_id uuid, p_days integer\", returns: \"integer\", security: \"definer\" },\n  { name: \"home_add\", args: \"p_organization_id uuid, p_table_id uuid, p_home_record_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"home_relations\", args: \"\", returns: \"TABLE(table_id uuid, home_record_id uuid, organization_id uuid, relation_id uuid)\", security: \"invoker\" },\n  { name: \"hot_doors_6_on\", args: \"p_person uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"hot_doors_7_on\", args: \"p_person uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"hub_changed_by\", args: \"p_organization_id uuid, p_kind text, p_ids uuid[]\", returns: \"TABLE(id uuid, at timestamp with time zone, who text)\", security: \"definer\" },\n  { name: \"hub_changed_by_many\", args: \"p_asks jsonb, p_door text DEFAULT NULL::text\", returns: \"TABLE(organization_id uuid, id uuid, at timestamp with time zone, who text)\", security: \"definer\" },\n  { name: \"hub_row_asked_alone\", args: \"p_org uuid, p_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"inbound_addresses\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"inbound_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_label text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"inbound_domain\", args: \"p_organization_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"inbound_mail_land\", args: \"p_address text, p_mail jsonb, p_secret text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"inbound_mail_map\", args: \"p_organization_id uuid, p_table_id uuid, p_mail jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"inbound_set\", args: \"p_organization_id uuid, p_inbound_id uuid, p_enabled boolean\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"inbox_clear\", args: \"p_organization_id uuid, p_item_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"inbox_counts\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(organization_id uuid, organization_name text, waiting integer, snoozed integer, cleared integer, overdue integer, oldest_waiting_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"inbox_remind_tick\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"inbox_snooze\", args: \"p_organization_id uuid, p_item_id uuid, p_until timestamp with time zone\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"inbox_unclear\", args: \"p_organization_id uuid, p_item_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"inbox_unsnooze\", args: \"p_organization_id uuid, p_item_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"index_payload\", args: \"p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 1000\", returns: \"TABLE(id uuid, searchable text)\", security: \"invoker\" },\n  { name: \"interface_chart\", args: \"p_interface_id uuid, p_chart_id text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"interface_chart_formula_ok\", args: \"p_org uuid, p_table uuid, p_key text, p_allowed text[], p_depth integer\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"interface_read\", args: \"p_interface_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"interface_rows\", args: \"p_interface_id uuid, p_element_id text, p_record_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"intern_provenance\", args: \"p_data jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"io_cell\", args: \"p_organization_id uuid, p_field jsonb, p_word text, p_date_order text DEFAULT 'mdy'::text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"io_change_actor\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"io_change_fields\", args: \"p_keys text[], p_old jsonb, p_new jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"io_change_via\", args: \"\", returns: \"text\", security: \"invoker\" },\n  { name: \"io_changed_field_ids\", args: \"p_organization_id uuid, p_table_id uuid, p_old jsonb, p_new jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"io_changed_keys\", args: \"p_old jsonb, p_new jsonb\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"io_comment_resolve\", args: \"p_organization_id uuid, p_comment_id uuid, p_resolved boolean DEFAULT true\", returns: \"boolean\", security: \"definer\" },\n  { name: \"io_comment_write\", args: \"p_organization_id uuid, p_record_id uuid, p_body text, p_anchor jsonb DEFAULT '{}'::jsonb, p_parent_comment_id uuid DEFAULT NULL::uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"io_comments\", args: \"p_organization_id uuid, p_record_id uuid, p_include_resolved boolean DEFAULT false\", returns: \"TABLE(id uuid, body text, anchor jsonb, parent_comment_id uuid, created_by uuid, created_at timestamp with time zone, resolved_at timestamp with time zone, resolved_by uuid)\", security: \"definer\" },\n  { name: \"io_csv_escape\", args: \"p_value text, p_delimiter text DEFAULT ','::text\", returns: \"text\", security: \"invoker\" },\n  { name: \"io_csv_parse\", args: \"p_text text, p_delimiter text DEFAULT NULL::text\", returns: \"TABLE(row_number integer, cells text[])\", security: \"invoker\" },\n  { name: \"io_export\", args: \"p_organization_id uuid, p_table_id uuid, p_columns text[] DEFAULT NULL::text[], p_limit integer DEFAULT 10000, p_required text DEFAULT 'viewer'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_export_csv\", args: \"p_organization_id uuid, p_table_id uuid, p_columns text[] DEFAULT NULL::text[], p_limit integer DEFAULT 10000, p_delimiter text DEFAULT chr(44), p_required text DEFAULT 'viewer'::text\", returns: \"text\", security: \"definer\" },\n  { name: \"io_import_begin\", args: \"p_organization_id uuid, p_table_id uuid, p_format text DEFAULT 'csv'::text, p_source_name text DEFAULT NULL::text, p_source_columns jsonb DEFAULT '[]'::jsonb, p_file_hash text DEFAULT NULL::text, p_policy jsonb DEFAULT '{}'::jsonb, p_dedupe_key text DEFAULT NULL::text, p_file_bytes bigint DEFAULT NULL::bigint, p_force boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_import_declare_columns\", args: \"p_organization_id uuid, p_table_id uuid, p_rows jsonb, p_mapping jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_import_finish\", args: \"p_organization_id uuid, p_import_id uuid, p_unmapped text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_import_forget\", args: \"p_organization_id uuid, p_import_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"io_import_open\", args: \"p_organization_id uuid, p_table_id uuid, p_format text DEFAULT 'csv'::text, p_source_name text DEFAULT NULL::text, p_source_columns jsonb DEFAULT '[]'::jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"io_import_plan\", args: \"p_organization_id uuid, p_table_id uuid, p_columns jsonb DEFAULT '[]'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_import_report\", args: \"p_organization_id uuid, p_import_id uuid, p_state text DEFAULT NULL::text, p_limit integer DEFAULT 100, p_offset integer DEFAULT 0\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_import_rows\", args: \"p_organization_id uuid, p_import_id uuid, p_rows jsonb, p_mapping jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_imports\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 25\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_infer_column\", args: \"p_organization_id uuid, p_table_id uuid, p_header text, p_samples jsonb DEFAULT '[]'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"io_infer_type\", args: \"p_samples jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"io_money_unit\", args: \"p_word text\", returns: \"text\", security: \"invoker\" },\n  { name: \"io_outbox_announce\", args: \"\", returns: \"trigger\", security: \"definer\" },\n  { name: \"io_outbox_backlog\", args: \"p_consumer text, p_event_key text, p_older_than interval DEFAULT '00:00:00'::interval\", returns: \"TABLE(organization_id uuid, waiting bigint, oldest timestamp with time zone, last_carried timestamp with time zone)\", security: \"definer\" },\n  { name: \"io_outbox_broadcast_stmt\", args: \"\", returns: \"trigger\", security: \"definer\" },\n  { name: \"io_outbox_consumed_by\", args: \"p_event_id uuid, p_consumer text, p_consumed_at timestamp with time zone\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"io_outbox_drain\", args: \"p_organization_id uuid, p_consumer text, p_limit integer DEFAULT 100, p_event_key text DEFAULT 'records.changed'::text\", returns: \"TABLE(outbox_id uuid, record_id uuid, table_id uuid, operation text, changed_field_ids jsonb, actor jsonb, occurred_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"io_outbox_last_consumed\", args: \"p_consumer text, p_event_key text, p_organization_id uuid\", returns: \"timestamp with time zone\", security: \"invoker\" },\n  { name: \"io_outbox_pending_organizations\", args: \"p_consumer text, p_event_key text\", returns: \"SETOF uuid\", security: \"definer\" },\n  { name: \"io_outbox_per_consumer\", args: \"\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"io_outbox_rearm\", args: \"p_organization_id uuid, p_dedupe_key text\", returns: \"void\", security: \"definer\" },\n  { name: \"io_outbox_release\", args: \"p_organization_id uuid, p_consumer text, p_older_than interval DEFAULT '00:15:00'::interval\", returns: \"integer\", security: \"definer\" },\n  { name: \"io_outbox_release_claimed\", args: \"p_organization_id uuid, p_consumer text, p_ids uuid[]\", returns: \"integer\", security: \"definer\" },\n  { name: \"io_outbox_subscribe\", args: \"p_consumer text, p_event_key text\", returns: \"timestamp with time zone\", security: \"definer\" },\n  { name: \"io_proposal_accept\", args: \"p_organization_id uuid, p_import_id uuid, p_column text, p_type text DEFAULT NULL::text, p_label text DEFAULT NULL::text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"io_proposal_reject\", args: \"p_organization_id uuid, p_import_id uuid, p_column text\", returns: \"boolean\", security: \"definer\" },\n  { name: \"io_proposal_spec\", args: \"p_proposal jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"io_record_changed\", args: \"\", returns: \"trigger\", security: \"definer\" },\n  { name: \"io_record_changed_stmt_delete\", args: \"\", returns: \"trigger\", security: \"definer\" },\n  { name: \"io_record_changed_stmt_insert\", args: \"\", returns: \"trigger\", security: \"definer\" },\n  { name: \"io_record_changed_stmt_update\", args: \"\", returns: \"trigger\", security: \"definer\" },\n  { name: \"io_relation_candidate\", args: \"p_organization_id uuid, p_table_id uuid, p_words text[]\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"io_restore\", args: \"p_organization_id uuid, p_record_id uuid, p_version integer\", returns: \"integer\", security: \"definer\" },\n  { name: \"io_restore\", args: \"p_organization_id uuid, p_record_id uuid, p_version integer, p_author jsonb\", returns: \"integer\", security: \"definer\" },\n  { name: \"io_revisions\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(version integer, changed_at timestamp with time zone, changed_by uuid, summary text, operation text, changed_fields jsonb)\", security: \"definer\" },\n  { name: \"io_sample_words\", args: \"p_samples jsonb\", returns: \"TABLE(word text)\", security: \"invoker\" },\n  { name: \"io_value_shape\", args: \"p_envelope jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"io_workflow_chain\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"is_a_retirement\", args: \"p_old_deleted timestamp with time zone, p_new_deleted timestamp with time zone, p_old_data jsonb, p_new_data jsonb, p_old_table uuid, p_new_table uuid, p_old_org uuid, p_new_org uuid, p_old_class text, p_new_class text\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"kernel_viewer_sets\", args: \"p_user uuid, p_orgs uuid[]\", returns: \"TABLE(organization_id uuid, fallback boolean, all_visible boolean, granted_all uuid[], carried_visible uuid[])\", security: \"definer\" },\n  { name: \"ladder_replanners\", args: \"p_roots text[] DEFAULT ARRAY['custom.has_visibility'::text, 'custom.effective_level'::text, 'custom.reaches_directly'::text, 'custom.visible_set'::text]\", returns: \"TABLE(fn text, lang text, why text, remedy text)\", security: \"definer\" },\n  { name: \"level_floor\", args: \"\", returns: \"permission_level\", security: \"definer\" },\n  { name: \"levels_of\", args: \"p_user_id uuid, p_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"levels_raised_by_a_less_specific_rung\", args: \"\", returns: \"TABLE(organization_id uuid, organization_name text, member_id uuid, member_email text, record_id uuid, addressed_level permission_level, answered_level permission_level)\", security: \"definer\" },\n  { name: \"list_door_disagreements\", args: \"p_pretend text DEFAULT NULL::text, p_only_organization uuid DEFAULT NULL::uuid, p_sample integer DEFAULT 200\", returns: \"TABLE(organization_id uuid, organization_name text, member_id uuid, table_id uuid, record_id uuid, door text, why text)\", security: \"invoker\" },\n  { name: \"list_door_disagreements\", args: \"p_pretend text, p_only_organization uuid, p_sample integer, p_exhaustive boolean\", returns: \"TABLE(organization_id uuid, organization_name text, member_id uuid, table_id uuid, record_id uuid, door text, why text)\", security: \"invoker\" },\n  { name: \"list_portals\", args: \"p_organization_id uuid, p_archived text DEFAULT 'active'::text\", returns: \"TABLE(portal_id uuid, title text, slug text, client_table_id uuid, client_table text, is_active boolean, tables integer, invited integer, signed_in integer, sign_in_method text, opened_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"list_portals_everywhere\", args: \"p_archived text DEFAULT 'active'::text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"listed_predicate_sql\", args: \"p_user uuid, p_organization_id uuid, p_table_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level, p_alias text DEFAULT 'r'::text\", returns: \"text\", security: \"invoker\" },\n  { name: \"lookup_value\", args: \"p_organization_id uuid, p_record_id uuid, p_field_data jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"mask_document\", args: \"p_document jsonb, p_visible_keys text[], p_notices jsonb, p_by_id boolean DEFAULT false, p_key_ids jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"mask_document\", args: \"p_document jsonb, p_visible_keys text[], p_notices jsonb, p_by_id boolean DEFAULT false, p_key_ids jsonb DEFAULT '{}'::jsonb, p_declared_keys text[] DEFAULT NULL::text[]\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"mask_history_data\", args: \"p_data jsonb, p_mask jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"mask_says_withheld\", args: \"p_mask jsonb, p_key text\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"may_invite_outside\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"may_see_table_structure\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"member_personal_tables\", args: \"p_organization_id uuid, p_person uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"member_records_take_over\", args: \"p_organization_id uuid, p_from uuid, p_to uuid, p_reason text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"merge_field_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"migrate_choice_keys\", args: \"p_organization_id uuid, p_table_id uuid, p_dry_run boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_delete\", args: \"p_organization_id uuid, p_record_id uuid, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_demote\", args: \"p_organization_id uuid, p_table_id uuid, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_extract_parent\", args: \"p_organization_id uuid, p_id uuid, p_parent_table_id uuid, p_moved_keys text[], p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_merge\", args: \"p_organization_id uuid, p_winner_id uuid, p_loser_id uuid, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_promote\", args: \"p_organization_id uuid, p_table_id uuid, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_purge\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_dry_run boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_purge_hard\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_compliance_reason text DEFAULT NULL::text, p_chunk integer DEFAULT 200, p_dry_run boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_purge_hard_request\", args: \"p_organization_id uuid, p_table_id uuid, p_compliance_reason text\", returns: \"void\", security: \"definer\" },\n  { name: \"migrate_reclass\", args: \"p_organization_id uuid, p_id uuid, p_to text DEFAULT 'field'::text, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_rename\", args: \"p_organization_id uuid, p_id uuid, p_to text, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_reparent\", args: \"p_organization_id uuid, p_id uuid, p_parent_id uuid, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_retype\", args: \"p_organization_id uuid, p_id uuid, p_to text, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_split\", args: \"p_organization_id uuid, p_record_id uuid, p_moved_keys text[], p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrate_undo\", args: \"p_organization_id uuid, p_log_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"migrations\", args: \"p_organization_id uuid, p_target_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 100\", returns: \"TABLE(id uuid, verb text, target_kind text, target_id uuid, note text, applied_at timestamp with time zone, applied_by uuid, undone_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"mirror_asks_the_whole_database\", args: \"\", returns: \"TABLE(schema_name text, table_name text, policy_name text, why text)\", security: \"invoker\" },\n  { name: \"my_level\", args: \"p_organization_id uuid, p_id uuid, p_type text DEFAULT 'record'::text\", returns: \"permission_level\", security: \"definer\" },\n  { name: \"my_levels\", args: \"p_organization_id uuid, p_ids jsonb, p_type text DEFAULT 'record'::text\", returns: \"TABLE(id uuid, level permission_level)\", security: \"definer\" },\n  { name: \"my_levels_across\", args: \"p_asks jsonb\", returns: \"TABLE(organization_id uuid, id uuid, level permission_level, refused text)\", security: \"definer\" },\n  { name: \"opening_view_shape\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"organization_clear\", args: \"p_organization_id uuid, p_confirm text, p_and_destroy boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"organization_contents\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"organization_has_a_public_table\", args: \"p_organization_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"organization_home_id\", args: \"p_organization_id uuid\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"organization_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"organization_pick_lists\", args: \"p_organization_id uuid\", returns: \"TABLE(id uuid, list_name text, description text, updated_at timestamp with time zone, lives_in text)\", security: \"definer\" },\n  { name: \"organization_references\", args: \"p_kind text, p_organization_id uuid, p_row jsonb\", returns: \"TABLE(site text, what text, ref_id uuid, openable boolean)\", security: \"invoker\" },\n  { name: \"owning_table\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"owning_table_gone\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"page_ceiling\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"integer\", security: \"invoker\" },\n  { name: \"page_contract\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"page_size\", args: \"p_organization_id uuid, p_door text, p_limit integer, p_default integer DEFAULT NULL::integer, p_ceiling integer DEFAULT NULL::integer\", returns: \"integer\", security: \"invoker\" },\n  { name: \"parity_field_types\", args: \"\", returns: \"TABLE(parity_type text, behavior text, made_of text)\", security: \"invoker\" },\n  { name: \"parity_type\", args: \"p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"parity_values\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(field_key text, field_id uuid, parity_type text, behavior text, unit text, format text, value jsonb, value_version integer, actor text, written_at timestamp with time zone)\", security: \"invoker\" },\n  { name: \"per_value_access_words\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"person_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"phone_canonical\", args: \"p_text text\", returns: \"text\", security: \"invoker\" },\n  { name: \"phone_display\", args: \"p_text text\", returns: \"text\", security: \"invoker\" },\n  { name: \"phone_pattern\", args: \"\", returns: \"text\", security: \"invoker\" },\n  { name: \"pick_list_create\", args: \"p_organization_id uuid, p_list_name text, p_description text DEFAULT NULL::text, p_items jsonb DEFAULT '[]'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pick_list_for_selection\", args: \"p_list_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pick_list_get\", args: \"p_list_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pick_list_index\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pick_list_index_everywhere\", args: \"\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pick_list_update\", args: \"p_list_id uuid, p_list_name text DEFAULT NULL::text, p_description text DEFAULT NULL::text, p_items jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pin_agent_cells\", args: \"p_new jsonb, p_old jsonb, p_agent_keys text[]\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"pipeline_board\", args: \"p_organization_id uuid, p_table_id uuid, p_measure text DEFAULT NULL::text\", returns: \"TABLE(stage_key text, stage_label text, stage_position integer, cards bigint, total numeric, wip_limit integer, over_limit boolean)\", security: \"definer\" },\n  { name: \"pipeline_board\", args: \"p_organization_id uuid, p_table_id uuid, p_measure text, p_filter jsonb\", returns: \"TABLE(stage_key text, stage_label text, stage_position integer, cards bigint, total numeric, wip_limit integer, over_limit boolean)\", security: \"definer\" },\n  { name: \"pipeline_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pipeline_gate_preview\", args: \"p_organization_id uuid, p_table_id uuid, p_stage text, p_gate jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pipeline_move\", args: \"p_organization_id uuid, p_record_id uuid, p_to text, p_also jsonb DEFAULT '{}'::jsonb, p_expected_version integer DEFAULT NULL::integer\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pipeline_move_many\", args: \"p_organization_id uuid, p_moves jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pipeline_pending\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pipeline_read\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pipeline_transition_refusal\", args: \"p_organization_id uuid, p_record_id uuid, p_to text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"pipelines\", args: \"p_organization_id uuid\", returns: \"TABLE(table_id uuid, table_name text, stage_field text, stage_label text, stages integer, rules integer, broken text, updated_at timestamp with time zone, updated_by uuid)\", security: \"definer\" },\n  { name: \"plural_of\", args: \"p_word text\", returns: \"text\", security: \"invoker\" },\n  { name: \"portal_accents\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"portal_admits\", args: \"p_organization_id uuid, p_user_id uuid DEFAULT NULL::uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"portal_archive\", args: \"p_organization_id uuid, p_portal_id uuid, p_confirm_title text, p_reason text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_card\", args: \"p_organization_id uuid, p_portal_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_declare\", args: \"p_organization_id uuid, p_title text, p_client_table_id uuid, p_tables jsonb, p_portal_id uuid DEFAULT NULL::uuid, p_slug text DEFAULT NULL::text, p_sign_in_method text DEFAULT 'magic_link'::text, p_config jsonb DEFAULT NULL::jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"portal_field_map\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(field_id uuid, field_key text, field_type text, points_at uuid)\", security: \"definer\" },\n  { name: \"portal_form\", args: \"p_organization_id uuid, p_portal_id uuid, p_form_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_form_submit\", args: \"p_organization_id uuid, p_portal_id uuid, p_form_id uuid, p_payload jsonb, p_client_key text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_invitation\", args: \"p_slug text, p_email text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_invite\", args: \"p_organization_id uuid, p_portal_id uuid, p_client_record_id uuid, p_email text, p_user_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_invite_accept\", args: \"p_token text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_me\", args: \"\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_preview\", args: \"p_organization_id uuid, p_portal_id uuid, p_principal_id uuid, p_table_id uuid\", returns: \"TABLE(record_id uuid, title text)\", security: \"definer\" },\n  { name: \"portal_principal_bind\", args: \"p_organization_id uuid, p_principal_id uuid, p_user_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_public\", args: \"p_slug text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_record_title\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"portal_restore\", args: \"p_organization_id uuid, p_portal_id uuid, p_confirm_title text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_revoke\", args: \"p_organization_id uuid, p_portal_id uuid, p_principal_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_self_signup\", args: \"p_slug text, p_email text, p_name text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"portal_slug\", args: \"p_organization_id uuid, p_title text, p_portal_id uuid DEFAULT NULL::uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"portal_tables\", args: \"p_organization_id uuid\", returns: \"TABLE(portal_id uuid, table_id uuid, name text)\", security: \"definer\" },\n  { name: \"portals\", args: \"p_organization_id uuid\", returns: \"TABLE(portal_id uuid, title text, slug text, client_table_id uuid, client_table text, is_active boolean, tables integer, invited integer, signed_in integer, sign_in_method text, opened_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"presentation_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"promote_field\", args: \"p_organization_id uuid, p_table_id uuid, p_field_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"promote_table\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"promoted_field_cap\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"promoted_fields\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(field_id uuid, field_key text, parity_type text, is_unique boolean, value_path text, index_arm text, index_expr text, index_name text, indexable boolean, why_not text)\", security: \"invoker\" },\n  { name: \"promoted_index_arm\", args: \"p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"promoted_index_ddl\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(step integer, purpose text, statement text)\", security: \"invoker\" },\n  { name: \"promoted_index_expr\", args: \"p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"promoted_index_name\", args: \"p_table_id uuid, p_field_key text, p_unique boolean\", returns: \"text\", security: \"invoker\" },\n  { name: \"promoted_query_sql\", args: \"p_organization_id uuid, p_table_id uuid, p_field_key text\", returns: \"text\", security: \"invoker\" },\n  { name: \"promoted_read\", args: \"p_organization_id uuid, p_table_id uuid, p_field_key text, p_value text\", returns: \"SETOF uuid\", security: \"invoker\" },\n  { name: \"promoted_value_path\", args: \"p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"promotion_inline_ceiling\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"protected_field_notice\", args: \"p_field custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"protected_field_query_refusal\", args: \"p_field_id uuid, p_verb text\", returns: \"text\", security: \"definer\" },\n  { name: \"protected_field_rule\", args: \"p_token text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"protected_matches\", args: \"p_field_id uuid, p_value jsonb DEFAULT NULL::jsonb\", returns: \"TABLE(row_id uuid, value jsonb)\", security: \"definer\" },\n  { name: \"protected_readers_problem\", args: \"p_token text, p_readers jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"protected_value\", args: \"p_token text, p_row_id uuid, p_field_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"protected_value_leaks\", args: \"p_field_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(place text, table_token text, field_key text, row_id uuid, ref text)\", security: \"definer\" },\n  { name: \"protected_values\", args: \"p_organization_id uuid, p_token text, p_row_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"provenance_prune\", args: \"p_organization_id uuid DEFAULT NULL::uuid, p_dry_run boolean DEFAULT true, p_limit integer DEFAULT 200000\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"provenance_retention_days\", args: \"p_organization_id uuid\", returns: \"integer\", security: \"definer\" },\n  { name: \"provenance_write\", args: \"p_organization_id uuid, p_conversation_id uuid, p_turn_id text, p_rows jsonb\", returns: \"integer\", security: \"definer\" },\n  { name: \"public_definition_owner\", args: \"p_organization_id uuid, p_table_id uuid, p_record_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"publish_bind\", args: \"p_organization_id uuid, p_kind text, p_resource_id uuid, p_slug text, p_render_mode text DEFAULT 'page'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"published_view_read\", args: \"p_slug text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"query_access_ids\", args: \"p_organization_id uuid, p_required text DEFAULT 'viewer'::text\", returns: \"uuid[]\", security: \"invoker\" },\n  { name: \"query_across_homes\", args: \"p_organization_id uuid, p_table_id uuid, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_required text DEFAULT 'viewer'::text\", returns: \"TABLE(record_id uuid, home_record_id uuid, data jsonb, created_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"query_by_coordinates\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_coordinates jsonb DEFAULT '[]'::jsonb, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_required text DEFAULT 'viewer'::text\", returns: \"TABLE(record_id uuid, table_id uuid, data jsonb, coordinates_matched integer)\", security: \"definer\" },\n  { name: \"query_can_see\", args: \"p_organization_id uuid, p_record_id uuid, p_required text DEFAULT 'viewer'::text\", returns: \"boolean\", security: \"definer\" },\n  { name: \"query_hot_paths\", args: \"\", returns: \"TABLE(name text, statement text)\", security: \"invoker\" },\n  { name: \"query_hot_paths_prepared\", args: \"\", returns: \"TABLE(name text, prepared boolean, generic_plans bigint)\", security: \"invoker\" },\n  { name: \"query_is_store_owner\", args: \"\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"query_prepare_hot\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"query_principal\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"query_record_as_of\", args: \"p_organization_id uuid, p_record_id uuid, p_recorded_at timestamp with time zone DEFAULT NULL::timestamp with time zone, p_world_on date DEFAULT NULL::date, p_required text DEFAULT 'viewer'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"query_record_document\", args: \"p_principal uuid, p_row custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"query_relation_edges\", args: \"p_organization_id uuid, p_flavor text DEFAULT NULL::text, p_role text DEFAULT NULL::text\", returns: \"TABLE(parent_id uuid, child_id uuid, role text, flavor text)\", security: \"definer\" },\n  { name: \"query_rollup\", args: \"p_organization_id uuid, p_roots uuid[], p_flavor text DEFAULT NULL::text, p_role text DEFAULT NULL::text, p_max_depth integer DEFAULT 33, p_required text DEFAULT 'viewer'::text\", returns: \"TABLE(record_id uuid, depth integer)\", security: \"definer\" },\n  { name: \"query_rollup_sum\", args: \"p_organization_id uuid, p_roots uuid[], p_field_key text, p_flavor text DEFAULT NULL::text, p_role text DEFAULT NULL::text, p_max_depth integer DEFAULT 33, p_required text DEFAULT 'viewer'::text\", returns: \"numeric\", security: \"definer\" },\n  { name: \"query_table_as_of\", args: \"p_organization_id uuid, p_table_id uuid, p_recorded_at timestamp with time zone DEFAULT NULL::timestamp with time zone, p_world_on date DEFAULT NULL::date, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_required text DEFAULT 'viewer'::text\", returns: \"TABLE(record_id uuid, data jsonb)\", security: \"definer\" },\n  { name: \"query_table_homes\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"SETOF uuid\", security: \"definer\" },\n  { name: \"query_visibility_parity\", args: \"p_organization_id uuid\", returns: \"TABLE(side text, container_type text, container_id uuid, item_type text, item_id uuid, stored_level permission_level, derived_level permission_level, reason text)\", security: \"definer\" },\n  { name: \"query_visible_ids\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid, p_required text DEFAULT 'viewer'::text\", returns: \"SETOF uuid\", security: \"definer\" },\n  { name: \"reachable_from\", args: \"p_organization_id uuid, p_roots uuid[]\", returns: \"TABLE(record_id uuid, depth integer, via text)\", security: \"invoker\" },\n  { name: \"reaches_directly\", args: \"p_user_id uuid, p_type text, p_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level\", returns: \"boolean\", security: \"definer\" },\n  { name: \"reaches_directly_many\", args: \"p_user_id uuid, p_targets uuid[], p_type text DEFAULT 'record'::text, p_required permission_level DEFAULT 'viewer'::permission_level\", returns: \"TABLE(target uuid, reaches boolean)\", security: \"definer\" },\n  { name: \"read_door_carried_ids\", args: \"p_user uuid, p_organization_id uuid, p_table_id uuid, p_required permission_level, OUT o_ids uuid[], OUT o_containers integer\", returns: \"record\", security: \"definer\" },\n  { name: \"read_door_granted_ids\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"uuid[]\", security: \"definer\" },\n  { name: \"read_door_ladder_ceiling\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"read_door_parity\", args: \"p_organization_id uuid, p_table_id uuid, p_user uuid, p_required permission_level, p_sample integer\", returns: \"TABLE(record_id uuid, set_based boolean, per_row boolean, verdict text)\", security: \"definer\" },\n  { name: \"read_mask\", args: \"p_organization_id uuid, p_record_id uuid, p_action text DEFAULT 'read'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"read_mask_at\", args: \"p_record_id uuid, p_level_given boolean, p_level permission_level, p_action text DEFAULT 'read'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"read_mask_for\", args: \"p_user_id uuid, p_organization_id uuid, p_table_id uuid, p_level permission_level, p_action text DEFAULT 'read'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"read_paths_outside_the_door\", args: \"\", returns: \"TABLE(object_name text, why text)\", security: \"invoker\" },\n  { name: \"read_record\", args: \"p_organization_id uuid, p_record_id uuid, p_by_id boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"read_records\", args: \"p_organization_id uuid, p_table_id uuid, p_by_id boolean DEFAULT false, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0\", returns: \"TABLE(id uuid, document jsonb, level permission_level)\", security: \"definer\" },\n  { name: \"read_records_archived\", args: \"p_organization_id uuid, p_table_id uuid, p_lane text DEFAULT 'org'::text, p_by_id boolean DEFAULT false, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0\", returns: \"TABLE(id uuid, document jsonb, level permission_level, archived_at timestamp with time zone, archived_by uuid, archived_by_name text)\", security: \"definer\" },\n  { name: \"read_records_by_ids\", args: \"p_organization_id uuid, p_table_id uuid, p_record_ids uuid[], p_by_id boolean DEFAULT false\", returns: \"TABLE(id uuid, document jsonb, level permission_level)\", security: \"definer\" },\n  { name: \"read_records_in_view_order\", args: \"p_organization_id uuid, p_view_id uuid, p_by_id boolean DEFAULT false, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0, p_filter jsonb DEFAULT NULL::jsonb\", returns: \"TABLE(id uuid, document jsonb, level permission_level, \\\"position\\\" numeric)\", security: \"definer\" },\n  { name: \"read_records_keyset\", args: \"p_organization_id uuid, p_table_id uuid, p_filter jsonb DEFAULT '{}'::jsonb, p_search text DEFAULT NULL::text, p_sort jsonb DEFAULT '[]'::jsonb, p_after jsonb DEFAULT NULL::jsonb, p_limit integer DEFAULT 50, p_time_zone text DEFAULT NULL::text, p_ids uuid[] DEFAULT NULL::uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"read_records_matching\", args: \"p_organization_id uuid, p_table_id uuid, p_filter jsonb DEFAULT '{}'::jsonb, p_by_id boolean DEFAULT false, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0\", returns: \"TABLE(id uuid, document jsonb, level permission_level)\", security: \"definer\" },\n  { name: \"read_records_page\", args: \"p_organization_id uuid, p_table_id uuid, p_filter jsonb DEFAULT '{}'::jsonb, p_search text DEFAULT NULL::text, p_sort jsonb DEFAULT '[]'::jsonb, p_view_id uuid DEFAULT NULL::uuid, p_by_id boolean DEFAULT false, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_time_zone text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"realtime_presence_topic_admits\", args: \"p_topic text\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"realtime_topic_admits\", args: \"p_topic text\", returns: \"boolean\", security: \"definer\" },\n  { name: \"record_aggregate\", args: \"p_organization_id uuid, p_table_id uuid, p_group_by jsonb DEFAULT '[]'::jsonb, p_measures jsonb DEFAULT '[]'::jsonb, p_bucket jsonb DEFAULT NULL::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_limit integer DEFAULT 200, p_required text DEFAULT 'viewer'::text, p_compare jsonb DEFAULT NULL::jsonb, p_search text DEFAULT NULL::text, p_time_zone text DEFAULT NULL::text, p_split_multi boolean DEFAULT false\", returns: \"TABLE(groups jsonb, measures jsonb, row_count bigint, prior_groups jsonb, prior_measures jsonb, prior_row_count bigint, delta jsonb, compare jsonb)\", security: \"definer\" },\n  { name: \"record_aggregate_as_of\", args: \"p_organization_id uuid, p_table_id uuid, p_recorded_at timestamp with time zone, p_measure text DEFAULT 'count'::text, p_field_key text DEFAULT NULL::text, p_group_by text DEFAULT NULL::text, p_match jsonb DEFAULT '{}'::jsonb\", returns: \"TABLE(bucket text, result numeric, row_count bigint, not_numbers bigint, a_non_number text)\", security: \"definer\" },\n  { name: \"record_applicability\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(rule_id uuid, rule_name text, rule_version integer, applies boolean, answer jsonb)\", security: \"invoker\" },\n  { name: \"record_archiver\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"record_as_of\", args: \"p_organization_id uuid, p_record_id uuid, p_at timestamp with time zone\", returns: \"TABLE(state jsonb, replayed boolean)\", security: \"definer\" },\n  { name: \"record_card\", args: \"p_viewer uuid, p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_carrying_edges\", args: \"p_id uuid, p_data_class text, p_data jsonb, p_deleted_at timestamp with time zone\", returns: \"TABLE(container_id uuid, item_id uuid, edge_role text)\", security: \"invoker\" },\n  { name: \"record_change_actions\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_change_many\", args: \"p_organization_id uuid, p_table_id uuid, p_changes jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_changes_drain\", args: \"p_organization_id uuid, p_consumer text, p_limit integer DEFAULT 100\", returns: \"TABLE(event_id uuid, organization_id uuid, table_id uuid, record_id uuid, kind text, operation text, version integer, fields jsonb, changed_field_ids jsonb, actor jsonb, chain jsonb, op_id uuid, occurred_at timestamp with time zone, via text)\", security: \"definer\" },\n  { name: \"record_delete\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"timestamp with time zone\", security: \"definer\" },\n  { name: \"record_drill\", args: \"p_organization_id uuid, p_table_id uuid, p_question jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_entity_edges\", args: \"p_organization_id uuid, p_id uuid, p_table_id uuid, p_data_class text, p_data jsonb, p_deleted_at timestamp with time zone\", returns: \"TABLE(target_type text, target_id uuid, edge_role text, field_id uuid, ord integer)\", security: \"invoker\" },\n  { name: \"record_filter_sql\", args: \"p_filter jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"record_filter_sql\", args: \"p_organization_id uuid, p_table_id uuid, p_filter jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"record_follow_set\", args: \"p_organization_id uuid, p_record_id uuid, p_follow boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_followers\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_headers\", args: \"p_organization_id uuid, p_ids uuid[]\", returns: \"TABLE(id uuid, table_id uuid, created_at timestamp with time zone, updated_at timestamp with time zone, version integer, deleted_at timestamp with time zone, mine boolean, created_by uuid)\", security: \"definer\" },\n  { name: \"record_history\", args: \"p_organization_id uuid, p_record_id uuid, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0\", returns: \"TABLE(version integer, occurred_at timestamp with time zone, operation text, operation_label text, actor jsonb, changes jsonb, migration_id uuid, undoable boolean)\", security: \"definer\" },\n  { name: \"record_org_hint\", args: \"p_id uuid, p_organization_id uuid\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"record_page_bundle\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"record_platform_keys\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"record_relation_edges\", args: \"p_organization_id uuid, p_id uuid, p_table_id uuid, p_data_class text, p_data jsonb, p_deleted_at timestamp with time zone\", returns: \"TABLE(target_id uuid, edge_role text, field_id uuid, ord integer)\", security: \"invoker\" },\n  { name: \"record_reparent\", args: \"p_organization_id uuid, p_record_id uuid, p_parent_id uuid\", returns: \"void\", security: \"definer\" },\n  { name: \"record_resolve\", args: \"p_organization_id uuid, p_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_restore\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_restore_preview\", args: \"p_organization_id uuid, p_record_id uuid, p_version integer, p_field_key text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_restore_version\", args: \"p_organization_id uuid, p_record_id uuid, p_version integer\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_restore_version\", args: \"p_organization_id uuid, p_record_id uuid, p_version integer, p_author jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_row_controls\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_row_controls_set\", args: \"p_organization_id uuid, p_record_id uuid, p_controls jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_runs\", args: \"p_organization_id uuid, p_record_id uuid, p_limit integer DEFAULT 50\", returns: \"TABLE(run_id uuid, kind text, name text, trigger_name text, status text, started_at timestamp with time zone, finished_at timestamp with time zone, steps integer, says text, ran_by uuid)\", security: \"definer\" },\n  { name: \"record_scope_context\", args: \"p_organization_id uuid, p_record_id uuid, p_relations integer DEFAULT 12, p_history integer DEFAULT 15, p_siblings integer DEFAULT 8\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_search_sql\", args: \"p_organization_id uuid, p_table_id uuid, p_search text, p_alias text DEFAULT 'r'::text, p_time_zone text DEFAULT NULL::text\", returns: \"text\", security: \"invoker\" },\n  { name: \"record_source_key\", args: \"p_table_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"record_source_keys\", args: \"p_table_id uuid\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"record_source_table\", args: \"p_key text\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"record_stage_pending\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_state_as_of\", args: \"p_record_id uuid, p_at timestamp with time zone\", returns: \"TABLE(state jsonb, replayed boolean)\", security: \"definer\" },\n  { name: \"record_table\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"record_triggers\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(trigger_id uuid, name text, definition_id uuid, definition_name text, table_id uuid, event text, operations jsonb, field_ids jsonb, via jsonb, is_active boolean, last_fired_at timestamp with time zone, fire_count integer, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"record_update\", args: \"p_organization_id uuid, p_record_id uuid, p_patch jsonb, p_expected_version integer DEFAULT NULL::integer\", returns: \"integer\", security: \"definer\" },\n  { name: \"record_update_adding_choices\", args: \"p_organization_id uuid, p_record_id uuid, p_patch jsonb, p_add jsonb, p_expected_version integer DEFAULT NULL::integer\", returns: \"integer\", security: \"definer\" },\n  { name: \"record_upsert\", args: \"p_organization_id uuid, p_table_id uuid, p_key text[], p_data jsonb, p_expected_version integer DEFAULT NULL::integer\", returns: \"uuid\", security: \"definer\" },\n  { name: \"record_value_one\", args: \"p_organization_id uuid, p_record_id uuid, p_key text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"record_values\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"record_values_of\", args: \"p_row custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"record_values_step\", args: \"p_row custom.record, p_cache jsonb DEFAULT '{}'::jsonb, OUT o_doc jsonb, OUT o_cache jsonb\", returns: \"record\", security: \"invoker\" },\n  { name: \"record_values_versioned\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(field_key text, field_id uuid, value jsonb, value_version integer, source jsonb, absent_reason text, actor text, on_behalf_of text, written_at timestamp with time zone, alternates jsonb)\", security: \"definer\" },\n  { name: \"record_words\", args: \"p_organization_id uuid, p_record_id uuid, p_noun text DEFAULT NULL::text\", returns: \"text\", security: \"definer\" },\n  { name: \"record_write\", args: \"p_organization_id uuid, p_table_id uuid, p_data jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"record_write_graph\", args: \"p_organization_id uuid, p_table_id uuid, p_parent jsonb, p_edges jsonb DEFAULT '[]'::jsonb, p_children jsonb DEFAULT '[]'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_write_graph_superseding\", args: \"p_organization_id uuid, p_table_id uuid, p_lock_key text, p_idempotence jsonb DEFAULT NULL::jsonb, p_parent jsonb DEFAULT NULL::jsonb, p_edges jsonb DEFAULT '[]'::jsonb, p_children jsonb DEFAULT '[]'::jsonb, p_chain jsonb DEFAULT '{\\\"mode\\\": \\\"first\\\"}'::jsonb, p_rows_state jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"record_write_many\", args: \"p_organization_id uuid, p_table_id uuid, p_rows jsonb[], p_ids uuid[] DEFAULT NULL::uuid[]\", returns: \"uuid[]\", security: \"definer\" },\n  { name: \"records_limits\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"records_search\", args: \"p_search text, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_table_ids uuid[] DEFAULT NULL::uuid[], p_organization_ids uuid[] DEFAULT NULL::uuid[], p_include_platform_tables boolean DEFAULT false\", returns: \"TABLE(record_id uuid, table_id uuid, table_name text, name text, organization_id uuid, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"refusals_claiming_a_level_never_asked\", args: \"\", returns: \"TABLE(function_name text, identity_args text, why text)\", security: \"invoker\" },\n  { name: \"relation_carry\", args: \"p_organization_id uuid, p_container_id uuid, p_item_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"relation_edges_withdraw\", args: \"p_organization_id uuid, p_field_ids uuid[], p_why text\", returns: \"integer\", security: \"definer\" },\n  { name: \"relation_halves_disagreements\", args: \"p_organization_id uuid DEFAULT NULL::uuid, p_record_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(organization_id uuid, record_id uuid, field_key text, field_id uuid, target_id uuid, direction text, remedy text, why text)\", security: \"definer\" },\n  { name: \"relation_halves_repair\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"relation_kernel_record\", args: \"p_organization_id uuid, p_kernel_table_id uuid, p_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"relation_name_key\", args: \"p_text text\", returns: \"text\", security: \"invoker\" },\n  { name: \"relation_names_match\", args: \"p_organization_id uuid, p_table_id uuid, p_names text[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"relation_own\", args: \"p_organization_id uuid, p_owner_id uuid, p_target_id uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"relation_restore\", args: \"p_organization_id uuid, p_relation_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"relation_reverse_field\", args: \"p_organization_id uuid, p_field_id uuid, p_label text DEFAULT NULL::text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"relation_reverse_set\", args: \"p_organization_id uuid, p_record_id uuid, p_field_id uuid, p_add uuid[] DEFAULT '{}'::uuid[], p_remove uuid[] DEFAULT '{}'::uuid[]\", returns: \"integer\", security: \"definer\" },\n  { name: \"relation_target_card\", args: \"p_organization_id uuid, p_record_id uuid, p_via_key text DEFAULT NULL::text\", returns: \"TABLE(target_id uuid, target_organization_id uuid, is_foreign boolean, masked boolean, reader_level permission_level, card jsonb, why text)\", security: \"definer\" },\n  { name: \"relation_target_external\", args: \"p_connection_token text, p_external_table text, p_external_key text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"relation_target_ours\", args: \"p_entity_token text, p_row_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"relation_targets\", args: \"p_organization_id uuid, p_record_id uuid, p_via_key text\", returns: \"SETOF uuid\", security: \"definer\" },\n  { name: \"relation_uncarry\", args: \"p_organization_id uuid, p_container_id uuid, p_item_id uuid\", returns: \"integer\", security: \"definer\" },\n  { name: \"relation_value_target_ok\", args: \"p_organization_id uuid, p_field_id uuid, p_field_data jsonb, p_target_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"relation_words\", args: \"p_organization_id uuid, p_field_id uuid, p_value text\", returns: \"text\", security: \"definer\" },\n  { name: \"relation_words_many\", args: \"p_organization_id uuid, p_field_id uuid, p_record_ids uuid[]\", returns: \"TABLE(record_id uuid, words text, archived boolean)\", security: \"definer\" },\n  { name: \"relation_words_with_icons_many\", args: \"p_organization_id uuid, p_field_id uuid, p_record_ids uuid[]\", returns: \"TABLE(record_id uuid, words text, archived boolean, icon text, table_icon text)\", security: \"definer\" },\n  { name: \"relative_window_for_reader\", args: \"p_window jsonb, p_organization_id uuid, p_instants boolean DEFAULT false\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"relative_window_resolve\", args: \"p_window jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"reopen_declared_doors\", args: \"\", returns: \"TABLE(reopened text)\", security: \"definer\" },\n  { name: \"required_epoch\", args: \"p_container_type text, p_container_id uuid, p_item_type text, p_item_id uuid\", returns: \"bigint\", security: \"definer\" },\n  { name: \"resolve_context\", args: \"p_entity_type text, p_entity_id uuid, p_record_ids uuid[] DEFAULT NULL::uuid[], p_table_ids uuid[] DEFAULT NULL::uuid[], p_system_item_refs text[] DEFAULT NULL::text[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"resolve_first_match\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"resolve_id\", args: \"p_organization_id uuid, p_id uuid\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"retired_actor_words\", args: \"\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"reverse_columns\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(key text, label text, source_field_id uuid, source_field_key text, source_field_label text, source_table_id uuid, source_table_name text, cardinality text, read_only boolean)\", security: \"definer\" },\n  { name: \"reverse_links_many\", args: \"p_organization_id uuid, p_table_id uuid, p_field_id uuid, p_record_ids uuid[], p_limit integer DEFAULT 10, p_offset integer DEFAULT 0\", returns: \"TABLE(record_id uuid, total integer, links jsonb)\", security: \"definer\" },\n  { name: \"reverse_links_many_fields\", args: \"p_organization_id uuid, p_table_id uuid, p_field_ids uuid[], p_record_ids uuid[], p_limit integer DEFAULT 10, p_offset integer DEFAULT 0\", returns: \"TABLE(field_id uuid, record_id uuid, total integer, links jsonb)\", security: \"invoker\" },\n  { name: \"revoke_view_share_link\", args: \"p_link_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"rollup_value\", args: \"p_organization_id uuid, p_record_id uuid, p_field_data jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"row_actions\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"row_sits_in_a_personal_table\", args: \"p_type text, p_organization_id uuid, p_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"row_template_bodies\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(template_id uuid, body jsonb)\", security: \"definer\" },\n  { name: \"row_template_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_spec jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"row_template_default\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(template_id uuid, name text, \\\"values\\\" jsonb, body jsonb)\", security: \"definer\" },\n  { name: \"row_templates\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(template_id uuid, name text, table_id uuid, \\\"values\\\" jsonb, created_at timestamp with time zone, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"rule_applies\", args: \"p_organization_id uuid, p_rule_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_context\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_declare\", args: \"p_organization_id uuid, p_spec jsonb, p_rule_id uuid DEFAULT NULL::uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"rule_dependency_edges\", args: \"p_organization_id uuid, p_row custom.record DEFAULT NULL::custom.record\", returns: \"TABLE(needs text, needed text)\", security: \"invoker\" },\n  { name: \"rule_eval\", args: \"p_organization_id uuid, p_expr jsonb, p_values jsonb, p_context jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_field_key\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"rule_field_label\", args: \"p_organization_id uuid, p_field_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"rule_filter_node_sql\", args: \"p_organization_id uuid, p_table_id uuid, p_node jsonb, p_map jsonb, p_visible text[]\", returns: \"text\", security: \"invoker\" },\n  { name: \"rule_filter_skip_withheld\", args: \"p_organization_id uuid, p_table_id uuid, p_node jsonb, p_visible text[]\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_is_me\", args: \"p_op text, p_a jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_is_me\", args: \"p_op text, p_a jsonb, p_organization_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"rule_members\", args: \"p_organization_id uuid, p_rule_id uuid\", returns: \"SETOF custom.record\", security: \"invoker\" },\n  { name: \"rule_members_visible\", args: \"p_organization_id uuid, p_rule_id uuid, p_limit integer DEFAULT 200, p_offset integer DEFAULT 0\", returns: \"TABLE(id uuid, document jsonb, level permission_level)\", security: \"definer\" },\n  { name: \"rule_membership\", args: \"p_organization_id uuid, p_rule_id uuid, p_record_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_node_kinds\", args: \"\", returns: \"TABLE(node text, evaluated_by text, note text)\", security: \"invoker\" },\n  { name: \"rule_restore\", args: \"p_organization_id uuid, p_rule_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"rule_run\", args: \"p_organization_id uuid, p_rule_id uuid, p_values jsonb, p_context jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_sql_op\", args: \"p_op text, p_a jsonb, p_b jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"rule_truth\", args: \"p_answer jsonb\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"rule_uses\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"rule_version\", args: \"p_organization_id uuid, p_rule_id uuid\", returns: \"integer\", security: \"invoker\" },\n  { name: \"said\", args: \"p_value text, p_when_there_is_none text\", returns: \"text\", security: \"invoker\" },\n  { name: \"scope_item_row_of\", args: \"p_field custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"scope_item_value_type\", args: \"p_field jsonb, p_carried jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"scope_items_of\", args: \"p_org uuid, p_table uuid\", returns: \"SETOF custom.record\", security: \"invoker\" },\n  { name: \"scope_member_reaches\", args: \"p_user_id uuid, p_record_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"scope_row_of\", args: \"p_rec custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"scope_rows_of\", args: \"p_org uuid, p_types uuid[] DEFAULT NULL::uuid[]\", returns: \"TABLE(id uuid, table_id uuid, type_sort integer, sort_order integer, name text, type_doc jsonb, row_doc jsonb)\", security: \"invoker\" },\n  { name: \"scope_setting_back\", args: \"p_value jsonb, p_behavior text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"scope_table_provision\", args: \"p_organization_id uuid, p_item_id uuid, p_scope_id uuid, p_home_id uuid DEFAULT NULL::uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"scope_type_row_of\", args: \"p_table custom.record\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"scope_value_columns\", args: \"p_org uuid, p_field jsonb, p_value_type text, p_value jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"seen_among\", args: \"p_user_id uuid, p_ids uuid[]\", returns: \"uuid[]\", security: \"definer\" },\n  { name: \"sensitivity_rank\", args: \"p_sensitivity text\", returns: \"integer\", security: \"invoker\" },\n  { name: \"set_table_confidential\", args: \"p_table_id uuid, p_readers jsonb, p_reason text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"set_table_confidential_arman_explicitly_approved\", args: \"p_table_id uuid, p_readers jsonb, p_arman_words text, p_approved_on date, p_maker_is_reader boolean DEFAULT NULL::boolean\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"set_table_organization\", args: \"p_table_id uuid, p_reason text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"set_view_share_link_copy\", args: \"p_link_id uuid, p_restrict boolean\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"set_view_share_link_protection\", args: \"p_link_id uuid, p_password text DEFAULT NULL::text, p_change_expiry boolean DEFAULT false, p_expires_at timestamp with time zone DEFAULT NULL::timestamp with time zone\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"share_access\", args: \"p_organization_id uuid, p_subject_id uuid\", returns: \"TABLE(principal_kind text, principal_id uuid, principal_label text, level permission_level, reason text, reason_detail text, via_type text, via_id uuid, revocable boolean)\", security: \"definer\" },\n  { name: \"share_grant\", args: \"p_organization_id uuid, p_subject_id uuid, p_principal_kind text, p_principal_id uuid, p_level permission_level DEFAULT 'viewer'::permission_level\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"share_lane_set\", args: \"p_organization_id uuid, p_subject_id uuid, p_choice text, p_level permission_level DEFAULT NULL::permission_level\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"share_lanes\", args: \"\", returns: \"TABLE(choice text, lane text, discoverable boolean, label text, means text)\", security: \"definer\" },\n  { name: \"share_levels\", args: \"\", returns: \"TABLE(level permission_level, ordinal integer, label text, means text)\", security: \"definer\" },\n  { name: \"share_lists_row\", args: \"p_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"share_people\", args: \"p_organization_id uuid, p_subject_id uuid DEFAULT NULL::uuid, p_query text DEFAULT NULL::text, p_limit integer DEFAULT 25\", returns: \"TABLE(user_id uuid, email text, display_name text, membership text, already_at permission_level, already_why text)\", security: \"definer\" },\n  { name: \"share_revoke\", args: \"p_organization_id uuid, p_subject_id uuid, p_principal_kind text, p_principal_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"share_subject_name\", args: \"p_organization_id uuid, p_type text, p_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"shared_only_disagreements\", args: \"p_pretend text DEFAULT NULL::text\", returns: \"TABLE(organization_id uuid, organization_name text, member_id uuid, record_id uuid, table_id uuid, ladder boolean, read_door boolean, rls_mirror boolean, why text)\", security: \"invoker\" },\n  { name: \"shared_view_read\", args: \"p_token text, p_password text DEFAULT NULL::text, p_unlock text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"shares_outside\", args: \"p_organization_id uuid\", returns: \"TABLE(invitation_id uuid, table_id uuid, table_name text, email text, level text, level_label text, status text, joined boolean, expired boolean, invited_at timestamp with time zone, expires_at timestamp with time zone, say text)\", security: \"definer\" },\n  { name: \"sign_request_sentence\", args: \"p_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"sign_request_state\", args: \"p_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"sign_requests\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(request_id uuid, render_id uuid, record_id uuid, field_key text, document_title text, signer_name text, signer_email text, signer_has_account boolean, state text, sentence text, document_version integer, document_hash text, sent_at timestamp with time zone, expires_at timestamp with time zone, viewed_at timestamp with time zone, signed_at timestamp with time zone, declined_at timestamp with time zone, invalidated_at timestamp with time zone, signature_id uuid, signature_mark text, reminder_count integer)\", security: \"definer\" },\n  { name: \"silent_page_doors\", args: \"\", returns: \"TABLE(door text, why text)\", security: \"definer\" },\n  { name: \"size_refusal\", args: \"p_organization_id uuid, p_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"source_next_pointer\", args: \"p_sources jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"source_pointer\", args: \"p_sources jsonb, p_source jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"space_templates\", args: \"p_filter jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"stage_rule_enforcement\", args: \"p_organization_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"stage_rule_on_fail_kinds\", args: \"\", returns: \"TABLE(behaviour text, note text)\", security: \"invoker\" },\n  { name: \"stamp_value_envelopes\", args: \"p_data jsonb, p_actor text, p_on_behalf_of text, p_at timestamp with time zone\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"status_groups_keyed\", args: \"p_organization_id uuid, p_options_table_id uuid, p_groups jsonb, p_kept jsonb, p_label text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"status_groups_of\", args: \"p_groups jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"storage_modes\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"store_census_pair_ceiling\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"store_field_part\", args: \"p_field_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"store_is_open\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"store_off_sentence\", args: \"p_organization_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"store_part_notice\", args: \"p_field custom.record, p_action text DEFAULT 'read'::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"store_part_who\", args: \"p_cells jsonb, p_action text DEFAULT 'read'::text\", returns: \"text\", security: \"definer\" },\n  { name: \"store_row_visible\", args: \"p_person uuid, p_table uuid, p_row custom.record, p_visible text[]\", returns: \"text[]\", security: \"definer\" },\n  { name: \"store_row_visible_with\", args: \"p_reveals jsonb, p_person uuid, p_row custom.record, p_visible text[]\", returns: \"text[]\", security: \"definer\" },\n  { name: \"store_seat_fallback\", args: \"p_org uuid\", returns: \"SETOF uuid\", security: \"definer\" },\n  { name: \"store_seat_has\", args: \"p_person uuid, p_record uuid, p_seat jsonb\", returns: \"boolean\", security: \"definer\" },\n  { name: \"store_seat_holders\", args: \"p_record uuid, p_seat jsonb\", returns: \"TABLE(user_id uuid, source text)\", security: \"definer\" },\n  { name: \"store_seat_invalid\", args: \"p_seat jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"store_seat_records\", args: \"p_person uuid, p_table uuid, p_seat jsonb\", returns: \"SETOF uuid\", security: \"definer\" },\n  { name: \"subscription_cadences\", args: \"p_organization_id uuid\", returns: \"text[]\", security: \"definer\" },\n  { name: \"subscription_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_spec jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"subscription_mute\", args: \"p_organization_id uuid, p_rule_id uuid, p_muted boolean DEFAULT true\", returns: \"boolean\", security: \"definer\" },\n  { name: \"subscription_preview\", args: \"p_organization_id uuid, p_rule_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"subscriptions\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(rule_id uuid, name text, table_id uuid, saved_view_id uuid, cadence text, schedule text, quiet_hours jsonb, channel text, recipient_user_id uuid, event_key text, muted boolean, mine boolean, i_may_mute boolean, last_sent_at timestamp with time zone, next_digest_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"synced_source_archive_log\", args: \"p_id uuid, p_job text DEFAULT NULL::text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"synced_source_archive_log_add\", args: \"p_id uuid, p_job text, p_entry jsonb, p_now timestamp with time zone DEFAULT now()\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"synced_source_by_ref\", args: \"p_organization_id uuid, p_source_kinds text[], p_source_ref text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"synced_source_finish\", args: \"p_id uuid, p_cursor jsonb, p_synced_at timestamp with time zone, p_report jsonb, p_mapping jsonb, p_run_id uuid\", returns: \"void\", security: \"definer\" },\n  { name: \"synced_source_read\", args: \"p_organization_id uuid, p_source_kind text, p_target uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"synced_source_save\", args: \"p_organization_id uuid, p_source_kind text, p_source_ref text, p_title text, p_target uuid, p_owner uuid, p_connector jsonb, p_actor uuid\", returns: \"uuid\", security: \"definer\" },\n  { name: \"synced_sources_for\", args: \"p_source_ref text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_access_setup\", args: \"p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_access_setup_preview\", args: \"p_table_id uuid, p_setup jsonb, p_moves jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_access_setup_revert\", args: \"p_table_id uuid, p_audit_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_access_setup_set\", args: \"p_table_id uuid, p_setup jsonb, p_moves jsonb DEFAULT '{}'::jsonb, p_reason text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_add_rung\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"permission_level\", security: \"invoker\" },\n  { name: \"table_agent_writable_set\", args: \"p_organization_id uuid, p_table_id uuid, p_agent_writable boolean\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_archive\", args: \"p_organization_id uuid, p_table_id uuid, p_chunk integer DEFAULT 50, p_include_table boolean DEFAULT true\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_archive_deliberately\", args: \"p_organization_id uuid, p_table_id uuid, p_typed_slug text, p_reason text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_capacity\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_carries_its_rows\", args: \"p_user_id uuid, p_table_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level\", returns: \"boolean\", security: \"definer\" },\n  { name: \"table_column_source\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"table_contents\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(record_id uuid, kind text, goes_at integer)\", security: \"invoker\" },\n  { name: \"table_copies_in_progress\", args: \"\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_copy_sync\", args: \"p_organization_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_create\", args: \"p_organization_id uuid, p_spec jsonb, p_fields jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"table_declare\", args: \"p_organization_id uuid, p_spec jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"table_decorate\", args: \"p_organization_id uuid, p_table_id uuid, p_path text[], p_value jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_decorations\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_dimensions\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_dimensions_set\", args: \"p_organization_id uuid, p_table_id uuid, p_overrides jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_duplicate\", args: \"p_table_id uuid, p_with_records boolean DEFAULT false, p_name text DEFAULT NULL::text, p_organization_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_duplicate_continue\", args: \"p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_ensure\", args: \"p_organization_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_facts\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(table_id uuid, visibility text, mine boolean, platform_owned boolean, kept_for text, offered_as_context boolean, keeper_group text, keeper_says text, used_in_kind text, used_in_id uuid, used_in_table_id uuid, foundation boolean)\", security: \"definer\" },\n  { name: \"table_find\", args: \"p_organization_id uuid, p_slug text DEFAULT NULL::text, p_name text DEFAULT NULL::text, p_kept_for text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_find_many\", args: \"p_organization_ids uuid[], p_slug text, p_kept_for text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_from_example\", args: \"p_organization_id uuid, p_home_id uuid, p_example jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_has_a_visible_record\", args: \"p_user uuid, p_organization_id uuid, p_table_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"table_home\", args: \"p_table_id uuid, p_to_organization_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_homes_named\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(home_id uuid, name text, declared boolean)\", security: \"definer\" },\n  { name: \"table_is_foundation\", args: \"p_data jsonb\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"table_is_live\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"table_is_options_table\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"table_is_platform_context\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"table_kept_for_derived\", args: \"p_data jsonb, p_is_kernel boolean, p_is_options boolean\", returns: \"text\", security: \"invoker\" },\n  { name: \"table_kept_out_of_lists\", args: \"p_kept_for text\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"table_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"table_kind_facts\", args: \"p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_level_facts\", args: \"p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_list_everywhere\", args: \"p_organization_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_list_everywhere\", args: \"p_organization_id uuid, p_include_platform_tables boolean\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"table_map_fields\", args: \"p_organization_id uuid, p_table_ids uuid[]\", returns: \"TABLE(table_id uuid, field_key text, field_label text, field_type text, relation_target uuid, inverse_key text, field_sort numeric, is_link boolean)\", security: \"definer\" },\n  { name: \"table_move\", args: \"p_table_id uuid, p_to_organization_id uuid, p_expected_version integer DEFAULT NULL::integer\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_page_bundle\", args: \"p_organization_id uuid, p_table_id uuid, p_view_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"table_placement\", args: \"p_organization_id uuid, p_table_id uuid, p_data jsonb, p_is_kernel boolean DEFAULT false\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"table_record_ceiling\", args: \"\", returns: \"integer\", security: \"invoker\" },\n  { name: \"table_record_ceiling\", args: \"p_organization_id uuid\", returns: \"integer\", security: \"invoker\" },\n  { name: \"table_restore\", args: \"p_organization_id uuid, p_table_id uuid, p_chunk integer DEFAULT 20\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_row_counts\", args: \"p_organization_id uuid, p_table_ids uuid[]\", returns: \"TABLE(table_id uuid, visible_rows bigint)\", security: \"definer\" },\n  { name: \"table_row_defaults\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_row_defaults_apply\", args: \"p_organization_id uuid, p_table_id uuid, p_after uuid DEFAULT NULL::uuid, p_budget_ms integer DEFAULT 4000\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_row_defaults_set\", args: \"p_organization_id uuid, p_table_id uuid, p_defaults jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_row_label\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_row_label_set\", args: \"p_organization_id uuid, p_table_id uuid, p_formula text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_rules\", args: \"p_organization_id uuid, p_table_id uuid, p_use text, p_record_type text DEFAULT NULL::text\", returns: \"SETOF custom.record\", security: \"invoker\" },\n  { name: \"table_share_outside\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_share_outside_accept\", args: \"p_token text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_share_outside_for_me\", args: \"\", returns: \"TABLE(invitation_id uuid, organization_id uuid, organization text, table_id uuid, table_name text, level text, level_label text, token text, expires_at timestamp with time zone, say text)\", security: \"definer\" },\n  { name: \"table_share_outside_grant\", args: \"p_organization_id uuid, p_table_id uuid, p_person text, p_level permission_level DEFAULT 'viewer'::permission_level\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_share_outside_invite\", args: \"p_organization_id uuid, p_table_id uuid, p_email text, p_level permission_level DEFAULT 'viewer'::permission_level\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_share_outside_resend\", args: \"p_organization_id uuid, p_invitation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_share_outside_revoke\", args: \"p_organization_id uuid, p_invitation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_stage_field\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"table_storage\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"table_sync\", args: \"p_organization_id uuid, p_home_id uuid, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_sync_cell\", args: \"p_organization_id uuid, p_record_id uuid, p_key text, p_land jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_sync_due_tick\", args: \"\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_sync_settings_set\", args: \"p_organization_id uuid, p_table_id uuid, p_settings jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_template_declare\", args: \"p_org_id uuid, p_name text, p_description text, p_fields jsonb\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"table_templates\", args: \"p_org_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_transfer_owner\", args: \"p_table_id uuid, p_to_person uuid, p_reason text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_type_field\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"table_unique_rule_fields\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"table_webhook_archive\", args: \"p_organization_id uuid, p_webhook_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"table_webhook_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_target_url text, p_events text[] DEFAULT NULL::text[], p_description text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"table_webhooks\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(webhook_id uuid, target_url text, description text, events text[], is_active boolean, last_attempt_at timestamp with time zone, last_success_at timestamp with time zone, consecutive_failures integer, owner_id uuid, created_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"table_work_kind\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"tables_at_home\", args: \"p_organization_id uuid, p_home_ids uuid[]\", returns: \"TABLE(table_id uuid, home_record_id uuid, kind text)\", security: \"definer\" },\n  { name: \"tables_described_without_asking\", args: \"\", returns: \"TABLE(function_name text, identity_args text, why text)\", security: \"invoker\" },\n  { name: \"tables_i_can_open\", args: \"\", returns: \"TABLE(table_id uuid, table_name text, organization_id uuid, organization_name text, member boolean, visibility text, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"tables_listed_among\", args: \"p_organization_id uuid, p_tables uuid[]\", returns: \"SETOF uuid\", security: \"invoker\" },\n  { name: \"tables_seen_among\", args: \"p_user_id uuid, p_organization_ids uuid[], p_among uuid[]\", returns: \"TABLE(organization_id uuid, id uuid, seen boolean)\", security: \"definer\" },\n  { name: \"tables_seen_once_per_group\", args: \"p_user_id uuid, p_organization_ids uuid[]\", returns: \"TABLE(organization_id uuid, id uuid, seen boolean)\", security: \"definer\" },\n  { name: \"tables_shared_with_me\", args: \"\", returns: \"TABLE(table_id uuid, organization_id uuid, organization text, table_name text, level text, level_label text, shared_at timestamp with time zone, opens boolean, say text)\", security: \"definer\" },\n  { name: \"template_archive\", args: \"p_template_id uuid, p_restore boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_declare\", args: \"p_scope text, p_spec jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_from_tables\", args: \"p_organization_id uuid, p_table_ids uuid[], p_include_rows boolean DEFAULT false, p_rows_per_table integer DEFAULT 25\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_install\", args: \"p_organization_id uuid, p_template_id uuid, p_budget_ms integer DEFAULT 4000\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_install_claim\", args: \"p_organization_id uuid, p_install_id uuid, p_kind text, p_label text, p_source_id uuid DEFAULT NULL::uuid, p_lease_seconds integer DEFAULT NULL::integer\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_install_fresh\", args: \"p_organization_id uuid, p_template_id uuid, p_title text DEFAULT NULL::text, p_install_id uuid DEFAULT NULL::uuid, p_budget_ms integer DEFAULT 4000\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_install_note\", args: \"p_organization_id uuid, p_install_id uuid, p_kind text, p_id uuid, p_label text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_instance_of_page\", args: \"p_organization_id uuid, p_page_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_instances\", args: \"p_organization_id uuid, p_catalogue_id text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_keep\", args: \"p_template_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_restore\", args: \"p_organization_id uuid, p_install_id uuid, p_budget_ms integer DEFAULT 4000\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_uninstall\", args: \"p_organization_id uuid, p_install_id uuid, p_budget_ms integer DEFAULT 4000\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"template_upgrade\", args: \"p_organization_id uuid, p_install_id uuid, p_template_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"templates\", args: \"p_filter jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"text_head_bytes\", args: \"p_text text, p_bytes bigint\", returns: \"text\", security: \"invoker\" },\n  { name: \"timeline_dependency_shift\", args: \"p_organization_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"trg_associations_bump_visibility\", args: \"\", returns: \"trigger\", security: \"definer\" },\n  { name: \"undeclared_keys\", args: \"p_organization_id uuid, p_table_id uuid, p_data jsonb\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"unmatched_people_resolve\", args: \"p_organization_id uuid, p_user_id uuid\", returns: \"integer\", security: \"definer\" },\n  { name: \"unresolved_sources_of\", args: \"p_sources jsonb, p_visible text[], p_by_id boolean DEFAULT false, p_key_ids jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"validate_custom_fields\", args: \"p_token text, p_organization_id uuid, p_values jsonb\", returns: \"void\", security: \"invoker\" },\n  { name: \"validate_value_envelope\", args: \"p_organization_id uuid, p_fields custom.record[], p_data jsonb\", returns: \"void\", security: \"invoker\" },\n  { name: \"validate_values\", args: \"p_organization_id uuid, p_fields custom.record[], p_values jsonb, p_record_type text DEFAULT NULL::text\", returns: \"void\", security: \"invoker\" },\n  { name: \"value_alternate_keys\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"value_envelope_keys\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"value_envelope_ok\", args: \"p_data jsonb\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"value_envelope_refusal\", args: \"p_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"value_read\", args: \"p_organization_id uuid, p_record_id uuid, p_key text\", returns: \"TABLE(field_key text, field_id uuid, value jsonb, value_version integer, source jsonb, absent_reason text, actor text, on_behalf_of text, written_at timestamp with time zone, alternates jsonb)\", security: \"definer\" },\n  { name: \"value_restore\", args: \"p_organization_id uuid, p_record_id uuid, p_field_key text, p_version integer\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"value_restore\", args: \"p_organization_id uuid, p_record_id uuid, p_field_key text, p_version integer, p_author jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"value_versions\", args: \"p_old jsonb, p_new jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"view_declare\", args: \"p_organization_id uuid, p_table_id uuid, p_spec jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"view_designate\", args: \"p_organization_id uuid, p_table_id uuid, p_view_id uuid, p_layout text DEFAULT NULL::text\", returns: \"uuid\", security: \"definer\" },\n  { name: \"view_keys\", args: \"\", returns: \"TABLE(path text, shape text, layouts text[], writer text, sentence text)\", security: \"invoker\" },\n  { name: \"view_keys_check\", args: \"p_organization_id uuid, p_table_id uuid, p_set jsonb, p_old jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"view_look_read\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"view_look_set\", args: \"p_organization_id uuid, p_table_id uuid, p_view_id uuid, p_look jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"view_record_order_set\", args: \"p_organization_id uuid, p_view_id uuid, p_record_ids uuid[]\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"view_share_links\", args: \"p_view_id uuid\", returns: \"TABLE(id uuid, token text, permission_level text, label text, expires_at timestamp with time zone, use_count integer, last_used_at timestamp with time zone, created_at timestamp with time zone, created_by uuid, created_by_name text, made_by_me boolean, has_password boolean, restrict_copy boolean)\", security: \"definer\" },\n  { name: \"views\", args: \"p_organization_id uuid, p_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(view_id uuid, name text, table_id uuid, filters jsonb, definition jsonb, created_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"visibility_ancestors\", args: \"p_item_type text, p_item_id uuid\", returns: \"TABLE(container_type text, container_id uuid, depth integer, max_level permission_level)\", security: \"definer\" },\n  { name: \"visibility_as_of\", args: \"p_organization_id uuid, p_record_id uuid, p_at timestamp with time zone\", returns: \"TABLE(principal_kind text, principal_id uuid, level permission_level, through_kind text, through_id uuid, reason text, replayed boolean, held_from timestamp with time zone, held_to timestamp with time zone)\", security: \"definer\" },\n  { name: \"visibility_cache_rebuild\", args: \"\", returns: \"integer\", security: \"definer\" },\n  { name: \"visibility_parity\", args: \"\", returns: \"TABLE(side text, container_type text, container_id uuid, item_type text, item_id uuid, stored_level permission_level, derived_level permission_level, reason text)\", security: \"definer\" },\n  { name: \"visibility_warm\", args: \"p_container_type text, p_container_id uuid\", returns: \"integer\", security: \"definer\" },\n  { name: \"visible_predicate_sql\", args: \"p_user uuid, p_organization_id uuid, p_table_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level, p_alias text DEFAULT 'r'::text\", returns: \"text\", security: \"definer\" },\n  { name: \"visible_record_ids\", args: \"p_user_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level\", returns: \"TABLE(id uuid)\", security: \"definer\" },\n  { name: \"visible_set\", args: \"p_user uuid, p_organization_id uuid, p_table_id uuid, p_required permission_level DEFAULT 'viewer'::permission_level, OUT o_all_visible boolean, OUT o_true_visibility platform.visibility[], OUT o_granted_all uuid[], OUT o_granted_visible uuid[], OUT o_carried_visible uuid[], OUT o_ladder_calls integer, OUT o_fallback boolean, OUT o_note text\", returns: \"record\", security: \"definer\" },\n  { name: \"where_id_opens\", args: \"p_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"where_lists_live\", args: \"p_list_ids uuid[]\", returns: \"TABLE(list_id uuid, lives_in text, address text, why text)\", security: \"definer\" },\n  { name: \"where_tables_live\", args: \"p_table_ids uuid[]\", returns: \"TABLE(table_id uuid, lives_in text, why text)\", security: \"definer\" },\n  { name: \"who_could_see_on\", args: \"p_record_id uuid, p_at timestamp with time zone\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"whole_value_ceiling\", args: \"p_organization_id uuid\", returns: \"bigint\", security: \"invoker\" },\n  { name: \"whole_value_complete\", args: \"p_organization_id uuid, p_record_id uuid, p_field_key text, p_file_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"whole_value_head\", args: \"p_text text\", returns: \"text\", security: \"invoker\" },\n  { name: \"whole_value_park\", args: \"p_organization_id uuid, p_table_id uuid, p_record_id uuid, p_owner_id uuid, p_visibility platform.visibility, p_data jsonb, p_park jsonb\", returns: \"void\", security: \"invoker\" },\n  { name: \"whole_value_pointer_of\", args: \"p_values jsonb, p_sources jsonb, p_key text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"whole_value_source\", args: \"p_text text, p_writer_src jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"whole_values_waiting\", args: \"p_organization_id uuid, p_record_ids uuid[]\", returns: \"TABLE(record_id uuid, field_key text, pointer text, value_version integer, sha256 text, bytes bigint, chars bigint, owner_id uuid, record_visibility text, table_id uuid, table_name text)\", security: \"definer\" },\n  { name: \"widget_kernel_id\", args: \"\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"with_retired\", args: \"p_doc jsonb, p_retired jsonb, p_visible text[], p_declared text[]\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"with_whole_value_pointers\", args: \"p_document jsonb, p_values jsonb, p_sources jsonb, p_visible text[], p_by_id boolean DEFAULT false, p_key_ids jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"withheld_marker\", args: \"p_mask jsonb, p_key text\", returns: \"jsonb\", security: \"invoker\" },\n  { name: \"withheld_sentence\", args: \"p_mask jsonb, p_key text\", returns: \"text\", security: \"invoker\" },\n  { name: \"work_approval_approvers\", args: \"p_organization_id uuid, p_subject_id uuid, p_approver_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(user_id uuid, name text, why text)\", security: \"definer\" },\n  { name: \"work_approval_decide\", args: \"p_organization_id uuid, p_approval_id uuid, p_approve boolean, p_note text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_approval_host_run\", args: \"p_organization_id uuid, p_fingerprint text, p_conversation_id uuid DEFAULT NULL::uuid, p_approval_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_approval_host_run_done\", args: \"p_organization_id uuid, p_approval_id uuid, p_ok boolean, p_outcome text, p_report jsonb DEFAULT NULL::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_approval_is_approver\", args: \"p_organization_id uuid, p_subject_id uuid, p_approver_id uuid, p_user_id uuid\", returns: \"boolean\", security: \"invoker\" },\n  { name: \"work_approval_kinds\", args: \"\", returns: \"text[]\", security: \"invoker\" },\n  { name: \"work_approval_may_decide\", args: \"p_organization_id uuid, p_approval_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"work_approval_read\", args: \"p_organization_id uuid, p_approval_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_approval_request\", args: \"p_organization_id uuid, p_subject_id uuid, p_change jsonb, p_note text DEFAULT NULL::text, p_approver_id uuid DEFAULT NULL::uuid, p_origin text DEFAULT 'person'::text, p_conversation_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_approval_withdrawal\", args: \"p_organization_id uuid, p_data jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"work_assign\", args: \"p_organization_id uuid, p_record_id uuid, p_assignee_user_id uuid, p_due_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_clear_due boolean DEFAULT false\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_assignment_fields\", args: \"p_options_table_id uuid DEFAULT NULL::uuid\", returns: \"TABLE(key text, label text, spec jsonb)\", security: \"invoker\" },\n  { name: \"work_decide_many\", args: \"p_organization_id uuid, p_decisions jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_has_assignment\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"work_inbox\", args: \"p_organization_id uuid DEFAULT NULL::uuid, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_include_decided boolean DEFAULT false, p_view text DEFAULT 'inbox'::text\", returns: \"TABLE(item_id uuid, kind text, origin text, title text, subject_id uuid, subject_kind text, summary text, state text, due_on timestamp with time zone, due_state text, actionable boolean, requested_by uuid, requested_by_name text, at timestamp with time zone, table_id uuid, table_name text, decided_by uuid, decided_by_name text, decided_at timestamp with time zone, outcome text, snoozed_until timestamp with time zone, cleared_at timestamp with time zone, snoozed_count integer, cleared_count integer, undo_seconds integer, undo_refusal text)\", security: \"definer\" },\n  { name: \"work_instantiation_shape\", args: \"p_organization_id uuid, p_instantiation_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_list\", args: \"p_organization_id uuid DEFAULT NULL::uuid, p_flavour text DEFAULT 'mine'::text, p_include_finished boolean DEFAULT false, p_limit integer DEFAULT 100, p_offset integer DEFAULT 0\", returns: \"TABLE(record_id uuid, table_id uuid, table_name text, title text, assignee_id uuid, assignee_name text, assignee_user_id uuid, due_on timestamp with time zone, due_state text, status text, terminal boolean, assigned_by uuid, updated_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"work_person\", args: \"p_organization_id uuid, p_user_id uuid, p_create boolean DEFAULT true\", returns: \"uuid\", security: \"definer\" },\n  { name: \"work_record_states\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"TABLE(state_id uuid, name text, sort integer, terminal boolean, is_current boolean, allowed boolean, refusal text)\", security: \"definer\" },\n  { name: \"work_relation_kinds\", args: \"\", returns: \"TABLE(kind text, available boolean, why text)\", security: \"invoker\" },\n  { name: \"work_set_state\", args: \"p_organization_id uuid, p_record_id uuid, p_state_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_slot_expire\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"integer\", security: \"definer\" },\n  { name: \"work_slot_hold\", args: \"p_organization_id uuid, p_table_id uuid, p_slot_key text, p_holder text, p_ttl interval DEFAULT '00:15:00'::interval\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_slot_holds\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"TABLE(hold_id uuid, slot_key text, holder text, expires_at timestamp with time zone, expired boolean)\", security: \"definer\" },\n  { name: \"work_slot_index_name\", args: \"p_table_id uuid\", returns: \"text\", security: \"invoker\" },\n  { name: \"work_slot_release\", args: \"p_organization_id uuid, p_hold_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"work_slots_declare\", args: \"p_organization_id uuid, p_name text, p_slug text, p_home_id uuid DEFAULT NULL::uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_state_id\", args: \"p_organization_id uuid, p_table_id uuid, p_value text\", returns: \"uuid\", security: \"invoker\" },\n  { name: \"work_states\", args: \"\", returns: \"TABLE(sort integer, name text, terminal boolean, next text[])\", security: \"invoker\" },\n  { name: \"work_take_assignment\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_template_declare\", args: \"p_organization_id uuid, p_name text, p_graph jsonb\", returns: \"uuid\", security: \"definer\" },\n  { name: \"work_template_instantiate\", args: \"p_organization_id uuid, p_template_id uuid, p_overrides jsonb DEFAULT '{}'::jsonb\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_template_refusal\", args: \"p_graph jsonb\", returns: \"text\", security: \"invoker\" },\n  { name: \"work_template_shape\", args: \"p_organization_id uuid, p_template_id uuid\", returns: \"jsonb\", security: \"definer\" },\n  { name: \"work_templates\", args: \"p_organization_id uuid, p_limit integer DEFAULT 100\", returns: \"TABLE(template_id uuid, name text, nodes integer, relations integer, created_at timestamp with time zone)\", security: \"definer\" },\n  { name: \"work_transition_refusal\", args: \"p_organization_id uuid, p_from_state_id uuid, p_to_state_id uuid\", returns: \"text\", security: \"definer\" },\n  { name: \"work_whose_turn\", args: \"p_organization_id uuid, p_table_id uuid, p_include_finished boolean DEFAULT false\", returns: \"TABLE(record_id uuid, title text, assignee_id uuid, turn text, due_on timestamp with time zone, state text, status text, terminal boolean)\", security: \"definer\" },\n  { name: \"world_reader_may_know_row\", args: \"p_organization_id uuid, p_record_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"world_reader_only\", args: \"p_organization_id uuid\", returns: \"boolean\", security: \"definer\" },\n  { name: \"world_reader_reads_public_definition\", args: \"p_organization_id uuid, p_table_id uuid, p_record_ids uuid[]\", returns: \"boolean\", security: \"definer\" },\n] as const;\n\n/** The campaign's own knobs, with the value the store resolves them to today. */\nexport const STORE_KNOBS = [\n  { key: \"accessible_entity_ids_guard\", value: \"true\", type: \"boolean\" },\n  { key: \"action_run_records_max\", value: \"5000\", type: \"integer\" },\n  { key: \"agent_context_value_cap_bytes\", value: \"0\", type: \"integer\" },\n  { key: \"agent_schema_changes\", value: \"\\\"never_ask\\\"\", type: \"string\" },\n  { key: \"ai_column_decision_engine\", value: \"false\", type: \"boolean\" },\n  { key: \"ai_fill_default_rows\", value: \"3\", type: \"integer\" },\n  { key: \"ai_fill_rows_max\", value: \"50\", type: \"integer\" },\n  { key: \"ai_fill_try_max\", value: \"10\", type: \"integer\" },\n  { key: \"archive_confirm_over\", value: \"1000\", type: \"integer\" },\n  { key: \"automation_catch_up_hours\", value: \"48\", type: \"integer\" },\n  { key: \"back_links\", value: \"true\", type: \"boolean\" },\n  { key: \"base_snapshot_keep\", value: \"30\", type: \"integer\" },\n  { key: \"batch_items_max\", value: \"500\", type: \"integer\" },\n  { key: \"choice_nudge\", value: \"\\\"ask\\\"\", type: \"string\" },\n  { key: \"closed_custom_field_tables\", value: \"[\\\"party\\\"]\", type: \"json\" },\n  { key: \"code_paths_enabled\", value: \"true\", type: \"boolean\" },\n  { key: \"consumer_chat_seeding_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_checkout_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_context_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_education_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_extension_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_grid_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_retirement_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_saved_ai_outputs_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"consumer_scopes_enabled\", value: \"false\", type: \"boolean\" },\n  { key: \"containment_depth_ceiling\", value: \"16\", type: \"integer\" },\n  { key: \"copy_stall_passes\", value: \"20\", type: \"integer\" },\n  { key: \"cross_organization_links\", value: \"false\", type: \"boolean\" },\n  { key: \"data_home_default_kind\", value: \"\\\"all\\\"\", type: \"string\" },\n  { key: \"data_home_default_order\", value: \"\\\"updated\\\"\", type: \"enum\" },\n  { key: \"data_home_default_scope\", value: \"\\\"all\\\"\", type: \"enum\" },\n  { key: \"data_home_default_view\", value: \"\\\"table\\\"\", type: \"enum\" },\n  { key: \"decision_undo_seconds\", value: \"5\", type: \"integer\" },\n  { key: \"decoration_rules_max\", value: \"50\", type: \"integer\" },\n  { key: \"decorations_max_bytes\", value: \"262144\", type: \"integer\" },\n  { key: \"document_letterhead\", value: \"{}\", type: \"json\" },\n  { key: \"document_max_bytes\", value: \"1048576\", type: \"integer\" },\n  { key: \"enrichment_batch_ceiling\", value: \"200\", type: \"integer\" },\n  { key: \"enrichment_confidence_floor\", value: \"0.6\", type: \"number\" },\n  { key: \"enrichment_cost_cap_cents\", value: \"2000\", type: \"integer\" },\n  { key: \"enrichment_estimate_output_tokens\", value: \"200\", type: \"integer\" },\n  { key: \"enrichment_sensitivity_ceiling\", value: \"\\\"internal\\\"\", type: \"string\" },\n  { key: \"entity_types_guard\", value: \"false\", type: \"boolean\" },\n  { key: \"example_rows_max\", value: \"500\", type: \"integer\" },\n  { key: \"export_rows_ceiling\", value: \"100000\", type: \"integer\" },\n  { key: \"external_principal_enabled\", value: \"true\", type: \"boolean\" },\n  { key: \"field_sensitivity_levels\", value: \"{\\\"edit\\\": {\\\"public\\\": \\\"edit_content\\\", \\\"internal\\\": \\\"edit_content\\\", \\\"restricted\\\": \\\"admin\\\", \\\"confidential\\\": \\\"admin\\\"}, \\\"read\\\": {\\\"public\\\": \\\"viewer\\\", \\\"internal\\\": \\\"viewer\\\", \\\"restricted\\\": \\\"admin\\\", \\\"confidential\\\": \\\"admin\\\"}}\", type: \"json\" },\n  { key: \"form_draft_days\", value: \"30\", type: \"integer\" },\n  { key: \"form_draft_max_bytes\", value: \"65536\", type: \"integer\" },\n  { key: \"form_draft_saves_per_hour\", value: \"240\", type: \"integer\" },\n  { key: \"form_redirect_domains\", value: \"[]\", type: \"json\" },\n  { key: \"grid_layout\", value: \"{\\\"mode\\\": \\\"auto\\\", \\\"wrap\\\": false, \\\"row_height\\\": \\\"normal\\\", \\\"fit_max_columns\\\": 8, \\\"freeze_first_column\\\": false}\", type: \"json\" },\n  { key: \"host_run_approval_days\", value: \"7\", type: \"integer\" },\n  { key: \"inbound_domain\", value: \"\\\"inbound.matrxserver.com\\\"\", type: \"string\" },\n  { key: \"inbox_reminder_after_days\", value: \"3\", type: \"integer\" },\n  { key: \"member_default_level\", value: \"\\\"editor\\\"\", type: \"enum\" },\n  { key: \"outside_invite_who\", value: \"\\\"org_admins_and_table_owners\\\"\", type: \"string\" },\n  { key: \"page_size_ceiling\", value: \"1000\", type: \"integer\" },\n  { key: \"protected_field_rules\", value: \"{\\\"hr_employee\\\": {\\\"arm\\\": \\\"hr.arm_write\\\", \\\"rule\\\": \\\"hr.custom_field_access\\\", \\\"readers\\\": [{\\\"field\\\": \\\"subject\\\"}, {\\\"capability\\\": \\\"hr.identity.read\\\"}, {\\\"capability\\\": \\\"hr.working_record.write\\\"}, {\\\"level\\\": \\\"editor\\\", \\\"capability\\\": \\\"hr.identity.write\\\"}]}, \\\"hr_candidate\\\": {\\\"arm\\\": \\\"hr.arm_write\\\", \\\"rule\\\": \\\"hr.custom_field_access\\\", \\\"readers\\\": [{\\\"field\\\": \\\"subject\\\"}, {\\\"capability\\\": \\\"hr.identity.read\\\"}, {\\\"capability\\\": \\\"hr.working_record.write\\\"}, {\\\"level\\\": \\\"editor\\\", \\\"capability\\\": \\\"hr.identity.write\\\"}]}, \\\"hr_position_assignment\\\": {\\\"arm\\\": \\\"hr.arm_write\\\", \\\"rule\\\": \\\"hr.custom_field_access\\\", \\\"readers\\\": [{\\\"field\\\": \\\"subject\\\"}, {\\\"capability\\\": \\\"hr.identity.read\\\"}, {\\\"capability\\\": \\\"hr.working_record.write\\\"}, {\\\"level\\\": \\\"editor\\\", \\\"capability\\\": \\\"hr.identity.write\\\"}]}, \\\"hr_training_assignment\\\": {\\\"arm\\\": \\\"hr.arm_write\\\", \\\"rule\\\": \\\"hr.custom_field_access\\\", \\\"readers\\\": [{\\\"field\\\": \\\"subject\\\"}, {\\\"capability\\\": \\\"hr.identity.read\\\"}, {\\\"capability\\\": \\\"hr.working_record.write\\\"}, {\\\"level\\\": \\\"editor\\\", \\\"capability\\\": \\\"hr.identity.write\\\"}]}}\", type: \"json\" },\n  { key: \"provenance_retention_days\", value: \"30\", type: \"number\" },\n  { key: \"retype_preview_bytes_max\", value: \"2000000\", type: \"integer\" },\n  { key: \"retype_preview_values_max\", value: \"100\", type: \"integer\" },\n  { key: \"row_action_steps_max\", value: \"60\", type: \"integer\" },\n  { key: \"row_actions_max\", value: \"24\", type: \"integer\" },\n  { key: \"sandbox_message_bytes\", value: \"65536\", type: \"integer\" },\n  { key: \"sandbox_org_components\", value: \"true\", type: \"boolean\" },\n  { key: \"scope_members_admitted\", value: \"true\", type: \"boolean\" },\n  { key: \"sheets_write_through\", value: \"true\", type: \"boolean\" },\n  { key: \"signup_provisioning_guard\", value: \"false\", type: \"boolean\" },\n  { key: \"stage_rule_enforcement\", value: \"\\\"refuse\\\"\", type: \"enum\" },\n  { key: \"table_record_ceiling\", value: \"150000\", type: \"integer\" },\n  { key: \"table_sync_rows_max\", value: \"20000\", type: \"integer\" },\n  { key: \"table_webhooks_max\", value: \"10\", type: \"integer\" },\n  { key: \"time_zone\", value: \"\\\"UTC\\\"\", type: \"string\" },\n  { key: \"value_max_bytes\", value: \"100000\", type: \"integer\" },\n  { key: \"view_record_order_max\", value: \"20000\", type: \"integer\" },\n  { key: \"week_start\", value: \"\\\"monday\\\"\", type: \"enum\" },\n  { key: \"world_publish_enabled\", value: \"true\", type: \"boolean\" },\n] as const;\n\n/**\n * Every SQLSTATE the store's own function bodies raise, with the functions that\n * raise it. This is the list the client's refusal mapper is checked against: a\n * code the store can raise and the package cannot name is a hole, and the\n * real-door suite says so by name.\n */\nexport const STORE_REFUSAL_CODES = [\n  { code: \"02000\", raised_by: \"_checklist_instantiate,_entity_change_file,_org_admin_table_gate,_portal_config_judge,_portal_invite_payload,_read_record_with,_record_restore_one,_share_write_person,_table_share_invite_payload,checklist_declare,checklist_run,checklist_step_complete,checklist_step_refusal,checklist_template_shape,conversation_scope_bind,dashboard_delete,dashboard_restore,dashboard_run,doc_letterhead,doc_render_body,doc_render_delete,doc_render_document,doc_render_read,doc_render_restore,doc_sign,doc_signature_intact,doc_signature_read,doc_template_delete,doc_template_read,doc_template_restore,doc_template_save,enrich_pin,entity_back_links,entity_custom_value_apply,entity_field_protect_arman_explicitly_approved,entity_field_retire,entity_field_update,entity_record_read,entity_row_propose,entity_row_write,entity_value_write,external_history_event,external_rows,external_stub_upsert,external_writes_set,field_choice_usage,field_duplicate,field_restore,field_retype_preview,field_update_rehoming_choices,form_archive,form_response_update,form_restore,form_set_password,io_restore,migrate_delete,migrate_extract_parent,migrate_merge,migrate_reclass,migrate_rename,migrate_reparent,migrate_retype,migrate_split,migrate_undo,organization_clear,pick_list_update,portal_archive,portal_card,portal_declare,portal_form,portal_form_submit,portal_invite,portal_invite_accept,portal_preview,portal_principal_bind,portal_restore,portal_revoke,record_change_many,record_delete,record_restore_preview,record_row_controls,record_row_controls_set,record_table,record_update,record_write_graph_superseding,relation_halves_repair,relation_restore,relation_uncarry,rule_restore,set_table_confidential_arman_explicitly_approved,share_access,share_grant,share_lane_set,share_people,share_revoke,table_agent_writable_set,table_archive,table_archive_deliberately,table_restore,table_row_defaults,table_row_defaults_apply,table_row_defaults_set,table_row_label,table_row_label_set,table_share_outside_accept,table_share_outside_grant,table_share_outside_invite,table_share_outside_resend,table_share_outside_revoke,template_from_tables,visibility_as_of,work_approval_decide,work_approval_host_run,work_approval_host_run_done,work_approval_read,work_approval_request,work_assign,work_record_states,work_set_state\" },\n  { code: \"0A000\", raised_by: \"checklist_step_complete,entity_custom_value_apply,entity_row_write,external_rows,external_source_declare,external_write_through,promote_field,promoted_index_expr,promoted_query_sql,promoted_read,read_records_keyset,rule_eval,rule_filter_node_sql,template_restore,work_assign\" },\n  { code: \"22003\", raised_by: \"context_resolve\" },\n  { code: \"22004\", raised_by: \"_entity_change_file,_entity_custom_fields_guard,_io_outbox_claim,_org_admin_table_gate,_portal_config_judge,_record_restore_one,_share_write_person,_value_envelope,actor_word,agg_assert_key,agg_compare_windows,agg_sql,anon_capture,anon_token_issue,anon_write,assert_client_may_reach,assert_scope_door,base_copy_finish,base_move,booking_declare,capture_submit,checklist_declare,context_resolve,context_template_define,context_type_write,copy_table_extras,dashboard_block_normalize,dashboard_declare,dashboard_window_sql,doc_render_write,doc_sign,doc_signature_write,doc_template_save,enrich_land,enrich_normalize,entity_field_protect_arman_explicitly_approved,entity_row_propose,entity_row_write,external_history_event,external_rows,external_source_declare,external_stub_upsert,external_write_through,external_writes_set,field_history,form_declare,form_look_options,form_response_update,form_submit,home_add,inbox_snooze,io_comment_write,io_import_begin,io_infer_column,io_outbox_drain,io_outbox_release_claimed,io_outbox_subscribe,io_restore,migrate_choice_keys,migrate_purge,migrate_purge_hard,migrate_reclass,migrate_split,migrate_undo,organization_clear,organization_contents,pipeline_declare,pipeline_gate_preview,portal_declare,portal_form_submit,portal_invite,portal_principal_bind,provenance_retention_days,provenance_write,query_across_homes,query_by_coordinates,query_rollup,record_aggregate_as_of,record_delete,record_reparent,record_resolve,record_restore,record_update,record_upsert,record_write,record_write_graph,record_write_graph_superseding,record_write_many,relation_carry,relation_halves_repair,relation_own,row_template_declare,rule_declare,set_table_confidential_arman_explicitly_approved,share_grant,subscription_declare,table_agent_writable_set,table_archive,table_archive_deliberately,table_declare,table_duplicate,table_move,table_restore,table_share_outside_grant,table_share_outside_invite,template_declare,value_restore,view_declare,view_designate,view_look_read,view_look_set,whole_value_complete,work_approval_decide,work_approval_host_run,work_approval_request,work_template_declare\" },\n  { code: \"22007\", raised_by: \"_template_date,agg_parse_moment,dashboard_window_sql\" },\n  { code: \"22012\", raised_by: \"formula_eval,rule_eval,rule_sql_op\" },\n  { code: \"22023\", raised_by: \"_action_check,_automation_advance,_automation_cond_norm,_automation_step,_booking_availability,_ctx_reference_value_holds,_ctx_store_scope,_ctx_table_template_field_holds,_ctx_tree_part,_decorations_check,_entity_change_file,_entity_custom_fields_guard,_form_flow_judge,_form_look_judge,_fx_date,_fx_datetime_parse,_fx_dl,_fx_ext,_fx_listop,_fx_num,_fx_recprop,_fx_regex,_fx_unit,_fx_unit_norm,_fxp_level,_fxp_resolve,_fxp_tokens,_nfx_arglist,_nfx_bin,_nfx_call,_nfx_expr,_nfx_primary,_nfx_tokens,_nfx_unary,_portal_config_judge,_rule_eval_seated,_schedules_stand_down,_stamp_check,_table_dimensions_check,_take_op_id,_template_bind,_template_install_core,_value_envelope,_view_field_key,_view_key_value,_work_shape_guard,_write_via_mark,action_run,actor_word,agent_change_trust,agg_assert_key,agg_calendar,agg_compare_windows,agg_sql,anon_token_issue,archive_guard_decide,archive_hold_answer,automation_test,base_activity,base_move,booking_busy_set,booking_declare,booking_sms_consent,button_press,containment_parent,context_scope_archive,context_scope_write,context_scopes,context_template_define,context_type_archive,context_type_write,context_values,count_records_archived,dashboard_block_normalize,dashboard_run,dashboard_target_field_assert,dashboard_window_sql,data_home,data_home_changed_by,doc_render_body,doc_render_write,doc_signature_write,drill_resolve,enrich_data_source,enrich_declare,enrich_land,enrich_normalize,enrich_pin,entity_back_links,entity_custom_value_apply,entity_fields_across,entity_read_mask,entity_reference_rows,entity_reference_search,entity_reference_words,entity_row_write,entity_value_write,external_history_event,external_source_declare,external_stub_upsert,external_write_through,field_access,field_access_set,field_declare_many,field_duplicate,field_history,field_notify_on_assign,field_update,filter_list_op,find_duplicates,form_declare,form_draft_save,form_response_update,form_set_password,form_visit,formula_eval,formula_history,formula_parse,formula_preview,formula_translate_notion,grid_layout_check,hub_changed_by,hub_changed_by_many,inbound_domain,inbox_snooze,io_export,io_import_begin,io_import_finish,io_import_plan,io_import_report,io_proposal_accept,list_portals,listed_predicate_sql,member_records_take_over,migrate_merge,migrate_reclass,my_levels,my_levels_across,organization_clear,page_size,pick_list_create,pick_list_update,pin_agent_cells,pipeline_move,pipeline_move_many,portal_declare,portal_form_submit,provenance_write,publish_bind,query_by_coordinates,query_rollup,query_rollup_sum,read_records_archived,read_records_in_view_order,read_records_keyset,read_records_page,record_aggregate_as_of,record_change_many,record_drill,record_filter_sql,record_row_controls_set,record_search_sql,record_update,record_upsert,record_write_graph,record_write_graph_superseding,record_write_many,records_search,relation_carry,relation_names_match,relation_reverse_field,relation_reverse_set,relative_window_for_reader,relative_window_resolve,reverse_links_many_fields,row_template_declare,rule_eval,rule_filter_node_sql,rule_members,rule_members_visible,rule_sql_op,scope_table_provision,set_table_confidential,set_table_organization,share_grant,share_lane_set,subscription_declare,table_access_setup_set,table_archive_deliberately,table_copy_sync,table_create,table_ensure,table_find,table_find_many,table_from_example,table_move,table_row_defaults_set,table_row_label_set,table_rules,table_share_outside_grant,table_sync,table_sync_cell,table_sync_settings_set,table_template_declare,table_transfer_owner,table_webhook_declare,template_declare,template_from_tables,template_install_claim,template_install_note,template_upgrade,templates,view_declare,view_designate,view_keys_check,view_look_set,view_record_order_set,visibility_as_of,where_lists_live,where_tables_live,work_approval_host_run,work_approval_request,work_decide_many,work_inbox,work_list,work_slot_hold\" },\n  { code: \"23502\", raised_by: \"synced_source_save\" },\n  { code: \"23503\", raised_by: \"_action_check,_automation_advance,_automation_flip,_automation_step,_automation_time_item,_automation_view_rule,_booking_availability,_checklist_instantiate,_containment_guard,_ctx_store_value,_decorations_check,_display_spec_for,_field_document_for,_field_type_parity_guard,_form_flow_judge,_pipeline_stage_key,_record_rule_uses,action_declare,action_run,agg_digest_assemble,anon_publish,anon_rate_take,anon_token_issue,anon_write,assert_organization_wall,automation_declare,automation_revision_restore,automation_revisions,automation_runs,automation_test,automations,autonumber_backfill,booking_busy_set,booking_cancel,booking_confirm,booking_declare,booking_hold,booking_reschedule,booking_sms_consent,button_press,capture_publish,checklist_declare,checklist_steps_table,comment_write,dashboard_declare,delete_rule,doc_sign,doc_template_save,enrich_declare,enrich_due,enrich_land,field_make_automatic,field_notify_on_assign,field_update,form_declare,form_draft_save,form_response_update,form_results,form_submit,grid_layout,home_add,inbound_declare,inbound_mail_land,inbound_set,io_comment_write,io_import_begin,io_import_finish,io_import_report,io_import_rows,io_proposal_accept,migrate_demote,migrate_promote,migrate_purge_hard,pipeline_board,pipeline_declare,pipeline_move,pipeline_read,pipeline_transition_refusal,promote_field,promote_table,read_records_in_view_order,read_records_page,record_applicability,record_reparent,record_write_graph_superseding,relation_carry,relation_own,resolve_first_match,row_template_declare,rule_applies,rule_declare,rule_eval,rule_filter_node_sql,rule_members,rule_members_visible,rule_run,subscription_mute,subscription_preview,table_decorate,table_dimensions_set,table_from_example,table_webhook_archive,table_webhook_declare,view_declare,view_designate,view_look_set,view_record_order_set,whole_value_complete,work_set_state,work_take_assignment,work_template_instantiate\" },\n  { code: \"23505\", raised_by: \"_booking_seat_take,_ctx_store_item,_ctx_store_scope,_ctx_store_type,_portal_config_judge,_restore_guard_one,_share_write_person,_unique_rule_holds,doc_sign,doc_signature_write,entity_field_declare,field_declare,field_restore,field_update,form_restore,home_add,inbound_declare,io_proposal_accept,relation_carry,relation_own,relation_restore,table_share_outside_resend,work_approval_decide,work_slot_hold\" },\n  { code: \"23514\", raised_by: \"_checklist_instantiate,_checklist_step_guard,_containment_guard,_ctx_scope_parent_holds,_ctx_store_item,_ctx_table_template_field_holds,_ctx_value_fits_its_scope,_dated_values_guard,_derived_fields,_display_format_check,_display_spec_for,_entity_choice_keys,_entity_custom_fields_guard,_field_choices_save,_field_class_guard,_field_default_fitted,_field_document_for,_field_kind_shape_ok,_field_shape_guard,_field_type_parity_guard,_kind_value_ok,_merge_field_shape_guard,_merge_field_temporal_guard,_promoted_field_cap_guard,_record_restore_one,_record_rule_uses,_record_source_key_is_record,_relation_halves_agree,_relation_kernel_targets,_resolve_choice_words,_rule_shape_guard,_rule_topology_guard,_store_relation_edge_names_its_field,_table_columns_word_guard,_table_shape_guard,_undeclared_key_guard,_value_envelope,_with_display,_work_shape_guard,_workdoors_approval_guard,action_run,assert_columns_are_defined,assert_entity_is_organization_scoped,booking_declare,capture_publish,capture_sheet_declare,checklist_declare,checklist_step_complete,dashboard_restore,doc_sign,doc_signature_write,doc_template_restore,doc_template_save,entity_field_protect_arman_explicitly_approved,entity_field_retire,entity_field_update,entity_records_find,entity_table,entity_value_write,field_declare,field_make_automatic,field_restore,field_retire,field_update,field_update_rehoming_choices,form_restore,home_add,io_comment_write,io_import_rows,migrate_merge,migrate_purge_hard,portal_archive,portal_restore,record_reparent,record_update_adding_choices,record_upsert,record_write_graph,record_write_graph_superseding,relation_carry,relation_halves_repair,relation_own,relation_restore,rollup_value,row_template_declare,rule_restore,status_groups_keyed,status_groups_of,table_access_setup_set,table_from_example,table_restore,template_upgrade,validate_value_envelope,validate_values,whole_value_complete,work_set_state,work_slots_declare,work_take_assignment,work_template_instantiate\" },\n  { code: \"42501\", raised_by: \"_agent_change_gate,_computed_door_org,_context_copy_fence,_copy_evaluation_note,_copy_evaluation_reimage,_copy_in_progress_guard,_doc_render_immutable,_doc_signature_immutable,_entity_change_file,_entity_custom_fields_guard,_field_definition_write,_field_write_door,_io_outbox_server_only,_not_a_member_refusal,_org_admin_table_gate,_portal_config_judge,_portal_principal_here,_read_record_with,_rule_definition_write,_share_write_person,_stamp_token,_store_door,_table_dimensions_infer,_table_duplicate_step,_table_shape_guard,_template_bind,_template_call,_template_install_core,_value_envelope,_withdraw_approvals_for_batch,_workdoors_approval_guard,admin_all_tables,agent_change_trust,agent_table_claim,agg_fields_readable_assert,anon_capture,anon_inbound_land,anon_publish,anon_token_issue,anon_token_verify,anon_write,assert_client_may_change,assert_client_may_open,assert_may_know_table,assert_organization_admin,assert_scope_door,assert_store_door,automation_app_watch,automation_claim_pending,automation_note,automation_resume,automation_step_mark,automation_webhook_receive,base_copy_finish,base_move,base_move_access_kept,base_move_remove_access,booking_confirm,booking_declare,booking_hold,capture_submit,checklist_run,comment_write,computed_refresh,context_item_archive,context_item_restore,context_item_write,context_resolve,context_scope_archive,context_scope_restore,context_scope_write,context_tags_set,context_type_archive,context_type_restore,context_type_write,conversation_scope_bind,conversation_scope_unbind,copy_table_extras,count_records_archived,dashboard_target_field_assert,doc_sign,enrich_declare,enrich_due,enrich_land,enrich_normalize,entity_custom_value_apply,entity_field_declare,entity_field_retire,entity_field_update,entity_row_propose,entity_row_write,entity_value_write,external_write_through,field_access_set,field_restore,field_update,form_declare,form_draft_save,form_public_asks,form_response_update,form_set_password,form_submit,formula_history,inbound_mail_land,inbox_clear,inbox_snooze,inbox_unclear,inbox_unsnooze,io_comment_resolve,io_comment_write,io_import_begin,io_import_finish,io_restore,member_personal_tables,migrate_purge,migrate_purge_hard,migrate_purge_hard_request,migrate_reclass,my_levels,my_levels_across,organization_clear,organization_contents,pick_list_get,pick_list_update,portal_declare,portal_form,portal_form_submit,portal_invitation,portal_invite,portal_invite_accept,portal_principal_bind,portal_self_signup,promote_table,protected_matches,query_visibility_parity,read_record,read_records,read_records_archived,read_records_by_ids,read_records_keyset,read_records_matching,read_records_page,record_delete,record_follow_set,record_row_controls,record_table,record_write_graph,relation_halves_disagreements,relation_halves_repair,resolve_context,reverse_links_many,scope_table_provision,share_grant,share_lane_set,space_templates,subscription_mute,subscription_preview,table_access_setup_set,table_agent_writable_set,table_archive_deliberately,table_copies_in_progress,table_copy_sync,table_duplicate,table_duplicate_continue,table_kind_facts,table_level_facts,table_move,table_row_defaults_apply,table_row_defaults_set,table_row_label_set,table_share_outside_accept,table_share_outside_grant,table_share_outside_invite,table_share_outside_resend,table_sync,table_sync_cell,table_templates,table_transfer_owner,table_webhook_declare,template_declare,template_from_tables,template_instances,template_restore,template_upgrade,templates,view_declare,view_look_set,view_record_order_set,visibility_as_of,where_lists_live,where_tables_live,whole_value_complete,work_approval_decide,work_approval_host_run,work_approval_host_run_done,work_approval_read,work_approval_request,work_person\" },\n  { code: \"42703\", raised_by: \"entity_table,portal_declare\" },\n  { code: \"42883\", raised_by: \"_template_call\" },\n  { code: \"42P17\", raised_by: \"_field_reads_what_it_reads,far_value\" },\n  { code: \"53400\", raised_by: \"anon_rate_take,delete_cascade_closure,enrich_due,enrich_land,promote_field\" },\n  { code: \"54000\", raised_by: \"_table_dimensions_check,action_run,comment_counts,data_home_changed_by,form_draft_save,hub_changed_by,hub_changed_by_many,pipeline_move_many,read_records_page,record_change_many,record_headers,relation_names_match,reverse_links_many,table_copy_sync,table_decorate,table_from_example,table_map_fields,table_row_counts,table_sync,table_webhook_declare,view_record_order_set,work_decide_many\" },\n  { code: \"54001\", raised_by: \"record_delete\" },\n  { code: \"55000\", raised_by: \"_code_depends_refuse,_io_outbox_claim,_template_install_core,base_move,entity_field_protect_arman_explicitly_approved,inbox_clear,inbox_snooze,io_outbox_release,io_outbox_subscribe,table_duplicate,table_ensure,table_move,template_restore,template_upgrade,work_approval_decide,work_approval_host_run_done,work_approval_request\" },\n  { code: \"57014\", raised_by: \"formula_eval\" },\n  { code: \"MXD01\", raised_by: \"_held_change_refusal\" },\n  { code: \"MXD02\", raised_by: \"entity_row_propose\" },\n  { code: \"MXPV1\", raised_by: \"field_retype_preview\" },\n  { code: \"P0001\", raised_by: \"_guest_record_ceiling,action_run,context_scope_write\" },\n  { code: \"P0002\", raised_by: \"_template_install_core,inbox_clear,inbox_snooze,publish_bind,template_archive,template_install_claim,template_install_note,template_keep,template_restore,template_uninstall,template_upgrade,whole_value_complete\" },\n  { code: \"P0R01\", raised_by: \"template_upgrade\" },\n  { code: \"PT409\", raised_by: \"entity_row_write,has_visibility_at,record_change_many,record_update,record_upsert,record_write_graph_superseding,table_move,whole_value_complete\" },\n  { code: \"PT428\", raised_by: \"_record_rule_uses\" },\n] as const;\n\n/** `platform.entity_types` — the registered tokens a Table or relation may name. */\nexport const ENTITY_TOKENS = [\n  \"access_delta_probe\",\n  \"access_delta_run\",\n  \"access_request\",\n  \"access_shadow_log\",\n  \"access_version\",\n  \"access_version_event\",\n  \"account_addon\",\n  \"account_closure\",\n  \"account_facts\",\n  \"acquisition_block\",\n  \"activity\",\n  \"admin_audit_log\",\n  \"admin_email_log\",\n  \"admin_markdown_sample\",\n  \"admin_user\",\n  \"admin_user_owned_resources_cache\",\n  \"admission_config\",\n  \"agent\",\n  \"agent_card\",\n  \"agent_definition_version\",\n  \"agent_drift_alert\",\n  \"agent_exemplar\",\n  \"agent_mandate_note\",\n  \"agent_prompt_block\",\n  \"agent_prompt_block_variant\",\n  \"agent_prompt_remediation\",\n  \"agent_required_flag_change\",\n  \"agent_run\",\n  \"agent_run_stage\",\n  \"agent_schedule\",\n  \"agent_schedule_claim\",\n  \"agent_shortcut\",\n  \"agent_surface_binding\",\n  \"agent_template\",\n  \"agent_term_list\",\n  \"agent_test_result\",\n  \"agent_test_run\",\n  \"agent_usage\",\n  \"agent_user_kv\",\n  \"ai_api\",\n  \"ai_calls\",\n  \"ai_device_model_file\",\n  \"ai_device_model_root\",\n  \"ai_endpoint\",\n  \"ai_media_generation_cache\",\n  \"ai_model\",\n  \"ai_model_alias\",\n  \"ai_model_artifact\",\n  \"ai_model_candidate\",\n  \"ai_model_presentation\",\n  \"ai_model_upstream\",\n  \"ai_model_variant\",\n  \"ai_model_verification_run\",\n  \"ai_model_want\",\n  \"ai_offering\",\n  \"ai_person_model_want\",\n  \"ai_provider\",\n  \"ai_request_latency\",\n  \"ai_runtime\",\n  \"ai_runtime_build\",\n  \"ai_runtime_compat\",\n  \"ai_setting\",\n  \"ai_setting_profile\",\n  \"ai_translation_cell\",\n  \"ai_usage_execution_facts\",\n  \"ai_usage_executions\",\n  \"ai_usage_hourly\",\n  \"ai_usage_hourly_watermark\",\n  \"analysis_result\",\n  \"anon_form\",\n  \"anon_form_password\",\n  \"anon_form_visit\",\n  \"anon_function_birth_grandfather\",\n  \"anon_hit\",\n  \"anon_inbound\",\n  \"anon_replay\",\n  \"anon_submission\",\n  \"anon_token\",\n  \"api_field_warning\",\n  \"api_request_log\",\n  \"app\",\n  \"app_config\",\n  \"app_config_history\",\n  \"app_definition_version\",\n  \"app_error\",\n  \"app_execution\",\n  \"app_instance\",\n  \"app_log\",\n  \"app_log_hourly\",\n  \"app_log_hourly_watermark\",\n  \"app_log_lines\",\n  \"app_log_muted_pattern\",\n  \"app_log_norm_exception\",\n  \"app_log_requests_hourly\",\n  \"app_rate_limit\",\n  \"app_setting\",\n  \"app_sync_status\",\n  \"applet_visitor_binding\",\n  \"approach\",\n  \"artifact\",\n  \"assessment\",\n  \"assessment_item\",\n  \"assessment_result\",\n  \"assignment_session\",\n  \"assist\",\n  \"assist_producer_policy\",\n  \"assist_producer_policy_history\",\n  \"association_type\",\n  \"assurance_level\",\n  \"attempt\",\n  \"attention_audience_rule\",\n  \"attention_audit\",\n  \"attention_item_state\",\n  \"attention_showing\",\n  \"audit_broken_functions\",\n  \"audit_canonical_findings\",\n  \"audit_exemption\",\n  \"audit_function_deps\",\n  \"audit_function_runtime_probe\",\n  \"audit_m2m_candidates\",\n  \"audit_refresh_log\",\n  \"audit_stale_registry\",\n  \"audit_unregistered_candidates\",\n  \"automation_delivery\",\n  \"automation_fired\",\n  \"base_entity_template\",\n  \"batch_cost_event\",\n  \"batch_provider_batch\",\n  \"batch_work_item\",\n  \"billing_capability\",\n  \"billing_capability_limit\",\n  \"billing_ci_package_build\",\n  \"billing_connect_account\",\n  \"billing_coupon\",\n  \"billing_coupon_redemption\",\n  \"billing_customer\",\n  \"billing_external_call_vendor\",\n  \"billing_free_network_counter\",\n  \"billing_free_period_grant\",\n  \"billing_free_use_counter\",\n  \"billing_hard_cost_reconciliation\",\n  \"billing_held_run\",\n  \"billing_org_payment_account\",\n  \"billing_payment\",\n  \"billing_payment_ask\",\n  \"billing_plan\",\n  \"billing_plan_limit\",\n  \"billing_price\",\n  \"billing_product\",\n  \"billing_provider_balance_snapshot\",\n  \"billing_spend_alarm\",\n  \"billing_spend_alarm_occurrence\",\n  \"billing_spend_approval\",\n  \"billing_spend_guardrail\",\n  \"billing_spend_hold\",\n  \"billing_stripe_event\",\n  \"billing_subscription\",\n  \"billing_usage_ledger\",\n  \"billing_usage_reset\",\n  \"billing_user_plan\",\n  \"block_state\",\n  \"board\",\n  \"browser_account_binding\",\n  \"browser_action_event\",\n  \"browser_authenticator_window\",\n  \"browser_capture\",\n  \"browser_control_request\",\n  \"browser_handoff\",\n  \"browser_login_attempt\",\n  \"browser_login_recipe\",\n  \"browser_profile\",\n  \"browser_profile_checkpoint\",\n  \"browser_run\",\n  \"browser_site_observation\",\n  \"browser_site_policy\",\n  \"browser_stream_ticket\",\n  \"build_lock\",\n  \"calendar_event\",\n  \"campaign_watch_ramp_gate_run\",\n  \"campaign_watch_switch_outbox\",\n  \"campaign_watch_switch_window\",\n  \"canvas_comment\",\n  \"canvas_comment_like\",\n  \"canvas_item\",\n  \"canvas_item_state\",\n  \"canvas_like\",\n  \"canvas_score\",\n  \"canvas_view\",\n  \"capture_window\",\n  \"carrying_rule\",\n  \"catalog_entries_history\",\n  \"catalog_entry\",\n  \"category\",\n  \"change_item\",\n  \"change_job\",\n  \"change_job_row\",\n  \"change_plan\",\n  \"change_type_default\",\n  \"change_work\",\n  \"chat_user_usage_summary\",\n  \"citations\",\n  \"class_purchase\",\n  \"classifier_revision_ledger\",\n  \"client_callable_door\",\n  \"client_callable_door_retirement\",\n  \"client_excluded_column_unregistered\",\n  \"cmp_entry\",\n  \"cmp_feedback\",\n  \"code_file\",\n  \"code_folder\",\n  \"code_repository\",\n  \"coding_session\",\n  \"coding_session_entry\",\n  \"collab_checkpoint\",\n  \"collab_op\",\n  \"collab_room\",\n  \"comment\",\n  \"commerce_asset_allocation\",\n  \"commerce_asset_grading\",\n  \"commerce_asset_identifier\",\n  \"commerce_asset_lot_event\",\n  \"commerce_asset_mandate_result\",\n  \"commerce_asset_price_factor\",\n  \"commerce_asset_reshoot_request\",\n  \"commerce_asset_review\",\n  \"commerce_asset_unknown\",\n  \"commerce_certified_printer\",\n  \"commerce_cloud_sync_connection\",\n  \"commerce_ebay_business_policy\",\n  \"commerce_ebay_category\",\n  \"commerce_ebay_category_aspect\",\n  \"commerce_ebay_category_tree\",\n  \"commerce_ebay_custom_policy\",\n  \"commerce_ebay_inventory_item\",\n  \"commerce_ebay_inventory_item_group\",\n  \"commerce_ebay_inventory_item_group_member\",\n  \"commerce_ebay_inventory_location\",\n  \"commerce_ebay_listing\",\n  \"commerce_ebay_marketplace_policy\",\n  \"commerce_ebay_media_asset\",\n  \"commerce_ebay_notification_destination\",\n  \"commerce_ebay_notification_event\",\n  \"commerce_ebay_notification_subscription\",\n  \"commerce_ebay_notification_topic\",\n  \"commerce_ebay_offer\",\n  \"commerce_ebay_order\",\n  \"commerce_ebay_order_line_item\",\n  \"commerce_ebay_shipping_fulfillment\",\n  \"commerce_ebay_store_category\",\n  \"commerce_human_correction\",\n  \"commerce_intake_artifact\",\n  \"commerce_intake_asset\",\n  \"commerce_intake_batch\",\n  \"commerce_label_batch\",\n  \"commerce_label_code\",\n  \"commerce_marketplace_account\",\n  \"commerce_marketplace_account_deletion_audit\",\n  \"commerce_marketplace_api_call\",\n  \"commerce_marketplace_rate_budget\",\n  \"commerce_marketplace_site\",\n  \"commerce_marketplace_sync_run\",\n  \"commerce_prediction_outcome\",\n  \"commerce_print_order\",\n  \"commerce_product\",\n  \"commerce_product_channel_ref\",\n  \"commerce_product_media\",\n  \"commerce_product_variant\",\n  \"commerce_recall_audit\",\n  \"communication_calendar_selected_snapshot_state\",\n  \"communication_channel_readiness\",\n  \"comparison_set\",\n  \"component_group\",\n  \"computed_org_mark\",\n  \"computed_reader_cols\",\n  \"computed_reader_judgement\",\n  \"config_manifest\",\n  \"config_read_bucket\",\n  \"contact_medium\",\n  \"contact_submission\",\n  \"content_certification\",\n  \"content_ir_converter_definition\",\n  \"content_ir_converter_run\",\n  \"content_ir_kind\",\n  \"content_ir_kind_component\",\n  \"content_ir_kind_component_incident\",\n  \"content_ir_kind_component_layer\",\n  \"content_ir_kind_conformance\",\n  \"content_ir_kind_edge\",\n  \"content_ir_kind_example\",\n  \"content_ir_kind_instance\",\n  \"content_ir_kind_surface\",\n  \"content_ir_render_inspection\",\n  \"content_lane\",\n  \"context_access_log\",\n  \"context_item\",\n  \"context_item_suggestion\",\n  \"context_item_value\",\n  \"context_value_refs\",\n  \"conversation\",\n  \"conversation_value\",\n  \"courts\",\n  \"credential_attachment\",\n  \"credential_item\",\n  \"credential_mutation_receipt\",\n  \"crm_address\",\n  \"crm_affiliation\",\n  \"crm_blocklist_entry\",\n  \"crm_contact_candidate\",\n  \"crm_deal\",\n  \"crm_deal_stage_event\",\n  \"crm_enrichment_call\",\n  \"crm_interaction\",\n  \"crm_merge_candidate\",\n  \"crm_outreach_list\",\n  \"crm_outreach_list_member\",\n  \"crm_party_merge\",\n  \"crm_party_research\",\n  \"crm_registry_ingest_run\",\n  \"crm_registry_source\",\n  \"crm_sending_claim\",\n  \"crm_sending_event\",\n  \"crm_sending_identity\",\n  \"crm_sending_identity_check\",\n  \"crm_sending_policy\",\n  \"custom_agent_table_origin\",\n  \"custom_agent_table_trust\",\n  \"custom_agg_digest_checked\",\n  \"custom_anon_form_draft\",\n  \"custom_base\",\n  \"custom_base_snapshot\",\n  \"custom_entity_definition\",\n  \"custom_field_definition\",\n  \"custom_field_target\",\n  \"custom_inbox_item_state\",\n  \"custom_io_outbox_consumer\",\n  \"custom_io_outbox_consumption\",\n  \"custom_portal\",\n  \"custom_portal_principal\",\n  \"custom_portal_table\",\n  \"custom_record\",\n  \"custom_share_tails_mine_repair\",\n  \"custom_synced_source\",\n  \"custom_template\",\n  \"custom_template_install\",\n  \"custom_whole_value_parked\",\n  \"cx_agent_memory\",\n  \"cx_agent_plan\",\n  \"cx_agent_task\",\n  \"cx_code_edit\",\n  \"cx_code_message_file\",\n  \"cx_conversation_documents\",\n  \"cx_media\",\n  \"cx_observational_memory\",\n  \"cx_observational_memory_event\",\n  \"cx_pending_injection\",\n  \"cx_request\",\n  \"cx_request_snapshot\",\n  \"cx_request_values\",\n  \"cx_tool_trace\",\n  \"cx_user_request\",\n  \"cx_user_todo\",\n  \"dashboard_saved_view\",\n  \"data_rights_event\",\n  \"data_store\",\n  \"data_store_members\",\n  \"dataset\",\n  \"ddl_guard_log\",\n  \"deck_suggestion\",\n  \"definer_class_exemption\",\n  \"definer_client_grant_grandfather\",\n  \"definer_grant_baseline\",\n  \"deprecated_relation\",\n  \"derive_run\",\n  \"desktop_app_account\",\n  \"desktop_app_instance\",\n  \"desktop_app_profile\",\n  \"dev_login_audit\",\n  \"device_handoff\",\n  \"dict_entry\",\n  \"dict_provider_publication\",\n  \"dict_setting\",\n  \"dm_conversation\",\n  \"dm_message\",\n  \"dm_participant\",\n  \"dm_session_member\",\n  \"doc_render\",\n  \"doc_signature\",\n  \"dockets\",\n  \"document\",\n  \"document_version\",\n  \"domain_classification\",\n  \"edge_payload_kind\",\n  \"egress_device\",\n  \"egress_pairing\",\n  \"egress_ticket\",\n  \"emails\",\n  \"embedding_cache\",\n  \"embeddings_google_gemini_2_1536\",\n  \"embeddings_oai_3_small_1536\",\n  \"embeddings_voyage_4_large_1024\",\n  \"embeddings_voyage_code_3_1024\",\n  \"endpoint_family_sweep_state\",\n  \"engine_owner_task\",\n  \"entity_grant\",\n  \"entity_protected_value\",\n  \"entity_protected_value_version\",\n  \"entity_relationship\",\n  \"entity_type\",\n  \"esign_campaign\",\n  \"esign_campaign_member\",\n  \"esign_consent_disclosure\",\n  \"esign_envelope\",\n  \"esign_envelope_certificate\",\n  \"esign_envelope_document\",\n  \"esign_envelope_draft\",\n  \"esign_envelope_event\",\n  \"esign_envelope_external_ref\",\n  \"esign_envelope_signer\",\n  \"esign_provider\",\n  \"esign_provider_binding\",\n  \"esign_saved_signature\",\n  \"esign_signing_key\",\n  \"esign_template\",\n  \"execution_event_cursor\",\n  \"extension_auth_code\",\n  \"external_api_reservation\",\n  \"external_conversation\",\n  \"external_delivery_event\",\n  \"external_inbox\",\n  \"external_link\",\n  \"external_message\",\n  \"external_provider_receipt\",\n  \"external_source\",\n  \"extract_sweep_state\",\n  \"fc_card\",\n  \"fc_detail\",\n  \"fc_set\",\n  \"feature_doc\",\n  \"feature_knob\",\n  \"feedback_comments\",\n  \"feedback_user_messages\",\n  \"field_component\",\n  \"file\",\n  \"file_analysis\",\n  \"file_entities\",\n  \"file_overrides\",\n  \"file_page_annotations\",\n  \"file_pages\",\n  \"file_rag_job\",\n  \"file_template\",\n  \"file_version\",\n  \"files_account_tier\",\n  \"files_machine_written_prefix\",\n  \"files_sync_mapping\",\n  \"files_user_account\",\n  \"flashcard_data\",\n  \"flashcard_history\",\n  \"flashcard_sets\",\n  \"flexible_data\",\n  \"folder\",\n  \"function_contract\",\n  \"game_badge\",\n  \"game_result\",\n  \"game_room\",\n  \"global_execution\",\n  \"global_execution_checkpoint\",\n  \"global_execution_control\",\n  \"global_execution_event\",\n  \"global_meter_entry\",\n  \"global_origin\",\n  \"global_request\",\n  \"google_document\",\n  \"growth_loop_event\",\n  \"growth_loop_run\",\n  \"growth_loop_stage_run\",\n  \"guardian_link\",\n  \"guest_conversion_audit\",\n  \"guest_execution_log\",\n  \"guest_executions\",\n  \"guided_checklist_run\",\n  \"heatmap_save\",\n  \"hindsight_enrollment\",\n  \"hindsight_finding\",\n  \"hindsight_regression_case\",\n  \"hindsight_replay\",\n  \"hindsight_replay_step\",\n  \"hindsight_review\",\n  \"hr_access_audit\",\n  \"hr_access_role\",\n  \"hr_accommodation_request\",\n  \"hr_ai_evidence\",\n  \"hr_alert_routing_rule\",\n  \"hr_application\",\n  \"hr_approval_authority\",\n  \"hr_approval_delegation\",\n  \"hr_asset\",\n  \"hr_asset_assignment\",\n  \"hr_attendance_exception\",\n  \"hr_auto_close_rule\",\n  \"hr_availability\",\n  \"hr_background_check\",\n  \"hr_benefits_event\",\n  \"hr_calculation_snapshot\",\n  \"hr_candidate\",\n  \"hr_candidate_conversion\",\n  \"hr_candidate_message\",\n  \"hr_careers_portal\",\n  \"hr_checklist_item\",\n  \"hr_checklist_run\",\n  \"hr_checklist_template\",\n  \"hr_checklist_template_item\",\n  \"hr_compensation\",\n  \"hr_corrective_action\",\n  \"hr_course\",\n  \"hr_course_version\",\n  \"hr_credential\",\n  \"hr_crew\",\n  \"hr_deduction_code\",\n  \"hr_department\",\n  \"hr_derived_grant\",\n  \"hr_disposition_event\",\n  \"hr_earning_code\",\n  \"hr_eeo_response\",\n  \"hr_emergency_contact\",\n  \"hr_employee\",\n  \"hr_employee_private\",\n  \"hr_employer_profile\",\n  \"hr_employment\",\n  \"hr_employment_pin\",\n  \"hr_engagement\",\n  \"hr_establishment\",\n  \"hr_external_identity\",\n  \"hr_field_policy\",\n  \"hr_goal\",\n  \"hr_holiday\",\n  \"hr_holiday_calendar\",\n  \"hr_i9\",\n  \"hr_i9_document\",\n  \"hr_incident\",\n  \"hr_incident_party\",\n  \"hr_interview\",\n  \"hr_interview_kit\",\n  \"hr_job_title\",\n  \"hr_jurisdiction\",\n  \"hr_jurisdiction_rule\",\n  \"hr_jurisdiction_rule_class\",\n  \"hr_jurisdiction_rule_org_decision\",\n  \"hr_jurisdiction_rule_test\",\n  \"hr_kiosk_device\",\n  \"hr_kiosk_session\",\n  \"hr_labor_target\",\n  \"hr_leave_case\",\n  \"hr_leave_enrollment\",\n  \"hr_leave_ledger\",\n  \"hr_leave_policy\",\n  \"hr_leave_request\",\n  \"hr_legal_hold\",\n  \"hr_legal_hold_item\",\n  \"hr_location\",\n  \"hr_new_hire_report\",\n  \"hr_offer\",\n  \"hr_opening\",\n  \"hr_overtime_alert\",\n  \"hr_overtime_alert_rule\",\n  \"hr_overtime_preapproval\",\n  \"hr_pay_group\",\n  \"hr_pay_period\",\n  \"hr_pay_period_employment\",\n  \"hr_payroll_export\",\n  \"hr_payroll_export_line\",\n  \"hr_position_assignment\",\n  \"hr_posting\",\n  \"hr_posting_publication\",\n  \"hr_provider_binding\",\n  \"hr_provider_event\",\n  \"hr_provisioning_result\",\n  \"hr_punch\",\n  \"hr_recalculation_batch\",\n  \"hr_record_class\",\n  \"hr_records_request\",\n  \"hr_reference_check\",\n  \"hr_reporting_line\",\n  \"hr_requisition\",\n  \"hr_restricted_note\",\n  \"hr_retention_rule\",\n  \"hr_review\",\n  \"hr_review_cycle\",\n  \"hr_review_peer_nomination\",\n  \"hr_review_response\",\n  \"hr_review_template\",\n  \"hr_role_assignment\",\n  \"hr_schedule\",\n  \"hr_schedule_change\",\n  \"hr_schedule_guidance\",\n  \"hr_schedule_template\",\n  \"hr_schedule_template_shift\",\n  \"hr_scorecard\",\n  \"hr_separation\",\n  \"hr_shift\",\n  \"hr_shift_claim\",\n  \"hr_staffing_requirement\",\n  \"hr_survey\",\n  \"hr_survey_invitation\",\n  \"hr_survey_question\",\n  \"hr_survey_response\",\n  \"hr_tax_registration\",\n  \"hr_tax_withholding\",\n  \"hr_time_adjustment\",\n  \"hr_training_assignment\",\n  \"hr_training_attempt\",\n  \"hr_transcript_entry\",\n  \"hr_verification_letter_request\",\n  \"hr_work_interval\",\n  \"hr_workflow_binding\",\n  \"hr_workflow_decision\",\n  \"hr_workflow_definition\",\n  \"hr_workflow_event\",\n  \"hr_workflow_failure\",\n  \"hr_workflow_flow_type\",\n  \"hr_workflow_instance\",\n  \"hr_workflow_step\",\n  \"hr_workflow_step_definition\",\n  \"hr_workweek\",\n  \"html_extraction\",\n  \"iam_access_audit\",\n  \"iam_access_setup\",\n  \"iam_api_key\",\n  \"iam_emergency_door_request\",\n  \"iam_oauth_app\",\n  \"iam_org_availability_key\",\n  \"iam_org_domain\",\n  \"iam_org_domain_route\",\n  \"iam_publish_binding\",\n  \"iam_publisher_verification\",\n  \"iam_read_lane_v2_rollout\",\n  \"iam_record_seat_change\",\n  \"iam_sign_in_event\",\n  \"iam_world_namespace\",\n  \"iam_world_publish_admission\",\n  \"idempotency\",\n  \"industry\",\n  \"industry_curator\",\n  \"infra_status\",\n  \"ingest_runs\",\n  \"integration_connection\",\n  \"integration_connection_resource\",\n  \"interview_decision_interview\",\n  \"interview_decision_question\",\n  \"interview_document_revision\",\n  \"interview_hole\",\n  \"interview_question\",\n  \"interview_session\",\n  \"interview_turn\",\n  \"invitation\",\n  \"invitation_code\",\n  \"invitation_request\",\n  \"io_comment\",\n  \"io_contract\",\n  \"io_import\",\n  \"io_outbox\",\n  \"item\",\n  \"item_mastery\",\n  \"judge_verdict\",\n  \"jurisdiction_policy\",\n  \"keyword_classification_queue\",\n  \"kg_alert\",\n  \"kg_chunk_entities\",\n  \"kg_chunks\",\n  \"kg_clusters\",\n  \"kg_edges\",\n  \"kg_entities\",\n  \"kg_entity_aliases\",\n  \"kg_suggestion_ack\",\n  \"kg_sweep_queue\",\n  \"kg_sweep_run\",\n  \"kg_sweep_state\",\n  \"kg_value_match\",\n  \"knob_override\",\n  \"knob_override_audit\",\n  \"knob_rung_lock\",\n  \"knob_scope_kind\",\n  \"knob_write_door\",\n  \"league_membership\",\n  \"learn_doc\",\n  \"library_doc\",\n  \"lifecycle_archive\",\n  \"lifecycle_archive_row\",\n  \"lifecycle_audit\",\n  \"lifecycle_entity_plan\",\n  \"lifecycle_map_build\",\n  \"lifecycle_reference_map\",\n  \"lifecycle_run\",\n  \"lifecycle_tier_ledger\",\n  \"location\",\n  \"mandate\",\n  \"mandate_advance_batch_row\",\n  \"mandate_binding\",\n  \"mandate_candidate\",\n  \"mandate_candidate_run\",\n  \"mandate_candidate_run_payload\",\n  \"mandate_goal_clauses\",\n  \"mandate_observation\",\n  \"mandate_proposal\",\n  \"mandate_readiness_verdict\",\n  \"mandate_reference\",\n  \"mandate_scan\",\n  \"mandate_treatment\",\n  \"marketing_initiative\",\n  \"masterwork_corpus_item\",\n  \"masterwork_run\",\n  \"masterwork_run_kind\",\n  \"masterwork_source\",\n  \"math_course_structure\",\n  \"math_problem\",\n  \"matrx_action_ledger\",\n  \"mcp_config\",\n  \"mcp_server\",\n  \"mcp_user_conn\",\n  \"media_capture_handoff\",\n  \"media_catalog_setting\",\n  \"media_library_item\",\n  \"media_selection_item\",\n  \"media_selection_job\",\n  \"media_source_library\",\n  \"meet_call_invite\",\n  \"meet_chat_message\",\n  \"meet_connection\",\n  \"meet_invitee\",\n  \"meet_meeting\",\n  \"meet_note\",\n  \"meet_occurrence_override\",\n  \"meet_participant\",\n  \"meet_recording\",\n  \"meet_session\",\n  \"meet_transcript_segment\",\n  \"membership\",\n  \"membership_grant\",\n  \"memory_trial\",\n  \"memory_trial_step\",\n  \"merge_field_provenance\",\n  \"message\",\n  \"message_template\",\n  \"message_template_detail\",\n  \"meta_excluded_schema\",\n  \"meta_table_stats_history\",\n  \"metadata_reserved_keys\",\n  \"microservice_project\",\n  \"migration_log\",\n  \"mtx_media_heal_queue\",\n  \"mtx_public_url_guard\",\n  \"ner_shadow\",\n  \"note\",\n  \"note_folder\",\n  \"notification\",\n  \"notification_channel_preference\",\n  \"notification_event_override\",\n  \"notification_event_type\",\n  \"notification_preference\",\n  \"notification_submission\",\n  \"notify_outsider_door_baseline\",\n  \"oauth_handoff_claim\",\n  \"opinion_clusters\",\n  \"opinions\",\n  \"ops_auth_lock_watchdog_log\",\n  \"ops_check_item\",\n  \"ops_check_run\",\n  \"ops_db_host_sample\",\n  \"ops_issue_class\",\n  \"ops_issue_event\",\n  \"ops_perf_client_event\",\n  \"ops_perf_sample\",\n  \"ops_perf_statement_snapshot\",\n  \"ops_proof_check\",\n  \"ops_proof_run\",\n  \"ops_proof_scenario\",\n  \"ops_source_read_cache\",\n  \"ops_test_replay_cache\",\n  \"org_admin_audit\",\n  \"org_change_policy\",\n  \"org_chart_publication\",\n  \"org_context_ledger\",\n  \"org_industries\",\n  \"org_member_control\",\n  \"org_module_config\",\n  \"org_move_txn\",\n  \"org_plan\",\n  \"org_sweep_list\",\n  \"organization\",\n  \"organization_preferences\",\n  \"organization_visibility_version\",\n  \"output_feedback\",\n  \"outreach_acceptance\",\n  \"page_extraction_job\",\n  \"page_extraction_page_run\",\n  \"page_extraction_results\",\n  \"page_extraction_runs\",\n  \"page_intent_queue\",\n  \"page_mapping_queue\",\n  \"page_vitals\",\n  \"part_config\",\n  \"part_config_sub\",\n  \"party\",\n  \"party_contact_point\",\n  \"passkey_credential\",\n  \"pb_claim_appeals_fd31de\",\n  \"pb_insurance_claims_fd31de\",\n  \"pc_article\",\n  \"pc_episode\",\n  \"pc_show\",\n  \"pc_studio_run\",\n  \"pc_studio_run_asset\",\n  \"pdf_consolidation_log\",\n  \"pdf_redaction_audit\",\n  \"pdf_redaction_key_escrow\",\n  \"permission_grant\",\n  \"personal_data_column\",\n  \"plan_cms_fill_item\",\n  \"plan_cms_fill_job\",\n  \"plan_entity\",\n  \"plan_node\",\n  \"plan_node_artifact\",\n  \"plan_node_step\",\n  \"plan_profile\",\n  \"platform_action_request\",\n  \"platform_actor_session\",\n  \"platform_actor_token\",\n  \"platform_actor_token_event\",\n  \"platform_class_approval_by_arman\",\n  \"platform_class_approval_by_org_admin\",\n  \"platform_continued_access\",\n  \"platform_cutover_census_run\",\n  \"platform_cutover_evaluation_replaced\",\n  \"platform_cutover_evaluation_write\",\n  \"platform_cutover_seam\",\n  \"platform_cutover_seam_measure\",\n  \"platform_cutover_seam_press\",\n  \"platform_dated_change\",\n  \"platform_doors_only_pending_cutover\",\n  \"platform_google_calendar_event_create_intent\",\n  \"platform_google_task_create_intent\",\n  \"platform_hidden_item\",\n  \"platform_kernel_fingerprint_record\",\n  \"platform_org_knob_override\",\n  \"platform_outcome_event\",\n  \"platform_outsider_consumer\",\n  \"platform_provision_base_contract_pending\",\n  \"platform_reachability\",\n  \"platform_reachability_rebuild_pending\",\n  \"platform_realtime_topic_prefix\",\n  \"platform_reference_category\",\n  \"platform_reference_declaration\",\n  \"platform_repo\",\n  \"platform_saved_view\",\n  \"platform_schema\",\n  \"platform_secure_delivery\",\n  \"platform_share_link\",\n  \"platform_strict_class_probe\",\n  \"platform_user_knob_override\",\n  \"podcast_race\",\n  \"position\",\n  \"presentation\",\n  \"processed_document\",\n  \"processed_document_page\",\n  \"product_capture_file\",\n  \"product_capture_item\",\n  \"product_capture_payload\",\n  \"product_capture_product\",\n  \"product_capture_question\",\n  \"profile\",\n  \"project\",\n  \"prompt\",\n  \"provider_account\",\n  \"provider_account_credential\",\n  \"provision\",\n  \"provision_generate_target\",\n  \"provision_grant\",\n  \"provision_marker\",\n  \"provision_rule_message\",\n  \"provision_schema\",\n  \"provision_shape_debt\",\n  \"provision_snapshot\",\n  \"provision_spec\",\n  \"provision_spec_grandfather\",\n  \"provision_vocabulary\",\n  \"provlock_recall_visits_all8u5\",\n  \"public_compat_wrapper\",\n  \"public_placement_baseline\",\n  \"public_placement_census\",\n  \"public_placement_domain\",\n  \"public_restore_permit\",\n  \"purpose\",\n  \"quiz_session\",\n  \"rag_ingest_run\",\n  \"rag_library_audit_log\",\n  \"rate_limit_buckets\",\n  \"reachability_pending\",\n  \"read_mask_kept\",\n  \"recompute_queue\",\n  \"record\",\n  \"record_alias\",\n  \"record_computed\",\n  \"record_follow\",\n  \"redaction_mapping\",\n  \"relationship_rule\",\n  \"research_analysis\",\n  \"research_content\",\n  \"research_context_bundle\",\n  \"research_document\",\n  \"research_intent\",\n  \"research_keyword\",\n  \"research_media\",\n  \"research_source\",\n  \"research_synthesis\",\n  \"research_tag\",\n  \"research_template\",\n  \"research_topic\",\n  \"retention_policy\",\n  \"retrieval_audit\",\n  \"review_queue\",\n  \"route_manifest_entry\",\n  \"row_version\",\n  \"rulebook\",\n  \"run_approval\",\n  \"run_approval_event\",\n  \"runtime_operation_stream\",\n  \"runtime_operation_stream_batch\",\n  \"sandbox_instance\",\n  \"sch_agent_task\",\n  \"sch_run\",\n  \"sch_task\",\n  \"sch_trigger\",\n  \"scheduler_automation_run_subject\",\n  \"schema_client_exposure\",\n  \"schema_migration_ledger\",\n  \"schema_migration_legacy\",\n  \"schema_migration_slot_grandfather\",\n  \"schema_templates\",\n  \"scope\",\n  \"scope_association_suggestion\",\n  \"scope_dataset_instance\",\n  \"scope_door_registry\",\n  \"scope_item_value_suggestion\",\n  \"scope_suggestion\",\n  \"scope_type\",\n  \"scrape_domain\",\n  \"scrape_domain_settings\",\n  \"scrape_failure_log\",\n  \"scrape_parsed_page\",\n  \"scrape_path_override\",\n  \"scrape_path_pattern\",\n  \"scrape_retry_queue\",\n  \"scraper_comparison_run\",\n  \"scraper_data_fetch_job\",\n  \"scraper_data_fetch_job_row\",\n  \"scraper_data_source\",\n  \"search_item\",\n  \"seo_ai_capability\",\n  \"seo_ai_visibility_brand_check\",\n  \"seo_ai_visibility_citation\",\n  \"seo_ai_visibility_claim\",\n  \"seo_ai_visibility_design_artifact\",\n  \"seo_ai_visibility_panel\",\n  \"seo_ai_visibility_panel_version\",\n  \"seo_ai_visibility_response\",\n  \"seo_ai_visibility_signal\",\n  \"seo_backlink\",\n  \"seo_backlink_change_event\",\n  \"seo_backlink_dimension_snapshot\",\n  \"seo_backlink_observation\",\n  \"seo_backlink_snapshot\",\n  \"seo_change_assessment\",\n  \"seo_change_event\",\n  \"seo_change_item\",\n  \"seo_change_metric\",\n  \"seo_change_set\",\n  \"seo_change_theory\",\n  \"seo_collection_run\",\n  \"seo_competitor\",\n  \"seo_competitor_observation\",\n  \"seo_competitor_opportunity\",\n  \"seo_coverage_mention\",\n  \"seo_coverage_tracker\",\n  \"seo_dimension_value_matcher\",\n  \"seo_engine_schedule\",\n  \"seo_geo_place\",\n  \"seo_gsc_dig_rule\",\n  \"seo_keyword\",\n  \"seo_keyword_class_rule\",\n  \"seo_keyword_edge\",\n  \"seo_keyword_facet\",\n  \"seo_keyword_market\",\n  \"seo_keyword_market_observation\",\n  \"seo_keyword_place\",\n  \"seo_keyword_saved_view\",\n  \"seo_keyword_topic\",\n  \"seo_landscape_brief\",\n  \"seo_link_gap_domain\",\n  \"seo_link_gap_match\",\n  \"seo_map_facet\",\n  \"seo_map_facet_value\",\n  \"seo_map_topic\",\n  \"seo_page_measurement_health\",\n  \"seo_page_performance\",\n  \"seo_pr_moment\",\n  \"seo_provider_call\",\n  \"seo_provider_task\",\n  \"seo_rank_observation\",\n  \"seo_rank_target\",\n  \"seo_raw_payload\",\n  \"seo_referring_domain_profile\",\n  \"seo_reputation_case\",\n  \"seo_search_performance_daily\",\n  \"seo_serp_mention\",\n  \"seo_serp_opportunity\",\n  \"seo_serp_result\",\n  \"seo_serp_snapshot\",\n  \"seo_site_geo_area\",\n  \"seo_site_keyword_offering\",\n  \"seo_site_keyword_value\",\n  \"seo_site_offering_value\",\n  \"seo_site_topic_value\",\n  \"seo_site_value_combo\",\n  \"seo_site_value_worth\",\n  \"seo_site_vocabulary\",\n  \"seo_source_request\",\n  \"seo_starter_pack\",\n  \"seo_starter_pack_item\",\n  \"seo_story_angle\",\n  \"seo_topic\",\n  \"seo_topical_map\",\n  \"seo_tracker_story\",\n  \"seo_web_analytics_daily\",\n  \"share_link\",\n  \"share_link_password\",\n  \"shareable_resource_registry\",\n  \"shared_canvas_item\",\n  \"short_link\",\n  \"shortcut_category\",\n  \"sign_in_fk_legacy\",\n  \"skill\",\n  \"skill_category\",\n  \"skill_detail\",\n  \"skill_render_definition\",\n  \"sms_consent\",\n  \"sms_conversation\",\n  \"sms_message\",\n  \"sms_message_media\",\n  \"sms_notification\",\n  \"sms_notification_preference\",\n  \"sms_phone_number\",\n  \"sms_rate_limits\",\n  \"sms_webhook_logs\",\n  \"social_account_insight_daily\",\n  \"social_ad\",\n  \"social_captured_post\",\n  \"social_kpi_goal\",\n  \"social_own_post_metric\",\n  \"social_post\",\n  \"social_post_analysis\",\n  \"social_post_comment\",\n  \"social_post_metric_snapshot\",\n  \"social_post_stat\",\n  \"social_post_transcript\",\n  \"social_profile\",\n  \"social_profile_snapshot\",\n  \"social_remix_output\",\n  \"social_swipe_collection\",\n  \"social_tracked_account\",\n  \"social_video_composition_version\",\n  \"social_video_project\",\n  \"social_video_variant\",\n  \"social_watchlist_hit\",\n  \"soft_delete_cascade_job\",\n  \"soft_delete_edge\",\n  \"source_authority\",\n  \"space_payload\",\n  \"stage_ref_kind\",\n  \"stamped_write_table\",\n  \"structure\",\n  \"structured_list\",\n  \"studio_cleaned_segments\",\n  \"studio_concept_items\",\n  \"studio_documents\",\n  \"studio_module_segments\",\n  \"studio_raw_segments\",\n  \"studio_recording_chunks\",\n  \"studio_recording_segments\",\n  \"studio_run\",\n  \"studio_session\",\n  \"studio_session_settings\",\n  \"study_attempt\",\n  \"study_goal\",\n  \"study_media\",\n  \"study_plan\",\n  \"study_plan_block\",\n  \"study_plan_day\",\n  \"study_reminder_context\",\n  \"study_reminder_delivery\",\n  \"study_session\",\n  \"study_source_chunk\",\n  \"study_streak\",\n  \"study_structured_section\",\n  \"superseded_policy\",\n  \"support_session\",\n  \"support_session_event\",\n  \"surface\",\n  \"system_announcement\",\n  \"system_context_item\",\n  \"system_context_item_org_value\",\n  \"system_error\",\n  \"system_orgs\",\n  \"system_write_failure\",\n  \"t13_backfill_ledger\",\n  \"t13_default_ledger\",\n  \"t13_row_column_events\",\n  \"tag\",\n  \"task\",\n  \"task_user_state\",\n  \"taxonomy_node\",\n  \"team\",\n  \"template_context_items\",\n  \"template_scope_types\",\n  \"templates\",\n  \"test_handset_inbox\",\n  \"test_handset_verification\",\n  \"thread\",\n  \"tool\",\n  \"tool_battle\",\n  \"tool_battle_cell\",\n  \"tool_binding\",\n  \"tool_bundle\",\n  \"tool_call\",\n  \"tool_call_facts\",\n  \"tool_canary_run\",\n  \"tool_catalog_cache\",\n  \"tool_catalog_call\",\n  \"tool_catalog_call_attempt\",\n  \"tool_catalog_call_detail\",\n  \"tool_catalog_endpoint\",\n  \"tool_catalog_entry\",\n  \"tool_catalog_provider\",\n  \"tool_definition_version\",\n  \"tool_executor\",\n  \"tool_feature_scorecard\",\n  \"tool_surface_defaults\",\n  \"tool_test_sample\",\n  \"tool_ui\",\n  \"tool_ui_incident\",\n  \"tool_ui_version\",\n  \"topic_placement_queue\",\n  \"transcript\",\n  \"trigger_event\",\n  \"udt_dataset_fields\",\n  \"udt_dataset_row_versions\",\n  \"udt_dataset_rows\",\n  \"udt_dataset_template\",\n  \"udt_dataset_template_fields\",\n  \"udt_document\",\n  \"udt_document_snapshot\",\n  \"udt_structured_list_items\",\n  \"udt_workbook_snapshot\",\n  \"ui_client\",\n  \"ui_decision_pick\",\n  \"ui_surface_action\",\n  \"ui_surface_agent_pref\",\n  \"ui_surface_agent_role\",\n  \"ui_surface_client_tool\",\n  \"ui_surface_config\",\n  \"ui_surface_item_type\",\n  \"ui_surface_value\",\n  \"ui_surface_write_target\",\n  \"univer_payload\",\n  \"unsubscribe_token\",\n  \"uploads_inflight\",\n  \"user\",\n  \"user_achievement\",\n  \"user_acquisition_facts\",\n  \"user_acquisition_facts_stored\",\n  \"user_acquisition_facts_stored_watermark\",\n  \"user_active_context\",\n  \"user_analysis_preference\",\n  \"user_email_preference\",\n  \"user_entity_state\",\n  \"user_feedback\",\n  \"user_follows\",\n  \"user_form_profile\",\n  \"user_markdown_sample\",\n  \"user_memory\",\n  \"user_preference\",\n  \"user_profile\",\n  \"user_secret\",\n  \"user_secret_audit\",\n  \"user_secret_grant\",\n  \"user_stat\",\n  \"user_storage_usage\",\n  \"user_surface_state\",\n  \"users_calendar_feed\",\n  \"users_notion_sync_source\",\n  \"vault_fill_approvals\",\n  \"vault_fill_devices\",\n  \"vault_fill_nonces\",\n  \"visibility_cache\",\n  \"visibility_epoch\",\n  \"voice\",\n  \"war_room\",\n  \"wbx_demo\",\n  \"wbx_guidance\",\n  \"wbx_highlight\",\n  \"wbx_pattern\",\n  \"wbx_recipe\",\n  \"wbx_screenshot\",\n  \"wbx_seo_audit\",\n  \"wc_claim\",\n  \"wc_impairment_definition\",\n  \"wc_injury\",\n  \"wc_report\",\n  \"web_analysis_item\",\n  \"web_brand\",\n  \"web_brand_asset\",\n  \"web_brand_choice\",\n  \"web_brand_exclusion\",\n  \"web_brand_offering\",\n  \"web_brand_persona\",\n  \"web_brand_relation_kind\",\n  \"web_brand_review\",\n  \"web_brand_testimony\",\n  \"web_business_fact\",\n  \"web_business_location\",\n  \"web_channel_analytics_daily\",\n  \"web_crawl_event\",\n  \"web_crawl_preset\",\n  \"web_crawl_schedule\",\n  \"web_crawl_session\",\n  \"web_crawl_url\",\n  \"web_discovered_item\",\n  \"web_domain_category\",\n  \"web_domain_category_observation\",\n  \"web_finding\",\n  \"web_gsc_page_stat\",\n  \"web_link_edge\",\n  \"web_listing_publisher\",\n  \"web_location_listing\",\n  \"web_news_item\",\n  \"web_offering_template\",\n  \"web_page\",\n  \"web_page_content\",\n  \"web_page_evidence\",\n  \"web_page_sitemap\",\n  \"web_property\",\n  \"web_provider\",\n  \"web_result\",\n  \"web_screenshot\",\n  \"web_site\",\n  \"web_site_endpoint_rule\",\n  \"web_site_item_config\",\n  \"web_site_offering\",\n  \"web_sitemap\",\n  \"web_snapshot\",\n  \"web_tag_manager_snapshot\",\n  \"web_temp_brand_firmographic\",\n  \"web_temp_brand_presence\",\n  \"web_temp_brand_recognition\",\n  \"web_voice_fingerprint\",\n  \"web_youtube_video\",\n  \"webhook_deliveries\",\n  \"webhook_dispatch_state\",\n  \"webhook_test_receipt\",\n  \"webhooks\",\n  \"wf_node_data_slot\",\n  \"work_claim\",\n  \"work_item\",\n  \"workbook\",\n  \"worker_heartbeat\",\n  \"workflow\",\n  \"workflow_card\",\n  \"workflow_checkpoint\",\n  \"workflow_checkpoint_value\",\n  \"workflow_comparison\",\n  \"workflow_definition_overview\",\n  \"workflow_definition_version\",\n  \"workflow_idempotency\",\n  \"workflow_job\",\n  \"workflow_node_events\",\n  \"workflow_node_outcome\",\n  \"workflow_plan\",\n  \"workflow_plan_event\",\n  \"workflow_plan_sample\",\n  \"workflow_recovery_audit\",\n  \"workflow_review_issue\",\n  \"workflow_run\",\n  \"workflow_run_cost\",\n  \"workflow_run_facts\",\n  \"workflow_run_log\",\n  \"workflow_runtime_surface\",\n  \"workflow_template\",\n  \"workflow_trigger\",\n  \"workflow_trigger_fire\",\n  \"workflow_work_item\",\n  \"working_document\",\n  \"write_guard_key\",\n  \"youtube_quota_day\",\n  \"youtube_search\",\n  \"youtube_video\",\n] as const;\n\nexport type StoreRefusalCode = (typeof STORE_REFUSAL_CODES)[number][\"code\"];\nexport type StoreDoorName = (typeof STORE_DOORS)[number][\"name\"];\nexport type EntityToken = (typeof ENTITY_TOKENS)[number];\nexport type KernelTableName = (typeof KERNEL_TABLES)[number][\"name\"];\n","// src/core/doors.ts — @ai-matrx/records\n//\n// THE DOOR TABLE. Every call this package can make names a door, and every door\n// it names is checked against `STORE_DOORS` — which is generated from `pg_proc`\n// on the live store, not written by a person.\n//\n// A door that is not there yet is answered `door_absent`, naming the door AND\n// the lane that owns it. That is the whole of \"nothing fails silently\" for this\n// package: there is no empty array standing in for a search nobody built, and\n// no `true` standing in for a proposal nobody can approve.\n\nimport { STORE_DOORS } from \"../store.generated\";\nimport type { RecordsError } from \"../results\";\nimport { doorAbsentRefusal } from \"./doorCall\";\n\n/** Which lane owes each door that does not exist yet (BUILD-BOOK \"Packages\"). */\nconst OWED_BY: Record<string, string> = {\n  table_archive_deliberately: \"lane 12 PLATFORM-APP-DATA P5 — matrx-frontend migrations/campaign/lane12_h_a_table_the_code_depends_on_is_archived_only_on_purpose.sql (chair's production apply)\",\n  entity_fields_across: \"lane 7 STANDARD-TABLES W2 — matrx-frontend migrations/campaign/lane7w2_b_one_read_of_a_tables_fields_across_organizations.sql (chair's production apply)\",\n  table_home: \"SC-1' — matrx-frontend migrations/campaign/sc1p_a_table_says_where_it_lives_and_its_owner_can_move_it.sql (and its grant file), applied by the chair\",\n  table_move: \"SC-1' / SC-1-TAILS — sc1p_a_table_says_where_it_lives_and_its_owner_can_move_it.sql, then sc1t_a_table_moves_with_the_tables_inside_it.sql, applied by the chair\",\n  record_aggregate: \"W5-SRV / W5-AGENT — `record_aggregate` is one of the eight verbs\",\n  field_propose: \"W5-AGENT — AGT-4/AGT-8, the proposal and its approvers\",\n  table_propose: \"W5-AGENT — AGT-8, the proposal and its approvers\",\n  merge_field_resolve: \"W5-MERGE-B — the resolver's server half\",\n  record_query: \"W1-INDEX / W5-SRV — the promoted-field query path\",\n  // Lane GRID-PRIMITIVES (2026-09-22): on the rehearsal branch; they reach the main database at\n  // the chair's 01:00–04:00 PT apply, and `pnpm records:generate` then lists them in\n  // STORE_DOORS. Until then each call answers door_absent naming this line — never a guess.\n  table_decorate: \"GRID-PRIMITIVES G1 — gridprim_a_table_wears_its_colors_and_its_layout.sql (chair's production apply)\",\n  table_decorations: \"GRID-PRIMITIVES G1 — gridprim_a_table_wears_its_colors_and_its_layout.sql (chair's production apply)\",\n  grid_layout: \"GRID-PRIMITIVES G1 — gridprim_a_table_wears_its_colors_and_its_layout.sql (chair's production apply)\",\n  formula_parse: \"GRID-PRIMITIVES G3 — gridprim_a_formula_is_typed_and_the_store_works_it_out.sql (chair's production apply)\",\n  action_declare: \"GRID-PRIMITIVES G2 — gridprim_a_row_action_runs_the_whole_selection_at_once.sql (chair's production apply)\",\n  row_actions: \"GRID-PRIMITIVES G2 — gridprim_a_row_action_runs_the_whole_selection_at_once.sql (chair's production apply)\",\n  action_run: \"GRID-PRIMITIVES G2 — gridprim_a_row_action_runs_the_whole_selection_at_once.sql (chair's production apply)\",\n  table_webhook_declare: \"GRID-PRIMITIVES G4 — gridprim_every_row_change_reaches_the_webhook.sql (chair's production apply)\",\n  table_webhooks: \"GRID-PRIMITIVES G4 — gridprim_every_row_change_reaches_the_webhook.sql (chair's production apply)\",\n  table_webhook_archive: \"GRID-PRIMITIVES G4 — gridprim_every_row_change_reaches_the_webhook.sql (chair's production apply)\",\n  table_from_example: \"GRID-PRIMITIVES G5 — gridprim_a_table_can_start_from_a_real_example.sql (chair's production apply)\",\n  autonumber_backfill: \"GRID-PRIMITIVES G5 — gridprim_a_table_can_start_from_a_real_example.sql (chair's production apply)\",\n  entity_row_write: \"lane 7 W3a — matrx-frontend migrations/campaign/lane7w3a_the_table_api_reaches_crm_people.sql (on the clone; chair's production apply)\",\n  table_list_everywhere: \"GRID-PRIMITIVES G9 — gridprim_every_picker_lists_both_stores.sql (chair's production apply)\",\n  table_sync: \"GRID-PRIMITIVES G10 — gridprim_a_synced_sheet_is_one_table_that_refreshes.sql (chair's production apply)\",\n  scope_table_provision: \"GRID-PRIMITIVES G11 — gridprim_a_scope_provisions_its_table_in_the_store.sql (chair's production apply)\",\n  table_row_counts: \"GRID-PRIMITIVES G12 — gridprim_every_table_counts_its_rows_and_every_row_shows_its_header.sql + its grant file (chair's production apply)\",\n  view_record_order_set: \"GRID-PRIMITIVES G13 — gridprim_a_view_keeps_the_order_a_person_dragged.sql + its grant file (chair's production apply)\",\n  table_share_outside_grant: \"GRID-PRIMITIVES G14 — gridprim_a_known_outsider_is_granted_at_once.sql + gridprim_a_signed_in_person_may_share_with_a_known_outsider.sql (chair's production apply)\",\n  read_records_in_view_order: \"GRID-PRIMITIVES G13 — gridprim_a_view_keeps_the_order_a_person_dragged.sql + its grant file (chair's production apply)\",\n  rule_members_visible: \"S2-PRIME FILTER-GROUPS — filtergroups_a_views_nested_question_is_one_where_clause.sql + its grant file (chair's production apply)\",\n  record_headers: \"GRID-PRIMITIVES G12 — gridprim_every_table_counts_its_rows_and_every_row_shows_its_header.sql + its grant file (chair's production apply)\",\n  pipeline_move_many: \"UI-CHAMPIONS S4 — uichamp_s4_a_selection_moves_and_decides_in_one_call.sql + its grant file (chair's production apply)\",\n  work_decide_many: \"UI-CHAMPIONS S4 — uichamp_s4_a_selection_moves_and_decides_in_one_call.sql + its grant file (chair's production apply)\",\n  portal_form: \"UI-CHAMPIONS S6 — uichamp_s6_a_portal_carries_its_look_and_its_forms.sql + uichamp_s6_a_signed_in_person_may_open_a_portals_look_and_forms.sql (chair's production apply)\",\n  portal_form_submit: \"UI-CHAMPIONS S6 — uichamp_s6_a_portal_carries_its_look_and_its_forms.sql + uichamp_s6_a_signed_in_person_may_open_a_portals_look_and_forms.sql (chair's production apply)\",\n  form_preview_asks: \"FORMS-FIX-1 — formsfix1_the_owners_preview_asks_the_store_the_same_question.sql + its grant file (chair's production apply)\",\n  // Lane PLATFORM-APP-DATA wave 1 (2026-10-02): proven on the nightly clone; they reach the main\n  // database when the chair applies them with Arman watching (new functions + their grant).\n  table_copies_in_progress: \"TABLE-ACTIONS — matrx-frontend migrations/campaign/tableactions_a_table_can_be_duplicated.sql (chair's production apply)\",\n  table_duplicate_continue: \"TABLE-ACTIONS — matrx-frontend migrations/campaign/tableactions_a_table_can_be_duplicated.sql (chair's production apply)\",\n  table_duplicate: \"TABLE-ACTIONS — matrx-frontend migrations/campaign/tableactions_a_table_can_be_duplicated.sql (chair's production apply)\",\n  table_restore: \"TABLE-ACTIONS — matrx-frontend migrations/campaign/tableactions_c_a_table_comes_back_in_passes_too.sql (chair's production apply)\",\n  table_find: \"PLATFORM-APP-DATA — matrx-frontend migrations/campaign/lane12_one_table_is_found_by_its_slug.sql + lane12_the_new_table_and_record_doors_can_be_reached.sql (chair's production apply)\",\n  table_ensure: \"PLATFORM-APP-DATA — matrx-frontend migrations/campaign/lane12_two_first_saves_make_one_table.sql + lane12_the_new_table_and_record_doors_can_be_reached.sql (chair's production apply)\",\n  record_upsert: \"PLATFORM-APP-DATA — matrx-frontend migrations/campaign/lane12_a_record_is_written_or_updated_by_its_key.sql + lane12_the_new_table_and_record_doors_can_be_reached.sql (chair's production apply)\",\n  // Lane VIEWS-AND-FIELDS sublane BL (2026-10-02): the reverse column (REL-9). Proven on the nightly\n  // clone; they reach the main database when the chair applies them, after\n  // visionreach_w4_a_the_store_asks_before_an_agent_changes_a_table.sql (its field_declare body).\n  reverse_columns: \"VIEWS-AND-FIELDS BL — matrx-frontend migrations/campaign/viewsfields_bl_a_link_shows_on_both_tables.sql (chair's production apply)\",\n  reverse_links_many: \"VIEWS-AND-FIELDS BL — matrx-frontend migrations/campaign/viewsfields_bl_a_link_shows_on_both_tables.sql (chair's production apply)\",\n  // Live on Matrx Main since 2026-10-06 (applied through the Supabase MCP); STORE_DOORS lists it at the\n  // next `pnpm records:generate`, until then `listKeyset` asks it as an owed door.\n  read_records_keyset: \"AP3-KEYSET-DOOR — the Supabase MCP migration ap3_keyset_the_page_door_pages_by_cursor (applied 2026-10-06)\",\n  rule_declare:\n    \"W1-RULE — `custom.record_write` writes `data_class = 'record'`, so the ONE write door cannot \" +\n    \"make a Rule record; declaring a Rule (and therefore a DOOR-18 subscription) needs a door of its own\",\n};\n\n/**\n * THE TRUST DOORS, AND WHY THEY ARE A SEPARATE TABLE.\n *\n * `iam.is_external_principal`, the publish binding and the world lane are NOT\n * the record store's. They are the platform's answer to \"who is this person to\n * us?\" and \"does this thing have a public address?\", and W2-TRUST owns them.\n * They live in schema `iam`, so `pnpm records:generate` — which reads `custom`\n * and only `custom` — does not and should not see them.\n *\n * They are therefore named here by hand, once, with the schema they belong to\n * said out loud. A client that pretended they were store doors would be lying\n * about which system answered it: when the world lane is closed, the sentence a\n * person reads is `iam`'s, not the store's.\n */\nexport const TRUST_SCHEMA = \"iam\";\n\nexport const TRUST_DOORS = {\n  /** VIS-31. A signed-in outsider: an account with no NON-personal organization. */\n  isExternalPrincipal: \"is_external_principal\",\n  /** The same answer with the plain-English reason attached. */\n  externalPrincipalCard: \"external_principal_card\",\n  /** EXACTLY the resources Visibility gave that outsider — never \"their organization's\". */\n  externalPrincipalReach: \"external_principal_reach\",\n  /** VIS-32. A record or a view bound to a public address with a declared render mode. */\n  publishBindingCreate: \"publish_binding_create\",\n  publishBindingRevoke: \"publish_binding_revoke\",\n  /** What a SIGNED-OUT visitor resolves. Returns nothing for an invented or revoked address. */\n  resolvePublishBinding: \"resolve_publish_binding\",\n  /** The same resolution plus WHAT the address holds: table | record | dashboard | page | view. */\n  resolvePublishBindingKind: \"resolve_publish_binding_kind\",\n  /** D-15. The one sentence that admits nothing was scanned — one function, so it cannot drift. */\n  worldPublishGapNotice: \"world_publish_gap_notice\",\n  publishToWorld: \"publish_to_world\",\n  worldPublishAdmit: \"world_publish_admit\",\n  claimWorldNamespace: \"claim_world_namespace\",\n} as const;\n\nexport type TrustDoorKey = keyof typeof TRUST_DOORS;\n\nconst DOOR_NAMES = new Set<string>(STORE_DOORS.map((d) => d.name));\n\nexport function doorExists(name: string): boolean {\n  return DOOR_NAMES.has(name);\n}\n\n/**\n * MAY A SCREEN ASK THIS DOOR AT ALL. True when the generated catalog lists it, or the config says\n * this store already has it (`RecordsConfig.knownDoors`). A door that is only OWED is not asked — so\n * before the chair's apply nothing is called and nothing is logged, and on the day the regenerated\n * catalog lists it the same screen starts asking with no code change.\n */\nexport function doorReady(config: { knownDoors?: readonly string[] | undefined } | null | undefined, name: string): boolean {\n  return DOOR_NAMES.has(name) || Boolean(config?.knownDoors?.includes(name));\n}\n\n/** The lane that owes a door the generated catalog does not list yet, or undefined. */\nexport function doorOwedBy(name: string): string | undefined {\n  return OWED_BY[name];\n}\n\n/** The refusal a missing door gets. It always says who owes it. */\nexport function doorAbsent(name: string): RecordsError {\n  return doorAbsentRefusal(name, OWED_BY[name]);\n}\n\n/** The doors this package calls, one place, so the suite can walk them. */\nexport const DOORS = {\n  // THE READ DOOR (DOOR-1). Every read of a record's values goes through these\n  // two and nothing else: they resolve the reader from the session, ask\n  // read access once per set, and mask the fields this reader may not see with a\n  // notice under `_hidden`. Selecting `custom.record` directly is the thing\n  // they exist to replace — it returns rows and fields the store never agreed\n  // this person could see.\n  readRecord: \"read_record\",\n  readRecords: \"read_records\",\n  // THE SAME READ DOOR, ADDRESSED BY AN ID SET. A realtime notice names the exact ids that\n  // moved; before this existed the only door that took them was the PAGE door, so a\n  // three-cell change re-read fifty rows in every watching browser. It is a separate NAME\n  // rather than a sixth argument to `read_records` because adding a defaulted argument to a\n  // live Postgres function makes every existing call ambiguous — `is not unique`. Same\n  // ladder, same level, same masking, same page ceiling.\n  readRecordsByIds: \"read_records_by_ids\",\n  // THE SAME READ DOOR, ADDRESSED BY A QUESTION. `custom.read_records_matching`\n  // takes the store's one filter shape (`RecordFilter` — the object\n  // `platform.saved_view` carries as `filters` and `custom.record_aggregate`\n  // takes as `p_filter`) and narrows the page INSIDE its own query, in the same\n  // WHERE as Visibility. A separate NAME for the same reason as above. It is\n  // what makes a number on a dashboard walkable: the filter is evaluated by\n  // `custom.record_filter_sql`, the one body `custom.agg_sql` also calls, so the\n  // rows it opens are the rows the number counted.\n  readRecordsMatching: \"read_records_matching\",\n  // THE SAME READ DOOR, ASKED FOR ONE PAGE THE STORE SORTED, SEARCHED AND COUNTED (DOOR-SPEED,\n  // 2026-09-25). `custom.read_records_page` takes the same filter, adds a sort (by the words a\n  // person sees on a choice column), a search over the columns this reader may see, a hand-ordered\n  // view's order, and answers the TOTAL of the matching visible set — the record-store twin of the\n  // older store's `get_user_table_data_paginated_v2`, so a grid never reads a whole table to draw\n  // one page. Its documents are built by `read_records_by_ids`. A separate NAME for the reason above.\n  readRecordsPage: \"read_records_page\",\n  // THE SAME PAGE, PAGED BY A CURSOR (AP3-KEYSET-DOOR, 2026-10-06). `custom.read_records_keyset` answers\n  // exactly the rows and order of `read_records_page` (same wall, ladder, mask, filter, search, sort),\n  // but the next page starts AFTER the last row's sort values + id instead of at an offset, so a write\n  // landing mid-read never skips or repeats a row. Each row also carries its `version` and\n  // `organization_id`, and `p_ids` re-reads exactly the named rows. A separate NAME for the reason above.\n  readRecordsKeyset: \"read_records_keyset\",\n  // THE SAME READ DOOR, ADDRESSED BY ABSENCE. Every door above answers LIVE rows\n  // only — each of them hard-codes `and r.deleted_at is null` — so until this one\n  // existed no screen could list an archived record however it was written, and\n  // `record_restore` below had nothing that could reach it (VERIFIER-10 F4).\n  // `custom.read_records_archived` is that body with the sign of one comparison\n  // flipped, plus the two facts only an archive needs: who archived it and when.\n  // A separate NAME for the same reason as its two siblings above.\n  readRecordsArchived: \"read_records_archived\",\n  // DOOR-8, the two clocks. `p_recorded_at` is what the store SAID then;\n  // `p_world_on` is what was TRUE of the world on that date, read out of dated\n  // values. A client that answered either one itself would be guessing.\n  queryRecordAsOf: \"query_record_as_of\",\n  // Rule 10 / test 14: how long value history is kept. The floor is a raise-only knob; the table's\n  // own days never go below it; both refusals are the store's sentences.\n  historyRetention: \"history_retention\",\n  historyRetentionSet: \"history_retention_set\",\n  historyRetentionFloorRaise: \"history_retention_floor_raise\",\n  queryTableAsOf: \"query_table_as_of\",\n  recordWrite: \"record_write\",\n  recordWriteMany: \"record_write_many\",\n  // MANY CHANGES TO ONE TABLE, ONE TRANSACTION (DOOR-SPEED, 2026-09-25). `custom.record_change_many`\n  // takes inserts, updates and archives: inserts through `record_write_many`, every update in ONE\n  // UPDATE statement (each record asked its editor rung, CAS honored), archives through\n  // `record_delete`. One refused change refuses the batch and nothing is saved; the hint names it.\n  recordChangeMany: \"record_change_many\",\n  // A PARENT, THE EDGES IT STANDS ON AND THE ROWS THAT BELONG TO IT — ALL OR NOTHING.\n  // `recordWrite` and `recordWriteMany` are each ONE statement, so a caller that needs a\n  // parent, its provenance edge and its child rows to land together had no door at all: a\n  // loop is N transactions, and a failure on child nineteen leaves a parent standing without\n  // the lines it promised. `custom.record_write_graph` is one statement, so it is one\n  // transaction — and it is not a second write path: it CALLS `custom.record_write_many` for\n  // the rows, `public.assoc_add` for an edge that points out of the store, and\n  // `platform.relation_set` for the parent's own declared relation to its children. Every\n  // guard, every trigger and the same editor rung, once. A refusal anywhere refuses the whole\n  // graph, by name, and nothing is written.\n  recordWriteGraph: \"record_write_graph\",\n  recordUpdate: \"record_update\",\n  // A NEW CHOICE AND THE CELL THAT TAKES IT, ONE TRANSACTION (lane CHOICE-COLUMN-EDIT,\n  // 2026-09-27). `p_add` is `{\"<column key>\": [\"words\", ...]}`: the words are added to that\n  // column's choices through `field_update`'s `options_add` (which needs the right to change\n  // the table's columns), then the cell is saved through `record_update`. Answers the new\n  // version, as `record_update` does.\n  recordUpdateAddingChoices: \"record_update_adding_choices\",\n  // THE FEATURE KNOB `custom/choice_nudge`, resolved for the signed-in person: `ask` (default),\n  // `always_add` or `never_add` — what a choice cell does with words that are not a choice.\n  choiceNudge: \"choice_nudge\",\n  // REMOVING A CHOICE THAT RECORDS HOLD (lane CHOICE-TAILS, 2026-09-27). How many records hold\n  // each choice of a column, and ONE save of the column's choices that also moves, keeps or\n  // clears the cells of each removed one (the column through `field_update`, every cell through\n  // `record_update`); it answers its own undo, which goes back through the same door.\n  fieldChoiceUsage: \"field_choice_usage\",\n  fieldUpdateRehomingChoices: \"field_update_rehoming_choices\",\n  recordDelete: \"record_delete\",\n  recordRestore: \"record_restore\",\n  // CHANGE WHAT A COLUMN HOLDS (FLD-4 / T12; merged-grid review 2, C3). The store converts every\n  // value that converts and keeps each one that does not in the record's `_retired`, with the\n  // reason — neither coerced nor deleted — and records the migration so it can be undone.\n  migrateRetype: \"migrate_retype\",\n  // T5 / REC-21: merge one record into another (values kept as alternates, links moved, the other\n  // archived and aliased), and put any recorded Migration back.\n  migrateMerge: \"migrate_merge\",\n  migrateUndo: \"migrate_undo\",\n  // CORE-VISION (2026-10-10): the structural Migrations a person runs on ONE record from its menu.\n  // Split moves the named values to a new record of the same Table (the original keeps its id);\n  // extract parent copies the named values up into a new record of another Table and puts this\n  // record under it. Both answer a `migration_id` that `migrateUndo` takes. `migrations` lists\n  // the Migration log for one target, newest first.\n  migrateSplit: \"migrate_split\",\n  migrateExtractParent: \"migrate_extract_parent\",\n  migrations: \"migrations\",\n  recordValues: \"record_values\",\n  recordValuesVersioned: \"record_values_versioned\",\n  valueRead: \"value_read\",\n  computedProvenance: \"computed_provenance\",\n  recordApplicability: \"record_applicability\",\n  applicableFields: \"applicable_fields\",\n  fieldOptions: \"field_options\",\n  pickListIndex: \"pick_list_index\",\n  pickListGet: \"pick_list_get\",\n  pickListForSelection: \"pick_list_for_selection\",\n  pickListUpdate: \"pick_list_update\",\n  parityValues: \"parity_values\",\n  tableDeclare: \"table_declare\",\n  // TABLE-CREATE-SPEED-2: a new Table, its Home and its columns in ONE call and ONE transaction.\n  tableCreate: \"table_create\",\n  // GETTING RID OF A TABLE — which is a JOB, NOT A STATEMENT (VERIFIER-11 F3).\n  // `record_delete` above is the store's one soft-delete door and it is right\n  // for a record; aimed at a TABLE it recurses through everything the Table\n  // contains inside one transaction, and that is unbounded by construction. A\n  // person pressing \"Delete this table\" on 1,430 records the product itself\n  // had just imported waited twelve seconds and was told `57014`, \"canceling\n  // statement due to statement timeout … Nothing was changed. Try a smaller\n  // page\" — advice that means nothing when what you are doing is getting rid\n  // of a table. `custom.table_archive` does the same work in passes and\n  // answers each one with numbers, so a screen shows a sentence and a count\n  // instead of a spinner and an SQLSTATE. It is STATELESS, so a run cut in\n  // half resumes exactly where it stopped: there is no job row to lose.\n  tableArchive: \"table_archive\",\n  // A TABLE THE APP'S CODE DEPENDS ON (`code_depends: true`, lane 12 P5) refuses every archive,\n  // rename, move and unmark door; this is the one way through: the typed slug, a reason, a person.\n  tableArchiveDeliberately: \"table_archive_deliberately\",\n  tableRestore: \"table_restore\",\n  // ADDING A COLUMN — the first thing anybody does with a table, and until\n  // 2026-09-19 there was no door for it. A Field is a record (REC-25), so a\n  // screen wrote one with `record_write`; that door writes ONE row with\n  // `data_class = 'record'` and cannot also add the key to the Table record's\n  // `fields` array, which the field guard requires before it accepts any\n  // definition at all. So every \"Add field\" ended on \"the table does not\n  // declare a field called … — declare it there first\". These three doors take\n  // what a person knows — a field type, a name, and for a choice list the\n  // choices themselves — and the STORE turns that into the document its own\n  // guards demand, so every client inherits one answer instead of each one\n  // re-deriving thirteen and getting them wrong.\n  fieldDeclare: \"field_declare\",\n  // TABLE-CREATE-SPEED: a new table's columns in ONE call, each through field_declare, one transaction.\n  fieldDeclareMany: \"field_declare_many\",\n  fieldUpdate: \"field_update\",\n  // F2 D11: what a change of a column's kind will do — the store runs the change and rolls it back.\n  fieldRetypePreview: \"field_retype_preview\",\n  fieldRetire: \"field_retire\",\n  // THE UNDO OF field_retire (lane STORE-RESTORE-DOORS): the set that went together comes back\n  // whole, the Table declares the columns again, and the values never left the records.\n  fieldRestore: \"field_restore\",\n  // DUPLICATE PROPERTY (Notion N5): the copy declared and every record's value copied, in one door.\n  fieldDuplicate: \"field_duplicate\",\n  // CHAIR-ROLLUP-HONEST: is a column a lookup or roll-up reads archived, and which.\n  fieldSourceArchived: \"field_source_archived\",\n  // KINDS-GLUE wave 3 N1: a Table as a kind — its Fields, choices and stamp, as the reader.\n  tableKindFacts: \"table_kind_facts\",\n  // CONFIDENTIAL-BY-ORG-ADMIN (Arman 2026-10-08): a table's level, and the organization admin's two doors.\n  tableLevelFacts: \"table_level_facts\",\n  setTableConfidential: \"set_table_confidential\",\n  setTableOrganization: \"set_table_organization\",\n  // CUSTOM FIELDS ON A STANDARD BUSINESS TABLE. Every door above is keyed by a\n  // custom Table's uuid, and a standard table has no Table record - so until\n  // 2026-09-20 `custom.applicable_fields(org, 'party', null)` answered `22P02\n  // invalid input syntax for uuid` and there was no other way in. These are\n  // keyed by the REGISTRY TOKEN instead, and they are one set for all 643\n  // tables the registry types Entity or Detail. The three value doors are\n  // SECURITY INVOKER in the database on purpose: the standard table's own\n  // row-level security is what decides who may read and write its rows, and a\n  // definer wrapper would replace it with a second access system.\n  entityTable: \"entity_table\",\n  entityFields: \"entity_fields\",\n  // Lane 7 W2: one read of a standard table's Fields (and their choices) across every\n  // organization a list spans — instead of entity_fields + field_options once per organization.\n  entityFieldsAcross: \"entity_fields_across\",\n  entityFieldDeclare: \"entity_field_declare\",\n  entityFieldUpdate: \"entity_field_update\",\n  entityFieldRetire: \"entity_field_retire\",\n  entityFieldRights: \"entity_field_rights\",\n  entityRecordRead: \"entity_record_read\",\n  // AP-4: the custom rows that link to one platform record, paged by an opaque cursor.\n  entityBackLinks: \"entity_back_links\",\n  entityRowWrite: \"entity_row_write\",\n  entityRecordsFind: \"entity_records_find\",\n  tableCapacity: \"table_capacity\",\n  tableStorage: \"table_storage\",\n  promoteTable: \"promote_table\",\n  promoteField: \"promote_field\",\n  promotedFields: \"promoted_fields\",\n  promotedRead: \"promoted_read\",\n  relationTargets: \"relation_targets\",\n  relationOwn: \"relation_own\",\n  // REL-DISP, 2026-09-21. WHAT A RELATION CELL READS, through that column's own\n  // display spec. `custom.record_words` is declared server_only — it takes a bare\n  // record id with no field to scope it — so these are how a screen gets the\n  // words, and they are the ONE way in: three separate copies of \"read tableList,\n  // find title_field, call rowName\" lived in labels.tsx, RelationPicker.tsx and\n  // PortalsPanel.tsx, and none of them could ever have shown two columns joined.\n  // The `_many` door is the batch TAILS-2 recorded as missing (\"there is still no\n  // batch door on the store\"), which is why the browser resolved labels one id at\n  // a time. The ladder is NOT batched: the store asks it per record inside\n  // `custom._words_for`, so batching buys a round trip and never a disclosure.\n  relationWords: \"relation_words\",\n  relationWordsMany: \"relation_words_many\",\n  // CHAIR-EMBEDDED-FIDELITY 14: the same answer plus each record's icon and its table's icon, one call.\n  relationWordsWithIconsMany: \"relation_words_with_icons_many\",\n  // VISION-REACH G1 (2026-10-02). Which records a column of NAMES names — asked once per column by\n  // the import panel and the grid's paste before they write, so a name matching nothing, or two\n  // records, is shown with a choice first. The write doors resolve the same names with the same\n  // matcher (`custom._relation_names_resolve`), so what the screen showed is what is written.\n  relationNamesMatch: \"relation_names_match\",\n  // VIEWS-AND-FIELDS BL (REL-9). The reverse columns of a Table, and a page of records' inbound\n  // links through one of them. Called through `owedDoor` until `pnpm records:generate` lists them.\n  reverseColumns: \"reverse_columns\",\n  reverseLinksMany: \"reverse_links_many\",\n  reverseLinksManyFields: \"reverse_links_many_fields\",\n  relationReverseField: \"relation_reverse_field\",\n  formulaPreview: \"formula_preview\",\n  relationReverseSet: \"relation_reverse_set\",\n  homeAdd: \"home_add\",\n  // CLOSE-LINK (CD-LINK-10): every Home a Table lives in, named for the reader, the declared one first.\n  tableHomesNamed: \"table_homes_named\",\n  recordReparent: \"record_reparent\",\n  containmentChain: \"containment_chain\",\n  storeIsOpen: \"store_is_open\",\n  // DOOR-1, from the screen's side. What level the CALLER holds on the subjects\n  // they name — the one question a screen has to answer BEFORE it draws a\n  // control, and the only one the store had no client answer to.\n  myLevels: \"my_levels\",\n  // DOOR-11. The record's own revision list. A screen that offers an optimistic\n  // save needs the version it LOADED, and the read door answers documents, not\n  // versions — so the version comes from here, once, for the one record being\n  // edited, and never for a whole list.\n  ioRevisions: \"io_revisions\",\n  resolveFirstMatch: \"resolve_first_match\",\n  // The kernels a package-owned Table needs to exist at all: a Home is a record\n  // in the person kernel, a Field is a record in the field kernel (REC-1).\n  personKernelId: \"person_kernel_id\",\n  fieldKernelId: \"field_kernel_id\",\n  ruleKernelId: \"rule_kernel_id\",\n  // And the Table kernel, which is how `tableList` asks the READ DOOR for this\n  // organization's Tables: a Table is a record like any other, so listing them\n  // is `read_records(org, table_kernel_id())` and never a select on a table.\n  tableKernelId: \"table_kernel_id\",\n  // A saved view references its membership Rule, and the STORE decides who is\n  // in it — the screen never re-implements the predicate.\n  pipelineDeclare: \"pipeline_declare\",\n  pipelineRead: \"pipeline_read\",\n  pipelineBoard: \"pipeline_board\",\n  pipelineTransitionRefusal: \"pipeline_transition_refusal\",\n  pipelineMove: \"pipeline_move\",\n  /** Lane S4: many cards, one call, a verdict and a version per card. */\n  pipelineMoveMany: \"pipeline_move_many\",\n  tableStageField: \"table_stage_field\",\n  // STAGE-RULES. A gate can refuse or it can hand the change to the approvals queue; the\n  // closed list is the store's, the knob is the organization's, and what is WAITING on a\n  // card has to be askable or a card that did not move looks like a card nobody dragged.\n  stageRuleOnFailKinds: \"stage_rule_on_fail_kinds\",\n  stageRuleEnforcement: \"stage_rule_enforcement\",\n  recordStagePending: \"record_stage_pending\",\n  pipelinePending: \"pipeline_pending\",\n  pipelineGatePreview: \"pipeline_gate_preview\",\n  ruleMembers: \"rule_members\",\n  ruleMembersVisible: \"rule_members_visible\",\n  ruleMembership: \"rule_membership\",\n  ruleRun: \"rule_run\",\n  ruleEval: \"rule_eval\",\n  // REC-15: the door that makes a Rule a RULE. `custom.record_write` into the\n  // Rule kernel produces a valid Rule document carrying `data_class = 'record'`,\n  // and every reader that goes LOOKING for a Rule looks for the class — so a\n  // subscription written that way was invisible to DOOR-18 and nothing fired.\n  // PRODUCTS row 1 — a form is a view on a real Table. `forms` lists an\n  // organization's own, `formDeclare` writes one, and `anonPublish` is the one\n  // act that opens it to people with no account. The PUBLIC pair\n  // (`custom.form_public`, `custom.form_submit`) is deliberately absent: those\n  // are server-lane doors and a browser never calls them.\n  forms: \"forms\",\n  formDeclare: \"form_declare\",\n  /**\n   * WHICH QUESTIONS THE OWNER'S PREVIEW ASKS NEXT (lane FORMS-FIX-1). The same store answer a\n   * stranger's form gets (`custom._form_questions_asked` → `custom.rule_eval`), behind the\n   * organization wall and the caller's own rung on the Table — never `rule_eval` from a browser.\n   */\n  formPreviewAsks: \"form_preview_asks\",\n  /** TYPEFORM-DUP: the owner's preview of the whole route — jumps, ending, score (`custom._form_route`). */\n  formPreviewRoute: \"form_preview_route\",\n  /** TYPEFORM-DUP: views, starts, completions, drop-off and answers per question. */\n  formResults: \"form_results\",\n  formKnobs: \"form_knobs\",\n  formLookOptions: \"form_look_options\",\n  /** CD-PAGE-08: set, clear or read a public form's password (only its hash is kept). */\n  formSetPassword: \"form_set_password\",\n  // PRODUCTS row 14 — \"let clients book a 30-minute consult\". A booking page IS an\n  // `anon_form`, so it is opened and closed by `anonPublish` like any other; this is\n  // the owner's list of them with the numbers that make it worth opening. The\n  // VISITOR's three (`booking_public`, `booking_hold`, `booking_confirm`) are\n  // deliberately absent: they are server-lane and a browser never calls them.\n  bookings: \"bookings\",\n  // The OWNER's side of a booking page, and the door that had no client method at\n  // all until 2026-09-21: without it the only way to get a booking page was to ask\n  // an agent, which made the agent the ONLY path rather than the faster one.\n  bookingDeclare: \"booking_declare\",\n  // PRODUCTS row 9 — \"pull my spreadsheet in\". W4-IO built `io_import_open` and\n  // `io_import_rows`; lane IMPORT gave a run an IDENTITY (the file's sha-256, so\n  // a re-import doubles nothing), a duplicate key, a policy, per-row outcomes\n  // with the source row on them, and the type inference that reads THIS\n  // organization — an address that belongs to a member is a person, a few\n  // repeating words are a dropdown, a column of names that are all records of\n  // another Table points at it. `importOpen` (the older, narrower way in) is\n  // deliberately absent from this catalog: `importBegin` is a superset and two\n  // ways to start an import from one client is how they drift.\n  importPlan: \"io_import_plan\",\n  importBegin: \"io_import_begin\",\n  importDeclareColumns: \"io_import_declare_columns\",\n  importRows: \"io_import_rows\",\n  importFinish: \"io_import_finish\",\n  importReport: \"io_import_report\",\n  imports: \"io_imports\",\n  importForget: \"io_import_forget\",\n  inferColumn: \"io_infer_column\",\n  // DOOR-19 (P8) — the address a Table owns. `inboundMailLand` is deliberately\n  // absent: it is the mail gateway's door, granted to `service_role` alone and\n  // declared `non_client_lane`, and a browser that could land mail at an\n  // arbitrary address would be writing into any table of any organization.\n  inboundDeclare: \"inbound_declare\",\n  inboundAddresses: \"inbound_addresses\",\n  inboundSet: \"inbound_set\",\n  // THE CLIENT PORTAL, OWNER'S SIDE (VIS-31 / PORTAL). A portal is how somebody\n  // with NO membership is let in to see the records that name them. `portals`\n  // lists them, `portalCard` opens one, `portalDeclare` states what it exposes,\n  // `portalInvite` and `portalRevoke` are the two acts on a person, and\n  // `portalPreview` is \"view as this client\" — it asks `custom.visible_set` for\n  // HER user id, the same call `custom.read_records` makes when she opens the\n  // page, so the preview cannot disagree with what she sees. The CLIENT-side\n  // pair (`custom.portal_public`, `custom.portal_invitation`, `custom.portal_me`)\n  // is deliberately absent here: those belong to the outsider's own shell.\n  portals: \"portals\",\n  // WHICH TABLES EACH PORTAL SHOWS (TAILS-3). The Portals RAIL lives on a\n  // Table's page beside Forms, Bookings and Dashboards, all of which are\n  // table-scoped; `custom.portals` takes no table, so an organization with one\n  // portal over Jobs saw that portal's cards on its Parts table, the empty\n  // state never rendered, and the whole build/ask offer was unreachable\n  // everywhere in that organization. This is the one question the rail has to\n  // ask, under the same wall and read-access gate as `portals` itself.\n  portalTables: \"portal_tables\",\n  tableFacts: \"table_facts\",\n  tablesLiveWhere: \"where_tables_live\",\n  // WHERE A TABLE LIVES, AND MOVING IT (SC-1' / SC-1-TAILS). `table_home` answers only when the\n  // caller may open the Table (custom.where_id_opens) and names its organization FROM THE TABLE;\n  // `table_move` moves it into another organization the caller belongs to, with every Table\n  // inside it, or refuses with one sentence.\n  tableHome: \"table_home\",\n  tableMove: \"table_move\",\n  // MOVING A WHOLE BASE (AT-NOTIFY-MOVE): `base_move` takes the Home and every table in it through `table_move`, then the Home and its base row follow.\n  baseMove: \"base_move\",\n  portalCard: \"portal_card\",\n  portalDeclare: \"portal_declare\",\n  portalInvite: \"portal_invite\",\n  portalRevoke: \"portal_revoke\",\n  portalPreview: \"portal_preview\",\n  // S6 — the CLIENT's two form doors. They are store doors (schema `custom`), called by a\n  // signed-in portal principal, and each refuses anybody who is not a live principal of that\n  // live portal — so, unlike the sign-in pair above, they belong in this table.\n  portalForm: \"portal_form\",\n  portalFormSubmit: \"portal_form_submit\",\n  // ORG-CLEANUP, 2026-09-22 — A PORTAL IS ARCHIVED, NEVER DELETED.\n  // `portals` keeps its signature and HIDES archived portals (the law's default\n  // is to hide); `list_portals(org, 'active'|'archived'|'all')` is the\n  // archive-aware reader, taking the platform archive filter's own three values\n  // so one door serves both lanes and no screen has to invent a second control.\n  // `portal_archive` / `portal_restore` are the way out and the way back; both\n  // take the portal's own title typed back, because ten portals can carry one\n  // title and the title alone is not what picks this one.\n  listPortals: \"list_portals\",\n  portalArchive: \"portal_archive\",\n  portalRestore: \"portal_restore\",\n  // MAKE-HOME wave 6a (2026-10-03) — the archive of forms, booking pages and checklist\n  // templates (CHAIR-DOORS-3B), and the row controls of a custom table (CHAIR-DOORS-2).\n  formArchive: \"form_archive\",\n  formRestore: \"form_restore\",\n  formsArchived: \"forms_archived\",\n  checklistTemplatesArchived: \"checklist_templates_archived\",\n  tableRowDefaults: \"table_row_defaults\",\n  tableRowDefaultsSet: \"table_row_defaults_set\",\n  tableRowDefaultsApply: \"table_row_defaults_apply\",\n  // ROW-LABEL-FORMULA (2026-10-10). The formula a Table names its records by, beside its single title\n  // column: read it back, and set or clear it. Every surface that names a record reads the result.\n  tableRowLabel: \"table_row_label\",\n  tableRowLabelSet: \"table_row_label_set\",\n  recordRowControls: \"record_row_controls\",\n  recordRowControlsSet: \"record_row_controls_set\",\n  // SCR-16 — the canvas. A dashboard is a record in the presentation kernel\n  // whose blocks are saved SPECS for the eighth verb; `dashboardRun` walks them\n  // under the CALLER'S principal, so nothing here is precomputed and nothing is\n  // summed in a browser. `dashboardStuck` is the seventh block kind on its own,\n  // because \"what has not moved in fourteen days\" is a question a screen asks\n  // outside a canvas too.\n  dashboards: \"dashboards\",\n  dashboardDeclare: \"dashboard_declare\",\n  dashboardRun: \"dashboard_run\",\n  dashboardStuck: \"dashboard_stuck\",\n  dashboardDelete: \"dashboard_delete\",\n  // AT-INTERFACE — an Interface opened by anybody it is shared with, and the rows one of its published elements exposes.\n  interfaceRead: \"interface_read\",\n  interfaceRows: \"interface_rows\",\n  // AT-FIX-G1b — one published chart of an Interface drawn for anybody it is shared with (members and outsiders alike).\n  interfaceChart: \"interface_chart\",\n  // PRODUCTS row 10 — \"fill in each company's industry and headcount, and keep\n  // it fresh\". An Enrichment is not an object of its own: it is a Field saying\n  // `source = agent`, with its instruction, inputs, model, confidence floor and\n  // freshness in `source_config` (AGT-6). `enrichCells` is the one a GRID calls —\n  // the badge data for a whole page in one round trip, because a badge asked per\n  // cell is fifty round trips to draw fifty badges. `enrichPin` is the half of\n  // this product that decides whether anybody ever trusts it: the moment a\n  // person types over an agent-owned cell the store pins it, and the next run\n  // leaves it exactly as they left it.\n  // PRODUCTS row 15 — \"let my crew photograph each bin and log the weight on\n  // site\". A capture sheet is the ONE Form object saying `audience = 'crew'`,\n  // opened by `capture_opened_at`; these five are SIGNED-IN doors granted to\n  // `authenticated`, unlike the public form's two, because a crew member has an\n  // account and their own level on the Table is the whole access decision.\n  captureSheetDeclare: \"capture_sheet_declare\",\n  capturePublish: \"capture_publish\",\n  captureSheets: \"capture_sheets\",\n  captureOpen: \"capture_open\",\n  captureSubmit: \"capture_submit\",\n  enrichments: \"enrichments\",\n  enrichDeclare: \"enrich_declare\",\n  enrichDue: \"enrich_due\",\n  enrichCells: \"enrich_cells\",\n  enrichLand: \"enrich_land\",\n  enrichPin: \"enrich_pin\",\n  enrichRuns: \"enrich_runs\",\n  // PRODUCTS row 4 — \"Who changed this price, and can I put it back?\" The\n  // history has been in the store since W3-HIST; until 2026-09-20 the only way\n  // to ask for it was `io_revisions`, which answers a raw uuid for the author\n  // and a list of KEYS for what moved. `recordHistory` answers the person (or\n  // the agent AND the person it acted for), the operation in the word somebody\n  // used, and every field with its before, its after, the Rule version that\n  // produced it and its source. `fieldHistory` is the other half nobody ships:\n  // one column's history across the whole Table.\n  recordHistory: \"record_history\",\n  fieldHistory: \"field_history\",\n  // A worked-out column's history, naming the formula version that produced each answer (CD-FORMULA-08).\n  formulaHistory: \"formula_history\",\n  // THE PUT-IT-BACK THREE. `restorePreview` names what will change BEFORE it\n  // does; `restoreVersion` puts the whole record back and `valueRestore` puts\n  // one column back (HIS-N-2). All three write a NEW version through the\n  // record's own write path — no stored version is ever altered.\n  restorePreview: \"record_restore_preview\",\n  restoreVersion: \"record_restore_version\",\n  valueRestore: \"value_restore\",\n  // SCR-18. The store has had comment doors at the `commenter` rung all along;\n  // these two add the people's NAMES and a mention that reaches somebody.\n  // AGT-N-9 / PRODUCTS row 11 — \"What's the history with this customer?\" A\n  // conversation can be ABOUT one record, and `recordScopeContext` is the ONE\n  // door that answers everything such a chat is allowed to know in a single\n  // round trip: the Fields with their (record, field, value version) triples,\n  // the relations one hop out, the history, the comments and the Table's other\n  // records — every piece assembled INSIDE the database through the read door\n  // under this person's own field-level security. A Field the store masks is\n  // named as withheld with the store's reason and never valued.\n  recordScopeContext: \"record_scope_context\",\n  conversationScope: \"conversation_scope\",\n  conversationScopeBind: \"conversation_scope_bind\",\n  conversationScopeUnbind: \"conversation_scope_unbind\",\n  conversationScopeContext: \"conversation_scope_context\",\n  commentThread: \"comment_thread\",\n  commentCounts: \"comment_counts\",\n  commentWrite: \"comment_write\",\n  commentResolve: \"io_comment_resolve\",\n  // AT-FIX-G2. Follow ONE record: the bell tells the follower when somebody else changes it or comments on it.\n  recordFollowSet: \"record_follow_set\",\n  recordFollowers: \"record_followers\",\n  // The eighth verb (AGT-N-8): a grouped, bucketed, filtered count/sum/avg/\n  // min/max computed INSIDE the read door's own query, so a chart shows exactly\n  // the rows this person may see and never fetches the ones they may not.\n  recordAggregate: \"record_aggregate\",\n  recordAggregateAsOf: \"record_aggregate_as_of\",\n  aggOperations: \"agg_operations\",\n  aggBuckets: \"agg_buckets\",\n  aggCalendar: \"agg_calendar\",\n  // DOOR-18: a subscription is a Rule record carrying a `subscription` block\n  // over a saved view. There is no subscription TABLE and no second notifier.\n  aggSubscriptions: \"agg_subscriptions\",\n  aggSubscriptionCadences: \"agg_subscription_cadences\",\n  // The OWNER's side of DOOR-18. `agg_subscriptions` is the notifier's reader\n  // and is not client-callable; these two are what a person reaches: what am I\n  // being told about, and switch this one off. A form's notify Rule is one of\n  // these rows, so \"tell me when a patient arrives\" can also be un-told.\n  subscriptions: \"subscriptions\",\n  subscriptionMute: \"subscription_mute\",\n  // The two DOOR-18 acts that had no door at all until 2026-09-20: WRITE a\n  // subscription (a Rule is declared, never written as a record — REC-72) and SEE\n  // the summary it would send right now without sending it.\n  subscriptionDeclare: \"subscription_declare\",\n  subscriptionPreview: \"subscription_preview\",\n  // A SUBSCRIPTION IS OVER A SAVED VIEW, so a person who has never saved one has\n  // nothing to subscribe to. These two are the saved-view pair (lane DIGESTS'\n  // `digests_a_saved_view_has_a_door.sql`), unreachable from this client until\n  // 2026-09-21: `views` lists this Table's, `viewDeclare` writes one. A LIST IS A\n  // DOOR, never a grant on `platform.saved_view` behind it.\n  views: \"views\",\n  viewDeclare: \"view_declare\",\n  // ROW-TEMPLATES (2026-10-04): a Table's row templates — list (viewer), declare/archive (editor).\n  rowTemplates: \"row_templates\",\n  rowTemplateDeclare: \"row_template_declare\",\n  // VIEW-SWITCH-NOT-DESIGNATION (2026-09-25): how a Table opens is designated by an EDITOR through\n  // this one door; `view_declare` refuses the default view's layout and is_default by name.\n  viewDesignate: \"view_designate\",\n  // VIEW-LOOK (lane VIEW-STATE-PERSONAL, VERIFIER-23 item 1, 2026-09-25): how ONE person is looking at\n  // a shared view — its grouping, date field, sort, filter, hidden columns, widths, layout — is her\n  // own look until an editor saves it onto the view (`view_declare`). Viewer on the Table.\n  viewLookRead: \"view_look_read\",\n  viewLookSet: \"view_look_set\",\n  // The cadence CATALOG a person's screen may ask for. `agg_subscription_cadences`\n  // above is the notifier's own and holds no client grant; this door delegates to\n  // it, so a picker and the digest runner can never offer different words.\n  subscriptionCadences: \"subscription_cadences\",\n  // The doc doors: a template is saved, a render is written once and frozen,\n  // and a signature is checked against the exact bytes that were signed.\n  docTemplateSave: \"doc_template_save\",\n  docRenderBody: \"doc_render_body\",\n  docRenderDocument: \"doc_render_document\",\n  docTokens: \"doc_tokens\",\n  docUnresolvedTokens: \"doc_unresolved_tokens\",\n  docSign: \"doc_sign\",\n  // THE SEAL IS ASKED THROUGH ITS OWN DOOR. `custom.doc_signature_intact` is the INTERNAL\n  // half of this pair — SECURITY INVOKER over a doors-only table, so a browser that calls it\n  // gets `42501 permission denied for table doc_signature`, which is what every SignBlock\n  // seal check got until 2026-09-22 (FIX-10B). `custom.doc_signature_read` is the definer\n  // door built for a client: it asks may_reach and may_open on the RECORD by name and\n  // returns the seal AND the verdict in one answer, because a seal a person can read and a\n  // verdict they cannot is how a changed agreement keeps wearing somebody's signature.\n  docSignatureRead: \"doc_signature_read\",\n  // THE PLURAL ACTS. Until 2026-09-20 this package read `custom.doc_template`,\n  // `custom.doc_render` and `custom.doc_signature` with a direct PostgREST\n  // `.from()`, and all three hold NO client SELECT — so every list in product #5\n  // opened on \"permission denied for view doc_template\". A list is a DOOR, never\n  // a grant on the thing behind it (DOORS-TWO).\n  docTemplates: \"doc_templates\",\n  docTemplateDelete: \"doc_template_delete\",\n  docTemplateRestore: \"doc_template_restore\",\n  // A saved document has a way out (FS4, 2026-10-23): soft, editor on its record, undone by restore.\n  docRenderDelete: \"doc_render_delete\",\n  docRenderRestore: \"doc_render_restore\",\n  docRenders: \"doc_renders\",\n  docSignatures: \"doc_signatures\",\n  // THE ANONYMOUS LANE (W4-ANON). It landed, and it landed as SEVEN doors\n  // rather than the one this package had guessed at: a token is issued and\n  // verified separately from the write it authorises, a form is published\n  // separately from being declared, and an offline capture by a SIGNED-IN\n  // person is a different door from a write by a stranger.\n  //\n  // This package used to name a door `anon_record_write`, which never existed —\n  // so `FormRunner` told every person that the public link was \"pending\" for a\n  // lane that had already shipped. A screen calling a live feature pending is\n  // the same silent failure as a screen calling a missing one live, and the fix\n  // is to name the doors the store actually has.\n  anonTokenIssue: \"anon_token_issue\",\n  anonTokenVerify: \"anon_token_verify\",\n  anonTokenRevoke: \"anon_token_revoke\",\n  /** The stranger's write. The TOKEN names the organization; a caller never does. */\n  anonWrite: \"anon_write\",\n  /** SCR-30. The signed-in OFFLINE path: the client mints the key, the store dedupes on it. */\n  anonCapture: \"anon_capture\",\n  anonPublish: \"anon_publish\",\n\n  // WORK (W4-WORK): a template instantiated as real records, whose turn it is,\n  // and a slot somebody is holding. `ChecklistRunner` and `BookingSlots` are\n  // screens over these and hold no state of their own.\n  workStates: \"work_states\",\n  workTemplateDeclare: \"work_template_declare\",\n  workTemplateInstantiate: \"work_template_instantiate\",\n  workTemplateShape: \"work_template_shape\",\n  /** Why a graph would be refused — asked BEFORE it is written, never after. */\n  workTemplateRefusal: \"work_template_refusal\",\n  workWhoseTurn: \"work_whose_turn\",\n  workTakeAssignment: \"work_take_assignment\",\n  workHasAssignment: \"work_has_assignment\",\n  workAssignmentFields: \"work_assignment_fields\",\n  workTransitionRefusal: \"work_transition_refusal\",\n  workInstantiationShape: \"work_instantiation_shape\",\n  workSlotsDeclare: \"work_slots_declare\",\n  workSlotHold: \"work_slot_hold\",\n  workSlotRelease: \"work_slot_release\",\n  workSlotHolds: \"work_slot_holds\",\n  workSlotExpire: \"work_slot_expire\",\n\n  // THE WORK LAYER'S OWN DOORS (lane WORK-DOORS, 2026-09-20). Until this lane\n  // all nineteen `custom.work_*` functions were SECURITY INVOKER with no client\n  // grant: REC-69, REC-70 and REC-71 were live in the store and unreachable\n  // from a browser. These are the verbs a person actually uses.\n  workPerson: \"work_person\",\n  workAssign: \"work_assign\",\n  workRecordStates: \"work_record_states\",\n  workSetState: \"work_set_state\",\n  workList: \"work_list\",\n  workTemplates: \"work_templates\",\n  /** THE ONE QUEUE: assignments, approvals and the agent's proposals together. */\n  workInbox: \"work_inbox\",\n  workApprovalApprovers: \"work_approval_approvers\",\n  workApprovalRequest: \"work_approval_request\",\n  workApprovalMayDecide: \"work_approval_may_decide\",\n  workApprovalDecide: \"work_approval_decide\",\n  /** Lane S4: many inbox decisions, one call, a verdict per item. */\n  workDecideMany: \"work_decide_many\",\n  /** Lane S5-PRIME-2: one person's own inbox state — snooze, clear, and the counts. */\n  inboxSnooze: \"inbox_snooze\",\n  inboxUnsnooze: \"inbox_unsnooze\",\n  inboxClear: \"inbox_clear\",\n  inboxUnclear: \"inbox_unclear\",\n  inboxCounts: \"inbox_counts\",\n  workApprovalRead: \"work_approval_read\",\n\n  // PRODUCTS row 13 — checklists and SOP runs.\n  checklistRefusal: \"checklist_refusal\",\n  checklistDeclare: \"checklist_declare\",\n  checklistTemplates: \"checklist_templates\",\n  checklistTemplateShape: \"checklist_template_shape\",\n  checklistStart: \"checklist_start\",\n  checklistRun: \"checklist_run\",\n  checklistRuns: \"checklist_runs\",\n  checklistStepComplete: \"checklist_step_complete\",\n  checklistStepRefusal: \"checklist_step_refusal\",\n\n  // THE GRID (lane GRID-PRIMITIVES, 2026-09-22) — what the /data grid rebuild calls. See ../grid.ts.\n  tableDecorate: \"table_decorate\",\n  tableDecorations: \"table_decorations\",\n  gridLayout: \"grid_layout\",\n  formulaParse: \"formula_parse\",\n  actionDeclare: \"action_declare\",\n  rowActions: \"row_actions\",\n  actionRun: \"action_run\",\n  // NOTION-PROPS-2/3 — a button column pressed on a row; the timeline dependency knob.\n  buttonPress: \"button_press\",\n  timelineDependencyShift: \"timeline_dependency_shift\",\n  recordsLimits: \"records_limits\",\n  // AUTOMATION-DOOR (2026-10-07) — automations on a table. See ../automation.ts.\n  automationDeclare: \"automation_declare\",\n  automations: \"automations\",\n  automationArchive: \"automation_archive\",\n  automationRestore: \"automation_restore\",\n  automationSetEnabled: \"automation_set_enabled\",\n  automationRuns: \"automation_runs\",\n  // AUTOMATIONS-AIRTABLE (2026-10-10) — run one automation once now on a picked row.\n  automationTest: \"automation_test\",\n  // AT-AUTO2 (2026-10-15) — every save of an automation, and restoring one.\n  automationRevisions: \"automation_revisions\",\n  automationRevisionRestore: \"automation_revision_restore\",\n  tableWebhookDeclare: \"table_webhook_declare\",\n  tableWebhooks: \"table_webhooks\",\n  tableWebhookArchive: \"table_webhook_archive\",\n  tableFromExample: \"table_from_example\",\n  autonumberBackfill: \"autonumber_backfill\",\n  // AT-SHARE-B (2026-10-17) — a Person column's \"Notify people when they're added\" switch (two automations).\n  fieldNotifyOnAssign: \"field_notify_on_assign\",\n  ioExport: \"io_export\",\n  tableListEverywhere: \"table_list_everywhere\",\n  dataHomeTables: \"data_home_tables\",\n  // CLOSE-LINK (2026-10-23): the same rows as ONE jsonb value, which PostgREST's 1,000-row cut never touches.\n  dataHome: \"data_home\",\n  adminAllTables: \"admin_all_tables\",\n  tableSync: \"table_sync\",\n  tableCopySync: \"table_copy_sync\",\n  tableSyncSettingsSet: \"table_sync_settings_set\",\n  scopeTableProvision: \"scope_table_provision\",\n  tableRowCounts: \"table_row_counts\",\n  recordHeaders: \"record_headers\",\n  viewRecordOrderSet: \"view_record_order_set\",\n  readRecordsInViewOrder: \"read_records_in_view_order\",\n  tableShareOutsideGrant: \"table_share_outside_grant\",\n\n  // FIND ONE TABLE, FIND-OR-MAKE ONE, WRITE-OR-UPDATE A RECORD BY ITS KEY (lane PLATFORM-APP-DATA).\n  // Called through `owedDoor` in client.ts: on a store whose generated catalog does not list them\n  // yet they are still ASKED, and a store that answers \"no such function\" is turned into this\n  // package's `door_absent` (naming the owing file above) — so the clone, which has them, works,\n  // and the main database, which does not yet, refuses by name.\n  // DUPLICATE A TABLE (lane TABLE-ACTIONS): a new Table with the source's fields, choice lists,\n  // views and (when asked) records, every id inside them remapped to the copy. Owed until the\n  // chair applies it; asked through `owedDoor` like the three below.\n  tableDuplicate: \"table_duplicate\",\n  tableDuplicateContinue: \"table_duplicate_continue\",\n  // AT-BASE — the last step of Duplicate base: the copies' links point at each other.\n  baseCopyFinish: \"base_copy_finish\",\n  // COPY-EXTRAS — the one step that carries a copied table's automations (OFF) and pages onto its copy.\n  copyTableExtras: \"copy_table_extras\",\n  tableCopiesInProgress: \"table_copies_in_progress\",\n  tableFind: \"table_find\",\n  // ONE CALL FOR EVERY ORGANIZATION (custom-experience lane F, 2026-10-19): table_find across many.\n  tableFindMany: \"table_find_many\",\n  tableEnsure: \"table_ensure\",\n  recordUpsert: \"record_upsert\",\n\n  // Declared here BECAUSE they do not exist yet: naming them is what makes the\n  // absence visible to `pnpm check:store-registry` and to the suite.\n  ruleDeclare: \"rule_declare\",\n  fieldPropose: \"field_propose\",\n  tablePropose: \"table_propose\",\n  mergeFieldResolve: \"merge_field_resolve\",\n} as const;\n\nexport type DoorKey = keyof typeof DOORS;\n\n/** Which of this package's doors the live store actually has, and which it does not. */\nexport function doorCensus(): { present: string[]; absent: string[] } {\n  const present: string[] = [];\n  const absent: string[] = [];\n  for (const name of Object.values(DOORS)) {\n    (doorExists(name) ? present : absent).push(name);\n  }\n  return { present: present.sort(), absent: absent.sort() };\n}\n","// src/core/supabase.ts — @ai-matrx/records (HEADLESS)\n//\n// THE ONE ADAPTER FROM A SUPABASE CLIENT TO THIS PACKAGE'S DATA SEAM.\n//\n// Why it exists, and what it cost to learn (2026-09-19, the independent verdict\n// on /data): `RecordsDataSource.rpc(fn, args, { schema })` says the schema\n// out loud, because every door of this store is `custom.<name>` and every door\n// of the trust layer is `iam.<name>`. supabase-js's own\n// `rpc(fn, args, options)` HAS NO `schema` OPTION — its third argument is\n// `{ head, get, count }`, and an unknown key is dropped in silence. So a\n// supabase client handed straight to `config.dataSource` as a structural cast\n// asked its default PostgREST profile, `public`, for every door, and the store\n// answered correctly and uselessly:\n//\n//   PGRST202 — Could not find the function public.table_kernel_id(...) in the\n//   schema cache\n//\n// Every screen in the record store was dead from a browser because of it, while\n// the desktop app and the browser extension each grew their own way of asking.\n// The class fix is ONE adapter, here, in the headless core, that every host\n// inherits — never three hosts remembering the same thing.\n//\n// The schema is chosen the ONE way supabase-js offers: `client.schema(name)`\n// returns a client bound to that PostgREST profile (it sets the\n// `Accept-Profile` / `Content-Profile` headers), and `.rpc()` on THAT is the\n// call. There is no per-call option that does it.\n//\n// This file holds no key and opens no connection: the host hands in a client\n// that already carries the operating person's session, which is what makes\n// DOOR-5 and AGT-N-4 true — the store sees the person, not us.\n\nimport type { PgError } from \"../results\";\nimport type { RecordsDataSource } from \"../ports\";\n\n/**\n * The structural shape of the supabase client this adapter needs. Deliberately\n * NOT `SupabaseClient<Database>`: a generated `Database` type makes\n * `schema().from().select()` enormous, and a host app that passed its typed\n * client in got `TS2589: Type instantiation is excessively deep and possibly\n * infinite` in its own build (matrx-frontend, 2026-09-18, on all three campaign\n * routes at once). The cast lives here, once, where it is explained.\n */\nexport interface SupabaseLike {\n  schema(name: string): {\n    rpc(\n      fn: string,\n      args?: Record<string, unknown>,\n    ): PromiseLike<{ data: unknown; error: PgError | null }>;\n    from(table: string): unknown;\n  };\n}\n\n/** The refusal a caller sees rather than a silent call to the wrong schema. */\nfunction refuse(code: string, message: string, hint: string): { data: null; error: PgError } {\n  return { data: null, error: { code, message, hint, details: \"\" } as unknown as PgError };\n}\n\n/**\n * Bind a supabase-js client (or anything with the same `schema(name).rpc()`\n * shape) as this package's data seam.\n *\n * Two things never happen here, both of them loudly:\n *\n *  - A call with NO schema is never sent. It is refused by name, because\n *    sending it would reach `public` and get the store's PGRST202 several\n *    layers away from the mistake.\n *  - A client with no `.schema()` is never used. supabase-js has had it since\n *    v2.0; a host that binds something else is told exactly what is missing\n *    instead of throwing `undefined is not a function` inside a render.\n */\nexport function supabaseDataSource(client: object): RecordsDataSource {\n  if (isBound(client)) return client;\n  const supabase = client as unknown as Partial<SupabaseLike>;\n  const hasSchema = typeof supabase.schema === \"function\";\n\n  const bound: RecordsDataSource = {\n    // PAGE-BUNDLE: the real adapter opens a table page with one `custom.table_page_bundle` call.\n    opensInOneCall: true,\n    rpc(fn, args, options) {\n      if (!hasSchema) {\n        return Promise.resolve(\n          refuse(\n            \"data_source_unbound\",\n            `The records client was given something that is not a supabase client: it has no schema() ` +\n              `method, so the door ${fn} cannot be called in the schema it lives in.`,\n            \"Pass a supabase-js v2 client (createClient(...)) to supabaseDataSource().\",\n          ),\n        );\n      }\n      const name = options?.schema;\n      if (!name) {\n        return Promise.resolve(\n          refuse(\n            \"schema_unsaid\",\n            `The door ${fn} was called without saying which schema it lives in. ` +\n              `Every door of this store is custom.${fn} and every trust door is iam.${fn}; ` +\n              `an unqualified call reaches PostgREST's default profile (public) and is refused there.`,\n            \"This is a bug in the caller, not in your data: /core says the schema on every call.\",\n          ),\n        );\n      }\n      return (supabase as SupabaseLike).schema(name).rpc(fn, args) as ReturnType<\n        RecordsDataSource[\"rpc\"]\n      >;\n    },\n    schema(name) {\n      return (supabase as SupabaseLike).schema(name) as ReturnType<RecordsDataSource[\"schema\"]>;\n    },\n  };\n  Object.defineProperty(bound, BOUND, { value: true, enumerable: false });\n  return bound;\n}\n\n/** Marks a data source this adapter made, so binding it twice is a no-op, never a double wrap. */\nconst BOUND = Symbol.for(\"@ai-matrx/records/supabaseDataSource\");\n\nfunction isBound(source: object): source is RecordsDataSource {\n  return (source as Record<symbol, unknown>)[BOUND] === true;\n}\n\n/**\n * WHAT `createRecordsClient` DOES WITH WHATEVER IT IS HANDED (lane PLATFORM-APP-DATA, 2026-10-02).\n *\n * The README has always shown `dataSource: supabase` — a PLAIN supabase-js client — and that\n * exact line answered every call \"Could not find the function public.table_kernel_id\" (PGRST202),\n * because supabase-js's own `rpc()` drops the `{ schema }` option in silence (see the header).\n * Measured on the clone as admin@admin.com, 2026-10-02. The example is now true:\n *\n *  - Already bound by `supabaseDataSource` → used as it is.\n *  - A supabase-js client (it has `schema()`, `from()` and an `auth` client) → bound here, once.\n *  - Nothing callable at all (no `rpc()`) → bound here too, so every call is REFUSED by name with\n *    the remedy (`data_source_unbound`) instead of throwing `rpc is not a function` in a render.\n *  - Anything else that has its own `rpc(fn, args, { schema })` — a host's adapter, a test\n *    double — is the host's own data seam and is used as it is: it promised to honor `schema`.\n */\nexport function asRecordsDataSource(source: unknown): RecordsDataSource {\n  if (source === null || typeof source !== \"object\") return supabaseDataSource({});\n  if (isBound(source)) return source;\n  const candidate = source as Partial<SupabaseLike> & { rpc?: unknown; from?: unknown; auth?: unknown };\n  const looksLikeSupabaseJs =\n    typeof candidate.schema === \"function\" &&\n    typeof candidate.from === \"function\" &&\n    candidate.auth !== null &&\n    typeof candidate.auth === \"object\";\n  if (looksLikeSupabaseJs || typeof candidate.rpc !== \"function\") return supabaseDataSource(source);\n  return source as RecordsDataSource;\n}\n","// src/drill.ts — @ai-matrx/records\n//\n// THE ONE READ CONTRACT FOR EVERY TABLE (lane DRILL-STANDARD-DOOR, DRILL-DOWN-DESIGN.md §d).\n//\n// A question — group by these Dimensions, show these Measures, cut time by day…year in the\n// organization's calendar, compare with a prior window, pivot one Dimension across — asked of\n// a SOURCE, and answered in one shape whichever kind of source it is:\n//\n//   { kind: \"table\",  id }      a custom Table in the record store (custom.record_aggregate,\n//                               its Dimensions from custom.table_dimensions)\n//   { kind: \"entity\", token }   a standard Postgres table by its registry token (\"agent\",\n//                               \"ai_model\"), or a DECLARED definition by its key (a fact over\n//                               several tables joined by their foreign keys, e.g. \"agents_by_model\")\n//\n// Three doors, all in schema `platform`, all SECURITY INVOKER: a standard table is counted by a\n// statement running as the person, so the table's own row security decides every row counted —\n// an answer never holds a number she could not assemble from rows she can open. Groups past the\n// cap (\"Groups shown before Other\", knob drill/groups_per_level) fold into ONE Other row, and the\n// total row says so in words.\n//\n// Vocabulary (Arman, 2026-09-29): \"Dimension\" and \"Measure\" are platform words; a saved\n// exploration is a Saved view. \"Drill definition\" is still a working label (DRILL-DOWN-DESIGN D0).\n\nimport type { Uuid } from \"./record\";\nimport type { RuleExpression } from \"./rule\";\n\n/** Where a question is asked. */\nexport type DrillSource =\n  | { kind: \"table\"; id: Uuid }\n  | { kind: \"entity\"; token: string };\n\n/** Who a question is asked for (the access lanes, applied to counting). */\nexport type DrillLane = \"mine\" | \"organization\" | \"platform\";\n\nexport type DrillGrain = \"hour\" | \"day\" | \"week\" | \"month\" | \"quarter\" | \"year\";\n\nexport type DrillMeasureOp =\n  | \"count\"\n  | \"count_distinct\"\n  | \"sum\"\n  | \"avg\"\n  | \"min\"\n  | \"max\"\n  | \"median\"\n  | \"percentile\"\n  | \"rate\"\n  | \"filled\"\n  | \"empty\"\n  | \"ratio\"\n  | \"sum_of\"\n  | \"span\";\n\n/**\n * The operations a question may ask ad hoc (`{op, of}`); a ratio, a percentile and a run rate are\n * declared, never ad hoc (each needs more than a column: its parts, its p, its per).\n */\nexport type DrillAdHocOp = Exclude<DrillMeasureOp, \"ratio\" | \"percentile\" | \"rate\" | \"sum_of\">;\n\n/**\n * A color a choice keeps on every chart and share bar (lane DRILL-PARITY-LAST): one of the package's\n * semantic chart tokens (light and dark), never a raw color — the old usage page's origin colors.\n */\nexport type DrillChartToken =\n  | \"--matrx-chart-1\"\n  | \"--matrx-chart-2\"\n  | \"--matrx-chart-3\"\n  | \"--matrx-chart-4\"\n  | \"--matrx-chart-5\"\n  | \"--matrx-chart-6\"\n  | \"--matrx-chart-7\"\n  | \"--matrx-chart-8\"\n  | \"--matrx-chart-9\"\n  | \"--matrx-chart-10\"\n  | \"--matrx-chart-other\";\n\n/** Every chart token a choice may name (the validator's list). */\nexport const DRILL_CHART_TOKENS: readonly DrillChartToken[] = [\n  \"--matrx-chart-1\", \"--matrx-chart-2\", \"--matrx-chart-3\", \"--matrx-chart-4\", \"--matrx-chart-5\",\n  \"--matrx-chart-6\", \"--matrx-chart-7\", \"--matrx-chart-8\", \"--matrx-chart-9\", \"--matrx-chart-10\", \"--matrx-chart-other\",\n];\n\n/** A value a Measure's own `where` narrows by: a value, null (\"not set\") or a list of them. */\nexport type DrillMeasureWhereValue = string | number | boolean | null | Array<string | number | boolean | null>;\n\n/** An axis a question can cut by. */\nexport interface DrillDimension {\n  key: string;\n  label: string;\n  /** The column (fact) or `join.column` it reads. */\n  from: string;\n  kind: \"choice\" | \"relation\" | \"boolean\" | \"text\" | \"time\";\n  cardinality?: \"low\" | \"medium\" | \"high\";\n  /** A code's words; `color` keeps the value one chart token on every chart and share bar. */\n  choices?: Array<{ value: string; label: string; color?: DrillChartToken }>;\n  /** A relation's target: a registry token (standard) or a Table id (custom). */\n  relation?: { token?: string; table_id?: Uuid; person?: boolean };\n  /** A time's grains, coarsest first. */\n  grains?: DrillGrain[];\n  /** The words the empty group reads (\"No embedding (nothing new to embed)\"); a screen's own default otherwise. */\n  empty_label?: string;\n  /**\n   * What the Dimension groups by, at most 140 characters (lane DRILL-FLIP-FIXES, the Spend cut tables'\n   * explanations): a screen shows it as the column header's tooltip, never as text on the page.\n   */\n  description?: string;\n  /**\n   * WHAT A LEVEL OF IT LOOKS LIKE (lane DRILL-LEVELS) — the same shape as the design-system's\n   * `MatrxDrillLevel`; judged by platform.drill_definition_problems and handed to a screen by\n   * drill_describe. Absent = the screen infers it.\n   */\n  level?: DrillLevel;\n}\n\n/**\n * A DIMENSION'S LEVEL PROFILE (lane DRILL-LEVELS): what a drilled value of it offers and says.\n *   breakouts  — Dimension references (`at:day` for a time) offered as one-click \"By …\" chips, in order;\n *                `<definition>:<dimension>` names a SIBLING definition's Dimension (`ai_usage_executions:conversation`):\n *                the screen switches the source there carrying the trail (lane DRILL-PRIMITIVE-2)\n *   show       — the Measures shown while grouping by it\n *   attributes — Dimension keys each value holds ONE of (a conversation's agent, a model's provider):\n *                columns while grouping by it, and the drilled value's header\n *   records    — the columns \"See these records\" shows at this level (a subset of `records.columns`)\n */\nexport interface DrillLevel {\n  breakouts?: string[];\n  show?: string[];\n  attributes?: string[];\n  records?: string[];\n}\n\n/** The longest a Dimension's or a Measure's `description` may be (a tooltip's budget). */\nexport const DRILL_DESCRIPTION_MAX = 140;\n\n/** A number a question can show. */\nexport interface DrillMeasure {\n  key: string;\n  label: string;\n  op: DrillMeasureOp;\n  /**\n   * The column it reads (absent for `count`, `ratio` and `sum_of`). A `max` / `min` of a time column\n   * is a MOMENT (\"Last active\"): it declares `unit: \"time\"`, is never additive, and no threshold reads it.\n   */\n  of?: string;\n  /**\n   * `ratio` only: (the sum of these Measures) / (the sum of `den`), recomputed for every group, Other\n   * and the total from their parts (never averaged). Each part is a `sum` or `count` Measure of the\n   * same definition (optionally narrowed by its own `where`), or another ratio — e.g. cost per request\n   * = `{op: \"ratio\", num: [\"cost\"], den: \"requests\"}`; cache-hit rate = `{num: [\"hits\"], den: [\"hits\",\n   * \"calls\"]}`; the enrichment multiplier = `{num: [\"avg_enriched\"], den: \"avg_plain\"}` (two ratios).\n   */\n  num?: string[];\n  /**\n   * `sum_of` only: these Measures added up, recomputed for every group, Other and the total from\n   * their own rows — total tokens = `{op: \"sum_of\", parts: [\"tokens_in\", \"tokens_cached\", \"tokens_out\"]}`.\n   * Each part is a `sum` or `count` that adds up, or another `sum_of`; at least two.\n   */\n  parts?: string[];\n  /** `ratio` only: the Measure (or the list of Measures, added up) it is divided by; null where that is zero. */\n  den?: string | string[];\n  /**\n   * `ratio` or `rate`: a multiplier, bound by the door — `1000` makes cost per character cost per\n   * 1,000 characters; `10` makes a monthly projection \"at ten times today's load\".\n   */\n  scale?: number;\n  /** `percentile` only: the fraction, above 0 and below 1 (`0.9` = p90). Recomputed for Other and the total from their own rows. */\n  p?: number;\n  /**\n   * `rate` only: the run rate's period. A run rate is the window's sum of `of` ÷ the window's length\n   * × one `per` (\"day\", or \"month\" = 30 days — the old KG projection's rule). A question showing one\n   * must have a window with a start; a window reaching past now counts only the time that has passed.\n   */\n  per?: \"day\" | \"month\";\n  /**\n   * This Measure only, narrowed to the rows whose Dimensions hold these values (Dimension key → a\n   * value, null or a list; never a time): \"cost of successful enriched runs\". Bound by the door.\n   */\n  where?: Record<string, DrillMeasureWhereValue>;\n  /**\n   * How a screen reads the number: usd, count, tokens, ms, share, times, …; `time` = a moment (ISO);\n   * `duration` = a length of time in milliseconds — what a `span` (`of` a time column: the latest\n   * minus the earliest moment, never additive, recomputed for Other and the total) declares.\n   */\n  unit?: string;\n  /** Counted once per this column's value (a measure on the \"one\" side of a join). */\n  at_grain?: string;\n  /** May it be summed across groups? */\n  additive?: boolean;\n  /**\n   * What the number counts, at most 140 characters (lane DRILL-FLIP-FIXES): a screen shows it as the\n   * column header's tooltip — \"Requests a person or an API caller made; automated runs count as Calls\".\n   */\n  description?: string;\n  /**\n   * (lane DRILL-ENGINE, 2026-10-18) How a summary-backed distinct count that is NOT exact over groups or hours is\n   * answered exactly, definer definitions only. `per_hour`: registry token of a per-hour total (the time column,\n   * `everyone`, this Measure's `of` column, each lane rule's column) read for an ungrouped question — exact to the\n   * hour. `raw_of`: the records column counted distinct, the whole question read from the records relation when the\n   * window is at most `raw_within_hours` long. Any other question showing it says \"not exact\".\n   */\n  exact?: { per_hour?: string; raw_of?: string; raw_within_hours?: number };\n}\n\n/** A named drill path: the levels a click walks, e.g. [\"created_at:year\", \"created_at:month\"]. */\nexport interface DrillPath {\n  key: string;\n  label: string;\n  levels: string[];\n}\n\n/**\n * A threshold on the groups of an answer (`having`). Judged on the current window, and applied\n * BEFORE the cut into Other: a group that misses any threshold is added into Other with the groups\n * past the limit, so the answer still adds up to its total; `distinct_groups` counts the groups that\n * met every threshold and the total row says how many did (\"3 of 41 groups meet the rule …\").\n * Exactly one of `value` / `share_of_total` / `times_median`.\n */\nexport interface DrillHaving {\n  /** A Measure the question shows (a screen shows the number it filters on). */\n  measure: string;\n  /** At least / more than; at most / less than (lane DRILL-FLIP-FIXES: \"groups where cost ≤ 5\"). */\n  op: \">=\" | \">\" | \"<=\" | \"<\";\n  /** The group's value against a number. */\n  value?: number;\n  /** The group's value against this percent (0–100] of the window's total; additive Measures only. */\n  share_of_total?: number;\n  /** The group's value against this multiple of the median group's value. */\n  times_median?: number;\n  /** With `times_median`: the median of the groups above zero only. */\n  median_nonzero?: boolean;\n  /**\n   * The address of the drill setting that holds the line (organizations and people decide):\n   * `drill.finding.<definition>.<finding>.<knob>` inside a finding. When present the setting's value\n   * is the threshold and the number written beside it is its default. Resolved by the door through\n   * platform.drill_knob; clients read the same value from platform.knob_snapshot.\n   */\n  knob?: string;\n}\n\n/** A question — what a Saved view stores and the explorer's URL encodes. */\nexport interface DrillQuestion {\n  /** Dimension keys, outermost first; a time as `key:grain` (\"created_at:week\"). At most four. */\n  by?: string[];\n  /** One Dimension drawn as the columns of a pivot. */\n  across?: string;\n  /** Measure keys, or an ad hoc `{op, of}` over a column the definition reads. */\n  show?: Array<string | { op: DrillAdHocOp; of?: string }>;\n  /**\n   * The store's own filter shape: a scalar is an equality, `null` is \"not set\", a list is any of\n   * them, `{from, to}` is a half-open range; `key:grain` = one period by its label.\n   */\n  where?: Record<string, unknown>;\n  /**\n   * A custom Table only: the view's Rule expression, which must hold beside `where`\n   * (custom.record_drill ANDs the two). A standard source refuses it.\n   */\n  rule?: RuleExpression;\n  window?: { key?: string; preset?: string; from?: string; to?: string };\n  compare?:\n    | \"previous_period\"\n    | \"same_period_last_year\"\n    | { against: \"previous_period\" | \"same_period_last_year\" | \"range\"; period?: DrillGrain; from?: string; to?: string; baseline?: { from: string; to: string }; to_date?: boolean };\n  sort?: { key: string; direction?: \"asc\" | \"desc\" };\n  /** Groups per level before Other; the knob's value when absent, never above the page ceiling. */\n  limit?: number;\n  lane?: DrillLane;\n  /** The drill path a screen's default click follows. */\n  path?: string;\n  /** Thresholds on the groups, applied before the cut into Other (see DrillHaving). */\n  having?: DrillHaving[];\n  /** Records only: the page's start. */\n  offset?: number;\n  /** Records only: which columns a record shows (a definer definition's records: of its declared columns). */\n  columns?: string[];\n}\n\n/** A definition's built-in Saved view: read-only; \"Save a copy\" makes a person's own. */\nexport interface DrillView {\n  key: string;\n  label: string;\n  question: DrillQuestion;\n  /**\n   * AT A GLANCE (lane DRILL-FLIP-FIXES, the Spend Explorer's costliest requests): Dimensions each group\n   * of the view's outer grouping has ONE value of — a request's person, agent, model — shown as text\n   * columns beside its numbers, no click required. A screen reads them by asking the same door with\n   * the group and these Dimensions (the group's values listed), so they obey the same lane and filters.\n   * A group holding several values of one says so.\n   */\n  attributes?: string[];\n  /**\n   * How the view's chart draws (lane DRILL-FLIP-FIXES, the CX tab's input vs output tokens): `stack`\n   * names two or more Measures that add up, drawn as one stacked bar per period (no split).\n   */\n  chart?: { stack?: string[] };\n}\n\n/**\n * A finding (\"dig here\"): a question whose `having` thresholds are the rule. Its lines are settings\n * at `drill.finding.<definition>.<finding>.<knob>`, seeded from `knobs` by the drill sync; a\n * threshold that reads one writes the setting's default beside it. A finding with no group says so.\n */\nexport interface DrillFinding {\n  key: string;\n  label: string;\n  question: DrillQuestion;\n  knobs: Record<string, { default: number; label: string; unit: string }>;\n}\n\n/**\n * The records behind a DEFINER definition's numbers: a registry relation carrying the fact's column\n * names (e.g. `bucket`), read by the door definer with the SAME filter compiler and the SAME lane\n * rule as the number, for a window (required), and never past the number's `as_of` (rows created\n * after it are not listed). The number and its records are the SAME counted rows, equal as of the\n * count (`as_of`); a value that changes afterwards reaches both at the next count.\n *\n * An INVOKER definition may declare records too (lane DRILL-GAPS): they are its own rows (`fact` is\n * the definition's own fact), read as the person through the table's row security, among the columns\n * the definition already reads — so a screen shows \"the recent runs\" without a host link.\n */\nexport interface DrillRecords {\n  /** The registry token of the records relation (e.g. \"ai_usage_executions\"). */\n  fact: string;\n  /** The columns a record shows, in order. */\n  columns: string[];\n  /** The words a person reads for a column, where its name would mislead (\"Request's top model\"). */\n  labels?: Record<string, string>;\n  /**\n   * What ONE record is, singular (\"execution\", \"log line\"): the noun \"See these records\" and their\n   * count read in. REQUIRED when the records are another relation's rows (`fact` is not the\n   * definition's own fact: an hourly summary's records are its executions, never \"hours\"); optional\n   * otherwise, where the definition's own grain (\"one row per deal\") already names it.\n   */\n  noun?: string;\n}\n\n/** The address of a finding's setting: `drill.finding.<definition>.<finding>.<knob>`. */\nexport function drillFindingKnob(definition: string, finding: string, knob: string): string {\n  return `drill.finding.${definition}.${finding}.${knob}`;\n}\n\nexport interface DrillDefinition {\n  key: string;\n  label: string;\n  source: DrillSource;\n  /** One sentence: \"one row per agent\". */\n  grain: string;\n  lanes: DrillLane[];\n  dimensions: DrillDimension[];\n  measures: DrillMeasure[];\n  paths: DrillPath[];\n  detail: { columns: string[]; open?: string };\n  default: DrillQuestion;\n  /** Keys that came from inference, so a screen can say so. */\n  inferred?: string[];\n  mode?: \"invoker\" | \"definer\";\n  /** Honest notes about what inference could not offer, in words. */\n  says?: string[];\n  /** Built-in Saved views, listed first and read-only. */\n  views?: DrillView[];\n  /** Findings (\"dig here\"), answered by the same door. */\n  findings?: DrillFinding[];\n  /** The records relation (what \"See these records\" reads): a definer definition's declared relation, or an invoker definition's own rows. */\n  records?: DrillRecords;\n  /**\n   * The drill setting (minutes) after which the definition's `as_of` is old enough for a screen to say\n   * \"the schedule is behind\" — null when the definition is counted live.\n   */\n  stale_after_knob: string | null;\n}\n\n/** One row of an answer. */\nexport interface DrillAnswerRow {\n  /** `group` a shown group · `other` every group past the cap · `total` the whole answer (or a pivot column's total). */\n  kind: \"group\" | \"other\" | \"total\";\n  /** Each asked Dimension -> its value (a period by its label). A pivot cell also carries the `across` key. */\n  groups: Record<string, unknown> | null;\n  measures: Record<string, number | string | null> | null;\n  row_count: number;\n  prior_groups: Record<string, unknown> | null;\n  prior_measures: Record<string, number | string | null> | null;\n  prior_row_count: number | null;\n  delta: Record<string, { current: number | null; prior: number | null; change: number | null; change_pct: number | null }> | null;\n  compare: Record<string, unknown> | null;\n  /** How many groups there were before the cap (current window). */\n  distinct_groups: number | null;\n  /** Relation Dimensions' labels, read as the person through the target's own row security. */\n  labels: Record<string, string>;\n  /** The answer's honest sentences (the cut, a column past its cap, a name that could not be read). */\n  says: string | null;\n  /** The moment a summary fact counted through (ISO); null when counted live from the table. */\n  as_of: string | null;\n}\n\nexport interface DrillAnswer {\n  rows: DrillAnswerRow[];\n  /** Every sentence the rows carry, once. */\n  says: string[];\n  /** The total row (kind total, no group). */\n  total: DrillAnswerRow | null;\n  /** The moment the answer counted through (the rows' `as_of`); null when counted live. */\n  as_of: string | null;\n}\n\n/** The records behind a number (\"see these records\"): the same filter, read as the person. */\nexport interface DrillRowsPage {\n  total: number;\n  limit: number;\n  offset: number;\n  rows: Array<Record<string, unknown>>;\n  next_offset?: number;\n  columns?: string[];\n  says?: string;\n  /** The moment these records are cut at — the number's `as_of`; null when read live. */\n  as_of: string | null;\n  /**\n   * A definer definition's records, first page only: every Measure that adds up (sum, count, ratio)\n   * summed over the SAME filter — what these records add up to, which is the number they open.\n   */\n  measures?: Record<string, number | string | null>;\n}\n\n/**\n * A DECLARED drill definition (a `*.drill.ts` file): an override of one standard table (its key\n * IS that table's registry token) or a fact over several tables (a key of its own). The one sync\n * script (scripts/drill-sync.ts) compiles each into `platform.drill_def__<key>()`; the store's\n * validator, platform.drill_definition_problems, judges it at sync, at census and on every ask.\n */\nexport interface DrillDeclaration {\n  key: string;\n  label: string;\n  grain: string;\n  /** The fact's registry token. */\n  fact: string;\n  /** invoker (default): the fact's own row security decides. definer: the lane rules below do. */\n  mode?: \"invoker\" | \"definer\";\n  lanes: DrillLane[];\n  /** invoker: which columns narrow the organization and mine lanes. */\n  lane_columns?: { organization?: string; mine?: string };\n  /** definer ONLY, and required for every lane: a closed vocabulary, never SQL. */\n  lane_rules?: {\n    mine?: { column: string };\n    organization?: { column: string; rule: \"member\" | \"admin\" };\n    platform?: { rule: \"super_admin\" };\n  };\n  /** Star joins along a real foreign key, many-to-one only. `from` is a fact column or `join.column`. */\n  joins?: Array<{ as: string; token: string; from: string }>;\n  dimensions: DrillDimension[];\n  measures: DrillMeasure[];\n  paths?: DrillPath[];\n  detail?: { columns: string[]; open?: string };\n  default?: DrillQuestion;\n  /** An override may hide inferred keys. */\n  hide?: string[];\n  /** Built-in Saved views (every question judged against this definition by the validator). */\n  views?: DrillView[];\n  /** Findings: questions with thresholds whose lines are settings. */\n  findings?: DrillFinding[];\n  /**\n   * definer: the relation its records are read from (the same filter and lane rule); invoker: its own\n   * fact, read as the person (lane DRILL-GAPS).\n   */\n  records?: DrillRecords;\n  /** definer ONLY, and only over a fact that keeps a `<table>_watermark`: the stale line's setting. */\n  stale_after_knob?: string;\n}\n\n/** Identity with a type: the one way a `*.drill.ts` file declares a definition. */\nexport function declareDrillDefinition<const T extends DrillDeclaration>(declaration: T): T {\n  return declaration;\n}\n\n/** Decode the door's rows into an answer: the total row found, every sentence once. */\nexport function drillAnswerOf(rows: DrillAnswerRow[]): DrillAnswer {\n  const says: string[] = [];\n  for (const row of rows) {\n    if (row.says && !says.includes(row.says)) says.push(row.says);\n  }\n  const total =\n    rows.find((r) => r.kind === \"total\" && (!r.groups || Object.keys(r.groups).length === 0)) ?? null;\n  const as_of = rows.find((r) => r.as_of != null)?.as_of ?? null;\n  return { rows, says, total, as_of };\n}\n\n/** The door's name for each call (schema `platform`). */\nexport const DRILL_SCHEMA = \"platform\";\nexport const DRILL_DOORS = {\n  describe: \"drill_describe\",\n  ask: \"drill_ask\",\n  rows: \"drill_rows\",\n} as const;\n","// src/core/query.ts — @ai-matrx/records\n//\n// THE QUERY. DOOR-6 … DOOR-10.\n//\n// Query by any combination of relation coordinates and any subset of them; as-of\n// a date on EITHER clock; promoted-field predicates. DOOR-10 is the one that\n// shapes this module: every query is filtered by Visibility INSIDE the query,\n// never post-filtered — which is why nothing here ever reads rows and then drops\n// some. The filtering happens in the store's own policies and in the doors; this\n// builder only describes what to ask for.\n//\n// DOOR-N-3: every hot read runs as a PREPARED statement. A client cannot prepare\n// anything itself, so the builder never concatenates a value into SQL: relation\n// coordinates resolve through `custom.relation_targets`, promoted predicates\n// through `custom.promoted_read`, and both are functions with typed parameters —\n// which is what \"prepared\" means on this side of the wire.\n\nimport type { RelationCoordinate } from \"../relation\";\nimport type { Timestamp, Uuid } from \"../record\";\n\n/**\n * DOOR-8. As-of on EITHER clock, and they are different questions:\n *   · `record` — the record clock: what this record looked like at version time.\n *   · `world` — the world clock: which values were true of the world then\n *     (the Field's `dated` modifier).\n */\nexport interface AsOf {\n  clock: \"record\" | \"world\";\n  at: Timestamp;\n}\n\n/** A predicate over a PROMOTED field (REC-5: promotion light -> heavy). */\nexport interface PromotedPredicate {\n  field_key: string;\n  /** The value as text, exactly as `custom.promoted_read` takes it. */\n  equals: string;\n}\n\nexport interface RecordQuery {\n  table_id: Uuid;\n  /** DOOR-6. Any combination, any subset. An empty list means \"no relation constraint\". */\n  relations?: RelationCoordinate[];\n  /** Predicates the store can answer from an index. */\n  promoted?: PromotedPredicate[];\n  /** DOOR-8. */\n  asOf?: AsOf;\n  /** DOOR-9. Ask across EVERY Home of this Table in one answer. */\n  acrossHomes?: boolean;\n  /** REC-23. Soft-deleted rows are out unless you say otherwise. */\n  includeDeleted?: boolean;\n  /** FLD-10. */\n  recordType?: string;\n  orderBy?: { column: \"created_at\" | \"updated_at\"; ascending?: boolean };\n  limit?: number;\n  offset?: number;\n}\n\n/**\n * What a query decomposes into: a set of door calls whose answers INTERSECT,\n * then one filtered read. Kept as data rather than hidden inside the client so\n * the suite can assert the plan as well as the answer — a query that quietly\n * stopped applying one of its coordinates is otherwise invisible.\n */\nexport interface QueryPlan {\n  /** One `relation_targets` call per coordinate; the id sets are intersected. */\n  relationCalls: Array<{ door: \"relation_targets\"; record_id: Uuid; via_key: string | null }>;\n  /** One `promoted_read` call per predicate; intersected with the above. */\n  promotedCalls: Array<{ door: \"promoted_read\"; field_key: string; value: string }>;\n  /** The filtered read over `custom.record`, which the store's policies gate. */\n  read: {\n    table_id: Uuid;\n    includeDeleted: boolean;\n    recordType: string | null;\n    asOf: AsOf | null;\n    acrossHomes: boolean;\n    orderBy: { column: string; ascending: boolean };\n    limit: number;\n    offset: number;\n  };\n  /**\n   * Stated so nobody has to guess: when this is true the answer is the\n   * intersection of the id sets above, and when it is false the read stands\n   * alone.\n   */\n  intersects: boolean;\n}\n\nexport const DEFAULT_PAGE_SIZE = 50;\n\nexport function planQuery(query: RecordQuery): QueryPlan {\n  const relationCalls = (query.relations ?? []).map((coordinate) => ({\n    door: \"relation_targets\" as const,\n    record_id: coordinate.record_id,\n    via_key: coordinate.role ?? null,\n  }));\n  const promotedCalls = (query.promoted ?? []).map((predicate) => ({\n    door: \"promoted_read\" as const,\n    field_key: predicate.field_key,\n    value: predicate.equals,\n  }));\n  return {\n    relationCalls,\n    promotedCalls,\n    read: {\n      table_id: query.table_id,\n      includeDeleted: query.includeDeleted ?? false,\n      recordType: query.recordType ?? null,\n      asOf: query.asOf ?? null,\n      acrossHomes: query.acrossHomes ?? false,\n      orderBy: {\n        column: query.orderBy?.column ?? \"created_at\",\n        ascending: query.orderBy?.ascending ?? false,\n      },\n      limit: query.limit ?? DEFAULT_PAGE_SIZE,\n      offset: query.offset ?? 0,\n    },\n    intersects: relationCalls.length + promotedCalls.length > 0,\n  };\n}\n\n/** The intersection of the id sets a plan's calls produced. Order is preserved from the first set. */\nexport function intersectIds(sets: Uuid[][]): Uuid[] {\n  if (sets.length === 0) return [];\n  const [first, ...rest] = sets as [Uuid[], ...Uuid[][]];\n  const others = rest.map((s) => new Set(s));\n  return first.filter((id) => others.every((set) => set.has(id)));\n}\n","// src/core/client.ts — @ai-matrx/records\n//\n// THE TYPED CLIENT OVER THE STORE'S DOORS, AND NOTHING ELSE.\n//\n// Every write in this file goes through `custom.record_write`,\n// `custom.record_update`, `custom.record_delete` or `custom.record_restore`.\n// There is no `insert`, no `update` and no `delete` against `custom.record`\n// anywhere in this package, and there is no code path that adds one: DOOR-N-1\n// says there is exactly one write door and `authenticated` holds no direct\n// INSERT, UPDATE or DELETE grant on the store — a client that tried would be\n// refused, and a client that TRIES is a defect even when it is refused.\n//\n// Reads go through the read door too (DOOR-1, DOOR-10): the filtered select over\n// `custom.record` is gated by the store's own policies, and this file never\n// takes rows and then drops some of them. Where it needs an id set it asks a\n// door for one.\n//\n// Nothing here throws. Every method answers `RecordsResult`, and every refusal\n// carries the store's own sentence.\n\nimport { EVERY_RECORD_TYPE, fieldAppliesToEveryType } from \"../recordType\";\nimport { takePrimedTablePageBundle } from \"./primedBundle\";\nimport { canonicalArgs, createDoorCall, primedDoorAnswer, recordsErrorSink, type DoorCall } from \"./doorCall\";\nimport { onRecordChanged } from \"./recordChanges\";\nimport type { ArchivedDoorRow, ArchivedRow, ArchiveLane } from \"../archive\";\nimport { DEFAULT_ARCHIVE_LANE } from \"../archive\";\nimport type {\n  AggregateBucket,\n  AggregateCompare,\n  AggregateMeasure,\n  AggregateRow,\n  RecordFilter,\n  StoreFilter,\n} from \"../aggregate\";\nimport { liftWithheld, stableFilterKey } from \"../aggregate\";\nimport { isLockedStub, splitLockedRows } from \"../record\";\nimport type {\n  CaptureFileRef,\n  CaptureOutcome,\n  CaptureSheetFace,\n  CaptureSheetSummary,\n} from \"../capture\";\nimport type {\n  DashboardBlock,\n  DashboardBlockResult,\n  DashboardRunResult,\n  DashboardSummary,\n  InterfaceRead,\n  InterfaceRows,\n  StuckRow,\n} from \"../dashboard\";\nimport type { DocRenderRow, DocSignatureRow, DocTemplateRow, DocToken, DocUnresolvedToken } from \"../doc\";\nimport type {\n  EnrichCell,\n  EnrichDeclared,\n  EnrichDueRow,\n  EnrichRun,\n  EnrichmentSummary,\n} from \"../enrich\";\nimport type {\n  CommentThreadRead,\n  CommentWritten,\n  RecordFollowers,\n  RecordFollowSet,\n  FieldHistoryEntry,\n  FormulaHistoryEntry,\n  RecordHistoryEntry,\n  RestorePreview,\n  RestoreResult,\n} from \"../history\";\nimport type {\n  DigestPreview,\n  MySubscription,\n  RowTemplateRow,\n  SavedViewRow,\n  SavedViewSpecIn,\n  Subscription,\n  SubscriptionSpec,\n} from \"../subscription\";\nimport { withCallersClock } from \"../subscription\";\nimport type {\n  AnonTokenBinding,\n  WorkApprovalDecision,\n  WorkDecideMany,\n  WorkDecideManyItem,\n  WorkInboxView,\n  InboxStateChange,\n  InboxCounts,\n  WorkApprovalFiled,\n  WorkApprover,\n  WorkAssignment,\n  WorkAssignmentField,\n  WorkChange,\n  WorkInboxItem,\n  WorkListFlavour,\n  WorkListItem,\n  WorkRecordState,\n  WorkGraph,\n  WorkInstantiation,\n  WorkSlotHold,\n  WorkState,\n  WorkTurn,\n} from \"../work\";\nimport type {\n  ChecklistDeclared,\n  ChecklistRunStarted,\n  ChecklistRunStep,\n  ChecklistRunSummary,\n  ChecklistSpec,\n  ChecklistStepCompleted,\n  ChecklistTemplateShape,\n  ChecklistTemplateSummary,\n} from \"../checklist\";\nimport type { TableRowLabel } from \"../rowLabel\";\nimport { clearsRowLabel } from \"../rowLabel\";\nimport type {\n  ArchivedChecklistTemplate,\n  ArchivedForm,\n  FormArchiveAnswer,\n  RecordRowControls,\n  RowDefaultsApplied,\n  TableRowDefaults,\n  TableRowDefaultsPatch,\n} from \"../rowControls\";\nimport type { ExternalPrincipalCard, PublishBinding, ResolvedPublishBinding, ResolvedPublishBindingKind } from \"../trust\";\nimport type { RelationIcons, RelationWordsManyArgs, ReverseColumn, ReverseLinks, ReverseLinksFieldsArgs, ReverseLinksManyArgs, SourceArchived } from \"../relation\";\nimport { isReverseField, sourceArchivedOf } from \"../relation\";\nimport { isDerivedField, withDerivedLooks, withFormulaLooks } from \"../formulaLook\";\nimport { REVERSE_LINKS_RECORDS_PER_CALL } from \"../relation\";\nimport type { RelationNamesAnswer } from \"../coerce\";\nimport { defaultOpLedger } from \"../ops\";\nimport { createScopeDoors, type ScopeDoors } from \"../scopes/doors\";\nimport type { Field } from \"../field\";\nimport type { FieldRetyped, FieldRetypePreview, HistoryRetention, MigrationEntry, MigrationUndone, ParentExtracted, RecordMoved, RecordSplit, RecordsMerged } from \"../retype\";\nimport type { FieldDuplicated } from \"../field\";\nimport { createPickListDoors, type PickListDoors } from \"./pickListDoors\";\nimport { asChoiceNudge, type ChoiceCellBack, type ChoiceNudge, type ChoiceRehome, type ChoicesRehomed, type ChoiceUsage } from \"../choice\";\nimport { parseTableCopiesInProgress, parseTableDuplicated, parseTableDuplicateProgress, parseTableHome, parseTableMoved, type TableCopyInProgress, type TableDuplicated, type TableDuplicateProgress, type TableHome, type TableMoved } from \"../placement\";\nimport type {\n  Pipeline,\n  PipelineColumn,\n  PipelineDeclared,\n  PipelineMoveResult,\n  PipelineMoveMany,\n  PipelineMoveManyItem,\n  PipelineSpec,\n  PipelineVerdict,\n  StagePending,\n  StagePendingOnBoard,\n  PipelineGate,\n  PipelineGatePreview,\n  StageRuleEnforcement,\n  StageRuleOnFail,\n} from \"../pipeline\";\nimport type {\n  EntityFieldRights,\n  EntityFieldsAcross,\n  EntityBackLinks,\n  EntityRecordRead,\n  EntityRowWritten,\n  EntityRecordsFound,\n  EntityTableFacts,\n  NewEntityFieldDeclaration,\n} from \"../entity-field\";\nimport type { BookingAvailability, BookingDeclared, BookingSummary, FormResults, FormRoute, FormSummary } from \"../rule\";\nimport type {\n  ImportColumnsDeclared,\n  ImportBatchResult,\n  ImportFinished,\n  ImportOpened,\n  ImportPlan,\n  ImportPolicy,\n  ImportReport,\n  ImportRun,\n  InboundAddress,\n  InboundDeclared,\n} from \"../import\";\nimport type {\n  ConversationScope,\n  ConversationScopeContext,\n  RecordScopeContext,\n} from \"../record-scope\";\nimport type {\n  FormLookOptions,\n  PortalArchiveAnswer,\n  PortalArchiveFilter,\n  PortalCard,\n  PortalConfigInput,\n  PortalFormAnswer,\n  PortalFormSpec,\n  PortalInvitation,\n  PortalPreviewRow,\n  PortalRevocation,\n  PortalSummary,\n  PortalTableRef,\n} from \"../portal\";\nimport { asPermissionLevel, type MyLevel } from \"../level\";\nimport type { FieldPatch, FieldProposal, NewFieldDeclaration, TableProposal } from \"../field\";\nimport type {\n  HiddenFieldNotice,\n  ReadRow,\n  RecordRevision,\n  ReadValue,\n  RecordDocument,\n  RecordChange,\n  RecordChangeResult,\n  RecordGraphWritten,\n  KeysetRow,\n  RecordKeysetPage,\n  RecordPage,\n  RecordPageSort,\n  RecordRead,\n  StoredRecord,\n  Timestamp,\n  Uuid,\n} from \"../record\";\nimport type { RecordsConfig } from \"../ports\";\nimport type { RecordsError, RecordsResult, WriteConflict } from \"../results\";\nimport { err, ok } from \"../results\";\nimport { decodeKeysetCursor, encodeKeysetCursor } from \"./keysetCursor\";\nimport {\n  parseFieldDrift,\n  type FieldDrift,\n  type Table,\n  type TableArchiveProgress,\n  type TableCapacity,\n  type TableRestoreProgress,\n} from \"../table\";\nimport type {\n  AutomationDeclared,\n  AutomationFlipped,\n  AutomationList,\n  AutomationRevisions,\n  AutomationRuns,\n  AutomationSpec,\n  AutomationTested,\n} from \"../automation\";\nimport type {\n  ActionRunResult,\n  DecorationPath,\n  FormulaParse,\n  FormulaPreview,\n  GridLayout,\n  IoExportPage,\n  RecordEvent,\n  RowAction,\n  TableDecorations,\n  RecordHeader,\n  TableListEntry,\n  AdminTable,\n  DataHomeTable,\n  TableRowCount,\n  TableSyncResult,\n  TableSyncSpec,\n  TableCopySpec,\n  TableSyncAnswer,\n  TableSyncSettings,\n  TableSyncSourceDocument,\n  TableWebhook,\n  TableWebhookDeclared,\n  ViewOrderSet,\n  OutsideShareAnswer,\n} from \"../grid\";\nimport type { ButtonPressed } from \"../button\";\nimport { exportPageXlsx } from \"../grid\";\nimport {\n  DOORS,\n  TRUST_DOORS,\n  TRUST_SCHEMA,\n  doorAbsent,\n  doorExists,\n  doorReady,\n} from \"./doors\";\nimport { mapPgError, staleWriteDetail } from \"./pgError\";\nimport { asRecordsDataSource } from \"./supabase\";\nimport { DRILL_DOORS, DRILL_SCHEMA, drillAnswerOf } from \"../drill\";\nimport type { DrillAnswer, DrillAnswerRow, DrillDefinition, DrillQuestion, DrillRowsPage, DrillSource } from \"../drill\";\nimport { announceRecordChanged, announceTableStructureChanged, markRecordRemoved, markRecordRestored } from \"./recordChanges\";\nimport type { TableKindFacts } from \"../table-kind\";\nimport type { TableLevelFacts, TableLevelSet, TableReaderRule } from \"../tableLevel\";\nimport { intersectIds, planQuery, type RecordQuery } from \"./query\";\nimport { formatCount } from \"@ai-matrx/kit/format\";\nimport { holdsRelativeDays, lookupFromFields, resolveRelativeDays, weekStartIndexOf } from \"../relativeDays\";\n\nconst DEFAULT_SCHEMA = \"custom\";\n\n// The door-call semantics live once, in ./doorCall (the light shell clients ask through it too).\nexport { canonicalArgs, A_PERSONS_REFUSAL, isAPersonsRefusal } from \"./doorCall\";\n\n/** One organization the client could not use, with the sentence that says why. */\nexport interface OrganizationUnavailable {\n  organization_id: Uuid;\n  reason: string;\n}\n\n/** `organizationsOpen`: the organizations whose store answers, and those that do not (with why). */\nexport interface OrganizationsOpenAnswer {\n  open: Uuid[];\n  unavailable: OrganizationUnavailable[];\n}\n\n/** `metadataSearch`: every match, each carrying the organization it came from. */\nexport interface MetadataSearchAnswer {\n  matches: Array<Record<string, unknown> & { organization_id: Uuid | null }>;\n  /** Organizations asked in order (the ones that answered). */\n  organizations_covered: Uuid[];\n  unavailable: OrganizationUnavailable[];\n}\n\n/** AT-SHARE-B. What `custom.field_notify_on_assign` answers: whether the column tells people, and the automations doing it. */\nexport interface FieldNotifyOnAssign {\n  field_id: Uuid;\n  notify_on_assign: boolean;\n  changed: boolean;\n  automation_ids: string[];\n  says?: string;\n}\n\n/** What `custom.base_move` answered when the whole base landed. */\nexport interface BaseMoved {\n  name: string;\n  toOrganizationId: Uuid;\n  /** How many tables went with the Home. */\n  tables: number;\n}\n\nexport interface RecordsClient extends PickListDoors {\n  /** The config this client was built with, so a screen can show who it is acting as. */\n  readonly config: RecordsConfig;\n  /**\n   * THE SCOPE DOORS (`custom.context_*`): scope types are Tables kept for context, scopes Records,\n   * context fields Fields, values cells. Built from this client's own door path. `@ai-matrx/records/scopes`.\n   */\n  readonly scopes: ScopeDoors;\n\n  // ── writes: the one door each ────────────────────────────────────────────\n  recordWrite(args: { table_id: Uuid; data: RecordDocument }): Promise<RecordsResult<Uuid>>;\n  /**\n   * WRITE THE RECORD THIS KEY NAMES, OR UPDATE IT WHEN IT IS ALREADY THERE — one call, race-safe\n   * (`custom.record_upsert`). `key` is the column key (or keys) that say which record this is,\n   * and every one must carry a `unique` rule: the store refuses any other column by its name.\n   * Two concurrent calls with the same key leave ONE record. An update goes through\n   * `record_update` (with `expectedVersion`, its stale-write refusal); a new record through\n   * `record_write`. Answers the record's id either way.\n   */\n  recordUpsert(args: {\n    table_id: Uuid;\n    key: string | string[];\n    data: RecordDocument;\n    expectedVersion?: number;\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * Write MANY new records of one Table in one call.\n   *\n   * `custom.record_write_many` asks the switch, the organization and the Table\n   * ONCE for the whole batch and inserts the rows in one statement — which is\n   * why a paste of 120 lines is one round trip per chunk instead of 120. It\n   * CREATES only: there is no bulk update door, because an update carries a\n   * per-row optimistic version and a batch would have to either drop that or\n   * fail the whole batch for one stale row.\n   *\n   * It returns the new ids IN THE ORDER THE ROWS WERE HANDED IN, so a caller\n   * can tie each id back to the line of the spreadsheet it came from. Hand in\n   * `ids` to choose them yourself; hand in none and the door mints them.\n   */\n  recordWriteMany(args: {\n    table_id: Uuid;\n    rows: RecordDocument[];\n    ids?: Uuid[];\n  }): Promise<RecordsResult<Uuid[]>>;\n  /**\n   * DOOR-SPEED. MANY CHANGES TO ONE TABLE IN ONE TRANSACTION, through\n   * `custom.record_change_many`: inserts, updates (each with an optional `expected_version`)\n   * and archives. Every update lands in ONE statement, so the store's change notice, history and\n   * activity fire once for the batch while every row trigger still judges every row. ONE REFUSED\n   * CHANGE REFUSES THE BATCH and nothing is saved; the store's own sentence comes back with the\n   * change's position in the hint. The answer is one result per change, in order.\n   */\n  recordChangeMany(args: { table_id: Uuid; changes: readonly RecordChange[] }): Promise<RecordsResult<RecordChangeResult[]>>;\n  /**\n   * A PARENT, THE EDGES IT STANDS ON AND THE ROWS THAT BELONG TO IT — ALL OR NOTHING.\n   *\n   * `recordWrite` and `recordWriteMany` are each ONE statement. A screen or a\n   * server path whose unit of work is a GRAPH — an AI artifact and the lines\n   * it produced, an order and its items, a research note and its citations —\n   * could therefore not save it as one thing: a loop is N transactions, and a\n   * failure on row nineteen leaves a parent standing without the lines it\n   * promised.\n   *\n   * `custom.record_write_graph` is one statement, so it is one transaction. It\n   * is NOT a second write path: it calls `custom.record_write_many` for the\n   * rows, `public.assoc_add` for an edge that points OUT of the store (the\n   * message a record was produced by), and `platform.relation_set` for the\n   * parent's own declared relation to its children. Same store switch, same\n   * editor rung on the Table, same value envelope, same undeclared-key guard,\n   * same history rows, same realtime notice.\n   *\n   * ONE REFUSAL REFUSES THE WHOLE GRAPH, BY NAME — the answer says which member\n   * failed and carries the store's own sentence about it, and nothing is\n   * written.\n   *\n   * Every child MUST name a `role`: it is the key of a declared RELATION field\n   * on the parent's Table, and an edge out of a record that names no field is\n   * refused by the store (REL-10 / T7) because without it nothing can read the\n   * relation's delete rule, its cardinality or its organization wall. The order\n   * children are handed in IS the order of the relation.\n   */\n  recordWriteGraph(args: {\n    table_id: Uuid;\n    parent: RecordDocument;\n    /** Each child: its document, the parent FIELD it fills, and optionally its own Table. */\n    children?: Array<{\n      data: RecordDocument;\n      role: string;\n      table_id?: Uuid;\n      position?: number;\n    }>;\n    /** Edges to things OUTSIDE the store. `direction` defaults to `\"in\"` — that thing produced this record. */\n    edges?: Array<{\n      entity: string;\n      id: Uuid;\n      direction?: \"in\" | \"out\";\n      label?: string;\n      role?: string;\n      position?: number;\n      metadata?: Record<string, unknown>;\n    }>;\n  }): Promise<RecordsResult<RecordGraphWritten>>;\n  recordUpdate(args: {\n    record_id: Uuid;\n    patch: Record<string, unknown>;\n    /** Leave it out and the last writer wins; supply it and a loser is TOLD. */\n    expectedVersion?: number;\n  }): Promise<RecordsResult<number>>;\n  /**\n   * A CELL THAT TAKES WORDS WHICH ARE NOT YET A CHOICE — the words become a choice of that\n   * column everywhere and the cell takes it, in ONE transaction (lane CHOICE-COLUMN-EDIT,\n   * `custom.record_update_adding_choices`). `add` is `{ \"<column key>\": [\"words\", ...] }`; the\n   * cell's value in `patch` is the words, and the store turns them into the new choice's key.\n   * Adding a choice changes the table's columns, so it needs that right; a refusal names it.\n   * Answers the new version, like `recordUpdate`, and announces the record changed.\n   */\n  recordUpdateAddingChoices(args: {\n    record_id: Uuid;\n    patch: Record<string, unknown>;\n    add: Record<string, string[]>;\n    expectedVersion?: number;\n  }): Promise<RecordsResult<number>>;\n  /**\n   * The Feature Knob `custom/choice_nudge` for the signed-in person in this client's\n   * organization: what a choice cell does with typed words that are not a choice\n   * (`decideTypedChoice` in `choice.ts` is the one place that acts on it).\n   */\n  choiceNudge(): Promise<RecordsResult<ChoiceNudge>>;\n  /**\n   * REC-23. Soft, and reversible within `retention`.\n   *\n   * 🚨 NOT FOR A TABLE. A Table is a record, so this door accepts one — and\n   * then recurses through every record the Table contains inside a single\n   * transaction, which is unbounded by construction and dies on `57014` at a\n   * size the product's own import reaches in half a minute. Use\n   * `tableArchive` below, which does the same work in resumable passes.\n   */\n  recordDelete(args: { record_id: Uuid }): Promise<RecordsResult<Timestamp>>;\n  /**\n   * MOVE A RECORD (a Table included) INTO ANOTHER HOME — `custom.record_reparent`, the one door that changes where a\n   * record is contained. `parent_id` is the Home's record id (null takes it out). Admin on the record, viewer on the Home.\n   */\n  recordReparent(args: { record_id: Uuid; parent_id: Uuid | null }): Promise<RecordsResult<null>>;\n  recordRestore(args: { record_id: Uuid }): Promise<RecordsResult<void>>;\n  /**\n   * CLOSE-LINK (CD-LINK-10) — WHERE A TABLE LIVES: every Home it lives in (`custom.table_homes_named`), each named for\n   * this reader, the Home it was declared in first (`declared`). A Home this reader may not open is named as withheld.\n   */\n  tableHomes(args: { table_id: Uuid }): Promise<RecordsResult<Array<{ home_id: Uuid; name: string | null; declared: boolean }>>>;\n  /**\n   * CLOSE-LINK (CD-LINK-10) — \"ALSO LIVES IN…\": the Table also lives in `home_record_id` (`custom.home_add`, admin on the\n   * Table). A person shared on that Home alone then knows the Table and sees the records inside that Home, never another's.\n   */\n  homeAdd(args: { table_id: Uuid; home_record_id: Uuid }): Promise<RecordsResult<Uuid>>;\n  /**\n   * ARCHIVING A WHOLE TABLE — ONE PASS OF IT (VERIFIER-11 F3).\n   *\n   * One call archives at most `chunk` of the table's live records through\n   * `custom.record_delete` (so every guard, history capture and outbox row\n   * still happens; nothing is hard-deleted) and comes back with the numbers a\n   * screen draws progress from. The CALLER LOOPS until `done` — that loop is\n   * the fix, because the one thing a single statement cannot be made to do is\n   * finish.\n   *\n   * `chunk: 0` changes nothing and only reports, so a screen can say \"1,430\n   * records will be archived\" BEFORE a person commits to it. `includeTable:\n   * false` empties the table and leaves it standing.\n   *\n   * RESUMABLE, WITHOUT A JOB ROW: what remains is read off the records\n   * themselves every call. A pass that fails, a closed tab or a deploy mid-run\n   * leaves a half-archived table and a next call that continues from exactly\n   * there. A caller must therefore never report \"nothing happened\" after a\n   * failed pass — `archived_total` says what really landed.\n   */\n  tableArchive(args: {\n    table_id: Uuid;\n    /**\n     * How many records this pass takes on. The door clamps it; it answers with what it\n     * took. Default 50 — measured: ~35ms a record against an 8s statement timeout, so\n     * 200 dies on `57014` and is the original defect one level up.\n     */\n    chunk?: number;\n    /** Archive the Table record itself once nothing live is left in it. Default true. */\n    includeTable?: boolean;\n  }): Promise<RecordsResult<TableArchiveProgress>>;\n\n  /**\n   * ONE PASS OF ARCHIVING, ON PURPOSE, A TABLE THE APP'S CODE DEPENDS ON\n   * (`custom.table_archive_deliberately`, lane 12 P5). Such a table (`code_depends: true`) refuses\n   * `tableArchive`, `recordDelete`, a slug / kept_for rename, `tableMove` and removal of the mark.\n   * This door takes the table's slug TYPED by the person and a reason, refuses an agent, and then\n   * archives through `custom.table_archive` (same progress answer; the caller loops until `done`).\n   * Use `archiveTypedTableDeliberately` (`@ai-matrx/records/typed-table`), which loops.\n   */\n  tableArchiveDeliberately(args: {\n    table_id: Uuid;\n    typed_slug: string;\n    reason: string;\n  }): Promise<RecordsResult<TableArchiveProgress>>;\n\n  /**\n   * BRINGING A WHOLE TABLE BACK — ONE PASS OF IT (`custom.table_restore`, lane TABLE-ACTIONS).\n   *\n   * 🚨 NOT `recordRestore` FOR A TABLE: that door brings the Table, its structure, every record\n   * and everything built on it back in one statement and dies on `57014` (the clone's \"Referral\n   * Intake Queue 2026-Q4 (copy 7)\"). This pass brings back the Table and its structure first, then\n   * at most `chunk` records, then what was built on it — all from the one archive event — and\n   * answers `done` when nothing the archive took is still waiting. Use {@link tableRestoreWhole}.\n   */\n  tableRestore(args: { table_id: Uuid; chunk?: number }): Promise<RecordsResult<TableRestoreProgress>>;\n  /**\n   * THE WHOLE RESTORE OF A TABLE — the loop every caller needs: `tableRestore` until `done`,\n   * halving the pass on a statement timeout (a pass that timed out changed nothing). `onPass`\n   * hears every pass's numbers. Answers the last pass, or the refusal that stopped it (what the\n   * passes before it brought back stays back; the next call carries on from there).\n   */\n  tableRestoreWhole(args: {\n    table_id: Uuid;\n    onPass?: (progress: TableRestoreProgress) => void;\n  }): Promise<RecordsResult<TableRestoreProgress>>;\n\n  /**\n   * DUPLICATE A TABLE — `custom.table_duplicate` (lane TABLE-ACTIONS).\n   *\n   * Makes a NEW Table from one the caller may open: its settings and look, every live column (new\n   * ids), every choice list as a new list (same words, colors, keys and order), every saved view\n   * (filters, sorts, layouts, every id inside them pointing at the copy), and with `withRecords`\n   * every live record (a link to another row of the same table follows to the copy's row; a link\n   * to another table stays). `name` defaults to \"<name> (copy)\", \"(copy 2)\", …;\n   * `organizationId` defaults to the source's organization and must be one the caller belongs to.\n   * The source is never written. The copy is made in passes of a few seconds (any size; the\n   * store answers \"copying\" until \"done\"), and this call loops them. Refused before anything is\n   * made, the refusal carries the store's one sentence (not given / archived / not a member there\n   * / a column linking across organizations).\n   */\n  tableDuplicate(args: {\n    tableId: Uuid;\n    withRecords?: boolean;\n    name?: string | null;\n    organizationId?: Uuid | null;\n    /** Called after every pass with what is copied so far (a progress bar is made of it). */\n    onProgress?: (progress: TableDuplicateProgress) => void;\n  }): Promise<RecordsResult<TableDuplicated>>;\n  /**\n   * FINISH A BASE COPY — `custom.base_copy_finish` (lane AT-BASE). After every table of a base was copied by `tableDuplicate`,\n   * points the copies at each other: `pairs` is {source table id: its copy's id}. Re-points each link column's target and each\n   * link cell whose row was copied too; links to a table outside the base stay. Only tables this person copied are touched.\n   */\n  baseCopyFinish(args: { organizationId: Uuid; pairs: Record<Uuid, Uuid> }): Promise<RecordsResult<{ relinked_columns: number; relinked_cells: number }>>;\n  /**\n   * CARRY A COPY'S EXTRAS — `custom.copy_table_extras` (lane COPY-EXTRAS). `pairs` is {source table id: its copy's id}. Every automation of a\n   * source is declared on its copy SWITCHED OFF and every page too, each column and view id pointed at the copy's own. The step's own\n   * refusals (one sentence each) come back in `extras_refused`; the base-move job in aidream calls the same function.\n   */\n  copyTableExtras(args: { organizationId: Uuid; pairs: Record<Uuid, Uuid> }): Promise<RecordsResult<{ automations: number; pages: number; extras_refused: string[] }>>;\n  /**\n   * CARRY ON A COPY — `custom.table_duplicate_continue` (lane TABLE-ACTIONS). The copy is made in\n   * passes of a few seconds each; `tableDuplicate` loops them, and this resumes one that a closed\n   * tab or a lost connection left unfinished (the copy is kept out of every table list until it\n   * is done). Only the person who started it; it answers the finished copy, or refuses.\n   */\n  tableDuplicateContinue(args: {\n    copyId: Uuid;\n    onProgress?: (progress: TableDuplicateProgress) => void;\n  }): Promise<RecordsResult<TableDuplicated>>;\n  /**\n   * THE CALLER'S UNFINISHED COPIES — `custom.table_copies_in_progress` (lane TABLE-ACTIONS). Each\n   * is still being made (carry it on with `tableDuplicateContinue`) or stopped because its source\n   * was archived meanwhile (discard it: `tableArchive` on the copy). Nobody else can see them.\n   */\n  tableCopiesInProgress(): Promise<RecordsResult<TableCopyInProgress[]>>;\n\n  // ── reads ────────────────────────────────────────────────────────────────\n  recordRead(args: {\n    record_id: Uuid;\n    withComputed?: boolean;\n    /** Also answer `version` (read in the same round, so the read takes as long as the slower of the two). */\n    withVersion?: boolean;\n    organization_id?: Uuid | null;\n  }): Promise<RecordsResult<RecordRead>>;\n  /**\n   * DOOR-1. A page of one Table's records THROUGH `custom.read_records`: the\n   * store decides which rows this reader may see and which fields of them, and\n   * a field it masked comes back present-and-null with its reason in `hidden`.\n   * `total` is null because the door counts nothing it has not read — a count\n   * of rows a person may not see is a leak with a number on it.\n   */\n  list(args: {\n    table_id: Uuid;\n    /**\n     * THE STORE'S ONE FILTER SHAPE (`RecordFilter`). Left out, this is the\n     * whole page. Supplied, the store narrows INSIDE its own query — never the\n     * browser, which can only ever filter the rows it was already allowed to\n     * see and would silently drop the rest of the answer.\n     *\n     * It is the same object a saved view stores as `filters` and the same one\n     * `recordAggregate` counts with, so the rows a drill-through opens are the\n     * rows the number on the dashboard counted.\n     */\n    filter?: StoreFilter;\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<{ rows: ReadRow[]; total: number | null; locked?: number }>>;\n  /**\n   * DOOR-SPEED. ONE PAGE THE STORE SORTED, SEARCHED, FILTERED AND COUNTED, through\n   * `custom.read_records_page` — the same wall, ladder, field mask and filter as `list`, with the\n   * order (`sort`, or a hand-ordered view's positions via `view_id`), a text `search` over the\n   * columns this reader may see (and the words of choice options), and the `total` of the\n   * matching visible set. It is what a grid pages with: nothing reads the whole table to draw one\n   * page. A sort on a column this reader cannot see (gone, or masked) is SKIPPED and named in\n   * `sort_ignored` — the page still loads; one worked out on every read is refused by name.\n   */\n  listPage(args: {\n    table_id: Uuid;\n    filter?: StoreFilter;\n    search?: string | null;\n    sort?: readonly RecordPageSort[];\n    view_id?: Uuid | null;\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<RecordPage>>;\n  /**\n   * AP3-KEYSET-DOOR. THE SAME PAGE AS `listPage`, PAGED BY A CURSOR, through\n   * `custom.read_records_keyset`: the same wall, ladder, field mask, filter, search and sort (no\n   * hand-ordered view), the same rows in the same order — but the next page starts after the last\n   * row's sort values and id, so a write landing mid-read never skips or repeats a row. Pass back\n   * `cursor` as `after` (it is opaque; `null` on the last page). A cursor handed to a different\n   * sort, filter or search is refused by name (\"start from the first page\"), never reinterpreted.\n   *\n   * Every row carries the `version` and `organization_id` it was read at, in the same statement as\n   * its values. With `ids`, it re-reads exactly those rows among the ones the reader may see (in the\n   * page's order; `after` ignored, `cursor` and `total` null) — get-by-id, the re-read after a write,\n   * and the changed ids of a realtime notice.\n   */\n  listKeyset(args: {\n    table_id: Uuid;\n    filter?: StoreFilter;\n    search?: string | null;\n    sort?: readonly RecordPageSort[];\n    after?: string | null;\n    ids?: readonly Uuid[];\n    limit?: number;\n  }): Promise<RecordsResult<RecordKeysetPage>>;\n  /**\n   * DOOR-1 FOR AN ID SET. Exactly these records of this Table, through\n   * `custom.read_records_by_ids` — the same ladder, the same level, the same\n   * field masking and the same page ceiling as `list`, addressed by id instead\n   * of by page. An id the reader may not see simply does not come back, which\n   * is the same answer `list` gives by omission.\n   *\n   * It exists because a realtime notice has always named the exact ids that\n   * moved and no door could take them: three cells changing re-read a fifty-row\n   * page in every watching browser.\n   */\n  listByIds(args: { table_id: Uuid; ids: readonly Uuid[] }): Promise<RecordsResult<ReadRow[]>>;\n  /**\n   * DOOR-1 FOR THE ROWS THAT LEFT: a page of one Table's ARCHIVED records,\n   * through `custom.read_records_archived` — the same ladder, the same level,\n   * the same field masking and the same page ceiling as `list`, with the sign\n   * of the `deleted_at` test flipped, plus who archived each one and when.\n   *\n   * 🚨 IT EXISTS BECAUSE ARCHIVING WAS A ONE-WAY DOOR (VERIFIER-10 F4). The\n   * store has always had `record_restore`, and it has always done exactly the\n   * right thing; what it did not have was any door that could LIST the records\n   * it would act on, because every read door answers live rows only. So an\n   * archived record was unreachable from every screen in the platform.\n   *\n   * `lane` is the archived-items law's two lanes — \"mine\" (what I archived) and\n   * \"org\" (what anybody in this organization archived), which is the default.\n   */\n  listArchived(args: {\n    table_id: Uuid;\n    lane?: ArchiveLane;\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<{ rows: ArchivedRow[]; total: number | null }>>;\n  query(query: RecordQuery): Promise<RecordsResult<{ rows: ReadRow[]; total: number | null }>>;\n  /**\n   * Every Table the person can see across ALL their organizations\n   * (`config.organizationIds`); `organization_id` is the page's optional filter\n   * (absent = all). Each Table carries its own `organization_id`.\n   */\n  tableList(args?: { organization_id?: Uuid | null }): Promise<RecordsResult<Table[]>>;\n  /**\n   * ONE Table's declaration by id — `null` when this reader may not see it or it is not a Table.\n   * The same kernel record `tableList` lists, read through `read_records_by_ids` for exactly\n   * that id, so a screen that opens one table never lists every table to find it (a list capped\n   * at 500 answered \"no table\" past the 500th).\n   */\n  tableRead(args: { table_id: Uuid; organization_id?: Uuid | null }): Promise<RecordsResult<Table | null>>;\n  /**\n   * ONE Table of THIS organization found by its slug — or, with no slug, by its name — in ONE\n   * request (`custom.table_find`). `null` when there is none or this reader may not see it: the\n   * store reads the candidates through the same read door `tableRead` uses, so a table she may\n   * not see answers exactly like one nobody made. Where several share a slug, the oldest she may\n   * see answers, every time (the same pick `ensureTable` makes). Never list every table to find one.\n   *\n   * `keptFor` (an app's table): the slug AND what the table is kept for must match — a person's own\n   * table of the same slug is a different table and never answers. With `keptFor` and no live\n   * match, an ARCHIVED match is answered as `{ id, organization_id, archived_at }` (no document), so\n   * a caller says \"archived — restore it\", never \"missing\".\n   */\n  tableFind(\n    args: ({ slug: string; name?: never } | { name: string; slug?: never }) & { keptFor?: string },\n  ): Promise<RecordsResult<Table | null>>;\n  /**\n   * `tableFind` BY SLUG FOR MANY ORGANIZATIONS IN ONE REQUEST (`custom.table_find_many`). Each\n   * organization meets the same walls `tableFind` does and is answered through `custom.table_find`\n   * itself. `tables` holds one live Table per organization that has one this reader may see (an\n   * organization with none is absent); `refused` holds each organization the store refused, with\n   * its own refusal, and never stops the others. Never loop `tableFind` over organizations.\n   */\n  tableFindMany(args: {\n    organizationIds: Uuid[];\n    slug: string;\n    keptFor?: string;\n  }): Promise<RecordsResult<{ tables: Table[]; refused: Array<{ organization_id: Uuid; error: RecordsError }> }>>;\n  /**\n   * IS THIS TABLE IN THE ARCHIVE? (lane HUB-FIX, 2026-09-23.) The archived row for one\n   * Table of this organization, or `null` when the archive does not hold it — which\n   * is an ANSWER, never \"it may have been deleted\". A table page that cannot find a\n   * Table asks this before saying anything: an archived Table's own address used to\n   * read \"…or it may have been deleted\" when it was archived and one click from back.\n   */\n  tableArchived(args: { table_id: Uuid }): Promise<RecordsResult<ArchivedRow | null>>;\n  /**\n   * WHO CAN SEE EACH TABLE, AND WHETHER THE CALLER MADE IT — `custom.table_facts`\n   * (lane HUB-FIX). `visibility` and `created_by` are record COLUMNS the Table document\n   * never carried, so a screen that sorts Tables into lanes asks this and folds the\n   * answer onto `tableList()`'s Tables with `withTableFacts`.\n   *\n   * 🚨 IT IS ITS OWN CALL, NOT PART OF `tableList()` (0.57.3). 0.57.2 folded it into\n   * every table list, so every screen that merely LISTS tables (the field editor's\n   * relation target, the import wizard, settings) paid a second round trip it never\n   * used — and every test double that answers a table list had to answer it too\n   * (records-ui 0.84.5's gate: 47 tests in 15 files red). Only the lane-sorting\n   * screens ask.\n   *\n   * The door-presence pattern: when the store's catalog does not carry the door the\n   * answer is `null` — nothing asked, nothing invented.\n   */\n  tableFacts(args?: { organization_id?: Uuid | null }): Promise<RecordsResult<TableFact[] | null>>;\n  /**\n   * WHICH STORE CURRENTLY WRITES each table — `custom.where_tables_live`.\n   *\n   * This is a batch cutover decision, not a Table's home address: during COPY\n   * mode an older table and its record-store copy share an id, and only this\n   * door knows which one the organization is still using. It is intentionally\n   * unbound from this client's organization because the door derives the answer\n   * from each supplied table and the caller's authority.\n   */\n  tablesLiveWhere(args: { table_ids: Uuid[] }): Promise<RecordsResult<TableLiveLocation[]>>;\n  /**\n   * WHICH ORGANIZATION A TABLE LIVES IN, BY NAME, AND WHERE IT MAY GO — `custom.table_home`\n   * (SC-1' / SC-1-TAILS). Read FROM THE TABLE, never from the organization the client is bound\n   * to, so it answers for a table shared from outside too. `null` = not given to this person,\n   * or not there (the store says the same for both, on purpose). A store without the door\n   * refuses `door_absent` — never a guessed organization.\n   */\n  tableHome(args: { table_id: Uuid }): Promise<RecordsResult<TableHome | null>>;\n  /**\n   * MOVE A TABLE into another organization the caller belongs to — `custom.table_move`. It\n   * carries every Table inside it or its rows and writes the change events; refused, NOTHING\n   * moved and the refusal carries the store's one sentence. `expected_version` is the Table's\n   * version the caller decided on (a concurrent change refuses with \"look again\").\n   */\n  tableMove(args: { table_id: Uuid; to_organization_id: Uuid; expected_version?: number | null }): Promise<RecordsResult<TableMoved>>;\n  /**\n   * MOVE A WHOLE BASE into another workspace (organization) the caller belongs to — `custom.base_move` (AT-NOTIFY-MOVE).\n   * Admin on the base's Home. Every table of the Home goes through the one table door (with its pages and automations), the\n   * Home and its base row follow, and the tables stay under that Home over there. All or nothing: a refusal moved nothing and\n   * carries the store's sentence (which table it stopped at, or that the caller is not in that workspace).\n   */\n  baseMove(args: { home_id: Uuid; to_organization_id: Uuid }): Promise<RecordsResult<BaseMoved>>;\n  /**\n   * The Fields that apply. NOTION-PROPS: a two-way link's reverse Field (`isReverseField`) is left out\n   * unless `withReverse` — every screen draws it as the table's reverse column (`reverseColumns`, with\n   * `read_only: false`), which reads and writes its links; listed as a Field too it would draw twice.\n   */\n  fields(args: { table_id: Uuid; recordType?: string; withReverse?: boolean }): Promise<RecordsResult<Field[]>>;\n  /**\n   * FLD-5 / FLD-6: a list field stores the id of an option RECORD, because\n   * every pick-list is already a Table. These are that Table's records — the\n   * store resolves which Table from the Field's own config, so no caller has to\n   * know it.\n   */\n  fieldOptions(args: { field_id: Uuid }): Promise<RecordsResult<StoredRecord[]>>;\n  /**\n   * How many records hold each choice of one choice column, keyed by the option's id\n   * (`custom.field_choice_usage`; counts only records the caller may see). What a column editor\n   * says before a choice that records still hold is removed: \"3 records use “X-ray”.\"\n   */\n  fieldChoiceUsage(args: { field_id: Uuid }): Promise<RecordsResult<Record<string, ChoiceUsage>>>;\n  /**\n   * A column's choices saved AND the records of each removed choice moved to another choice,\n   * kept as other values, or cleared — ONE transaction (`custom.field_update_rehoming_choices`).\n   * `rehome` is keyed by the removed option's id. The answer carries `undo`; sending\n   * `{ patch: { options: undo.options }, cells_back: undo.cells_back }` back through this same\n   * call puts the list and every cell back, again in one transaction.\n   */\n  fieldUpdateRehomingChoices(args: {\n    field_id: Uuid;\n    patch: FieldPatch;\n    rehome?: Record<string, ChoiceRehome> | undefined;\n    cells_back?: readonly ChoiceCellBack[] | undefined;\n  }): Promise<RecordsResult<ChoicesRehomed>>;\n  tableCapacity(args: { table_id: Uuid }): Promise<RecordsResult<TableCapacity>>;\n\n  // ── declaring a Table, and the kernels a Table needs to exist ────────────\n  /**\n   * REC-1: a Table has to live somewhere, so a Home comes first — and a Home is\n   * an ordinary record in the person kernel. `homeId` is therefore required and\n   * `personKernelId()` is how a caller gets a Table to write one into.\n   */\n  tableDeclare(args: { spec: Record<string, unknown>; homeId: Uuid }): Promise<RecordsResult<Uuid>>;\n  /**\n   * FIND THIS TABLE BY ITS SLUG, OR MAKE IT — ONE call, ONE transaction (`custom.table_ensure`).\n   * The store holds a lock on (organization, slug) across the find and the make, so two tabs\n   * saving their first record at once get the SAME table; a second call adds any column the spec\n   * names that the table lacks and never retypes or drops one. `spec.fields` are full\n   * `custom.field_declare` specs. Prefer `ensureTable(client, NewTableSpec)`, which builds them.\n   *\n   * `drift` names every column the table already has whose stored shape differs from the spec\n   * (type, format, label, multi, required, unique) — reported, never applied. `[]` when nothing\n   * differs; `null` only from a store too old to compare (see `FieldDrift`).\n   */\n  tableEnsure(args: { spec: Record<string, unknown> }): Promise<\n    RecordsResult<{ table_id: Uuid; home_id: Uuid | null; created: boolean; drift: FieldDrift[] | null }>\n  >;\n  /**\n   * ADD A FIELD TO A TABLE. One call, and the store does the three things no\n   * client can do for itself: it turns a parity type into the behavior,\n   * modifiers, format, unit, relation target and Rules its own guards demand;\n   * it tells the TABLE about the field (REC-1 / FLD-8 — a definition for a\n   * field the table never declared is refused, which is the sentence every\n   * \"Add field\" used to end on); and it stores the definition as a FIELD\n   * rather than as a plain record, so the delete rules and the\n   * formula-dependency check can see it.\n   *\n   * A choice list carries its `options` as words. The store keeps them the only\n   * way FLD-5 / FLD-6 allows — as the records of a Table it declares for them —\n   * so nobody is made to build a table before they can have a dropdown.\n   */\n  fieldDeclare(args: { table_id: Uuid; spec: NewFieldDeclaration }): Promise<RecordsResult<Uuid>>;\n  /** Several columns of one Table in ONE call and one transaction (`custom.field_declare_many`): all or none. */\n  fieldDeclareMany(args: { table_id: Uuid; specs: NewFieldDeclaration[] }): Promise<RecordsResult<Uuid[]>>;\n  /**\n   * A NEW TABLE IN ONE CALL (`custom.table_create`): its Home, the Table under it and its columns, in\n   * one transaction, so a refusal anywhere leaves nothing behind. Prefer `declareTable(client, spec)`.\n   */\n  tableCreate(args: { spec: Record<string, unknown>; fields: NewFieldDeclaration[] }): Promise<\n    RecordsResult<{ table_id: Uuid; home_id: Uuid; field_ids: Uuid[] }>\n  >;\n  /** One field's own settings. What it HOLDS is a conversion and is refused here by name. */\n  fieldUpdate(args: { field_id: Uuid; patch: FieldPatch }): Promise<RecordsResult<Uuid>>;\n  /**\n   * WHAT A CHANGE OF KIND WILL DO, before it is made (`custom.field_retype_preview`): the store runs the\n   * same `field_update` patch inside a subtransaction, counts what converts, what is kept aside and the\n   * choices it makes, and rolls every row back. Nothing is written.\n   */\n  fieldRetypePreview(args: { field_id: Uuid; patch: FieldPatch }): Promise<RecordsResult<FieldRetypePreview>>;\n  /**\n   * CHANGE WHAT A COLUMN HOLDS, through `custom.migrate_retype` (FLD-4 / T12). `to` is the store's\n   * behavior word — `text`, `range` (numbers and dates), `boolean`, `list`, `relation`. Every value\n   * that converts is converted; every value that does not is kept in that record's `_retired`\n   * with the reason, never coerced and never deleted. The answer counts both.\n   */\n  migrateRetype(args: { field_id: Uuid; to: string; note?: string }): Promise<RecordsResult<FieldRetyped>>;\n  /**\n   * MERGE ONE RECORD INTO ANOTHER, through `custom.migrate_merge` (T5 / REC-21). The loser's values\n   * the winner did not hold move across, the ones that differ are kept as ranked alternates, every\n   * link to the loser now points at the winner, and the loser is archived with its id resolving to\n   * the winner. Editor on BOTH records is decided first. The answer's `migration_id` is what\n   * `migrateUndo` takes.\n   */\n  migrateMerge(args: { winner_id: Uuid; loser_id: Uuid; note?: string | null }): Promise<RecordsResult<RecordsMerged>>;\n  /** Put a recorded Migration back (`custom.migrate_undo`): a retype or a merge, by its id. */\n  migrateUndo(args: { migration_id: Uuid }): Promise<RecordsResult<MigrationUndone>>;\n  /**\n   * SPLIT ONE RECORD IN TWO, through `custom.migrate_split` (Rule 11 / REC-22). The named values\n   * MOVE to a new record of the same Table; the original keeps its id, so every link to it still\n   * resolves. Editor on the record is decided first. `migrateUndo(migration_id)` puts it back.\n   */\n  migrateSplit(args: { record_id: Uuid; moved_keys: string[]; note?: string | null }): Promise<RecordsResult<RecordSplit>>;\n  /**\n   * EXTRACT A PARENT, through `custom.migrate_extract_parent` (Rule 11 / test 5). The named values\n   * are COPIED up into a new record of `parent_table_id`, and this record is put under it. Its old\n   * parent, if any, becomes the new parent's parent. `migrateUndo(migration_id)` puts it back.\n   */\n  migrateExtractParent(args: { record_id: Uuid; parent_table_id: Uuid; moved_keys: string[]; note?: string | null }): Promise<RecordsResult<ParentExtracted>>;\n  /**\n   * MOVE A RECORD TO ANOTHER TABLE, through `custom.migrate_retype`'s record arm (test 9 / REC-N-18). The\n   * record keeps its id — every link to it still resolves — and its values whose column `to_table_id` lacks\n   * are taken off and kept in History with the reason (`misfits`). Full (admin) on the record is decided\n   * first; the table must be in the same organization. `migrateUndo(migration_id)` puts it back whole.\n   */\n  migrateMoveRecord(args: { record_id: Uuid; to_table_id: Uuid; note?: string | null }): Promise<RecordsResult<RecordMoved>>;\n  /** The Migration log for one record or Table (`custom.migrations`), newest first. */\n  migrations(args: { target_id?: Uuid | null; limit?: number }): Promise<RecordsResult<MigrationEntry[]>>;\n  /**\n   * HOW LONG HISTORY IS KEPT (Rule 10 / test 14), through `custom.history_retention`. `floor_days` is the\n   * organization's floor (knob `extensibility.user_tables.history_retention_floor_days`: 30 by default, an\n   * organization may raise it, never lower it); `table_days` is the table's own, never below the floor.\n   */\n  historyRetention(args?: { table_id?: Uuid | null }): Promise<RecordsResult<HistoryRetention>>;\n  /** Set a table's value-history retention (`custom.history_retention_set`); below the floor is refused in the store's words. */\n  historyRetentionSet(args: { table_id: Uuid; days: number }): Promise<RecordsResult<number>>;\n  /** Raise this organization's retention floor (`custom.history_retention_floor_raise`); a lower number is refused. */\n  historyRetentionFloorRaise(args: { days: number }): Promise<RecordsResult<number>>;\n  /**\n   * ONE RECORD ON EITHER CLOCK, through `custom.query_record_as_of` (Rule 10 / test 6).\n   * `recorded_at` answers what the store SAID at that moment; `world_on` answers what was TRUE of\n   * the world on that date, read from `dated` values. Both may be given. `null` data means the\n   * record is not visible to this person (or did not exist then) — an absence, not an empty record.\n   */\n  recordAsOf(args: { record_id: Uuid; recorded_at?: string | null; world_on?: string | null }): Promise<RecordsResult<Record<string, unknown> | null>>;\n  /**\n   * REL-DISP. THE WORDS ONE RELATION CELL SHOWS, resolved by the store through\n   * that column's own display spec — one column or several, joined by its\n   * separator. Never resolve a relation label any other way: the store's\n   * `custom._words_for` is the one body that decides what a record is called, it\n   * asks the read-access ladder BEFORE it reads the name, and a record this reader\n   * may not open comes back as the withheld sentence rather than its name or id.\n   * A value that is not an id is handed straight back — it is already words.\n   */\n  relationWords(args: { field_id: Uuid; value: string }): Promise<RecordsResult<string | null>>;\n  /**\n   * The same answer for a WHOLE PAGE of cells in one round trip. Prefer this\n   * wherever a grid, board, list or picker resolves more than one chip: the\n   * per-id lane is what made a page of relation cells a page of requests.\n   */\n  relationWordsMany(\n    args: RelationWordsManyArgs,\n  ): Promise<RecordsResult<Record<string, string>> & { archived?: readonly string[]; icons?: Record<string, RelationIcons> }>;\n  /**\n   * VISION-REACH G1. Which records of `table_id` each name names — its name column, case and\n   * spacing ignored, only records this reader may see. Hand the answer to `relationNameIndexOf`\n   * and pass that to the coercion as `relationNames`. Up to 5,000 names a call; more are sent in\n   * groups by this method.\n   */\n  relationNamesMatch(args: { table_id: Uuid; names: string[] }): Promise<RecordsResult<RelationNamesAnswer>>;\n  /**\n   * VIEWS-AND-FIELDS BL (REL-9). The REVERSE COLUMNS of a Table: one per relation column of another\n   * table (or this one) that links here, read-only, virtual — never a Field of this Table, so\n   * `applicableFields` does not list them. A linking table this reader may not know is left out.\n   */\n  reverseColumns(args: { table_id: Uuid }): Promise<RecordsResult<ReverseColumn[]>>;\n  /**\n   * A page of records' links through ONE reverse column, in one round trip per 200 records:\n   * `{ [record id]: { total, links: [{ id, words }] } }`, only linking records this reader may see.\n   * `limit` (1–50) and `offset` page one record's links — a record with thousands of links costs\n   * one count and one page. A record with no links answers `{ total: 0, links: [] }`.\n   */\n  reverseLinksMany(args: ReverseLinksManyArgs): Promise<RecordsResult<Record<string, ReverseLinks>>>;\n  /**\n   * The same, through SEVERAL reverse columns in ONE call (`custom.reverse_links_many_fields`):\n   * `{ [source field id]: { [record id]: { total, links } } }`. A store without the door answers\n   * `door_absent` — ask `reverseLinksMany` per column then.\n   */\n  reverseLinksFields(args: ReverseLinksFieldsArgs): Promise<RecordsResult<Record<string, Record<string, ReverseLinks>>>>;\n  /**\n   * NOTION-PROPS. A TWO-WAY LINK: makes (or returns) the reverse Field of relation `field_id` on its\n   * target table (`custom.relation_reverse_field`), so the link is a column there that edits the same\n   * links. Its key is the reverse column's key; `label` defaults to the linking table's name.\n   */\n  relationReverseField(args: { field_id: Uuid; label?: string }): Promise<RecordsResult<Uuid>>;\n  /**\n   * NOTION-PROPS. Adds and removes links from the reverse side of a two-way link\n   * (`custom.relation_reverse_set`): each id becomes a write of THAT record's forward Field.\n   * Answers how many records changed.\n   */\n  relationReverseSet(args: { record_id: Uuid; field_id: Uuid; add?: readonly Uuid[]; remove?: readonly Uuid[] }): Promise<RecordsResult<number>>;\n  /** Take a field off a table. Refuses the title field, the last field, and one another field reads through. */\n  fieldRetire(args: { field_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /**\n   * Bring a removed column back (`custom.field_restore`): the set that was retired with it, the\n   * Table's declaration of those columns, and the links they made. The values never left.\n   */\n  fieldRestore(args: { field_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /**\n   * DUPLICATE PROPERTY (Notion N5) — `custom.field_duplicate`: a new column right after this one, named\n   * \"<name> (1)\", the same kind (choices with their colors, unit, link, formula, rules, sensitivity), and\n   * every record's value copied into it in one statement. A link column copies its definition only (its\n   * values are links); a formula, lookup or roll-up works its answer out itself. Needs the table's\n   * add-a-column rung, the same as `fieldDeclare`.\n   */\n  fieldDuplicate(args: { field_id: Uuid }): Promise<RecordsResult<FieldDuplicated>>;\n  /**\n   * CHAIR-ROLLUP-HONEST. Is a column this lookup or roll-up reads archived — the link it reads\n   * through, a back-link's linking column, or the far column it totals (`custom.field_source_archived`)?\n   * `null` while every source is live. Bring it back with `fieldRestore({ field_id })`.\n   */\n  fieldSourceArchived(args: { field_id: Uuid }): Promise<RecordsResult<SourceArchived | null>>;\n  /**\n   * A TABLE AS A KIND (KINDS-GLUE wave 3, N1): `custom.table_kind_facts` verbatim — the Table's\n   * live Fields, choices and stamp, as the asking person. The door finds the Table's organization\n   * itself, so this works for a Table in any organization the person may open; anything else is\n   * refused (`42501`, the store's sentence).\n   */\n  tableKindFacts(args: { table_id: Uuid }): Promise<RecordsResult<TableKindFacts>>;\n  /**\n   * A TABLE'S ACCESS LEVEL (CONFIDENTIAL-BY-ORG-ADMIN): `custom.table_level_facts` verbatim - its level,\n   * readers, who approves a change (`set_by`) and whether THIS person may (`can_set`). Draw the control only\n   * when `can_set` is true; anyone who may know the table may ask.\n   */\n  tableLevelFacts(args: { table_id: Uuid }): Promise<RecordsResult<TableLevelFacts>>;\n  /**\n   * MAKE A CUSTOM TABLE CONFIDENTIAL, or change whom it names (`custom.set_table_confidential`). Succeeds\n   * only for an owner/admin of the table's own organization on an ordinary custom table; the approver, seat,\n   * reason and date are recorded. `readers` is the list of `{field, level}` rules (a person field of the\n   * table); `reason` is required.\n   */\n  setTableConfidential(args: { table_id: Uuid; readers: TableReaderRule[]; reason: string }): Promise<RecordsResult<TableLevelSet>>;\n  /** THE WAY BACK: the same caller rule, the table is Organization again (`custom.set_table_organization`). */\n  setTableOrganization(args: { table_id: Uuid; reason: string }): Promise<RecordsResult<TableLevelSet>>;\n  /**\n   * THE COLUMNS THIS TABLE HAD AND NO LONGER HAS (grids review 3): its retired Field records,\n   * newest first, through the same archived door the Table archive uses — addressed at the Field\n   * kernel (every Field is a record in it) and paged until the door answers short.\n   */\n  fieldsRetired(args: { table_id: Uuid }): Promise<RecordsResult<ArchivedRow[]>>;\n  // ── CUSTOM FIELDS ON A STANDARD BUSINESS TABLE (REC-34 / REC-40 / FLD-8) ──\n  // Named by the registry TOKEN, because a standard table has no Table record.\n  // One set for all 643 tables the registry types Entity or Detail, and no\n  // per-table code anywhere in this package or in any screen that uses it.\n  /** What the registry says about a token, and whether it can hold a value at all. */\n  entityTable(args: { token: string }): Promise<RecordsResult<EntityTableFacts>>;\n  /**\n   * The fields THIS organization added to that standard table. `include_retired: true` also answers the\n   * ones taken away (`entityFieldRetire`), live first, each with `archived_at` set — the archived view a\n   * screen offers, with `fieldRestore({ field_id })` to bring one back. Live fields carry `archived_at: null`.\n   */\n  entityFields(args: { token: string; include_retired?: boolean }): Promise<RecordsResult<Field[]>>;\n  /** The fields EVERY named organization added to that standard table, with their choices, in one read. */\n  entityFieldsAcross(args: { token: string; organization_ids: Uuid[] }): Promise<RecordsResult<EntityFieldsAcross>>;\n  /** Add a column to a standard table. An organization admin's right - it changes the table for everybody. */\n  entityFieldDeclare(args: { token: string; spec: NewEntityFieldDeclaration }): Promise<RecordsResult<Uuid>>;\n  /** One field's own settings. A TYPE change is refused here by name, as it is on a custom table. */\n  entityFieldUpdate(args: { field_id: Uuid; patch: Record<string, unknown> }): Promise<RecordsResult<Uuid>>;\n  /** Take a custom field off a standard table. The values already written stay in each row. */\n  entityFieldRetire(args: { field_id: Uuid }): Promise<RecordsResult<Uuid>>;\n  /** May this person add a column here - and if not, the store's own sentence saying why. */\n  entityFieldRights(args: { token: string }): Promise<RecordsResult<EntityFieldRights>>;\n  /** REC-53 in one answer: the row's real columns AND its custom values AND the definitions. */\n  entityRecordRead(args: { token: string; record_id: Uuid }): Promise<RecordsResult<EntityRecordRead>>;\n  /**\n   * AP-4: the custom rows that link to one platform record, by which field and in which table.\n   * Keyed by the ROW's organization (`organization_id`), never the client's active one. Paged:\n   * pass the previous answer's `next_cursor` as `cursor`.\n   */\n  entityBackLinks(args: {\n    token: string;\n    record_id: Uuid;\n    organization_id: Uuid;\n    limit?: number;\n    cursor?: string | null;\n  }): Promise<RecordsResult<EntityBackLinks>>;\n  /**\n   * THE one write door for a standard row (`custom.entity_row_write`, as the person): custom values\n   * as a patch (a key left out is left alone, a key set to null is cleared with its envelope),\n   * archive / restore, and real columns only where the store lists them. The row's own organization\n   * governs; `expected_version` refuses a stale write; a change that changes nothing writes nothing.\n   */\n  entityRowWrite(args: {\n    token: string;\n    /**\n     * null ADDS a row (chairblk3_a): only for a token whose API facts say `create_via: \"insert\"`\n     * (`drill_describe(...).api.create_via` — task and project), as one insert AS THE PERSON in\n     * `organization_id` (default: this client's organization); the answer carries `created: true`\n     * and the new `id`. Every other token refuses in its own words.\n     */\n    record_id: Uuid | null;\n    /** A change by id: only to say which organization the row must belong to. A new row: where it goes. */\n    organization_id?: Uuid | null;\n    custom?: Record<string, unknown>;\n    columns?: Record<string, unknown>;\n    expected_version?: number | null;\n    archive?: boolean | null;\n  }): Promise<RecordsResult<EntityRowWritten>>;\n  /** Rows of that standard table with this custom value. Refuses a field nobody declared. */\n  entityRecordsFind(args: {\n    token: string;\n    key: string;\n    value?: unknown;\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<EntityRecordsFound>>;\n\n  /** The kernel Tables a caller writes a Home, a Field or a Rule into. */\n  personKernelId(): Promise<RecordsResult<Uuid>>;\n  fieldKernelId(): Promise<RecordsResult<Uuid>>;\n  ruleKernelId(): Promise<RecordsResult<Uuid>>;\n\n  // ── Rules: the STORE decides membership, never a screen ──────────────────\n  /** Every record the Rule says is a member. A saved view's list is this, not a filter a screen ran. */\n  /** PRODUCTS row 7 — the whole board: its stage column, its stages in the declared\n   *  order, and every Rule WITH the sentence it says when it refuses. */\n  pipelineRead(args: { table_id: Uuid }): Promise<RecordsResult<Pipeline>>;\n  /** The store's own count and total per column, over what this person may see. */\n  pipelineBoard(args: {\n    table_id: Uuid;\n    measure?: string | null;\n    /**\n     * S2-PRIME — the view's question, either shape (`StoreFilter`). Given, the headings count and\n     * total exactly the cards the same filter puts on the board (`custom.pipeline_board`'s\n     * four-argument door); left out, the whole table this person may see, as before.\n     */\n    filter?: StoreFilter | null;\n  }): Promise<RecordsResult<PipelineColumn[]>>;\n  /** Whether this card may go to that column — asked BEFORE the finger lets go. */\n  pipelineTransitionRefusal(args: {\n    record_id: Uuid;\n    to: string;\n  }): Promise<RecordsResult<PipelineVerdict>>;\n  /**\n   * Move a record to a stage. An ORDINARY record write, judged by the same Rules.\n   *\n   * It answers an OBJECT on every path. A gate whose `on_fail` is `require_approval`\n   * comes back `applied: false` with the wait it filed — the record has NOT moved, and a\n   * screen that treated the call's success as the move's success would show the card in\n   * the wrong column while somebody is still deciding.\n   */\n  pipelineMove(args: {\n    record_id: Uuid;\n    to: string;\n    also?: Record<string, unknown>;\n    expected_version?: number | null;\n  }): Promise<RecordsResult<PipelineMoveResult>>;\n  /**\n   * MOVE MANY CARDS IN ONE CALL (lane S4, `custom.pipeline_move_many`). Each card is judged by\n   * `pipeline_move` exactly as one is, in its own savepoint: a refused card writes nothing and the\n   * others still land. `expected_version` is required per card — a card that changed since the\n   * board loaded answers `changed_since_loaded` and is never overwritten. A refusal of the WHOLE\n   * call (a stranger, an empty batch, more than the `custom/batch_items_max` knob) is the error.\n   */\n  pipelineMoveMany(args: { moves: PipelineMoveManyItem[] }): Promise<RecordsResult<PipelineMoveMany>>;\n  /** Declare (or re-state) a pipeline: the stage column and its transition Rules. */\n  pipelineDeclare(args: {\n    table_id: Uuid;\n    spec: PipelineSpec;\n  }): Promise<RecordsResult<PipelineDeclared>>;\n  /** Which column of this table holds its stage, or null when it is not a board. */\n  tableStageField(args: { table_id: Uuid }): Promise<RecordsResult<string | null>>;\n  /** The closed list of what a gate does when it says no — the store is the authority. */\n  stageRuleOnFailKinds(): Promise<RecordsResult<{ behaviour: StageRuleOnFail; note: string }[]>>;\n  /** Whether this organization's gates refuse or warn. One opinion, asked once. */\n  stageRuleEnforcement(): Promise<RecordsResult<StageRuleEnforcement>>;\n  /** What is waiting on this card: approvals filed against its own stage column. */\n  recordStagePending(args: { record_id: Uuid }): Promise<RecordsResult<StagePending[]>>;\n  /** The same question for a whole board, in ONE call — what a Kanban badges cards from. */\n  pipelinePending(args: { table_id: Uuid }): Promise<RecordsResult<StagePendingOnBoard[]>>;\n  /**\n   * WHAT THIS GATE WOULD DO TO THIS BOARD TODAY — for a gate that has not been saved.\n   *\n   * The settings screen calls it on every edit of the condition, which is why it takes\n   * the gate rather than a rule id: no saved-rule door can answer about a rule that does\n   * not exist yet. The store compiles it with the same compiler `pipelineDeclare` uses,\n   * so the number here and the refusal at the door are the same rule — a preview with its\n   * own compiler would be wrong exactly at the edge of the condition, which is the only\n   * place anybody looks.\n   *\n   * A gate that does not say what it demands is REFUSED, not answered zero: \"no cards\n   * would be stopped\" beside a half-written rule is the sentence that gets it saved.\n   */\n  pipelineGatePreview(args: {\n    table_id: Uuid;\n    stage: string;\n    gate: PipelineGate | Record<string, unknown>;\n  }): Promise<RecordsResult<PipelineGatePreview>>;\n  /**\n   * SERVER LANE ONLY. `custom.rule_members` walks the whole scope table through the evaluator and\n   * returns STORED rows — no read-access ladder, no masking — so no browser role holds EXECUTE on it\n   * and it answers 42501 from a signed-in seat. A screen reads a Rule's members through\n   * `ruleMembersVisible`.\n   */\n  ruleMembers(args: { rule_id: Uuid }): Promise<RecordsResult<StoredRecord[]>>;\n  /**\n   * S2-PRIME — THE MEMBERS OF A MEMBERSHIP RULE THIS PERSON MAY SEE, a page at a time\n   * (`custom.rule_members_visible`): the list door asked the Rule's own test, so the rows are the\n   * read door's — the same ladder, masked documents, the same page ceiling.\n   */\n  ruleMembersVisible(args: { rule_id: Uuid; limit?: number; offset?: number }): Promise<RecordsResult<ReadRow[]>>;\n  /** Is this one record a member, and WHY — the store's own answer. */\n  ruleMembership(args: { rule_id: Uuid; record_id: Uuid }): Promise<RecordsResult<unknown>>;\n  /** Run a stored Rule against a document. */\n  ruleRun(args: { rule_id: Uuid; values: Record<string, unknown>; context?: Record<string, unknown> }): Promise<RecordsResult<unknown>>;\n  /** Evaluate a Rule expression that has not been stored — the conditional logic a form runner asks about. */\n  ruleEval(args: { expr: unknown; values: Record<string, unknown>; context?: Record<string, unknown> }): Promise<RecordsResult<unknown>>;\n  /**\n   * Write ONE Rule as a real Rule. `recordWrite` into the Rule kernel makes a\n   * valid Rule document that carries `data_class = 'record'`, and every reader\n   * that looks for a Rule looks for the class — `custom.agg_subscriptions`\n   * selects `where data_class = 'rule'` — so a subscription written that way\n   * fires at nobody. This is the door that closes it.\n   */\n  // ── Forms: a form is a VIEW ON A REAL TABLE (SCR-13, PRODUCTS row 1) ──────\n  /** This organization's forms, with how many answers arrived and how many are in the table. */\n  forms(args?: { table_id?: Uuid | null }): Promise<RecordsResult<FormSummary[]>>;\n  /**\n   * THIS ORGANIZATION'S BOOKING PAGES (PRODUCTS row 14), with the numbers that make\n   * the list worth opening: how many are booked, canceled, still ahead, and how many\n   * slots somebody is holding right now. A booking page is an `anon_form`, so it is\n   * opened and closed with `anonPublish` exactly as a form is.\n   */\n  bookings(args?: { table_id?: Uuid | null }): Promise<RecordsResult<BookingSummary[]>>;\n  /**\n   * CREATE OR RE-STATE ONE BOOKING PAGE over one Table. `admin` on the Table,\n   * because a booking page decides what a stranger may write into it and which\n   * hours of the organization's week are on offer.\n   *\n   * `slot`, `status` and `booked_with` are the store's to fill in: a question\n   * naming any of the three is refused BY NAME, so a page cannot be built that\n   * lets a visitor choose their own status. It does NOT publish — `anonPublish`\n   * is the one act that opens a public surface, for a booking page exactly as\n   * for a form.\n   *\n   * Until 2026-09-21 this door had no client method, so the ONLY way to a\n   * booking page was to ask an agent for one. The agent path is the faster one,\n   * never the only one.\n   */\n  bookingDeclare(args: {\n    table_id: Uuid;\n    title: string;\n    questions: unknown[];\n    availability?: Partial<BookingAvailability> | null;\n    presentation?: Record<string, unknown> | null;\n    submission_cap?: number | null;\n    quarantine_rule_id?: Uuid | null;\n    notify_rule_id?: Uuid | null;\n    form_id?: Uuid | null;\n    slug?: string | null;\n    home_id?: Uuid | null;\n  }): Promise<RecordsResult<BookingDeclared>>;\n  /** Create or re-state one form. A question naming no Field of that Table is refused BY NAME. */\n  formDeclare(args: {\n    table_id: Uuid;\n    title: string;\n    questions: unknown[];\n    presentation?: Record<string, unknown> | null;\n    submission_cap?: number | null;\n    quarantine_rule_id?: Uuid | null;\n    notify_rule_id?: Uuid | null;\n    form_id?: Uuid | null;\n    slug?: string | null;\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * WHICH OF A FORM'S QUESTIONS ARE ASKED, given the answers so far — for the OWNER's preview of\n   * a draft (`custom.form_preview_asks`). One row per question in order; `asked` is false only\n   * when the store's own Rule said so. Undecided and unworkable conditions are asked, the second\n   * with the store's sentence in `said`.\n   */\n  formPreviewAsks(args: {\n    table_id: Uuid;\n    questions: unknown[];\n    values: Record<string, unknown>;\n  }): Promise<RecordsResult<Array<{ field_key: string; asked: boolean; decided: boolean; said: string | null }>>>;\n  /**\n   * WHAT A FORM'S LOOK MAY BE, AND WHAT IT WOULD LOOK LIKE (`custom.form_look_options`): the\n   * organization's public pictures (the same list a portal's look offers), the colors, and the\n   * look a stranger would see for the draft `presentation` — the builder's preview draws that.\n   */\n  formLookOptions(args?: { presentation?: Record<string, unknown> | null }): Promise<RecordsResult<FormLookOptions>>;\n  /**\n   * THE ROUTE THROUGH A DRAFT FORM (`custom.form_preview_route`, lane TYPEFORM-DUP): which questions\n   * are asked given the answers so far (showIf AND logic jumps), the ending reached and the score —\n   * the store's walk, the one the stranger's page and `custom.form_submit` read too.\n   */\n  formPreviewRoute(args: {\n    table_id: Uuid;\n    questions: unknown[];\n    endings?: unknown[] | null;\n    values: Record<string, unknown>;\n  }): Promise<RecordsResult<FormRoute>>;\n  /** A form's results (`custom.form_results`): views, starts, completions, drop-off, answers. */\n  formResults(args: { form_id: Uuid }): Promise<RecordsResult<FormResults>>;\n  /** TYPEFORM-2: the organization's form knobs (`custom.form_knobs`): owner header, choice auto-advance. */\n  formKnobs(): Promise<RecordsResult<{ show_owner_header: boolean; choice_auto_advance: boolean }>>;\n  /**\n   * CD-PAGE-08: a public form's password (`custom.form_set_password`). A string of 4 to 128 characters sets it,\n   * `\"\"` clears it, `null` changes nothing; every call answers whether the form has one now.\n   */\n  formSetPassword(args: { form_id: Uuid; password: string | null }): Promise<RecordsResult<{ has_password: boolean }>>;\n\n  // ── PULLING A SPREADSHEET IN (PRODUCTS row 9) ────────────────────────────\n  // The BYTES are parsed here (`importCsv` / `importXlsx` in `core/io.ts`,\n  // because Postgres cannot unzip a workbook). EVERYTHING after the parse is\n  // the store's: the mapping, the type inference, the coercion of `$1,250.00`\n  // into money and of an email into the person it belongs to, the duplicate\n  // check, the provenance and the per-row outcome. There is no second importer\n  // in this package and there is no place for one to drift to.\n  /**\n   * What the store makes of a file's columns, before anything is written.\n   * `columns` is `[{header, samples}]` — the first page of the file is plenty.\n   */\n  importPlan(args: {\n    table_id: Uuid;\n    columns: Array<{ header: string; samples: unknown[] }>;\n  }): Promise<RecordsResult<ImportPlan>>;\n  /**\n   * Open a run. `file_hash` is the run's IDENTITY: the same bytes into the same\n   * table a second time answer the FIRST run with `already: true` and write\n   * nothing, so a re-import doubles nothing. `force` re-opens deliberately.\n   */\n  importBegin(args: {\n    table_id: Uuid;\n    format?: \"csv\" | \"xlsx\";\n    source_name?: string | null;\n    source_columns?: unknown[];\n    file_hash?: string | null;\n    policy?: ImportPolicy;\n    /** A Field key. A row whose value for it is already here is a duplicate. */\n    dedupe_key?: string | null;\n    file_bytes?: number | null;\n    force?: boolean;\n  }): Promise<RecordsResult<ImportOpened>>;\n  /**\n   * IMPORT-2. ADD THE COLUMNS THIS FILE HAS AND THIS TABLE HAS NOT — a step of\n   * its own, BEFORE the run is opened, so the screen can show \"8 columns added\"\n   * and the person can then name one of them as the file's duplicate key\n   * (`importBegin` refuses a key naming a column that does not exist yet).\n   * Answers the mapping the file should be sent with. Admin on the Table.\n   */\n  importDeclareColumns(args: {\n    table_id: Uuid;\n    rows: Array<Record<string, unknown>>;\n    /** Header -> Field key the person already mapped by hand; never declared. */\n    mapping?: Record<string, string>;\n  }): Promise<RecordsResult<ImportColumnsDeclared>>;\n  /**\n   * One BATCH of rows. The batch is PLANNED and then written as ONE statement\n   * through the batched write door, so 250 round trips became one; a batch a\n   * guard refuses falls back to one write a row, and the answer says which it\n   * was. Send `ImportOpened.rows_per_call` the first time and\n   * `ImportBatchResult.rows_per_call` — measured — every time after that.\n   */\n  importRows(args: {\n    import_id: Uuid;\n    rows: Array<Record<string, unknown>>;\n    /** Header -> Field key. A header that already spells a key needs no entry. */\n    mapping?: Record<string, string>;\n  }): Promise<RecordsResult<ImportBatchResult>>;\n  /**\n   * Close the run and decide the columns the file had and the table did not:\n   * `propose` (the ONE approvals inbox, and the only choice a non-admin has),\n   * `create` (an admin adds them outright) or `ignore`.\n   */\n  importFinish(args: {\n    import_id: Uuid;\n    unmapped?: \"propose\" | \"create\" | \"ignore\";\n  }): Promise<RecordsResult<ImportFinished>>;\n  /** The refused rows, or the ones already here, WITH the source row on each. */\n  importReport(args: {\n    import_id: Uuid;\n    state?: \"refused\" | \"duplicate\";\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<ImportReport>>;\n  /** This organization's import runs, newest first. How you find yesterday's. */\n  imports(args?: { table_id?: Uuid | null; limit?: number }): Promise<RecordsResult<ImportRun[]>>;\n  /**\n   * Forget the RECEIPT for a file so the same bytes can be imported again\n   * deliberately. Never touches the records that import wrote.\n   */\n  importForget(args: { import_id: Uuid }): Promise<RecordsResult<boolean>>;\n\n  // ── THE ADDRESS A TABLE OWNS (DOOR-19, P8) ───────────────────────────────\n  /**\n   * Give a table its own address. The answer carries `mail_route`: the one\n   * sentence saying what has to exist in DNS before anything arrives. Show it\n   * wherever the address is shown — an address that silently swallows mail is\n   * the failure this whole door is against.\n   */\n  inboundDeclare(args: { table_id: Uuid; label?: string | null }): Promise<RecordsResult<InboundDeclared>>;\n  inboundAddresses(args?: { table_id?: Uuid | null }): Promise<RecordsResult<InboundAddress[]>>;\n  inboundSet(args: { inbound_id: Uuid; enabled: boolean }): Promise<RecordsResult<{ inbound_id: Uuid; address: string; enabled: boolean; message: string }>>;\n\n  // ── Portals: the OWNER's side of the client portal (VIS-31 / PORTAL) ──────\n  /** Every portal over this organization the caller may know about, with its numbers. */\n  portals(): Promise<RecordsResult<PortalSummary[]>>;\n  /**\n   * The SAME list, archive-aware. `custom.portals` keeps its signature and hides\n   * archived portals, because the archived-items law's default is to hide;\n   * this is the one door that also answers the other lane, so a rail gets the\n   * law's one-click reveal without inventing a second control or a second door.\n   * A fourth word is refused `22023` — there is no fourth answer on any surface.\n   */\n  listPortals(args?: { archived?: PortalArchiveFilter }): Promise<RecordsResult<PortalSummary[]>>;\n  /**\n   * PUT ONE PORTAL AWAY. Nothing is deleted and there is no purge: every Table\n   * it exposes and every person invited to it is kept exactly as it is, and\n   * `portalRestore` hands it all back. `confirm_title` is the portal's own title\n   * typed back — ten portals can carry one title, so the title is not what picks\n   * this one and the door refuses `23514` when it does not match.\n   */\n  portalArchive(args: {\n    portal_id: Uuid;\n    confirm_title: string;\n    reason?: string | null;\n  }): Promise<RecordsResult<PortalArchiveAnswer>>;\n  /** The way back. Everyone invited signs in exactly as before, and it shows the same Tables. */\n  portalRestore(args: {\n    portal_id: Uuid;\n    confirm_title: string;\n  }): Promise<RecordsResult<PortalArchiveAnswer>>;\n  /**\n   * PUT ONE FORM OR BOOKING PAGE AWAY (`custom.form_archive`, admin on its table). Its address stops\n   * answering; everything it collected is kept. `formRestore` brings it back.\n   */\n  formArchive(args: { form_id: Uuid }): Promise<RecordsResult<FormArchiveAnswer>>;\n  formRestore(args: { form_id: Uuid }): Promise<RecordsResult<FormArchiveAnswer>>;\n  /** The archived forms and booking pages, newest first; `table_id` narrows to one table. */\n  formsArchived(args?: { table_id?: Uuid | null; limit?: number }): Promise<RecordsResult<ArchivedForm[]>>;\n  /**\n   * The archived checklist templates. A template is a record: `recordDelete` archives it and\n   * `recordRestore` brings it back.\n   */\n  checklistTemplatesArchived(args?: {\n    about_table_id?: Uuid | null;\n    limit?: number;\n  }): Promise<RecordsResult<ArchivedChecklistTemplate[]>>;\n  /**\n   * How a table names its records: the row-label FORMULA it keeps (`{First} & \" \" & {Last}`), the title\n   * column it falls back to, which is in force, and whether the caller may change it. Writes nothing.\n   */\n  tableRowLabel(args: { table_id: Uuid }): Promise<RecordsResult<TableRowLabel>>;\n  /**\n   * Set the table's row-label formula, or clear it (null / blank). The store parses it against the table's\n   * own columns and refuses an unknown column in a sentence, writing nothing. Answers the new state.\n   */\n  tableRowLabelSet(args: { table_id: Uuid; formula: string | null }): Promise<RecordsResult<TableRowLabel>>;\n  /** What a table's NEW rows start with (Shown to, and the web half once it lands). */\n  tableRowDefaults(args: { table_id: Uuid }): Promise<RecordsResult<TableRowDefaults>>;\n  /** Set them (the table's maker or an admin of it). A key left out is left alone; null = the default. */\n  tableRowDefaultsSet(args: { table_id: Uuid; defaults: TableRowDefaultsPatch }): Promise<RecordsResult<TableRowDefaults>>;\n  /**\n   * ONE PASS of \"apply to existing rows\": rows nobody set by hand follow the table's defaults.\n   * `done: false` → call again with `after: next_after`. `rowDefaultsApplyAll` walks every pass.\n   */\n  tableRowDefaultsApply(args: { table_id: Uuid; after?: Uuid | null }): Promise<RecordsResult<RowDefaultsApplied>>;\n  /** Every pass of `tableRowDefaultsApply`, summed; the last pass's sentence when it took one pass. */\n  rowDefaultsApplyAll(args: { table_id: Uuid; maxPasses?: number }): Promise<RecordsResult<RowDefaultsApplied>>;\n  /** One row's Shown to (and web half), with who may change it. */\n  recordRowControls(args: { record_id: Uuid }): Promise<RecordsResult<RecordRowControls>>;\n  recordRowControlsSet(args: {\n    record_id: Uuid;\n    controls: { shown_to?: string | null; published_to_web?: boolean; indexed?: boolean | null };\n  }): Promise<RecordsResult<RecordRowControls>>;\n  /**\n   * Which Tables each portal of this organization exposes.\n   *\n   * The one question a TABLE-scoped Portals rail has to ask: \"is the table I\n   * am standing on in any portal?\" Same wall and same read-access gate as\n   * `portals`, so a pair here is always a portal `portals` also returned.\n   */\n  portalTables(): Promise<RecordsResult<PortalTableRef[]>>;\n  /** ONE portal in full: what it shows, and who it was opened to. */\n  portalCard(args: { portal_id: Uuid }): Promise<RecordsResult<PortalCard>>;\n  /**\n   * Create or RE-STATE one portal. Re-stating REPLACES what it exposes — a\n   * Table left out of `tables` stops being exposed in the same act — and leaves\n   * the people alone: who is invited is not part of what the portal shows.\n   */\n  portalDeclare(args: {\n    title: string;\n    client_table_id: Uuid;\n    tables: Array<{\n      table_id: Uuid;\n      names_via: string;\n      visible_fields?: string[];\n      editable_fields?: string[];\n      comments?: boolean;\n    }>;\n    portal_id?: Uuid | null;\n    slug?: string | null;\n    sign_in_method?: string | null;\n    /**\n     * S6 — the portal's own look and its forms. A key given REPLACES that key; a key not given\n     * is KEPT (leave `config` out and both stay exactly as they are). The store judges it and\n     * refuses by name: a logo that is not a public picture of this organization's Files, an\n     * accent that is not a design-system color name, a form whose Table the portal does not show.\n     */\n    config?: PortalConfigInput | null;\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * S6 — THE CLIENT'S SIDE: one form of HER portal (`custom.portal_form`). Refused unless the\n   * caller is a live principal of that live portal and the form is on its list; the Field that\n   * names the client is never one of the questions — the portal fills it.\n   */\n  portalForm(args: { portal_id: Uuid; form_id: Uuid }): Promise<RecordsResult<PortalFormSpec>>;\n  /**\n   * S6 — send one form of her portal (`custom.portal_form_submit`). The store fills the Field\n   * that names the client with her own record, and the answer reaches her own list at once\n   * (`accepted`) or waits for the office (`held`, with the store's sentence). `client_key`\n   * makes a retry the same submission.\n   */\n  portalFormSubmit(args: {\n    portal_id: Uuid;\n    form_id: Uuid;\n    answers: Record<string, unknown>;\n    client_key?: string | null;\n  }): Promise<RecordsResult<PortalFormAnswer>>;\n  /**\n   * Invite one person, as one record of the portal's client Table.\n   *\n   * `user_id` is deliberately NOT a parameter here. From a screen it is always\n   * null: an invitation confers NOTHING until the person follows their sign-in\n   * link and the platform gives them an identity, and the door's own `say`\n   * sentence states exactly that. A screen that passed an id would be granting\n   * access on somebody else's behalf.\n   */\n  portalInvite(args: {\n    portal_id: Uuid;\n    client_record_id: Uuid;\n    email: string;\n  }): Promise<RecordsResult<PortalInvitation>>;\n  /** Take one person's way in away. The answer's `say` names the consequence. */\n  portalRevoke(args: { portal_id: Uuid; principal_id: Uuid }): Promise<RecordsResult<PortalRevocation>>;\n  /**\n   * VIEW AS THIS CLIENT. The door asks `custom.visible_set` for HER user id —\n   * the same call `custom.read_records` makes when she opens the page — so this\n   * cannot disagree with what she sees. It REFUSES with `02000` and a sentence\n   * when she has not signed in yet; show the sentence, never an empty list.\n   */\n  portalPreview(args: {\n    portal_id: Uuid;\n    principal_id: Uuid;\n    table_id: Uuid;\n  }): Promise<RecordsResult<PortalPreviewRow[]>>;\n\n  // ── dashboards (SCR-16): saved blocks, run under the caller's principal ──\n  /** This organization's dashboards, optionally only those whose subject is one Table. */\n  dashboards(args?: { table_id?: Uuid | null }): Promise<RecordsResult<DashboardSummary[]>>;\n  /**\n   * AT-INTERFACE — one Interface as this viewer may see it (no organization needed: a share of the\n   * interface record is the way in). `null` = not there, archived, or not shared with her.\n   */\n  interfaceRead(args: { interface_id: Uuid }): Promise<RecordsResult<InterfaceRead | null>>;\n  /** The rows one PUBLISHED element of an Interface exposes (a builder may name a draft one). */\n  interfaceRows(args: {\n    interface_id: Uuid;\n    element_id: string;\n    record_id?: Uuid | null;\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<InterfaceRows | null>>;\n  /**\n   * AT-FIX-G1b — one PUBLISHED chart of an Interface as its reader may see it, in the shape one block of\n   * `dashboardRun` answers (the same chart draws from it). The groups and measures are worked out by the store\n   * over the rows her interface access shows and only through the columns the interface door exposes; a chart\n   * that reads any other column answers `refused` (naming none). `null` = not there, archived, or not shared with her.\n   */\n  interfaceChart(args: { interface_id: Uuid; chart_id: string }): Promise<RecordsResult<DashboardBlockResult | null>>;\n  /**\n   * Create or re-state one dashboard. Every block is judged on the way IN —\n   * a block naming a field this Table does not have is refused BY NAME, with\n   * the table's own field list in the hint — so a canvas cannot be saved broken.\n   */\n  dashboardDeclare(args: {\n    table_id: Uuid;\n    name: string;\n    blocks?: DashboardBlock[];\n    presentation?: Record<string, unknown> | null;\n    dashboard_id?: Uuid | null;\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * Run every block and answer the numbers. `filter` is the ONE filter bar\n   * across the canvas: it is merged UNDER each block's own filter, so a block\n   * deliberately scoped to one stage stays scoped while the bar moves the rest.\n   * A block that refuses carries the store's sentence and the others still answer.\n   */\n  dashboardRun(args: {\n    dashboard_id: Uuid;\n    filter?: RecordFilter;\n    /**\n     * S3 — compare every block that does not carry its own comparison (the\n     * block's own wins, as its own filter does). A block with no date to\n     * compare along answers alone and says so in `compare_refused`.\n     */\n    compare?: AggregateCompare | null;\n    /** S3 — re-cut every bucketed block to one date grain (the canvas's picker). */\n    grain?: AggregateBucket | null;\n  }): Promise<RecordsResult<DashboardRunResult>>;\n  /** The seventh block kind on its own: records that have sat on the same value too long. */\n  dashboardStuck(args: {\n    table_id: Uuid;\n    state_key: string;\n    days?: number;\n    filter?: RecordFilter;\n    limit?: number;\n  }): Promise<RecordsResult<StuckRow[]>>;\n  // ── a crew, a phone and no signal (PRODUCTS row 15 / SCR-30) ─────────────\n  /**\n   * Declare or re-state a crew capture sheet over a Table. Admin on the Table.\n   * Closed to the crew until `capturePublish`, like every publishing act here.\n   */\n  captureSheetDeclare(args: {\n    table_id: Uuid;\n    title: string;\n    questions: Array<Record<string, unknown>>;\n    presentation?: Record<string, unknown> | null;\n    sheet_id?: Uuid | null;\n    notify_rule_id?: Uuid | null;\n  }): Promise<RecordsResult<Uuid>>;\n  /** Open the sheet to the crew, or close it. Admin on the Table. */\n  capturePublish(args: { sheet_id: Uuid; open?: boolean }): Promise<RecordsResult<string | null>>;\n  /** The crew sheets of this organization, with what has come in through each. */\n  captureSheets(args?: { table_id?: Uuid | null }): Promise<RecordsResult<CaptureSheetSummary[]>>;\n  /**\n   * Everything a phone needs to run one sheet OFFLINE — the questions, the Fields\n   * with their ids and parity types, and an honest `may_capture` with a sentence.\n   * Load it once on a signal; it is the last network call before the walk.\n   */\n  captureOpen(args: { sheet_id: Uuid }): Promise<RecordsResult<CaptureSheetFace | null>>;\n  /**\n   * One capture: the answers, the file references, the device, the moment the phone\n   * took it and the place. Idempotent on `client_key`, which the PHONE mints when\n   * the capture is taken, offline, before its first attempt — send the same key on\n   * every retry and the answer comes back `replay: true` with the first record's id.\n   */\n  captureSubmit(args: {\n    sheet_id: Uuid;\n    client_key: string;\n    answers: Record<string, unknown>;\n    files?: CaptureFileRef[];\n    device?: string | null;\n    captured_at?: string | null;\n    location?: Record<string, unknown> | null;\n  }): Promise<RecordsResult<CaptureOutcome | null>>;\n\n  // ── a column a model owns (PRODUCTS row 10 / AGT-6) ──────────────────────\n  /** Every agent-owned column, with how many cells are filled, stale or pinned, and what it has cost. */\n  enrichments(args?: { table_id?: Uuid | null }): Promise<RecordsResult<EnrichmentSummary[]>>;\n  /**\n   * Define, change or TURN ON an Enrichment on one Field. Admin on the Table.\n   * `{enabled: true}` on its own turns an existing one on without resetting it —\n   * and turning it on is what authorises every value it writes afterwards.\n   */\n  enrichDeclare(args: {\n    field_id: Uuid;\n    spec: Record<string, unknown>;\n  }): Promise<RecordsResult<EnrichDeclared>>;\n  /**\n   * The rows that need this column filled in, each with what the instruction may\n   * read. A cell somebody pinned is never returned. This is what a PREVIEW shows\n   * before anybody enables anything.\n   */\n  enrichDue(args: {\n    field_id: Uuid;\n    limit?: number;\n    include_fresh?: boolean;\n  }): Promise<RecordsResult<EnrichDueRow[]>>;\n  /**\n   * THE BADGE DATA FOR A WHOLE PAGE, in one call. Who wrote each value, when, out\n   * of what source, its candidates, whether a person pinned it and whether it is\n   * past its freshness date. Asked per cell this would be one round trip per badge.\n   */\n  enrichCells(args: {\n    table_id: Uuid;\n    field_keys?: string[] | null;\n    record_ids?: Uuid[] | null;\n  }): Promise<RecordsResult<EnrichCell[]>>;\n  /** Hold one cell against the model that fills its column, or hand it back. */\n  enrichPin(args: {\n    record_id: Uuid;\n    field_key: string;\n    pinned?: boolean;\n  }): Promise<RecordsResult<{ pinned: boolean; says: string }>>;\n  /** What this column has cost, run by run. */\n  enrichRuns(args?: { field_id?: Uuid | null; limit?: number }): Promise<RecordsResult<EnrichRun[]>>;\n  /** Take a dashboard away. The records it counted are untouched — a canvas owns nothing. */\n  dashboardDelete(args: { dashboard_id: Uuid }): Promise<RecordsResult<boolean>>;\n\n  // ── the eighth verb (AGT-N-8): the aggregate, computed in the read door ──\n  /**\n   * Group, bucket, filter and measure INSIDE `custom.record_aggregate`. The\n   * aggregate node sits above the read-access join, so what a chart draws is\n   * exactly what this person may see — the rest is never fetched, let alone\n   * summed and then hidden.\n   */\n  recordAggregate(args: {\n    table_id: Uuid;\n    /**\n     * OPTIONAL FILTER (active-org law): with `config.organizationIds` set, the table is looked\n     * up across all the person's organizations and the aggregate runs in the one that OWNS it\n     * (each row then carries that `organization_id`); this narrows the lookup to one. Absent and\n     * no `organizationIds` ⇒ this client's own organization, exactly as before.\n     */\n    organization_id?: Uuid | null;\n    /** Field keys whose values become the groups. */\n    groupBy?: string[];\n    /** `count` needs no key; every other operation reads one Field. */\n    measures?: AggregateMeasure[];\n    /** A date Field truncated to a period — a group whose expression is a date_trunc. */\n    bucket?: { key: string; by: AggregateBucket } | null;\n    /**\n     * A scalar is an equality and an object is a half-open moment window, and\n     * either way it lands in the SAME WHERE as read access.\n     */\n    filter?: StoreFilter;\n    limit?: number;\n    /**\n     * S3 — answer the same question over a prior window too (previous period,\n     * same period last year, or a fixed baseline). Each row then carries\n     * `prior_measures`, `delta` and the two `compare` windows. Buckets are cut\n     * in the organization's calendar (knobs `custom/time_zone`, `custom/week_start`).\n     */\n    compare?: AggregateCompare | null;\n    /**\n     * The grid's search, narrowing the answer to the rows `listPage`'s search would show (the\n     * same predicate, `custom.record_search_sql`). Blank or absent: nothing changes.\n     */\n    search?: string | null;\n    /** The reader's time zone for the search's date matches (absent = the organization's calendar). */\n    time_zone?: string | null;\n    /**\n     * A CHART counts each part of a many-value column under its own group (a row tagged A and B counts once under A and once\n     * under B; a multi-link counts per linked record id); a grid group-by (absent / false) keeps the exact combination.\n     */\n    splitMulti?: boolean;\n  }): Promise<RecordsResult<AggregateRow[]>>;\n  /** Historical aggregate computed by the store at its recorded-time read door. */\n  recordAggregateAsOf(args: {\n    table_id: Uuid;\n    recorded_at: string;\n    measure?: string;\n    field_key?: string | null;\n    group_by?: string | null;\n    match?: Record<string, unknown>;\n  }): Promise<RecordsResult<Array<{\n    bucket: string | null;\n    result: number | null;\n    row_count: number;\n    not_numbers: number;\n    a_non_number: string | null;\n  }>>>;\n  /** The measures the store itself offers. Asked, never hardcoded in a picker. */\n  aggOperations(): Promise<RecordsResult<string[]>>;\n  /** The periods the store itself buckets by. */\n  aggBuckets(): Promise<RecordsResult<string[]>>;\n  /**\n   * The organization's calendar (knobs `custom/time_zone`, `custom/week_start`), cut by the SAME door the\n   * relative date filters and the chart buckets use. A calendar or timeline reads its first day of the week\n   * from here, never from a constant of its own (lane NOTION-SMALL-4).\n   */\n  aggCalendar(): Promise<RecordsResult<{ time_zone: string; week_start: string }>>;\n\n  // ── THE ONE READ CONTRACT (lane DRILL-STANDARD-DOOR): any source, one answer shape ──\n  /**\n   * A source's drill definition — its Dimensions, Measures, drill paths and first screen.\n   * `{kind: \"table\", id}` is a custom Table; `{kind: \"entity\", token}` a standard table by its\n   * registry token or a declared definition by its key.\n   */\n  drillDescribe(args: { source: DrillSource }): Promise<RecordsResult<DrillDefinition>>;\n  /**\n   * Ask a source a question: grouped, bucketed (day…year in the organization's calendar),\n   * compared, pivoted. A standard table is counted AS THE PERSON (its own row security decides\n   * every row); groups past the cap fold into one Other row and the total row says so.\n   */\n  drillAsk(args: { source: DrillSource; question?: DrillQuestion }): Promise<RecordsResult<DrillAnswer>>;\n  /** The records behind a number, through the same filter, read as the person. */\n  drillRows(args: {\n    source: DrillSource;\n    where?: DrillQuestion[\"where\"];\n    window?: DrillQuestion[\"window\"];\n    sort?: DrillQuestion[\"sort\"];\n    lane?: DrillQuestion[\"lane\"];\n    columns?: string[];\n    limit?: number;\n    offset?: number;\n    /** The viewer's search term, asked of the door (`platform._drill_compile` reads `question.search`). */\n    search?: string;\n  }): Promise<RecordsResult<DrillRowsPage>>;\n\n  // ── subscriptions (DOOR-18): a Rule record over a saved view ─────────────\n  /**\n   * Every subscription in this organization, optionally narrowed to one saved\n   * view or one cadence. There is no subscription table: each one is a Rule\n   * record carrying a `subscription` block, so a subscription is readable,\n   * historied and agent-writable like anything else.\n   */\n  aggSubscriptions(args?: {\n    saved_view_id?: Uuid | null;\n    cadence?: string | null;\n  }): Promise<RecordsResult<Subscription[]>>;\n  /** The cadences the store itself offers. Asked, never hardcoded in a picker. */\n  aggSubscriptionCadences(): Promise<RecordsResult<string[]>>;\n  /**\n   * The same cadences, through the door a PERSON may call.\n   * `aggSubscriptionCadences` is the notifier's own and holds no client grant,\n   * so a screen that asked for it was refused and fell back to a list typed\n   * into the picker — which drifts from what the digest runner honors. This\n   * one delegates to the same array, so there is exactly one list.\n   */\n  subscriptionCadences(): Promise<RecordsResult<string[]>>;\n  /**\n   * WHAT THIS PERSON IS BEING TOLD ABOUT, and what they may switch off.\n   *\n   * Mine, plus anyone's over a Table I hold admin on — narrowed to Tables I can\n   * already open, so the list never reveals one. `aggSubscriptions` above is the\n   * NOTIFIER's reader and no client can call it; this is the owner's.\n   */\n  subscriptions(args?: { table_id?: Uuid | null }): Promise<RecordsResult<MySubscription[]>>;\n  /**\n   * Switch one on or off. Muting is honored in ONE place — the reader every\n   * consumer goes through — so a screen can never say a subscription is off\n   * while it keeps firing.\n   */\n  subscriptionMute(args: { rule_id: Uuid; muted: boolean }): Promise<RecordsResult<boolean>>;\n  /**\n   * WRITE ONE. The store refuses a cadence no runner acts on, a channel this\n   * platform does not send on and quiet hours nobody can parse — by name — then\n   * declares the Rule through `rule_declare`, because a Rule written as a record\n   * carries `data_class = 'record'` and every reader that goes looking for a Rule\n   * steps straight past it (REC-72).\n   */\n  subscriptionDeclare(args: {\n    table_id: Uuid;\n    spec: SubscriptionSpec;\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * SHOW ME ONE NOW. The summary this subscription would send at this moment, with\n   * what entered, left and changed NAMED. It assembles only: nothing is delivered,\n   * nothing is recorded and the watermark does not move.\n   */\n  subscriptionPreview(args: { rule_id: Uuid }): Promise<RecordsResult<DigestPreview>>;\n  /**\n   * THE SAVED VIEWS OF A TABLE — what a subscription may be written over. Narrowed\n   * in SQL as the definer to Tables this caller can already open, so the list can\n   * never reveal a Table.\n   */\n  views(args?: { table_id?: Uuid | null }): Promise<RecordsResult<SavedViewRow[]>>;\n  /**\n   * SAVE ONE VIEW. VIEWER on the Table, not editor: writing down a question about a\n   * Table is not changing it, and requiring editor would mean the people who read a\n   * Table could not subscribe to anything in it.\n   */\n  viewDeclare(args: { table_id: Uuid; spec: SavedViewSpecIn }): Promise<RecordsResult<Uuid>>;\n  /** A Table's row templates (\"New from template\"). VIEWER on the Table. */\n  rowTemplates(args: { table_id: Uuid }): Promise<RecordsResult<RowTemplateRow[]>>;\n  /**\n   * SAVE ONE ROW TEMPLATE — `{name, values}` by Field key; the same name again changes it, and\n   * `{template_id, archived: true}` archives it. EDITOR on the Table: it is how everyone's new rows start.\n   */\n  rowTemplateDeclare(args: {\n    table_id: Uuid;\n    spec: { name?: string; values?: Record<string, unknown>; template_id?: Uuid; archived?: boolean };\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * DESIGNATE HOW A TABLE OPENS — \"Make this the default\". EDITOR on the Table: the named view\n   * becomes the table's only default and, when `layout` is given, that is the layout everyone opens\n   * it in. A layout press never designates (`viewDeclare` refuses the default view's layout and\n   * is_default by name — VIEW-SWITCH-NOT-DESIGNATION, VERIFIER-21).\n   */\n  viewDesignate(args: { table_id: Uuid; view_id: Uuid; layout?: string | null }): Promise<RecordsResult<Uuid>>;\n  /**\n   * ARCHIVE ONE SAVED VIEW (lane TABLE-ACTIONS, T3.5). The soft delete of the `platform.saved_view`\n   * row behind it — `platform.saved_view_archive('custom/records', id)`, which asks its own ladder\n   * (the view's creator, or admin on the view) and clears a default it held. The records are\n   * untouched. `null` when the view was already gone. `viewRestore` (or Trash) brings it back.\n   */\n  viewArchive(args: { view_id: Uuid }): Promise<RecordsResult<Record<string, unknown> | null>>;\n  /** PUT AN ARCHIVED VIEW BACK — the platform's one restore door, `platform.entity_undelete('platform_saved_view', id)`. */\n  viewRestore(args: { view_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /**\n   * THE CALLER'S OWN LOOK AT EACH SAVED VIEW OF A TABLE — `{ \"<view id>\": { look, updated_at } }`.\n   * A look is the view settings one person chose while looking (a board's grouping, a calendar's\n   * date field, a sort, a filter, hidden columns, widths, the layout), kept for her alone until an\n   * editor saves it onto the view with `viewDeclare` (\"Save to view\"). Viewer on the Table.\n   */\n  viewLookRead(args: { table_id: Uuid }): Promise<RecordsResult<Record<string, { look: Record<string, unknown>; updated_at: string }>>>;\n  /**\n   * KEEP THE CALLER'S OWN LOOK AT ONE VIEW — the whole look, as definition keys (`group_field`,\n   * `date_field`, `sorts`, `where`, `presentation`, `layout`, …; a key set to null hides the view's\n   * own). `look: null` is \"Reset to view\". The shared view row is never written. Answers the look\n   * as kept (null after a reset).\n   */\n  viewLookSet(args: { table_id: Uuid; view_id: Uuid; look: Record<string, unknown> | null }): Promise<RecordsResult<Record<string, unknown> | null>>;\n\n  // ── documents (W3-DOC): save, render once, sign the exact bytes ──────────\n  docTemplateSave(args: {\n    table_id: Uuid;\n    name: string;\n    body: string;\n    template_id?: Uuid | null;\n  }): Promise<RecordsResult<Uuid>>;\n  /** The body with every token resolved against one record. Read-only, no render row. */\n  docRenderBody(args: { template_id: Uuid; record_id: Uuid }): Promise<RecordsResult<string>>;\n  /** Write the render — frozen bytes a signature can be checked against. */\n  docRenderDocument(args: { template_id: Uuid; record_id: Uuid }): Promise<RecordsResult<Uuid>>;\n  /** Every token in a body, in order, with the Field id each one points at. */\n  docTokens(args: { body: string }): Promise<RecordsResult<DocToken[]>>;\n  /** The tokens this Table cannot answer, each with the store's own reason. */\n  docUnresolvedTokens(args: { table_id: Uuid; body: string }): Promise<RecordsResult<DocUnresolvedToken[]>>;\n  docSign(args: {\n    render_id: Uuid;\n    field_key: string;\n    signer_name: string;\n    signer_user_id?: Uuid | null;\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * One signature: the seal AND whether what was signed is still what is there.\n   * The store answers both, in one call, never the screen. Viewer on the record.\n   */\n  docSignatureRead(args: { signature_id: Uuid }): Promise<RecordsResult<unknown>>;\n  /** Every template that renders one Table. Viewer on the Table. */\n  docTemplates(args: { table_id: Uuid }): Promise<RecordsResult<DocTemplateRow[]>>;\n  /**\n   * Retire one template. EDITOR on the Table it renders, because a template is\n   * that Table's wording. Documents already rendered keep their frozen bytes\n   * and their seals, so this can never invalidate a signature.\n   */\n  docTemplateDelete(args: { template_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /** Bring back a removed template (the undo of docTemplateDelete, same rung). */\n  docTemplateRestore(args: { template_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /**\n   * Remove one saved document (soft). EDITOR on its record. Its bytes, hash and\n   * any signature stay exactly as they were; docRenderRestore brings it back.\n   */\n  docRenderDelete(args: { render_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /** The undo of docRenderDelete, same rung. */\n  docRenderRestore(args: { render_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /** Every frozen render of one record, newest first. Viewer on the record. */\n  docRenders(args: { record_id: Uuid }): Promise<RecordsResult<DocRenderRow[]>>;\n  /** Every signature on one record. Viewer on the record. */\n  docSignatures(args: { record_id: Uuid }): Promise<RecordsResult<DocSignatureRow[]>>;\n  /**\n   * DOOR-11. One record's revisions, newest first. The read door answers\n   * documents and deliberately not versions, so a screen that wants to save\n   * optimistically reads the version of the record it LOADED from here — for\n   * the one record being edited, never for a list.\n   */\n  revisions(args: { record_id: Uuid }): Promise<RecordsResult<RecordRevision[]>>;\n  /**\n   * PRODUCTS row 4. One record's version list, newest first: who (a person, or\n   * an agent AND the person it acted for), when, the operation in the word\n   * somebody used, and every field that moved with its before, its after, the\n   * Rule version that produced a derived value and its source pointer. Viewer\n   * on the record — reading how something got to be the way it is is reading.\n   */\n  recordHistory(args: {\n    record_id: Uuid;\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<RecordHistoryEntry[]>>;\n  /**\n   * AGT-N-9 — EVERYTHING A CHAT OPENED ON THIS RECORD MAY KNOW, IN ONE ROUND TRIP.\n   *\n   * The Fields with their `(record, field, value version)` triples, the relations one hop\n   * out, the history, the comments and the Table's other records — assembled INSIDE the\n   * database, every piece through the read door, under this person's own field-level\n   * security. A Field the store masks comes back in `withheld` with the store's own\n   * sentence and no value; a Field the organization keeps out of conversations comes back\n   * there too, saying which of the two it is.\n   */\n  recordScopeContext(args: {\n    record_id: Uuid;\n    relations?: number;\n    history?: number;\n    siblings?: number;\n  }): Promise<RecordsResult<RecordScopeContext>>;\n  /** What is this conversation about? */\n  conversationScope(args: { conversation_id: Uuid }): Promise<RecordsResult<ConversationScope>>;\n  /** Point a conversation at one record. Refused unless this person may open it. */\n  conversationScopeBind(args: {\n    conversation_id: Uuid;\n    record_id: Uuid;\n  }): Promise<RecordsResult<ConversationScope>>;\n  /** This conversation is no longer about a particular record. */\n  conversationScopeUnbind(args: {\n    conversation_id: Uuid;\n  }): Promise<RecordsResult<ConversationScope>>;\n  /** The binding AND the context of a bound conversation, in one round trip. */\n  conversationScopeContext(args: {\n    conversation_id: Uuid;\n    relations?: number;\n    history?: number;\n    siblings?: number;\n  }): Promise<RecordsResult<ConversationScopeContext>>;\n  /**\n   * \"Who changed the price on ANY record?\" One column's history across a whole\n   * Table, narrowed to the records this person may see by a predicate in the\n   * same statement. A column that names no Field is refused BY NAME, never\n   * answered empty.\n   */\n  fieldHistory(args: {\n    table_id: Uuid;\n    field_key: string;\n    limit?: number;\n    offset?: number;\n    record_id?: Uuid;\n  }): Promise<RecordsResult<FieldHistoryEntry[]>>;\n  /**\n   * A FORMULA, ROLLUP OR LOOKUP COLUMN'S HISTORY ON ONE RECORD (CD-FORMULA-08). Its answer at every moment it changed,\n   * worked out from the values and the formula as they were, with the formula version that produced it. A column\n   * people type into is refused by name (its history is `fieldHistory`).\n   */\n  formulaHistory(args: { record_id: Uuid; field_key: string; limit?: number }): Promise<RecordsResult<FormulaHistoryEntry[]>>;\n  /**\n   * WHAT A RESTORE WOULD CHANGE, BEFORE IT DOES. Editor on the record: this is\n   * the first half of an act, and somebody who may not perform it is not shown\n   * its preview. Pass `field_key` for one column.\n   */\n  restorePreview(args: {\n    record_id: Uuid;\n    version: number;\n    field_key?: string;\n  }): Promise<RecordsResult<RestorePreview>>;\n  /** Put the whole record back to a version, as a NEW version. Editor. */\n  restoreVersion(args: { record_id: Uuid; version: number }): Promise<RecordsResult<RestoreResult>>;\n  /** Put ONE column back to what it said at a version, as a NEW version (HIS-N-2). Editor. */\n  valueRestore(args: {\n    record_id: Uuid;\n    field_key: string;\n    version: number;\n  }): Promise<RecordsResult<RestoreResult>>;\n  /**\n   * SCR-18. The record's comment thread with everybody named, plus what THIS\n   * person may do in it — decided by the store, in the same call, so a screen\n   * never draws a composer the write door will refuse.\n   */\n  commentThread(args: {\n    record_id: Uuid;\n    include_resolved?: boolean;\n  }): Promise<RecordsResult<CommentThreadRead>>;\n  /**\n   * How many OPEN comments each named row has (up to 500 rows; rows with none are absent), read\n   * through the same reader as the thread — one call for a whole card of rows.\n   */\n  commentCounts(args: { record_ids: readonly Uuid[] }): Promise<RecordsResult<Record<string, number>>>;\n  /**\n   * Write a comment at the `commenter` rung, optionally naming people. A\n   * mention is a reference and not a regex over the body: the ids come from the\n   * picker and the store refuses one who is not in the organization, or who\n   * cannot open the record — because that notification would be a dead end.\n   */\n  commentWrite(args: {\n    record_id: Uuid;\n    body: string;\n    field_key?: string;\n    parent_comment_id?: Uuid;\n    mentions?: Uuid[];\n  }): Promise<RecordsResult<CommentWritten>>;\n  /** Resolve (or re-open) a thread. `commenter` — resolution is not a delete. */\n  commentResolve(args: { comment_id: Uuid; resolved?: boolean }): Promise<RecordsResult<boolean>>;\n  /**\n   * Follow ONE record (AT-FIX-G2; Airtable's \"follow a record\"). While followed, a change or a comment by SOMEBODY ELSE\n   * puts a notice in this person's bell, written in the same transaction as the change; the notice opens the record.\n   * `follow: false` stops it. Anybody who may read the record may follow it; the row is always the caller's own.\n   */\n  recordFollowSet(args: { record_id: Uuid; follow?: boolean }): Promise<RecordsResult<RecordFollowSet>>;\n  /** Who follows this record, and whether this person does. Empty for somebody who cannot open the record. */\n  recordFollowers(args: { record_id: Uuid }): Promise<RecordsResult<RecordFollowers>>;\n  /**\n   * Every value of one record WITH its envelope — its own version, who wrote\n   * it, who they were acting for and when. The timeline IS the record (REC-19);\n   * there is no second history table.\n   */\n  recordValuesVersioned(args: { record_id: Uuid; organization_id?: Uuid | null }): Promise<RecordsResult<ReadValue[]>>;\n\n  // ── the doors that do not exist yet, named rather than faked ─────────────\n  /**\n   * Metadata search across EVERY organization the person belongs to (`config.organizationIds`;\n   * `organization_id` narrows to one): the Tables and Fields whose name, key, label or description\n   * holds `text` (case-insensitive; structure, never rows). Each match is `{id, kind: \"table\" |\n   * \"field\", name, description, organization_id}` (a Field adds `key`, `table_id`, `field_type`).\n   * An organization whose read door refuses is listed in `unavailable` WITH its reason and\n   * never hides the rest. Only when NO organization answers is the whole search a failure (the\n   * first refusal).\n   */\n  metadataSearch(args: {\n    text: string;\n    organization_id?: Uuid | null;\n  }): Promise<RecordsResult<MetadataSearchAnswer>>;\n  /**\n   * WHICH of the person's organizations can this client use right now? Asks every organization\n   * in scope (`organization_id` narrows to one) whether its record store is open, so a host can\n   * say \"organization X is unavailable: <reason>\" instead of silently dropping it. Organization\n   * order is the person's own, never completion order.\n   */\n  organizationsOpen(args?: {\n    organization_id?: Uuid | null;\n  }): Promise<RecordsResult<OrganizationsOpenAnswer>>;\n  /**\n   * The organization that OWNS a table or record — the one a write to it must run in. A\n   * `table_id` is looked up across all the person's organizations; a `record_id` is opened in its\n   * own. `null` = found in none of them. Never a permission: the store's doors still decide.\n   */\n  ownerOrganization(args: {\n    table_id?: Uuid | null;\n    record_id?: Uuid | null;\n    organization_id?: Uuid | null;\n  }): Promise<RecordsResult<Uuid | null>>;\n  // ── the anonymous lane (W4-ANON) ─────────────────────────────────────────\n  /**\n   * Mint an embed token. `mode` is `read` OR `write` and never both — the store\n   * refuses a token carrying two decisions. The secret comes back ONCE, because\n   * only its digest is stored: a database read cannot produce a working token.\n   * `allowedOrigins` is required and matched EXACTLY, so `example.com.evil.test`\n   * fails a check that a suffix match would pass.\n   */\n  anonTokenIssue(args: {\n    mode: \"read\" | \"write\";\n    allowedOrigins: string[];\n    formId?: Uuid | null;\n    savedViewId?: Uuid | null;\n    recordId?: Uuid | null;\n    expiresAt?: Timestamp | null;\n  }): Promise<RecordsResult<{ token_id: Uuid; secret: string }>>;\n  /** What a secret is good for, from an origin. The store's sentence when it is not. */\n  anonTokenVerify(args: {\n    secret: string;\n    origin: string;\n    requiredMode?: \"read\" | \"write\" | null;\n  }): Promise<RecordsResult<AnonTokenBinding>>;\n  anonTokenRevoke(args: { token_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /**\n   * A STRANGER'S WRITE. The token supplies the organization, so this call names\n   * none — and what it produces is a QUARANTINED SUBMISSION, not a record:\n   * `custom.record` is never touched here. `clientKey` makes a replay free and\n   * idempotent, which is what lets a flaky phone retry safely.\n   */\n  anonWrite(args: {\n    secret: string;\n    origin: string;\n    payload: Record<string, unknown>;\n    clientKey?: string | null;\n    rawPayload?: Record<string, unknown>;\n  }): Promise<RecordsResult<Uuid>>;\n  /**\n   * SCR-30, and it is the SIGNED-IN offline path, not the stranger's. The client\n   * mints `clientKey` BEFORE the first attempt, offline, and the store's own\n   * replay ledger dedupes on it — so a reconnect that fires the same capture\n   * thirty times writes one record and returns the same id every time.\n   */\n  anonCapture(args: {\n    table_id: Uuid;\n    clientKey: string;\n    payload: Record<string, unknown>;\n    device?: string | null;\n    capturedAt?: Timestamp | null;\n  }): Promise<RecordsResult<Uuid>>;\n  /** Open or close a form to strangers. An admin act on the Table, never an editor one. */\n  anonPublish(args: { form_id: Uuid; published?: boolean }): Promise<RecordsResult<Timestamp | null>>;\n\n  // ── checklists and SOP runs (PRODUCTS row 13) ────────────────────────────\n  /**\n   * What is wrong with a checklist somebody is writing, in the words they would\n   * use. `null` means it is fine. Pure — it reads no row and writes nothing —\n   * so an editor may ask it on every keystroke and the refusal arrives BEFORE\n   * the save rather than after it.\n   */\n  checklistRefusal(args: { spec: ChecklistSpec }): Promise<RecordsResult<string | null>>;\n  /**\n   * Store a checklist, whole: ordered steps, who each belongs to by role, how\n   * many days in each is due, what each waits for, what each asks for, and what\n   * starts a run. Pass `template_id` to change the checklist that already\n   * exists rather than making a second one.\n   */\n  checklistDeclare(args: {\n    spec: ChecklistSpec;\n    template_id?: Uuid | null;\n  }): Promise<RecordsResult<ChecklistDeclared>>;\n  checklistTemplates(args?: {\n    about_table_id?: Uuid | null;\n    limit?: number;\n  }): Promise<RecordsResult<ChecklistTemplateSummary[]>>;\n  checklistTemplateShape(args: { template_id: Uuid }): Promise<RecordsResult<ChecklistTemplateShape>>;\n  /**\n   * Run a checklist for one record: one work item per step in the ONE work\n   * layer, assigned by role to real people, dated from the offsets,\n   * dependencies carried across. `roles` names who stands in each role for THIS\n   * run, over whatever the checklist says by default.\n   */\n  checklistStart(args: {\n    template_id: Uuid;\n    about_record_id?: Uuid | null;\n    roles?: Record<string, Uuid>;\n    startingAt?: Timestamp | null;\n  }): Promise<RecordsResult<ChecklistRunStarted>>;\n  checklistRun(args: { run_id: Uuid }): Promise<RecordsResult<ChecklistRunStep[]>>;\n  checklistRuns(args?: {\n    about_table_id?: Uuid | null;\n    about_record_id?: Uuid | null;\n    includeClosed?: boolean;\n    limit?: number;\n  }): Promise<RecordsResult<ChecklistRunSummary[]>>;\n  /**\n   * Tick a step off with whatever it asked for. Refused by name while a step it\n   * waits for is open, or while what it asks for is missing — and the same\n   * refusal meets `workSetState`, because the rule lives in the store and not\n   * in this door.\n   */\n  checklistStepComplete(args: {\n    step_id: Uuid;\n    evidence?: Record<string, unknown>;\n  }): Promise<RecordsResult<ChecklistStepCompleted>>;\n  /** Why this step cannot be finished right now. `null` means it can. */\n  checklistStepRefusal(args: { step_id: Uuid }): Promise<RecordsResult<string | null>>;\n\n  // ── work (W4-WORK): templates, turns and slots ───────────────────────────\n  /** The five states and what each one may become. Asked, never hardcoded in a picker. */\n  workStates(): Promise<RecordsResult<WorkState[]>>;\n  /** Why this graph would be refused — asked BEFORE it is written. `null` means it is fine. */\n  workTemplateRefusal(args: { graph: WorkGraph }): Promise<RecordsResult<string | null>>;\n  workTemplateDeclare(args: { name: string; graph: WorkGraph }): Promise<RecordsResult<Uuid>>;\n  /**\n   * REC-70: the WHOLE graph is created in one act, judged before any of it is\n   * written, so a half-made checklist is not a state this store can be in.\n   */\n  workTemplateInstantiate(args: {\n    template_id: Uuid;\n    overrides?: Record<string, Record<string, unknown>>;\n  }): Promise<RecordsResult<WorkInstantiation>>;\n  workTemplateShape(args: { template_id: Uuid }): Promise<RecordsResult<unknown>>;\n  workInstantiationShape(args: { instantiation_id: Uuid }): Promise<RecordsResult<unknown>>;\n  /** Whose turn each record is, with its state and whether that state is terminal. */\n  workWhoseTurn(args: { table_id: Uuid; includeFinished?: boolean }): Promise<RecordsResult<WorkTurn[]>>;\n  /** Does this Table carry assignment at all? A screen asks before it offers one. */\n  workHasAssignment(args: { table_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /** The Fields assignment is made of, so nothing here invents a column name. */\n  workAssignmentFields(args?: { options_table_id?: Uuid | null }): Promise<RecordsResult<WorkAssignmentField[]>>;\n  /** Add assignment to a Table. */\n  workTakeAssignment(args: { table_id: Uuid }): Promise<RecordsResult<unknown>>;\n  /** Why this move would be refused. `null` means it is allowed. */\n  workTransitionRefusal(args: { from_state_id: Uuid; to_state_id: Uuid }): Promise<RecordsResult<string | null>>;\n  /** Declare the Table slots are held in. Idempotent — a second call finds the first. */\n  workSlotsDeclare(args: { name: string; slug: string; homeId?: Uuid | null }): Promise<RecordsResult<unknown>>;\n  /**\n   * SCR-29. Take a slot for a while. THE STORE decides, under a unique index —\n   * two people racing for the same slot do not both get it, whatever either\n   * screen believed a moment earlier.\n   */\n  workSlotHold(args: {\n    table_id: Uuid;\n    slotKey: string;\n    holder: string;\n    ttl?: string;\n  }): Promise<RecordsResult<unknown>>;\n  workSlotRelease(args: { hold_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /** Every hold on this Table, with whether it has already lapsed. */\n  workSlotHolds(args: { table_id: Uuid }): Promise<RecordsResult<WorkSlotHold[]>>;\n  workSlotExpire(args: { table_id: Uuid }): Promise<RecordsResult<number>>;\n\n  // ── the work layer a person actually uses (lane WORK-DOORS, 2026-09-20) ──\n  /**\n   * THE ONE INBOX. Assignments, approvals and the agent's proposals, in one\n   * ordered list with ONE row shape — PRODUCTS.md row 6. A second queue for the\n   * agent's suggestions is the thing this replaces.\n   */\n  workInbox(args?: {\n    limit?: number;\n    offset?: number;\n    includeDecided?: boolean;\n    /** Lane S5-PRIME-2: \"inbox\" (default), \"snoozed\" or \"done\" — this person's own views. */\n    view?: WorkInboxView;\n  }): Promise<RecordsResult<WorkInboxItem[]>>;\n  /**\n   * SNOOZE ONE ITEM OF MY INBOX UNTIL A TIME (lane S5-PRIME-2, `custom.inbox_snooze`). Only my\n   * inbox changes; the approval or record is never written. A time already past, a snooze past a\n   * year, and a decided item are refused by name.\n   */\n  inboxSnooze(args: { item_id: Uuid; until: Timestamp }): Promise<RecordsResult<InboxStateChange>>;\n  /** Take my snooze off: it is back in my inbox now. */\n  inboxUnsnooze(args: { item_id: Uuid }): Promise<RecordsResult<InboxStateChange>>;\n  /**\n   * CLEAR (mark done) ONE ITEM OF MY INBOX. A decision still owed is refused (\"This one needs a\n   * decision\"). It comes back if somebody else changes it.\n   */\n  inboxClear(args: { item_id: Uuid }): Promise<RecordsResult<InboxStateChange>>;\n  /** Put a cleared item back in my inbox. */\n  inboxUnclear(args: { item_id: Uuid }): Promise<RecordsResult<InboxStateChange>>;\n  /**\n   * WHAT WAITS ON ME, COUNTED (`custom.inbox_counts`) — the same predicate the inbox lists with.\n   * `everyOrganization` counts every organization I belong to (the shell badge: what waits on a\n   * person is theirs, not the selected organization's).\n   */\n  inboxCounts(args?: { everyOrganization?: boolean }): Promise<RecordsResult<InboxCounts[]>>;\n  /** \"My work\", \"work I assigned\", \"waiting on somebody being chosen\". */\n  workList(args?: {\n    flavour?: WorkListFlavour;\n    includeFinished?: boolean;\n    limit?: number;\n    offset?: number;\n  }): Promise<RecordsResult<WorkListItem[]>>;\n  /**\n   * Give one record to one person: the Assignee value AND editor access, in one\n   * transaction. Passing no `user_id` un-assigns and says plainly that nobody's\n   * access was taken away.\n   */\n  workAssign(args: {\n    record_id: Uuid;\n    user_id?: Uuid | null;\n    dueDate?: string | null;\n    clearDue?: boolean;\n  }): Promise<RecordsResult<WorkAssignment>>;\n  /** The states this record may be moved to, and the sentence for each it may not. */\n  workRecordStates(args: { record_id: Uuid }): Promise<RecordsResult<WorkRecordState[]>>;\n  /** Move it. The store refuses a move the model forbids, in its own words. */\n  workSetState(args: { record_id: Uuid; state_id: Uuid | null }): Promise<RecordsResult<unknown>>;\n  /** The person-kernel record standing for a signed-in person here. */\n  workPerson(args: { user_id: Uuid; create?: boolean }): Promise<RecordsResult<Uuid | null>>;\n  /** The templates this person may run, so a picker has ids to offer. */\n  workTemplates(args?: { limit?: number }): Promise<RecordsResult<Array<{\n    template_id: Uuid;\n    name: string;\n    nodes: number;\n    relations: number;\n    created_at: string;\n  }>>>;\n  /** Who may decide a change about this subject, and why each of them may. */\n  workApprovalApprovers(args: {\n    subject_id: Uuid | null;\n    approver_id?: Uuid | null;\n  }): Promise<RecordsResult<WorkApprover[]>>;\n  /** Ask for a change instead of making it. Viewer on the subject is enough to ASK. */\n  workApprovalRequest(args: {\n    subject_id: Uuid;\n    change: WorkChange;\n    note?: string | null;\n    approver_id?: Uuid | null;\n    origin?: \"person\" | \"agent\";\n    conversation_id?: Uuid | null;\n  }): Promise<RecordsResult<WorkApprovalFiled>>;\n  /** Whether THIS person may decide THIS one — so a screen never draws a dead button. */\n  workApprovalMayDecide(args: { approval_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /** Approve or decline. Approving APPLIES the change, as the person approving. */\n  workApprovalDecide(args: {\n    approval_id: Uuid;\n    approve: boolean;\n    note?: string | null;\n  }): Promise<RecordsResult<WorkApprovalDecision>>;\n  /**\n   * DECIDE MANY INBOX ITEMS IN ONE CALL (lane S4, `custom.work_decide_many`). Each is judged by\n   * `work_approval_decide` exactly as one is, in its own savepoint: a refused decision leaves that\n   * item waiting and the others still stand. Verdicts: approved, declined, already_decided,\n   * no_right, refused — each with the store's own sentence.\n   */\n  workDecideMany(args: { decisions: WorkDecideManyItem[] }): Promise<RecordsResult<WorkDecideMany>>;\n  /** One waiting change in full, for the person deciding it or the one who asked. */\n  workApprovalRead(args: { approval_id: Uuid }): Promise<RecordsResult<Record<string, unknown>>>;\n\n  // ── the trust doors: `iam`'s, not the store's ────────────────────────────\n  /** VIS-31. Is this account a signed-in outsider — no NON-personal organization? */\n  isExternalPrincipal(args?: { user_id?: Uuid | null }): Promise<RecordsResult<boolean>>;\n  /** The same answer WITH the plain-English reason a screen shows. */\n  externalPrincipalCard(args?: { user_id?: Uuid | null }): Promise<RecordsResult<ExternalPrincipalCard>>;\n  /** Exactly the resource ids Visibility gave that outsider. Never an organization's list. */\n  externalPrincipalReach(args: {\n    resourceType: string;\n    user_id?: Uuid | null;\n  }): Promise<RecordsResult<Array<{ resource_id: Uuid }>>>;\n  /** VIS-32. Bind a record or a view to a public address with a declared render mode. */\n  publishBindingCreate(args: {\n    slug: string;\n    resourceType: string;\n    resource_id: Uuid;\n    renderMode?: string;\n  }): Promise<RecordsResult<PublishBinding>>;\n  publishBindingRevoke(args: { slug: string }): Promise<RecordsResult<unknown>>;\n  /** What a SIGNED-OUT visitor resolves. Empty for an invented, revoked or unpublished address. */\n  resolvePublishBinding(args: { slug: string }): Promise<RecordsResult<ResolvedPublishBinding[]>>;\n  /** The same resolution plus what the address holds (table | record | dashboard | page | view). */\n  resolvePublishBindingKind(args: { slug: string }): Promise<RecordsResult<ResolvedPublishBindingKind[]>>;\n  /** D-15. The ONE sentence admitting nothing was scanned, so four surfaces cannot drift. */\n  worldPublishGapNotice(): Promise<RecordsResult<string>>;\n  /** Put a resource in the world lane. Refuses by name while the lane is closed. */\n  publishToWorld(args: {\n    resourceType: string;\n    resource_id: Uuid;\n    discoverable?: boolean;\n  }): Promise<RecordsResult<unknown>>;\n  /**\n   * Declare a Rule. It is NOT `recordWrite` into the rule kernel, and that is\n   * the whole point: `custom.record_write` inserts `data_class = 'record'`, so a\n   * document written that way is not a Rule and the store's own rule doors\n   * (`custom.rule_members`, `custom.agg_subscriptions`) never see it. Writing\n   * one through the record door and calling it a Rule would be a silent\n   * failure — a screen that looked like it had subscribed you to something.\n   */\n  ruleDeclare(args: { spec: Record<string, unknown>; rule_id?: Uuid | null }): Promise<RecordsResult<Uuid>>;\n  fieldPropose(proposal: FieldProposal): Promise<RecordsResult<never>>;\n  tablePropose(proposal: TableProposal): Promise<RecordsResult<never>>;\n\n  // ── promotion (REC-5) ────────────────────────────────────────────────────\n  promoteTable(args: { table_id: Uuid }): Promise<RecordsResult<unknown>>;\n  promoteField(args: { table_id: Uuid; field_id: Uuid }): Promise<RecordsResult<unknown>>;\n\n  /**\n   * @deprecated The record store is never off (owner ruling, 2026-10-03: everything is on by\n   * default). This answers `true` whenever the door answers; a refusal means the store could not\n   * be reached, never that it is off. Do not gate a screen on it.\n   */\n  storeIsOpen(): Promise<RecordsResult<boolean>>;\n  /**\n   * WHAT THIS PERSON MAY DO TO THESE THINGS — asked once, for a whole page.\n   *\n   * There is no principal argument, on purpose: the door resolves the caller\n   * from the session, so a person can ask about their OWN access and about\n   * nobody else's. A subject they hold nothing on answers `level: null`, which\n   * is an answer; the row is never omitted, because a screen that could not\n   * tell \"no access\" from \"not asked yet\" would draw one of them as the other.\n   */\n  myLevels(args: { ids: Uuid[]; subject?: \"record\" }): Promise<RecordsResult<MyLevel[]>>;\n\n  // ── THE GRID (lane GRID-PRIMITIVES) — see ../grid.ts for every shape ─────\n  /** G1. Write ONE leaf of a Table's colors, or clear it with `null`. Editor on the Table. */\n  tableDecorate(args: { table_id: Uuid; path: DecorationPath; value: unknown }): Promise<RecordsResult<TableDecorations>>;\n  /** G1. A Table's colors as a screen paints them, with what went stale named. */\n  tableDecorations(args: { table_id: Uuid }): Promise<RecordsResult<TableDecorations>>;\n  /** G1. The layout a grid opens with: platform → organization knob → the view's own. */\n  gridLayout(args: { table_id: Uuid; view_id?: Uuid | null }): Promise<RecordsResult<GridLayout>>;\n  /** G3. The older grid's formula text → the store's expression. Never refuses a typo: answers ok:false. */\n  formulaParse(args: { table_id: Uuid; text: string }): Promise<RecordsResult<FormulaParse>>;\n  /**\n   * NOTION-PROPS. The formula being typed, parsed AND worked out for one record of the table\n   * (`custom.formula_preview`): the parse, plus `value` — what a saved formula column would show on\n   * that record — or `error` when it parses and cannot be worked out there. Writes nothing.\n   */\n  formulaPreview(args: { table_id: Uuid; record_id: Uuid | null; text: string }): Promise<RecordsResult<FormulaPreview>>;\n  /** G2. Declare a Table's row actions — the whole list. Editor on the Table. */\n  actionDeclare(args: { table_id: Uuid; actions: RowAction[] }): Promise<RecordsResult<RowAction[]>>;\n  /** G2. A Table's row actions, each saying whether it can run here. */\n  rowActions(args: { table_id: Uuid }): Promise<RecordsResult<{ actions: RowAction[]; stale: unknown[] }>>;\n  /**\n   * G2. Run one action on a selection, in ONE transaction. A refusal changed NOTHING; read\n   * every record and field that refused with `actionRefusals(result.error)`.\n   */\n  actionRun(args: { action_id: Uuid; record_ids: Uuid[] }): Promise<RecordsResult<ActionRunResult>>;\n  /**\n   * AUTOMATION-DOOR. Declare (or, with `automation_id`, replace) one automation on a Table — editor on the Table.\n   * A spec the store refuses comes back as `data.ok === false` with `_errors`, one sentence per path.\n   */\n  automationDeclare(args: { table_id: Uuid; spec: AutomationSpec; automation_id?: Uuid | null }): Promise<RecordsResult<AutomationDeclared>>;\n  /** AUTOMATION-DOOR. A Table's automations with their last run; archived ones only when asked. */\n  automations(args: { table_id: Uuid; include_archived?: boolean }): Promise<RecordsResult<AutomationList>>;\n  /** AUTOMATION-DOOR. Archive one (it switches off and keeps its history). Editor on the Table. */\n  automationArchive(args: { automation_id: Uuid }): Promise<RecordsResult<AutomationFlipped>>;\n  /** AUTOMATION-DOOR. Bring an archived one back (it stays off until `automationSetEnabled`). */\n  automationRestore(args: { automation_id: Uuid }): Promise<RecordsResult<AutomationFlipped>>;\n  /** AUTOMATION-DOOR. Switch one on or off. */\n  automationSetEnabled(args: { automation_id: Uuid; enabled: boolean }): Promise<RecordsResult<AutomationFlipped>>;\n  /** AUTOMATION-DOOR. Run history, newest first: status, the store's own sentence, every step. */\n  automationRuns(args: { automation_id: Uuid; limit?: number; cursor?: string | null }): Promise<RecordsResult<AutomationRuns>>;\n  /**\n   * AUTOMATIONS-AIRTABLE. Test an automation now (Airtable's \"Run test\"): its steps run once on `record_id` (none for\n   * a schedule), switched on or not, and the run lands in its history as `trigger.on = \"test\"`. Editor on the Table.\n   */\n  automationTest(args: { automation_id: Uuid; record_id?: Uuid | null }): Promise<RecordsResult<AutomationTested>>;\n  /** AT-AUTO2. Every saved version of an automation, newest first. */\n  automationRevisions(args: { automation_id: Uuid }): Promise<RecordsResult<AutomationRevisions>>;\n  /** AT-AUTO2. Restore one version: one more save through automation_declare (admin on the table). */\n  automationRevisionRestore(args: { automation_id: Uuid; revision_id: Uuid }): Promise<RecordsResult<AutomationDeclared>>;\n  /** G4. Send every change to this Table's records to an https webhook. Admin. The secret is shown once. */\n  tableWebhookDeclare(args: {\n    table_id: Uuid;\n    target_url: string;\n    events?: RecordEvent[] | null;\n    description?: string | null;\n  }): Promise<RecordsResult<TableWebhookDeclared>>;\n  /** G4. The webhooks a Table sends to, with their delivery health — never the secret. */\n  tableWebhooks(args: { table_id: Uuid }): Promise<RecordsResult<TableWebhook[]>>;\n  /** G4. Switch one off. It is never deleted. */\n  tableWebhookArchive(args: { webhook_id: Uuid }): Promise<RecordsResult<boolean>>;\n  /** G5. Number the records an autonumber column found already there, in creation order. */\n  autonumberBackfill(args: { field_id: Uuid }): Promise<RecordsResult<{ numbered: number; highest: number | null; says: string }>>;\n  /**\n   * AT-SHARE-B. A Person column's \"Notify people when they're added\" switch (`custom.field_notify_on_assign`).\n   * `on: null` only READS whether it is on; `true` declares the column's two notify automations (edited, new\n   * record), `false` archives them. Turning it on or off asks to change the table's structure.\n   */\n  fieldNotifyOnAssign(args: { field_id: Uuid; on: boolean | null }): Promise<RecordsResult<FieldNotifyOnAssign>>;\n  /**\n   * NOTION-PROPS-3. PRESS A BUTTON COLUMN ON ONE ROW (`custom.button_press`): a link comes back filled from\n   * the row for the screen to open; a row action or an automation runs in the store and its result comes\n   * back. A button with nothing set up is refused by name (22023).\n   */\n  buttonPress(args: { record_id: Uuid; field_id: Uuid }): Promise<RecordsResult<ButtonPressed>>;\n  /**\n   * NOTION-PROPS-3. The knob `data/timeline_dependency_shift` for the signed-in person in this organization:\n   * whether moving a record on a timeline moves the records waiting on it (default true).\n   */\n  timelineDependencyShift(): Promise<RecordsResult<boolean>>;\n  /**\n   * FB5 (ADV-5 F4/F10): the record store's screen limits for the signed-in person in this organization, each a\n   * knob (`custom.records_limits`): the AI column fill's try size, one fill's row cap and the Fill box's start, and\n   * a table copy's stall bound. Asked once per client; a store without the door answers the knobs' defaults.\n   */\n  recordsLimits(): Promise<RecordsLimits>;\n  /** G5. One page of the export door — exactly the rows and columns the read door serves this person. */\n  ioExport(args: { table_id: Uuid; columns?: string[] | null; limit?: number }): Promise<RecordsResult<IoExportPage>>;\n  /** G5. That page as an .xlsx; a withheld column is named on its own sheet. */\n  /**\n   * G9. Every table a picker may offer here, from BOTH stores, each saying which store opens it.\n   * A table the app keeps out of default lists (`custom.table_kept_out_of_lists`: an agent's\n   * outputs) is left out unless `include_platform_tables` is true — the \"Show platform tables\" switch.\n   */\n  tableListEverywhere(args?: { include_platform_tables?: boolean }): Promise<RecordsResult<{ success: boolean; tables: TableListEntry[] }>>;\n  /**\n   * Every table the person reaches (`custom.data_home_tables`), as the data home lists them.\n   * `organization_id` names one organization; `null` asks for every organization the person\n   * reaches — never the client's bound organization by default. A table the app keeps out of\n   * default lists (an agent's outputs) is answered only with `include_platform_tables: true`.\n   */\n  dataHomeTables(args: { organization_id: Uuid | null; include_platform_tables?: boolean }): Promise<RecordsResult<DataHomeTable[]>>;\n  /**\n   * Every table of EVERY organization (`custom.admin_all_tables`) — the admin section's list. The\n   * store's walls admit a platform admin to system organizations only, so this is a separate door that\n   * answers only on the admin lane for a platform admin; anyone else gets a refusal, not an empty list.\n   */\n  adminAllTables(): Promise<RecordsResult<AdminTable[]>>;\n  /**\n   * G10. Refresh a synced source (a sheet tab) into ONE Table under `home_id`: new rows added,\n   * changed rows updated, rows the source dropped archived — never destroyed; columns the\n   * person added in Matrx survive. Build the spec with `sheetSyncSpec`.\n   */\n  tableSync(args: { home_id: Uuid; spec: TableSyncSpec }): Promise<RecordsResult<TableSyncResult>>;\n  /** Lane SYNC-AIRTABLE: a table synced from another table's view, in the active organization. */\n  tableCopySync(spec: TableCopySpec): Promise<RecordsResult<TableSyncAnswer>>;\n  /** Lane SYNC-AIRTABLE: auto-refresh / write-back of one synced table (editor of it). */\n  tableSyncSettingsSet(args: { table_id: Uuid; settings: TableSyncSettings }): Promise<RecordsResult<TableSyncSourceDocument>>;\n  /**\n   * G11. The record-store Table a context scope's template-bound item provisions — one per item\n   * and scope. A scope provisioned before the move answers with its moved Table (same id); the\n   * Home defaults to the organization's own.\n   */\n  scopeTableProvision(args: { item_id: Uuid; scope_id: Uuid; home_id?: Uuid | null }): Promise<RecordsResult<Uuid>>;\n  /** G12. The rows of each Table this reader may see, in one call (fold with `withRowCounts`). A Table she may not know gets no row. */\n  tableRowCounts(args: { table_ids: Uuid[] }): Promise<RecordsResult<TableRowCount[]>>;\n  /** G12. Each live record's own header (created, updated, version) that the read door does not answer. */\n  recordHeaders(args: { ids: Uuid[] }): Promise<RecordsResult<RecordHeader[]>>;\n  /**\n   * G14. Share a Table with a person by email or account id: an existing account outside the\n   * organization is granted at once and notified (never made a member); an address with no\n   * account is invited. The organization's outside-sharing setting decides first.\n   */\n  tableShareOutsideGrant(args: { table_id: Uuid; person: string; level?: \"viewer\" | \"commenter\" | \"editor\" | \"admin\" }): Promise<RecordsResult<OutsideShareAnswer>>;\n  /** G13. Keep a hand-set order on a saved view: the named rows first, in this order (build it with `moveInOrder`). */\n  viewRecordOrderSet(args: { view_id: Uuid; record_ids: Uuid[] }): Promise<RecordsResult<ViewOrderSet>>;\n  /**\n   * G13 + ORDER-FILTER. A page of a hand-ordered view: placed rows by position, then the rest by\n   * created time. `filter` is the list door's question (`StoreFilter`: a flat map or a nested\n   * Rule — the view's own `where`, or a number clicked on a dashboard); given, the store reads\n   * exactly the rows that match, in their places, and `limit`/`offset` page THAT order. Each row\n   * answers the position stored for it; rows the filter hides keep theirs.\n   */\n  readInViewOrder(args: { view_id: Uuid; filter?: StoreFilter | null | undefined; limit?: number; offset?: number }): Promise<RecordsResult<Array<ReadRow & { position: number | null }>>>;\n  exportXlsx(args: {\n    table_id: Uuid;\n    columns?: string[] | null;\n    limit?: number;\n    labels?: Record<string, string>;\n    sheetLabel?: string;\n  }): Promise<RecordsResult<Uint8Array>>;\n}\n\n/** One Table's two lane facts, as `custom.table_facts` answers them. */\nexport interface TableFact {\n  table_id: Uuid;\n  /**\n   * The old lane word (personal · internal · public), now worked out by the store from `shown_to`\n   * and `published_to_web` (access ladder). Read those two; this stays for older stores.\n   */\n  visibility: string;\n  /** Whether the person signed in MADE this Table. Never who did. */\n  mine: boolean;\n  /** Access ladder \"Shown to\": only_me · my_team · everyone · everyone_on_ai_matrx; null = the default. */\n  shown_to?: string | null;\n  /** Access ladder \"Published to the web\": the only way anyone outside the organization opens it. */\n  published_to_web?: boolean;\n}\n\n/**\n * WHERE A TABLE IS CURRENTLY READ AND WRITTEN during the older-table cutover.\n * `tableHome` is an address read from one Table record; this applies the\n * organization's migration switch to a batch of ids, including same-id copies.\n */\nexport interface TableLiveLocation {\n  table_id: Uuid;\n  lives_in: \"record\" | \"older\";\n  why: string | null;\n}\n\n/**\n * The facts folded onto a table list: `visibility` on every Table the facts name,\n * `created_by` ONLY as the caller's own id and only on the Tables the caller made.\n * Pure — returns new objects and leaves the list it was given alone.\n */\n/** Carries the offline data source's \"not sent yet\" mark from a read row (see `ReadRow.waiting`). */\nfunction waitingMark(row: unknown): { waiting?: true } {\n  return (row as { waiting?: unknown } | null)?.waiting === true ? { waiting: true } : {};\n}\n\nexport function withTableFacts<T extends { id: Uuid }>(\n  tables: readonly T[],\n  facts: readonly TableFact[] | null | undefined,\n  me: Uuid | null | undefined,\n): T[] {\n  if (!facts) return [...tables];\n  const byId = new Map(facts.map((f) => [f.table_id, f]));\n  return tables.map((table) => {\n    const fact = byId.get(table.id);\n    if (!fact) return table;\n    return {\n      ...table,\n      visibility: fact.visibility,\n      ...(fact.shown_to !== undefined ? { shown_to: fact.shown_to } : {}),\n      ...(fact.published_to_web !== undefined ? { published_to_web: fact.published_to_web } : {}),\n      ...(fact.mine && me ? { created_by: me } : {}),\n    };\n  });\n}\n\n\n/** How many Table-kernel records `tableList` asks for per page (the read door's own ceiling). */\nconst TABLE_LIST_PAGE = 500;\n/**\n * How many records one `custom.table_archive` pass takes on by default — see the measurement in\n * `tableArchive`. A screen loop starts here and halves on a statement timeout.\n */\nexport const TABLE_ARCHIVE_PASS = 20;\n/** Rows one `custom.table_restore` pass takes on by default (the door also stops itself at 1 s). */\nexport const TABLE_RESTORE_PASS = 20;\n/** The smallest pass the restore loop halves down to on a statement timeout. */\nconst TABLE_RESTORE_MIN_PASS = 1;\n/** A restore loop that has not finished after this many passes stops and says so. */\nconst TABLE_RESTORE_MAX_PASSES = 500;\n/**\n * A copy whose passes move nothing (answers \"busy\", or the same counts at the same step) this many\n * times in a row stops and says so, naming the half copy — never \"Copying…\" for hours (FIX-SNAP2).\n */\nexport const COPY_STALL_PASSES = 20;\n\n/** The record store's screen limits (`recordsLimits`), each a knob in `platform.feature_knob`. */\nexport interface RecordsLimits {\n  /** A fill of at most this many rows runs at once; a bigger one meets the confirm step (knob custom/ai_fill_try_max). */\n  aiFillTryMax: number;\n  /** The most rows one fill covers (knob custom/ai_fill_rows_max). */\n  aiFillRowsMax: number;\n  /** The number the \"Fill N rows\" box starts at (knob custom/ai_fill_default_rows). */\n  aiFillDefaultRows: number;\n  /** Passes a table copy may make without moving before it stops (knob custom/copy_stall_passes). */\n  copyStallPasses: number;\n  /**\n   * The highest sensitivity an AI fill may read (knob custom/enrichment_sensitivity_ceiling): public, internal,\n   * restricted or confidential. custom.enrich_due drops anything above it; screens default an AI column's inputs by it.\n   */\n  enrichmentSensitivityCeiling: string;\n}\n\n/**\n * The knobs' own defaults (the values their rows were seeded with), answered only by a store that has no\n * `records_limits` door (the in-memory sample, an older store) or refuses it — never in place of a knob the door read.\n */\nexport const RECORDS_LIMITS_DEFAULTS: Readonly<RecordsLimits> = Object.freeze({\n  aiFillTryMax: 10,\n  aiFillRowsMax: 50,\n  aiFillDefaultRows: 3,\n  copyStallPasses: COPY_STALL_PASSES,\n  enrichmentSensitivityCeiling: \"internal\",\n});\n\n/** The door's answer as limits: each a whole number, else the knob's default for that one. */\nexport function recordsLimitsFrom(raw: unknown): RecordsLimits {\n  const o = raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : {};\n  const whole = (v: unknown, fallback: number, min: number): number => {\n    const n = typeof v === \"number\" ? v : Number(v);\n    return Number.isFinite(n) && n >= min ? Math.floor(n) : fallback;\n  };\n  return {\n    aiFillTryMax: whole(o.ai_fill_try_max, RECORDS_LIMITS_DEFAULTS.aiFillTryMax, 0),\n    aiFillRowsMax: whole(o.ai_fill_rows_max, RECORDS_LIMITS_DEFAULTS.aiFillRowsMax, 1),\n    aiFillDefaultRows: whole(o.ai_fill_default_rows, RECORDS_LIMITS_DEFAULTS.aiFillDefaultRows, 1),\n    copyStallPasses: whole(o.copy_stall_passes, RECORDS_LIMITS_DEFAULTS.copyStallPasses, 1),\n    enrichmentSensitivityCeiling:\n      typeof o.enrichment_sensitivity_ceiling === \"string\" && o.enrichment_sensitivity_ceiling.trim()\n        ? o.enrichment_sensitivity_ceiling.trim().toLowerCase()\n        : RECORDS_LIMITS_DEFAULTS.enrichmentSensitivityCeiling,\n  };\n}\n\n/** The surface every record-store saved view is kept under (`custom.view_declare` writes it). */\nconst SAVED_VIEW_SURFACE = \"custom/records\";\n\n/** `custom.table_kept_out_of_lists`: the placement words the set door `custom.data_home_tables` leaves out by default. */\nconst DATA_HOME_KEPT_OUT_OF_LISTS: ReadonlySet<string> = new Set([\"agent_output\", \"copying\"]);\n\nexport function createRecordsClient(given: RecordsConfig): RecordsClient {\n  // THE README IS TRUE: `dataSource: supabase` (a plain supabase-js client) is bound here, once,\n  // so every door is asked in its own schema instead of PostgREST's `public` (supabase.ts).\n  const config: RecordsConfig = { ...given, dataSource: asRecordsDataSource(given.dataSource) };\n  const schema = config.schema ?? DEFAULT_SCHEMA;\n  const org = config.organizationId;\n  const ledger = config.opLedger ?? defaultOpLedger;\n  const mintOp = (): Uuid => ledger.mint();\n  const scream = recordsErrorSink(config.onError);\n  // FB5: the screen limits (knobs), asked once for the life of this client.\n  let limitsAsked: Promise<RecordsLimits> | null = null;\n  const askLimits = (): Promise<RecordsLimits> => {\n    limitsAsked ??= callDoor<unknown>(DOORS.recordsLimits, { p_organization_id: org }, \"recordsLimits\").then(\n      (result) => (result.ok ? recordsLimitsFrom(result.data) : { ...RECORDS_LIMITS_DEFAULTS }),\n      () => ({ ...RECORDS_LIMITS_DEFAULTS }),\n    );\n    return limitsAsked;\n  };\n\n  // ---------------------------------------------------------------------------------------------\n  // PAGE-BUNDLE (lane PAGE-BUNDLE, 2026-10-07). A TABLE PAGE OPENS IN ONE CALL, NOT FIFTEEN.\n  //\n  // THE USE CASE: Dr. Patel's front desk opens \"Visits\". The page asked the store for its table row,\n  // fields, views, look, decorations, row actions, reverse columns, layout, level and recent imports\n  // in three waves, one waiting on the one before (measured on production: 3 round trips, ~1.5 s of\n  // doors one after another). `custom.table_page_bundle` answers all of them in one call.\n  //\n  // HOW IT STAYS THE SAME: the bundle holds each door's OWN answer under the door's name and exact\n  // arguments. A caller still asks its door — `callDoor` serves that answer from the bundle, once,\n  // only when the name and every argument match what the bundle asked, and otherwise asks the door\n  // as it always did. So every mapping, mask, refusal and cache above this line is untouched.\n  //\n  // WHEN: only for a data source that says it opens in one call (`opensInOneCall`: the real\n  // supabase adapters), and only when `applicable_fields` or another shape door of a Table is the\n  // FIRST thing asked about it. A refusal inside the bundle, a door the store lacks, a bundle that\n  // fails: each is a miss, and the door is asked itself — a bundle never turns a refusal into \"empty\".\n  // An answer is used once and forgotten after BUNDLE_TTL_MS; a structure change drops the Table's.\n  // ---------------------------------------------------------------------------------------------\n  const BUNDLE_TTL_MS = 10_000;\n  const BUNDLE_OPENERS = new Set([\"applicable_fields\", \"views\", \"view_look_read\", \"table_decorations\", \"row_actions\", \"reverse_columns\", \"record_change_actions\", \"grid_layout\", \"io_imports\"]);\n  const bundleParts = new Map<string, { data: unknown; at: number }>();\n  const bundleFlights = new Map<string, Promise<void>>();\n  const bundleAsked = new Map<string, number>();\n  let bundleKernel: string | null = null;\n  const bundleKey = (door: string, args: Record<string, unknown>): string => `${door}|${canonicalArgs(args)}`;\n\n  function bundleTableOf(door: string, args: Record<string, unknown>): string | null {\n    const t = args[\"p_table_id\"];\n    if (door === \"read_records_by_ids\") {\n      const ids = args[\"p_record_ids\"];\n      return typeof t === \"string\" && t === bundleKernel && Array.isArray(ids) && ids.length === 1 && typeof ids[0] === \"string\" ? (ids[0] as string) : null;\n    }\n    if (door === \"my_levels\") {\n      const ids = args[\"p_ids\"];\n      return args[\"p_type\"] === \"record\" && Array.isArray(ids) && ids.length === 1 && typeof ids[0] === \"string\" ? (ids[0] as string) : null;\n    }\n    return typeof t === \"string\" ? t : null;\n  }\n\n  async function fillBundle(tableId: string, viewId: unknown): Promise<void> {\n    try {\n      const view = typeof viewId === \"string\" ? viewId : null;\n      type BundleAnswer = { parts?: Array<{ door: string; args: Record<string, unknown>; data?: unknown; error?: string }> } | null;\n      const usable = (r: { data: unknown; error: unknown } | null): r is { data: BundleAnswer; error: null } =>\n        r !== null && !r.error && r.data !== null && typeof r.data === \"object\" && Array.isArray((r.data as { parts?: unknown }).parts);\n      // PAGE-BUNDLE-2: the server render may already have asked this bundle as the same person.\n      const primedAnswer = takePrimedTablePageBundle(org, tableId, view);\n      let response: { data: unknown; error: unknown } | null = primedAnswer ? await primedAnswer : null;\n      if (!usable(response)) {\n        response = await config.dataSource.rpc(\n          \"table_page_bundle\",\n          { p_organization_id: org, p_table_id: tableId, p_view_id: view },\n          { schema },\n        );\n      }\n      if (!usable(response)) return;\n      const answer = response.data;\n      if (!answer || !Array.isArray(answer.parts)) return;\n      const now = Date.now();\n      for (const part of answer.parts) {\n        if (part.error !== undefined || part.data === undefined) continue; // a refusing part is asked by its own door\n        if (part.door === \"table_kernel_id\" && typeof part.data === \"string\") bundleKernel = part.data;\n        bundleParts.set(bundleKey(part.door, part.args), { data: part.data, at: now });\n      }\n    } catch {\n      // a bundle that cannot be asked is a miss for every part: the doors are asked themselves\n    }\n  }\n\n  // ---------------------------------------------------------------------------------------------\n  // PAGE-BUNDLE-2: A RECORD PAGE OPENS IN ONE CALL TOO. `custom.record_page_bundle(org, record)` answers\n  // the record page's own doors (the record, its row controls, the caller's level, history head,\n  // comment thread, computed provenance, header) the same way: each part the door's own answer under\n  // its exact arguments, used once, only on an exact match; a refusing part is asked by its own door.\n  // A write that lands on the record drops whatever of its bundle is still held.\n  // ---------------------------------------------------------------------------------------------\n  const RECORD_OPENERS = new Set([\"read_record\", \"record_row_controls\", \"record_history\", \"comment_thread\", \"computed_provenance\"]);\n  const recordFlights = new Map<string, Promise<void>>();\n  const recordAsked = new Map<string, number>();\n  let recordChangesHeard = false;\n\n  function bundleRecordOf(door: string, args: Record<string, unknown>): string | null {\n    if (RECORD_OPENERS.has(door)) return typeof args[\"p_record_id\"] === \"string\" ? (args[\"p_record_id\"] as string) : null;\n    const ids = args[\"p_ids\"];\n    const one = Array.isArray(ids) && ids.length === 1 && typeof ids[0] === \"string\" ? (ids[0] as string) : null;\n    if (door === \"record_headers\") return one;\n    if (door === \"my_levels\" && args[\"p_type\"] === \"record\") return one;\n    return null;\n  }\n\n  async function fillRecordBundle(recordId: string): Promise<void> {\n    if (!recordChangesHeard) {\n      recordChangesHeard = true;\n      onRecordChanged((changed) => {\n        recordAsked.delete(changed);\n        for (const key of [...bundleParts.keys()]) if (key.includes(changed)) bundleParts.delete(key);\n      });\n    }\n    try {\n      const usable = (r: { data: unknown; error: unknown } | null): boolean =>\n        r !== null && !r.error && r.data !== null && typeof r.data === \"object\" && Array.isArray((r.data as { parts?: unknown }).parts);\n      const primedAnswer = takePrimedTablePageBundle(org, `record:${recordId}`, null);\n      let response: { data: unknown; error: unknown } | null = primedAnswer ? await primedAnswer : null;\n      if (!usable(response)) {\n        response = await config.dataSource.rpc(\"record_page_bundle\", { p_organization_id: org, p_record_id: recordId }, { schema });\n      }\n      if (!usable(response)) return;\n      const now = Date.now();\n      for (const part of (response!.data as { parts: Array<{ door: string; args: Record<string, unknown>; data?: unknown; error?: string }> }).parts) {\n        if (part.error !== undefined || part.data === undefined) continue;\n        bundleParts.set(bundleKey(part.door, part.args), { data: part.data, at: now });\n      }\n    } catch {\n      // a bundle that cannot be asked is a miss for every part: the doors are asked themselves\n    }\n  }\n\n  /** The record bundle's answer to this exact call, once — or undefined when this is not a record page door. */\n  async function fromRecordBundle(door: string, args: Record<string, unknown>): Promise<{ data: unknown } | null | undefined> {\n    if (!doorReady(config, \"record_page_bundle\")) return undefined;\n    const recordId = bundleRecordOf(door, args);\n    if (!recordId) return undefined;\n    const opener = RECORD_OPENERS.has(door);\n    if (!opener && !recordFlights.has(recordId) && !recordAsked.has(recordId)) return undefined;\n    const asked = recordAsked.get(recordId);\n    const fresh = asked !== undefined && Date.now() - asked < BUNDLE_TTL_MS;\n    if (!fresh && opener) {\n      recordAsked.set(recordId, Date.now());\n      const flight = fillRecordBundle(recordId).finally(() => recordFlights.delete(recordId));\n      recordFlights.set(recordId, flight);\n    }\n    const flight = recordFlights.get(recordId);\n    if (flight) await flight;\n    const key = bundleKey(door, args);\n    const held = bundleParts.get(key);\n    if (!held) return opener ? null : undefined;\n    bundleParts.delete(key);\n    return Date.now() - held.at < BUNDLE_TTL_MS ? { data: held.data } : null;\n  }\n\n  /** The bundle's answer to this exact call, once — or null, and the door is asked. */\n  async function fromBundle(door: string, args: Record<string, unknown>): Promise<{ data: unknown } | null> {\n    if (!config.dataSource.opensInOneCall) return null;\n    const fromRecord = await fromRecordBundle(door, args);\n    if (fromRecord !== undefined) return fromRecord;\n    if (!doorReady(config, \"table_page_bundle\")) return null;\n    const tableId = bundleTableOf(door, args);\n    if (tableId) {\n      const asked = bundleAsked.get(tableId);\n      const fresh = asked !== undefined && Date.now() - asked < BUNDLE_TTL_MS;\n      if (!fresh && BUNDLE_OPENERS.has(door)) {\n        bundleAsked.set(tableId, Date.now());\n        const flight = fillBundle(tableId, door === \"grid_layout\" ? args[\"p_view_id\"] : null).finally(() => bundleFlights.delete(tableId));\n        bundleFlights.set(tableId, flight);\n      }\n      const flight = bundleFlights.get(tableId);\n      if (flight) await flight;\n    } else if (door === \"table_kernel_id\") {\n      // The Table kernel is one id for the whole store. Asked in the same moment as the Table's first\n      // shape door, it waits for that bundle (one tick, so the opener has started); once any bundle\n      // has told it, it is never asked again.\n      if (bundleKernel === null) {\n        await new Promise((resolve) => setTimeout(resolve, 0));\n        await Promise.all([...bundleFlights.values()]);\n      }\n      return bundleKernel === null ? null : { data: bundleKernel };\n    } else {\n      return null;\n    }\n    const key = bundleKey(door, args);\n    const held = bundleParts.get(key);\n    if (!held) return null;\n    bundleParts.delete(key);\n    return Date.now() - held.at < BUNDLE_TTL_MS ? { data: held.data } : null;\n  }\n\n  function bundleDrop(tableId: string | null): void {\n    if (tableId === null) {\n      bundleParts.clear();\n      bundleAsked.clear();\n      return;\n    }\n    bundleAsked.delete(tableId);\n    for (const key of [...bundleParts.keys()]) if (key.includes(tableId)) bundleParts.delete(key);\n  }\n\n  const primedFor = primedDoorAnswer;\n\n  // THE ONE DOOR CALL (./doorCall), with what only this client has handed in: the page bundle and the\n  // generated door catalog.\n  const callDoor: DoorCall = createDoorCall({\n    dataSource: config.dataSource,\n    schema,\n    onError: scream,\n    doorReady: (door) => doorReady(config, door),\n    absent: doorAbsent,\n    held: fromBundle,\n    wrote: (_door, args) => {\n      const tableId = args[\"p_table_id\"];\n      bundleDrop(typeof tableId === \"string\" ? tableId : null);\n    },\n  });\n  const scopes: ScopeDoors = createScopeDoors(callDoor);\n\n  /**\n   * A STRUCTURE DOOR ANSWERED YES: the Table's shape moved, so every `table:<uuid>` card on this\n   * page re-reads its kind facts (KINDS-GLUE wave 3 §1.4). `null` = the door was addressed by a\n   * Field id and did not name the Table; listeners refresh every Table they hold.\n   */\n  let personKernelOnce: Uuid | null = null;\n\n  /** `allow_other` is a choice list's own setting and the store keeps it in the column's config (STORE-RULE-GAPS). */\n  function fieldDoorSpec(spec: NewFieldDeclaration): Record<string, unknown> {\n    const { allow_other, ...rest } = spec;\n    return allow_other === undefined ? rest : { ...rest, config: { ...(rest.config ?? {}), allow_other } };\n  }\n\n  function structureMoved<T>(tableId: Uuid | null, result: RecordsResult<T>): RecordsResult<T> {\n    if (result.ok) {\n      bundleDrop(tableId);\n      announceTableStructureChanged(tableId);\n    }\n    return result;\n  }\n\n  /**\n   * A DOOR THIS PACKAGE CALLS BEFORE THE MAIN DATABASE HAS IT (lane PLATFORM-APP-DATA).\n   *\n   * `callDoor` refuses a door the generated catalog does not list without asking anybody —\n   * right for a door nobody has built, wrong for one that is proven on the nightly clone and\n   * waiting for the chair's apply: the clone could never be tested through this package. So an\n   * OWED door is asked, and a store that answers \"no such function\" (PostgREST's PGRST202 or\n   * Postgres's 42883) is answered `door_absent` naming the file that owes it — the same refusal,\n   * the same sentence, with nothing read and nothing written. Once `pnpm records:generate` lists\n   * the door this is exactly `callDoor`.\n   */\n  async function owedDoor<T>(\n    door: string,\n    args: Record<string, unknown>,\n    where: string,\n  ): Promise<RecordsResult<T>> {\n    if (doorExists(door)) return callDoor<T>(door, args, where);\n    const primed = primedFor(door, args);\n    if (primed) return ok(primed.data as T);\n    const response = await config.dataSource.rpc(door, args, { schema });\n    if (response.error) {\n      const code = (response.error as { code?: string }).code;\n      const refusal =\n        code === \"PGRST202\" || code === \"42883\" ? doorAbsent(door) : mapPgError(response.error, where);\n      scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where });\n      return err(refusal);\n    }\n    return ok(response.data as T);\n  }\n\n  /**\n   * THE COPY'S LOOP (lane TABLE-ACTIONS). Each pass is a few seconds of work on the store; this\n   * calls `custom.table_duplicate_continue` until the store says \"done\", reporting every pass.\n   * THE CALLER LOOPS, as with tableArchive: a pass that fails leaves a copy the next call (or\n   * `tableDuplicateContinue`) carries on from exactly where it stopped.\n   */\n  /** How long the copy loop waits when another pass of the same copy is running. */\n  const COPY_BUSY_WAIT_MS = 1000;\n\n  async function carryOnCopy(\n    answer: unknown,\n    onProgress?: (progress: TableDuplicateProgress) => void,\n  ): Promise<RecordsResult<TableDuplicated>> {\n    // The first door's header (`from`, `organization`): the carry-on door never repeats it, so it is\n    // kept here and laid under every later answer before that answer is read.\n    const first = answer && typeof answer === \"object\" ? (answer as Record<string, unknown>) : {};\n    const header: Record<string, unknown> = {};\n    if (first.from !== undefined) header.from = first.from;\n    if (first.organization !== undefined) header.organization = first.organization;\n    // A refusal AFTER the store made a copy names that copy in `detail.copyId`, so a caller that\n    // must not leave it in anyone's list (a snapshot, a base copy) can put it away.\n    const unreadable = (copyId: string | null): RecordsResult<TableDuplicated> => {\n      const refusal: RecordsError = {\n        code: \"not_supported\",\n        message: \"The record store answered the copy in a shape this client cannot read. Look in the table list before trying again.\",\n        ...(copyId ? { hint: `copy ${copyId}`, detail: { copyId } } : {}),\n      };\n      scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where: \"tableDuplicate\" });\n      return err(refusal);\n    };\n    let current = answer;\n    let copyId: string | null = null;\n    // FB5: the bound is the knob custom/copy_stall_passes (default 20).\n    const stallPasses = (await askLimits()).copyStallPasses;\n    // THE STALL BOUND (live walk 2026-10-19, FIX-SNAP2): a pass that moved nothing — \"busy\", or the\n    // same counts at the same step — is counted; COPY_STALL_PASSES of them in a row stop the copy and\n    // say so, naming the half copy. The links step moves a cursor the counts do not show, so there a\n    // pass that did units is progress.\n    let lastMark: string | null = null;\n    let still = 0;\n    for (let pass = 0; pass < 10_000; pass += 1) {\n      const progress = parseTableDuplicateProgress(current);\n      if (!progress) return unreadable(copyId);\n      copyId = progress.tableId;\n      onProgress?.(progress);\n      const mark = JSON.stringify([progress.step, progress.choiceLists, progress.fields, progress.views, progress.records]);\n      const moved = progress.status !== \"busy\"\n        && (mark !== lastMark || (progress.step === \"links\" && (progress.pass?.units ?? 0) > 0));\n      if (progress.status !== \"busy\") lastMark = mark;\n      still = moved ? 0 : still + 1;\n      if (still >= stallPasses) {\n        const r = progress.records;\n        const at = r ? `${formatCount(r.done, { locale: \"en-US\" })} of ${formatCount(r.total, { locale: \"en-US\" })} rows` : `step ${progress.step || \"busy\"}`;\n        const refusal: RecordsError = {\n          code: \"internal\",\n          message: `The copy of ${progress.tableName} stopped moving at ${at} after ${stallPasses} passes, so it was stopped and not handed over.`,\n          hint: `copy ${progress.tableId}`,\n          detail: { copyId: progress.tableId, stalledAt: progress.step, passes: stallPasses },\n        };\n        scream({ code: refusal.code, message: refusal.message, hint: `copy ${progress.tableId}`, where: \"tableDuplicate\" });\n        return err(refusal);\n      }\n      if (progress.status === \"done\") {\n        const copied = parseTableDuplicated({ ...header, ...(current as Record<string, unknown>) });\n        return copied ? ok(copied) : unreadable(copyId);\n      }\n      if (progress.status === \"failed\" || progress.status === \"discarded\") {\n        // Not handed over: the store's sentence, and the copy's id so a screen can offer \"discard\".\n        const refusal: RecordsError = {\n          code: \"refused_by_rule\",\n          message: progress.sentence ?? \"This copy was stopped and not handed over.\",\n          hint: `copy ${progress.tableId}`,\n          detail: { copyId: progress.tableId },\n        };\n        scream({ code: refusal.code, message: refusal.message, where: \"tableDuplicate\" });\n        return err(refusal);\n      }\n      if (progress.status === \"busy\") {\n        // Another pass of this copy is running (another tab): wait, then ask again.\n        await new Promise((resolve) => setTimeout(resolve, COPY_BUSY_WAIT_MS));\n      }\n      const next = await owedDoor<unknown>(DOORS.tableDuplicateContinue, { p_table_id: progress.tableId }, \"tableDuplicate\");\n      if (!next.ok) {\n        const had = next.error.detail;\n        const detail = had && typeof had === \"object\" && !Array.isArray(had)\n          ? { ...(had as Record<string, unknown>), copyId: progress.tableId }\n          : had === undefined ? { copyId: progress.tableId } : { storeDetail: had, copyId: progress.tableId };\n        return err({ ...next.error, detail });\n      }\n      current = next.data;\n    }\n    return unreadable(copyId);\n  }\n\n  /**\n   * A PLATFORM DOOR IN `public` — the saved-view archive and the one restore door. Not the store's\n   * catalog (it reads `custom` only), so no census check; a missing door arrives as Postgres's own\n   * \"function not found\" through the same refusal funnel.\n   */\n  async function publicDoor<T>(\n    door: string,\n    args: Record<string, unknown>,\n    where: string,\n    schema = \"public\",\n  ): Promise<RecordsResult<T>> {\n    const response = await config.dataSource.rpc(door, args, { schema });\n    if (response.error) {\n      const refusal = mapPgError(response.error, where);\n      scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where });\n      return err(refusal);\n    }\n    return ok(response.data as T);\n  }\n\n  /**\n   * A TRUST DOOR — `iam`'s, not the store's.\n   *\n   * There is no `doorExists` check here on purpose: the store's generated\n   * catalog reads `custom` and only `custom`, so a census of it says nothing\n   * true about `iam`. A trust door that is not there answers with Postgres's\n   * own `42883`, which arrives through the same refusal funnel carrying the\n   * name that was called — an honest \"no such function\", never an empty array\n   * standing in for \"there is nothing\".\n   */\n  async function trustDoor<T>(\n    door: string,\n    args: Record<string, unknown>,\n    where: string,\n  ): Promise<RecordsResult<T>> {\n    const response = await config.dataSource.rpc(door, args, { schema: TRUST_SCHEMA });\n    if (response.error) {\n      const refusal = mapPgError(response.error, where);\n      scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where });\n      return err(refusal);\n    }\n    return ok(response.data as T);\n  }\n\n  /**\n   * A DOOR OF THE OLDER STORE — `workbench`'s, not this store's.\n   *\n   * Same reasoning as `trustDoor`: the generated catalog reads `custom` and\n   * only `custom`, so `doorExists` says nothing true about `workbench` and\n   * there is deliberately no census check here. A door that is not there\n   * arrives as Postgres's own `42883` through the same refusal funnel, carrying\n   * the name that was called — an honest \"no such function\", never an empty map\n   * standing in for \"these cells have no words\".\n   */\n  /**\n   * A DRILL DOOR — `platform`'s, not the store's (lane DRILL-STANDARD-DOOR).\n   *\n   * The one read contract answers a custom Table AND a standard table, so it lives beside the\n   * registry, not inside the record store; the generated catalog reads `custom` only and says\n   * nothing true about it, so there is no census check. A door not on the database yet arrives as\n   * PostgREST's own \"function not found\" through the same refusal funnel, naming what was called.\n   */\n  async function drillDoor<T>(\n    door: string,\n    args: Record<string, unknown>,\n    where: string,\n  ): Promise<RecordsResult<T>> {\n    const primed = primedFor(door, args);\n    if (primed) return ok(primed.data as T);\n    const response = await config.dataSource.rpc(door, args, { schema: DRILL_SCHEMA });\n    if (response.error) {\n      const refusal = mapPgError(response.error, where);\n      scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where });\n      return err(refusal);\n    }\n    return ok(response.data as T);\n  }\n\n  /**\n   * The read door returns ONE masked document with the notices folded in under\n   * `_hidden` (`custom.mask_document`). A screen wants them apart: the values it\n   * draws, and the reasons it shows where a value is missing. This splits them\n   * and nothing else — it never decides what is hidden, it only reads what the\n   * store already decided.\n   */\n  // THE TABLE KERNEL'S ID IS A CONSTANT OF THE STORE, so it is asked once per client and every\n  // caller shares the one answer (and the one request while it is in flight). A failed answer\n  // is not remembered: the next caller asks again.\n  let kernelAsked: Promise<RecordsResult<Uuid>> | null = null;\n  function tableKernel(where: string): Promise<RecordsResult<Uuid>> {\n    kernelAsked ??= callDoor<Uuid>(DOORS.tableKernelId, {}, where).then((answer) => {\n      if (!answer.ok) kernelAsked = null;\n      return answer;\n    });\n    return kernelAsked;\n  }\n\n  function unfold(document: unknown): { document: RecordDocument; hidden: Record<string, HiddenFieldNotice> } {\n    const raw = (document ?? {}) as Record<string, unknown>;\n    const hidden = (raw._hidden ?? {}) as Record<string, HiddenFieldNotice>;\n    const values: RecordDocument = {};\n    for (const [key, value] of Object.entries(raw)) {\n      if (key === \"_hidden\") continue;\n      values[key] = value;\n    }\n    return { document: values, hidden };\n  }\n\n  async function readValues(recordId: Uuid): Promise<RecordsResult<ReadValue[]>> {\n    return callDoor<ReadValue[]>(\n      DOORS.recordValuesVersioned,\n      { p_organization_id: org, p_record_id: recordId },\n      \"recordRead\",\n    );\n  }\n\n  // ── READS SPAN EVERY ORGANIZATION; WRITES KEEP ONE ─────────────────────────\n  // (active-org-is-never-a-list-filter.md.) `org` is the write destination. A\n  // read asks each of the person's organizations through a sibling client bound\n  // to it, so every row keeps its own `organization_id`.\n  const readOrgs = (filter?: Uuid | null): Array<Uuid | null> => {\n    if (filter) return [filter];\n    const all = [...(org ? [org] : []), ...(config.organizationIds ?? [])];\n    const unique = [...new Set(all)];\n    return unique.length > 0 ? unique : [org];\n  };\n  const siblings = new Map<Uuid, RecordsClient>();\n  const clientFor = (target: Uuid | null): RecordsClient => {\n    if (target === org) return client;\n    const key = target as Uuid;\n    let sibling = siblings.get(key);\n    if (!sibling) {\n      sibling = createRecordsClient({ ...config, organizationId: target, organizationIds: [] });\n      siblings.set(key, sibling);\n    }\n    return sibling;\n  };\n  /** Where a record was last opened successfully — the next open goes straight there. */\n  const recordOrgs = new Map<Uuid, Uuid | null>();\n  async function acrossOrgs<T>(\n    filter: Uuid | null | undefined,\n    ask: (sub: RecordsClient) => Promise<RecordsResult<T>>,\n    merge: (parts: T[]) => T,\n  ): Promise<RecordsResult<T>> {\n    const targets = readOrgs(filter);\n    if (targets.length === 1) return ask(clientFor(targets[0] ?? null));\n    const answers = await Promise.all(targets.map((t) => ask(clientFor(t))));\n    const parts: T[] = [];\n    let firstError: RecordsError | null = null;\n    for (const a of answers) {\n      if (a.ok) parts.push(a.data);\n      else firstError ??= a.error;\n    }\n    // A refusal from one organization is already screamed by its door; only when\n    // NOTHING answered is the whole read a failure.\n    if (parts.length === 0 && firstError) return err(firstError);\n    return ok(merge(parts));\n  }\n  /** Open one record in ITS OWN organization: the one it was seen in, else the\n   *  page's, else each of the person's — first that answers wins. */\n  async function openInOwnOrg<T>(\n    recordId: Uuid,\n    filter: Uuid | null | undefined,\n    ask: (sub: RecordsClient) => Promise<RecordsResult<T>>,\n    found: (data: T) => boolean,\n  ): Promise<RecordsResult<T>> {\n    const known = recordOrgs.get(recordId);\n    const targets = filter\n      ? [filter]\n      : known !== undefined\n        ? [known, ...readOrgs().filter((t) => t !== known)]\n        : readOrgs();\n    let last: RecordsResult<T> | null = null;\n    for (const t of targets) {\n      const answer = await ask(clientFor(t));\n      if (answer.ok && found(answer.data)) {\n        recordOrgs.set(recordId, t);\n        return answer;\n      }\n      last ??= answer;\n    }\n    return last as RecordsResult<T>;\n  }\n\n  /** Does this client span organizations (a host set `organizationIds`, or the page filtered)? */\n  const spans = (filter?: Uuid | null): boolean => Boolean(filter) || (config.organizationIds?.length ?? 0) > 0;\n  /**\n   * STRUCTURE SEARCH IN ONE ORGANIZATION — what `metadataSearch` means (the server's\n   * `RecordStore.metadata_search` is the same verb): the Tables and Fields whose name, key, label\n   * or description holds `text`, case-insensitively, never rows. Structure is records too, so this\n   * is the read door asked about the two kernels, every page, then matched here; the store decides\n   * which Tables and Fields this reader may see. An empty `text` matches every Table and Field.\n   * Until 2026-10-02 this refused as an absent door and the words reached nothing (lane 3).\n   */\n  const structureSearchIn = async (\n    target: Uuid | null,\n    text: string,\n  ): Promise<RecordsResult<MetadataSearchAnswer>> => {\n    const needle = (text ?? \"\").trim().toLowerCase();\n    const tableKernelAnswer = await tableKernel(\"metadataSearch.kernel\");\n    if (!tableKernelAnswer.ok) return err(tableKernelAnswer.error);\n    const fieldKernelAnswer = await callDoor<Uuid>(DOORS.fieldKernelId, {}, \"metadataSearch.fieldKernel\");\n    if (!fieldKernelAnswer.ok) return err(fieldKernelAnswer.error);\n    const matches: MetadataSearchAnswer[\"matches\"] = [];\n    for (const [kind, kernel] of [[\"table\", tableKernelAnswer.data], [\"field\", fieldKernelAnswer.data]] as const) {\n      for (let offset = 0; ; offset += TABLE_LIST_PAGE) {\n        const door = await callDoor<Array<{ id: Uuid; document: unknown; level: string }>>(\n          DOORS.readRecords,\n          { p_organization_id: target, p_table_id: kernel, p_limit: TABLE_LIST_PAGE, p_offset: offset },\n          \"metadataSearch\",\n        );\n        if (!door.ok) return err(door.error);\n        const page = door.data ?? [];\n        for (const row of page) {\n          const doc = unfold(row.document).document as Record<string, unknown>;\n          const words = (k: string): string => (typeof doc[k] === \"string\" ? (doc[k] as string) : \"\");\n          const name = words(\"name\") || words(\"label\") || words(\"key\");\n          const description = words(\"description\");\n          const haystack = [words(\"name\"), words(\"label\"), words(\"key\"), description].join(\"\\n\").toLowerCase();\n          if (needle && !haystack.includes(needle)) continue;\n          matches.push({\n            id: row.id,\n            kind,\n            name,\n            description: description || null,\n            ...(kind === \"field\"\n              ? { key: words(\"key\") || null, table_id: words(\"entity_definition_id\") || null, field_type: doc[\"type\"] ?? null }\n              : {}),\n            organization_id: target,\n          });\n        }\n        if (page.length < TABLE_LIST_PAGE) break;\n      }\n    }\n    matches.sort((a, b) => String(a[\"name\"] ?? \"\").localeCompare(String(b[\"name\"] ?? \"\")));\n    return ok({ matches, organizations_covered: target ? [target] : [], unavailable: [] });\n  };\n  const unavailableReason = (error: RecordsError): string =>\n    `${error.message}${error.hint ? ` ${error.hint}` : \"\"}`;\n\n  // ROLLUP-FORMAT: the fields of a table with the number format its formulas, rollups and lookups inherit worked out.\n  // A rollup / lookup with no declared format reads the look of the column it picks on the table its link reaches\n  // (forward: this table's own relation; back: another table's relation to this one, by key or inverse key), so the\n  // far table's fields are read too (their own looks first, so lookup -> formula -> rollup settles). Only done when\n  // a derived column lacks a format; a far table that cannot be read leaves that column as it was.\n  const withLooksFromLinkedTables = async (tableId: Uuid, fields: Field[], trail: readonly Uuid[]): Promise<Field[]> => {\n    const base = withFormulaLooks(fields);\n    const vias = new Set<string>();\n    for (const f of base as unknown as Array<Record<string, unknown>>) {\n      const via = (f[\"config\"] as { via?: unknown } | null | undefined)?.via;\n      if (isDerivedField(f) && !f[\"display_format\"] && typeof via === \"string\" && via) vias.add(via);\n    }\n    if (!vias.size || trail.length >= 3) return base;\n    const here = [...trail, tableId];\n    let reverse: ReverseColumn[] | undefined;\n    const far = new Map<string, Array<readonly Record<string, unknown>[]>>();\n    for (const via of vias) {\n      const own = base.find((f) => f.key === via && f.type === \"relation\");\n      let targets: Uuid[] = [];\n      if (own) targets = own.relation_target ? [own.relation_target] : [];\n      else {\n        if (!reverse) {\n          const cols = await client.reverseColumns({ table_id: tableId });\n          reverse = cols.ok ? cols.data : [];\n        }\n        targets = reverse.filter((c) => c.key === via).map((c) => c.source_table_id);\n      }\n      const lists: Array<readonly Record<string, unknown>[]> = [];\n      for (const id of targets.filter((t) => !here.includes(t))) {\n        const door = await callDoor<Array<{ id: Uuid; data: unknown }>>(\n          DOORS.applicableFields,\n          { p_organization_id: org, p_table_id: id },\n          \"fields\",\n        );\n        if (!door.ok) continue;\n        const farFields = (door.data ?? []).map((row) => ({ id: row.id, ...(row.data as object) }) as Field);\n        lists.push((await withLooksFromLinkedTables(id, farFields, here)) as unknown as Array<Record<string, unknown>>);\n      }\n      far.set(via, lists);\n    }\n    return withDerivedLooks(base, (via) => far.get(via) ?? []);\n  };\n\n  /**\n   * ADVERSARIAL-11 F3. A filter that says \"today\", \"overdue\" or \"this week\" is worked out HERE, in the\n   * zone this reader is in right now (relativeDays.ts), and goes out as exact bounds, so the day never\n   * depends on a saved zone that is a browser behind. A filter with no relative window is returned as is\n   * without reading anything; a failed read of the Fields leaves the filter for the store to work out.\n   */\n  async function readersFilter<F>(table_id: Uuid, filter: F): Promise<F> {\n    if (!holdsRelativeDays(filter)) return filter;\n    const [fields, calendar] = await Promise.all([client.fields({ table_id }), client.aggCalendar()]);\n    if (!fields.ok) return filter;\n    const weekStart = calendar.ok ? weekStartIndexOf(calendar.data.week_start) : 1;\n    return resolveRelativeDays(filter, lookupFromFields(fields.data), { weekStart }) as F;\n  }\n\n  const client: RecordsClient = {\n    config,\n    scopes,\n\n    async recordWrite({ table_id, data }) {\n      // THE OP ID RIDES THE ENVELOPE. `_op_id` is a platform envelope key — the same class as\n      // `_actor` — which the store lifts out BEFORE its undeclared-key guard and BEFORE\n      // storage, so it never lands on the record. It comes back in the realtime notice, which\n      // is how this browser recognizes the echo of its own write and does not re-read a page\n      // it has already updated. See `../ops.ts`.\n      const result = await callDoor<Uuid>(\n        DOORS.recordWrite,\n        { p_organization_id: org, p_table_id: table_id, p_data: { ...data, _op_id: mintOp() } },\n        \"recordWrite\",\n      );\n      // A NEW RECORD IS A CHANGE TOO (VIEWS-AND-FIELDS BL): a record made on one table can change\n      // what ANOTHER screen shows — the linked table's reverse column — so it is announced like\n      // every other write door's answer, never only through the realtime notice.\n      if (result.ok && typeof result.data === \"string\") announceRecordChanged(result.data);\n      return result;\n    },\n\n    async recordWriteMany({ table_id, rows, ids }) {\n      // ONE CALL IS ONE OPERATION, so one op id for the whole batch: the store announces one\n      // statement once, and it REFUSES a batch carrying two different ids by name.\n      const opId = mintOp();\n      return callDoor<Uuid[]>(\n        DOORS.recordWriteMany,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_rows: rows.map((row) => ({ ...row, _op_id: opId })),\n          ...(ids === undefined ? {} : { p_ids: ids }),\n        },\n        \"recordWriteMany\",\n      );\n    },\n\n    async recordChangeMany({ table_id, changes }) {\n      // ONE BATCH IS ONE OPERATION: one op id on every insert and patch, so the browser that made\n      // the change recognizes the one notice announcing it.\n      const opId = mintOp();\n      // EVERY RECORD A BATCH TOUCHED IS ANNOUNCED, as a single `recordUpdate` is (merged-grid\n      // review 2026-09-26): a paste or a bulk set is one `record_change_many`, and the record\n      // panel open on one of those rows kept its old values because nothing told it.\n      const result = await callDoor<RecordChangeResult[]>(\n        DOORS.recordChangeMany,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_changes: changes.map((change) =>\n            change.op === \"insert\"\n              ? { op: \"insert\", data: { ...change.data, _op_id: opId } }\n              : change.op === \"update\"\n                ? {\n                    op: \"update\",\n                    record_id: change.record_id,\n                    patch: { ...change.patch, _op_id: opId },\n                    ...(change.expected_version === undefined || change.expected_version === null\n                      ? {}\n                      : { expected_version: change.expected_version }),\n                  }\n                : { op: \"archive\", record_id: change.record_id },\n          ),\n        },\n        \"recordChangeMany\",\n      );\n      if (result.ok) for (const changed of result.data ?? []) if (changed?.id) announceRecordChanged(changed.id);\n      return result;\n    },\n\n    async recordWriteGraph({ table_id, parent, children, edges }) {\n      // ONE GRAPH IS ONE OPERATION, so one op id for the whole thing: the door copies the\n      // parent's onto every child, and the store announces the statement once.\n      const opId = mintOp();\n      return callDoor<RecordGraphWritten>(\n        DOORS.recordWriteGraph,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_parent: { ...parent, _op_id: opId },\n          p_edges: edges ?? [],\n          p_children: (children ?? []).map((child) => ({\n            data: child.data,\n            role: child.role,\n            ...(child.table_id === undefined ? {} : { table_id: child.table_id }),\n            ...(child.position === undefined ? {} : { position: child.position }),\n          })),\n        },\n        \"recordWriteGraph\",\n      );\n    },\n\n    async recordUpdate({ record_id, patch, expectedVersion }) {\n      const result = await callDoor<number>(\n        DOORS.recordUpdate,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_patch: { ...patch, _op_id: mintOp() },\n          ...(expectedVersion === undefined ? {} : { p_expected_version: expectedVersion }),\n        },\n        \"recordUpdate\",\n      );\n      if (result.ok) announceRecordChanged(record_id);\n      return result;\n    },\n\n    async recordUpdateAddingChoices({ record_id, patch, add, expectedVersion }) {\n      const result = await callDoor<number>(\n        DOORS.recordUpdateAddingChoices,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_patch: { ...patch, _op_id: mintOp() },\n          p_add: add,\n          ...(expectedVersion === undefined ? {} : { p_expected_version: expectedVersion }),\n        },\n        \"recordUpdateAddingChoices\",\n      );\n      if (result.ok) announceRecordChanged(record_id);\n      return result;\n    },\n\n    async choiceNudge() {\n      const result = await callDoor<string>(DOORS.choiceNudge, { p_organization_id: org }, \"choiceNudge\");\n      if (!result.ok) return result;\n      return ok(asChoiceNudge(result.data));\n    },\n\n    async recordDelete({ record_id }) {\n      const result = await callDoor<Timestamp>(\n        DOORS.recordDelete,\n        { p_organization_id: org, p_record_id: record_id },\n        \"recordDelete\",\n      );\n      if (result.ok) {\n        markRecordRemoved(record_id);\n        announceRecordChanged(record_id);\n      }\n      return result;\n    },\n\n    async tableHomes({ table_id }) {\n      return callDoor<Array<{ home_id: Uuid; name: string | null; declared: boolean }>>(\n        DOORS.tableHomesNamed,\n        { p_organization_id: org, p_table_id: table_id },\n        \"tableHomes\",\n      );\n    },\n\n    async homeAdd({ table_id, home_record_id }) {\n      const result = await callDoor<Uuid>(\n        DOORS.homeAdd,\n        { p_organization_id: org, p_table_id: table_id, p_home_record_id: home_record_id },\n        \"homeAdd\",\n      );\n      if (result.ok) announceRecordChanged(table_id);\n      return result;\n    },\n\n    async recordReparent({ record_id, parent_id }) {\n      const result = await callDoor<null>(\n        DOORS.recordReparent,\n        { p_organization_id: org, p_record_id: record_id, p_parent_id: parent_id },\n        \"recordReparent\",\n      );\n      if (result.ok) announceRecordChanged(record_id);\n      return result;\n    },\n\n    async recordRestore({ record_id }) {\n      const result = await callDoor<void>(\n        DOORS.recordRestore,\n        { p_organization_id: org, p_record_id: record_id },\n        \"recordRestore\",\n      );\n      if (result.ok) {\n        markRecordRestored(record_id);\n        announceRecordChanged(record_id);\n      }\n      return result;\n    },\n\n    async tableArchive({ table_id, chunk, includeTable }) {\n      // EVERY ARGUMENT IS SAID OUT LOUD, including the two the function\n      // defaults. A caller that leaves `p_chunk` off is agreeing to a number it\n      // cannot see, and a loop's pass size is the one thing a loop actually has\n      // an opinion about. So the package states it — and the door still clamps\n      // it and reports what it actually took.\n      //\n      // WHY 20 (TABLE_ARCHIVE_PASS). Measured against the live store on 2026-09-22 one record\n      // cost ~35ms to archive, so 200 died on `57014` and 50 (~1.8s) was chosen. Re-measured on\n      // the clone 2026-10-03 through PostgREST, under the load the store actually carries now (a\n      // record also takes its history capture, outbox row, associations, and the last pass takes\n      // what is built on the table): ~150ms a record — a pass of 10 took 1.6s, 10 + the Table\n      // itself 3.2s — so 50 is ~7.5s against the 8s statement timeout and timed out under load.\n      // 20 is ~3-4s with the Table's own pass included; the caller's loop still halves on a\n      // timeout (useTableArchive), so a busier store slows the run, never fails it.\n      return callDoor<TableArchiveProgress>(\n        DOORS.tableArchive,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_chunk: chunk ?? TABLE_ARCHIVE_PASS,\n          p_include_table: includeTable ?? true,\n        },\n        \"tableArchive\",\n      );\n    },\n\n    async tableArchiveDeliberately({ table_id, typed_slug, reason }) {\n      // OWED, like `tableRestore` below: proven on the nightly clone, waiting for the chair's\n      // production apply (lane 12 P5). `callDoor` refused it before the network on every store,\n      // the clone included, so the typed-table suite could never reach the door it tests.\n      return owedDoor<TableArchiveProgress>(\n        DOORS.tableArchiveDeliberately,\n        { p_organization_id: org, p_table_id: table_id, p_typed_slug: typed_slug, p_reason: reason },\n        \"tableArchiveDeliberately\",\n      );\n    },\n\n    async tableRestore({ table_id, chunk }) {\n      // THE DOOR LANDED: `custom.table_restore` is in the generated catalog (2026-10-03).\n      return callDoor<TableRestoreProgress>(\n        DOORS.tableRestore,\n        { p_organization_id: org, p_table_id: table_id, p_chunk: chunk ?? TABLE_RESTORE_PASS },\n        \"tableRestore\",\n      );\n    },\n\n    async tableRestoreWhole({ table_id, onPass }) {\n      let size = TABLE_RESTORE_PASS;\n      for (let pass = 0; pass < TABLE_RESTORE_MAX_PASSES; pass += 1) {\n        const answered = await client.tableRestore({ table_id, chunk: size });\n        if (!answered.ok) {\n          if (answered.error.code === \"timed_out\" && size > TABLE_RESTORE_MIN_PASS) {\n            size = Math.max(TABLE_RESTORE_MIN_PASS, Math.floor(size / 2));\n            continue;\n          }\n          // The door is on the main database now (2026-10-03); a store that does not serve it\n          // answers `store_not_served` and nothing is tried blind in its place — the one-call\n          // `record_restore` fallback left with the door's arrival, since it brought back the\n          // table's row and none of its rows' archive marks.\n          return answered;\n        }\n        onPass?.(answered.data);\n        if (answered.data.done) return answered;\n      }\n      return err({\n        code: \"internal\",\n        message: `The table is not all back after ${TABLE_RESTORE_MAX_PASSES} passes. Bring it back again to carry on — it picks up where this left off.`,\n      } as RecordsError);\n    },\n\n    async tableDuplicate({ tableId, withRecords, name, organizationId, onProgress }) {\n      // Every argument said out loud, as tableArchive does: whether the rows come too is the one\n      // thing a person decided, so the package never leaves it to a default nobody sees.\n      const first = await owedDoor<unknown>(\n        DOORS.tableDuplicate,\n        {\n          p_table_id: tableId,\n          p_with_records: withRecords ?? false,\n          p_name: name?.trim() ? name.trim() : null,\n          p_organization_id: organizationId ?? null,\n        },\n        \"tableDuplicate\",\n      );\n      if (!first.ok) return first;\n      return carryOnCopy(first.data, onProgress);\n    },\n\n    async tableCopiesInProgress() {\n      const answered = await owedDoor<unknown>(DOORS.tableCopiesInProgress, {}, \"tableCopiesInProgress\");\n      if (!answered.ok) return answered;\n      return ok(parseTableCopiesInProgress(answered.data));\n    },\n\n    async tableDuplicateContinue({ copyId, onProgress }) {\n      const pass = await owedDoor<unknown>(DOORS.tableDuplicateContinue, { p_table_id: copyId }, \"tableDuplicateContinue\");\n      if (!pass.ok) return pass;\n      return carryOnCopy(pass.data, onProgress);\n    },\n\n    async recordRead({ record_id, withComputed = false, withVersion = false, organization_id }) {\n      if (organization_id && organization_id !== org) {\n        return clientFor(organization_id).recordRead({ record_id, withComputed, withVersion, organization_id });\n      }\n      if (readOrgs(organization_id).length > 1) {\n        return openInOwnOrg(\n          record_id,\n          organization_id,\n          (sub) => sub.recordRead({ record_id, withComputed, withVersion, organization_id: (sub.config.organizationId) }),\n          () => true,\n        );\n      }\n      // DOOR-1: `custom.read_record` resolves the reader from the session,\n      // refuses a record they have no read access to in the store's own sentence,\n      // and masks the fields their level does not reach. This client no longer\n      // selects `custom.record` for a read — that path returned rows and fields\n      // the store had not agreed this person could see.\n      // THE VERSION COMES WITH THE READ when asked (`withVersion`): the read door answers the document only,\n      // so its header (the version a safe edit must carry) is asked in the same round, never as a caller's\n      // second call. Off by default so a screen that draws first and versions later is never held back.\n      const [door, header] = await Promise.all([\n        callDoor<unknown>(DOORS.readRecord, { p_organization_id: org, p_record_id: record_id }, \"recordRead\"),\n        // A version that cannot be read never takes the record away: it comes back as null.\n        withVersion\n          ? callDoor<RecordHeader[]>(DOORS.recordHeaders, { p_organization_id: org, p_ids: [record_id] }, \"recordRead.version\").catch(\n              () => null,\n            )\n          : Promise.resolve(null),\n      ]);\n      if (!door.ok) return err(door.error);\n      const version = header && header.ok ? (header.data?.find((h) => h.id === record_id)?.version ?? null) : null;\n      const { document, hidden } = unfold(door.data);\n\n      // 🚨 A DECORATION NEVER TAKES THE RECORD AWAY (lane LIMITS-FIX-UI, 2026-09-21).\n      //\n      // `custom.computed_provenance` answers WHICH RULE produced a worked-out value\n      // (FLD-9). It is a footnote beside the record — and it has NO EXECUTE grant to\n      // `authenticated`, measured on the live catalog:\n      //\n      //   read_record          authenticated may: t\n      //   record_history       authenticated may: t\n      //   field_history        authenticated may: t\n      //   computed_provenance  authenticated may: f\n      //\n      // `Peek` asks for the record WITH provenance, so this line returned that door's\n      // refusal AS THE RECORD'S: the owner of an organization opened a record in it and\n      // was told \"You do not have access to this\", above a history, a running checklist\n      // and a comment box that all loaded perfectly. Reported twice — by the SCREENS-2\n      // lane on a dental practice, and by crew E2, who checked at the doors and found\n      // the record read itself answering correctly from that very seat.\n      //\n      // So the record comes back. The footnote's absence is REPORTED rather than\n      // swallowed (nothing fails silently): `computedUnavailable` carries the refusal,\n      // and a screen that draws rule provenance says it could not read it instead of\n      // drawing nothing and meaning two different things by it.\n      let computed: RecordRead[\"computed\"] = [];\n      let computedUnavailable: RecordsError | null = null;\n      if (withComputed) {\n        const provenance = await callDoor<RecordRead[\"computed\"]>(\n          DOORS.computedProvenance,\n          { p_organization_id: org, p_record_id: record_id },\n          \"recordRead.computed\",\n        );\n        if (provenance.ok) computed = provenance.data ?? [];\n        else computedUnavailable = provenance.error;\n      }\n      return ok({ record_id, document, hidden, computed, computedUnavailable, ...(withVersion ? { version } : {}) });\n    },\n\n    async listByIds({ table_id, ids }) {\n      // NOTHING ASKED FOR IS AN EMPTY ANSWER, not a round trip. The door says the same, but\n      // a call that cannot return a row should not cost one.\n      if (ids.length === 0) return ok([]);\n      const door = await callDoor<Array<{ id: Uuid; document: unknown; level: string }>>(\n        DOORS.readRecordsByIds,\n        { p_organization_id: org, p_table_id: table_id, p_record_ids: ids },\n        \"listByIds\",\n      );\n      if (!door.ok) return err(door.error);\n      return ok(\n        splitLockedRows(\n          (door.data ?? []).map((row): ReadRow => {\n            const { document, hidden } = unfold(row.document);\n            return { id: row.id, document, level: row.level, hidden, ...waitingMark(row) };\n          }),\n        ).rows,\n      );\n    },\n\n    async tableFacts(args) {\n      if (!doorExists(DOORS.tableFacts)) return ok(null);\n      if (args?.organization_id && args.organization_id !== org) {\n        return clientFor(args.organization_id).tableFacts(args);\n      }\n      if (readOrgs(args?.organization_id).length > 1) {\n        return acrossOrgs<TableFact[] | null>(\n          args?.organization_id,\n          (sub) => sub.tableFacts({ organization_id: sub.config.organizationId }),\n          (parts) => parts.flatMap((p) => p ?? []),\n        );\n      }\n      return callDoor<TableFact[]>(DOORS.tableFacts, { p_organization_id: org }, \"tableFacts\");\n    },\n\n    async tablesLiveWhere({ table_ids }) {\n      if (table_ids.length === 0) return ok([]);\n      const answered = await callDoor<unknown>(DOORS.tablesLiveWhere, { p_table_ids: table_ids }, \"tablesLiveWhere\");\n      if (!answered.ok) return answered;\n      if (!Array.isArray(answered.data)) {\n        const refusal: RecordsError = {\n          code: \"not_supported\",\n          message: \"The record store answered where these tables are written in a shape this client cannot read, so no write location was assumed.\",\n          hint: \"Regenerate @ai-matrx/records against the store (pnpm records:generate) — the door and this client disagree.\",\n        };\n        scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where: \"tablesLiveWhere\" });\n        return err(refusal);\n      }\n      const locations: TableLiveLocation[] = [];\n      for (const row of answered.data) {\n        const value = row && typeof row === \"object\" ? row as { table_id?: unknown; lives_in?: unknown; why?: unknown } : null;\n        if (!value || typeof value.table_id !== \"string\" || (value.lives_in !== \"record\" && value.lives_in !== \"older\") || (value.why !== null && value.why !== undefined && typeof value.why !== \"string\")) {\n          const refusal: RecordsError = { code: \"not_supported\", message: \"The record store returned an invalid table write location, so no write location was assumed.\" };\n          scream({ code: refusal.code, message: refusal.message, where: \"tablesLiveWhere\" });\n          return err(refusal);\n        }\n        locations.push({ table_id: value.table_id as Uuid, lives_in: value.lives_in, why: typeof value.why === \"string\" ? value.why : null });\n      }\n      return ok(locations);\n    },\n\n    async baseCopyFinish({ organizationId, pairs }) {\n      const answered = await callDoor<{ relinked_columns?: number; relinked_cells?: number }>(\n        DOORS.baseCopyFinish,\n        { p_organization_id: organizationId, p_pairs: pairs },\n        \"baseCopyFinish\",\n      );\n      if (!answered.ok) return answered;\n      return ok({ relinked_columns: Number(answered.data?.relinked_columns ?? 0), relinked_cells: Number(answered.data?.relinked_cells ?? 0) });\n    },\n\n    async copyTableExtras({ organizationId, pairs }) {\n      const answered = await callDoor<{ automations?: number; pages?: number; extras_refused?: unknown }>(\n        DOORS.copyTableExtras,\n        { p_organization_id: organizationId, p_pairs: pairs },\n        \"copyTableExtras\",\n      );\n      if (!answered.ok) return answered;\n      const refused = Array.isArray(answered.data?.extras_refused) ? answered.data.extras_refused.filter((x): x is string => typeof x === \"string\") : [];\n      return ok({ automations: Number(answered.data?.automations ?? 0), pages: Number(answered.data?.pages ?? 0), extras_refused: refused });\n    },\n\n    async tableHome({ table_id }) {\n      const answered = await callDoor<unknown>(DOORS.tableHome, { p_table_id: table_id }, \"tableHome\");\n      if (!answered.ok) return answered;\n      if (answered.data === null || answered.data === undefined) return ok(null);\n      const home = parseTableHome(answered.data);\n      if (!home) {\n        const refusal: RecordsError = {\n          code: \"not_supported\",\n          message: \"The record store answered where this table lives in a shape this client cannot read, so nothing is claimed about it.\",\n          hint: \"Regenerate @ai-matrx/records against the store (pnpm records:generate) — the door and this client disagree.\",\n        };\n        scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where: \"tableHome\" });\n        return err(refusal);\n      }\n      return ok(home);\n    },\n\n    async tableMove({ table_id, to_organization_id, expected_version }) {\n      const answered = await callDoor<unknown>(\n        DOORS.tableMove,\n        { p_table_id: table_id, p_to_organization_id: to_organization_id, p_expected_version: expected_version ?? null },\n        \"tableMove\",\n      );\n      if (!answered.ok) return answered;\n      const moved = parseTableMoved(answered.data);\n      if (!moved) {\n        const refusal: RecordsError = {\n          code: \"not_supported\",\n          message: \"The record store answered the move in a shape this client cannot read. Look where the table lives before trying again.\",\n        };\n        scream({ code: refusal.code, message: refusal.message, where: \"tableMove\" });\n        return err(refusal);\n      }\n      return ok(moved);\n    },\n\n    async baseMove({ home_id, to_organization_id }) {\n      const answered = await callDoor<unknown>(DOORS.baseMove, { p_home_id: home_id, p_to_organization_id: to_organization_id }, \"baseMove\");\n      if (!answered.ok) return answered;\n      const d = answered.data as { moved?: unknown; name?: unknown; to_organization_id?: unknown; tables?: unknown } | null;\n      if (!d || d.moved !== true || typeof d.to_organization_id !== \"string\") {\n        const refusal: RecordsError = {\n          code: \"not_supported\",\n          message: \"The record store answered the base move in a shape this client cannot read. Look where the base lives before trying again.\",\n        };\n        scream({ code: refusal.code, message: refusal.message, where: \"baseMove\" });\n        return err(refusal);\n      }\n      return ok({\n        name: typeof d.name === \"string\" ? d.name : \"\",\n        toOrganizationId: d.to_organization_id as Uuid,\n        tables: Array.isArray(d.tables) ? d.tables.length : 0,\n      });\n    },\n\n    async tableArchived({ table_id }) {\n      // Through the SAME archived door a table's own archive uses, addressed at\n      // the Table kernel (every Table is a record in it). Paged until the door\n      // answers short, so a Table past the first page is still found.\n      const kernel = await callDoor<Uuid>(DOORS.tableKernelId, {}, \"tableArchived.kernel\");\n      if (!kernel.ok) return err(kernel.error);\n      const PAGE = 200;\n      for (let page = 0; page < 25; page += 1) {\n        const answered = await this.listArchived({\n          table_id: kernel.data,\n          lane: \"org\",\n          limit: PAGE,\n          offset: page * PAGE,\n        });\n        if (!answered.ok) return err(answered.error);\n        const hit = answered.data.rows.find((row) => row.id === table_id);\n        if (hit) return ok(hit);\n        if (answered.data.total !== null) return ok(null);\n      }\n      return ok(null);\n    },\n\n    async listArchived({ table_id, lane = DEFAULT_ARCHIVE_LANE, limit = 50, offset = 0 }) {\n      // THE ROWS THAT LEFT, THROUGH THE STORE. The lane is handed to the door\n      // rather than applied here, for the reason every filter in this client is:\n      // a browser can only ever narrow the rows it was already given, so a lane\n      // decided on this side would silently drop the rest of the answer and call\n      // it \"mine\".\n      const door = await callDoor<ArchivedDoorRow[]>(\n        DOORS.readRecordsArchived,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_lane: lane,\n          p_limit: limit,\n          p_offset: offset,\n        },\n        \"listArchived\",\n      );\n      if (!door.ok) return err(door.error);\n      const rows: ArchivedRow[] = (door.data ?? []).map((row) => {\n        const { document, hidden } = unfold(row.document);\n        return {\n          id: row.id,\n          document,\n          level: row.level,\n          hidden,\n          archivedAt: row.archived_at,\n          archivedBy: row.archived_by ?? null,\n          archivedByName: row.archived_by_name ?? null,\n        };\n      });\n      // The same honest arithmetic `list` does, for the same reason: a short\n      // page has reached the end of the set this reader may see, so its size is\n      // known; a full page says only \"at least this many\", which is not a total.\n      const total = rows.length < limit ? offset + rows.length : null;\n      return ok({ rows, total });\n    },\n\n    async list({ table_id, filter: asked, limit = 50, offset = 0 }) {\n      const filter = await readersFilter(table_id, asked);\n      // ONE DOOR FOR ALL FOUR SURFACES. The grid, the board, the record list\n      // and a dashboard drill-through all arrive here, and they all ask\n      // `custom.read_records_matching` — with `{}` when nobody asked a\n      // question. The filtered and the unfiltered page are then the SAME body\n      // in the database, decided by the same ladder, so a narrowed screen can\n      // never be a differently-judged screen.\n      const door = await callDoor<Array<{ id: Uuid; document: unknown; level: string }>>(\n        DOORS.readRecordsMatching,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_filter: filter ?? {},\n          p_limit: limit,\n          p_offset: offset,\n        },\n        \"list\",\n      );\n      if (!door.ok) return err(door.error);\n      const read: ReadRow[] = (door.data ?? []).map((row) => {\n        const { document, hidden } = unfold(row.document);\n        return { id: row.id, document, level: row.level, hidden, ...waitingMark(row) };\n      });\n      // HEADER-ONLY STUBS ARE NOT ROWS (honest-hidden-rows): a row this person cannot open is\n      // counted in `locked`, never drawn. The page was short or full by what the DOOR returned.\n      const { rows, locked } = splitLockedRows(read);\n      // WHAT THE TOTAL HONESTLY IS, AND WHEN IT IS KNOWN FOR NOTHING.\n      //\n      // The door reads live records only — a deleted record is not in its set —\n      // and it counts nothing, so a total taken from the table would be a count\n      // of rows this reader may not see, with a number on it. That stays true\n      // and no count is ever asked for.\n      //\n      // But a SHORT PAGE already answers the question. If the door was asked\n      // for `limit` and handed back fewer, the reader has reached the end of\n      // the set it is allowed to see, so the size of that set is exactly\n      // `offset + rows.length` — the visible total, arrived at by arithmetic on\n      // a page that had to be read anyway, with no second query and no leak.\n      // Until 2026-09-21 this answered null unconditionally and a table holding\n      // ten records told its owner \"Unknown total — showing the 10 records\n      // loaded so far\", which is a screen refusing to say a thing it knows.\n      //\n      // 🚨 THIS RESTS ON ONE FACT ABOUT THE DOOR, AND THE FACT IS NOT THE\n      // OBVIOUS ONE. `custom.read_records_matching` DOES clamp through\n      // `custom.page_size(org, door, limit, 200)` — the first draft of this\n      // comment said it did not, and the live clause below caught that while it\n      // was being written. What makes the inference safe is what that helper\n      // does at the ceiling: measured on the live store 2026-09-21, a request\n      // over it is REFUSED BY NAME — \"custom.read_records_matching was asked for 1001\n      // rows; this store serves at most 1000 rows in one page, so nothing was\n      // read rather than quietly reading fewer\" — and 1, 50, 200 and 1000 each\n      // come back as themselves. A page is therefore never quietly made\n      // smaller, so a successful call that returns fewer rows than it asked for\n      // has reached the end of the set and nothing else.\n      //\n      // If that ever changed — if the door began shrinking a page instead of\n      // refusing it — a clamped FULL page would read as a short one and a\n      // person with two hundred records would be told they have fifty. So the\n      // live suite asserts the refusal, not the absence of a clamp; that clause\n      // is what makes this inference safe to keep rather than a thing that\n      // quietly rots.\n      //\n      // A FULL page says only \"at least this many\", which is not a total, so it\n      // stays null and the screen keeps saying what it is actually showing.\n      // Stubs sit in positions the earlier pages cannot be asked about, so with any stub on the page\n      // the count is exact only from the first page; later it is honestly unknown.\n      const total =\n        read.length >= limit ? null : locked === 0 ? offset + rows.length : offset === 0 ? rows.length : null;\n      return ok({ rows, total, ...(locked > 0 ? { locked } : {}) });\n    },\n\n    async listPage({ table_id, filter: asked, search, sort, view_id, limit = 50, offset = 0 }) {\n      const filter = await readersFilter(table_id, asked);\n      const door = await callDoor<{\n        total: number | string;\n        limit: number;\n        offset: number;\n        rows: Array<{ id: Uuid; document: unknown; level: string }> | null;\n        sort_ignored?: unknown;\n        filter_ignored?: unknown;\n      }>(\n        DOORS.readRecordsPage,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_filter: filter ?? {},\n          p_search: search ?? null,\n          p_sort: sort ?? [],\n          p_view_id: view_id ?? null,\n          p_limit: limit,\n          p_offset: offset,\n        },\n        \"listPage\",\n      );\n      if (!door.ok) return err(door.error);\n      const answer = door.data;\n      const { rows, locked: lockedOnPage } = splitLockedRows(\n        (answer?.rows ?? []).map((row): ReadRow => {\n          const { document, hidden } = unfold(row.document);\n          return { id: row.id, document, level: row.level, hidden, ...waitingMark(row) };\n        }),\n      );\n      // HEADER-ONLY STUBS ARE NOT ROWS (honest-hidden-rows). The live page door puts them in only\n      // a plain page (no filter, search, sort or view). Its total can therefore include stubs on\n      // an earlier or later page, so plain pages ask the aggregate for the readable total.\n      let total = Number(answer?.total ?? 0);\n      let locked = 0;\n      const unfiltered = (!filter || Object.keys(filter).length === 0) && (!search || search.trim() === \"\") && view_id == null;\n      const plainPage = unfiltered && (!sort || sort.length === 0);\n      // A SORTED PAGE OF THE WHOLE TABLE (walk 2026-10-08 D8). A sort places no header row, so a member of\n      // a Confidential table with a default sort (Title ↑) read \"No records yet · 0 rows\". The store's\n      // sort-only page now answers `locked`: how many rows of the table this reader cannot open.\n      const lockedOffPage = Number((answer as { locked?: number | string } | null)?.locked ?? 0);\n      if (!plainPage && unfiltered && Number.isFinite(lockedOffPage) && lockedOffPage > 0) {\n        locked = Math.max(lockedOnPage, lockedOffPage);\n      }\n      if (plainPage) {\n        const counted = await client.recordAggregate({ table_id, measures: [{ op: \"count\" }] });\n        if (!counted.ok) return err(counted.error);\n        const openable = Number(counted.data[0]?.row_count ?? 0);\n        if (!Number.isFinite(openable) || openable < 0) {\n          return err({ code: \"internal\", message: \"The store's readable-row count is not a valid page total.\", hint: \"Refresh this table. If it continues, the store must return a non-negative count.\" });\n        }\n        // The two doors are separate snapshots. An insert between them makes the readable count\n        // larger than the page's earlier total; keep that newer count and do not invent locks.\n        locked = openable <= total ? Math.max(lockedOnPage, total - openable) : lockedOnPage;\n        total = openable;\n      } else if (lockedOnPage > 0 && locked === 0) {\n        // Complex pages normally exclude stubs at the store. If an older store still returns one,\n        // remove only what this answer proves instead of guessing about unseen pages.\n        locked = lockedOnPage;\n        total = Math.max(rows.length, total - lockedOnPage);\n      }\n      return ok({\n        rows,\n        ...(locked > 0 ? { locked } : {}),\n        total,\n        limit: Number(answer?.limit ?? limit),\n        offset: Number(answer?.offset ?? offset),\n        sort_ignored: Array.isArray(answer?.sort_ignored)\n          ? (answer.sort_ignored as unknown[]).filter((k): k is string => typeof k === \"string\")\n          : [],\n        filter_ignored: Array.isArray(answer?.filter_ignored)\n          ? (answer.filter_ignored as unknown[]).filter((k): k is string => typeof k === \"string\")\n          : [],\n      });\n    },\n\n    async listKeyset({ table_id, filter: asked, search, sort, after, ids, limit = 50 }) {\n      const filter = await readersFilter(table_id, asked);\n      // The cursor is opened at the edge: a string that is not one of the store's cursors is refused\n      // here, by name — it is never sent as \"no cursor\", which would quietly start again at page 1.\n      let pAfter: Record<string, unknown> | null = null;\n      if (ids === undefined && after) {\n        pAfter = decodeKeysetCursor(after);\n        if (!pAfter) {\n          const hint = \"Pass back the cursor exactly as the last page answered it, or start from the first page, without a cursor.\";\n          const refusal: RecordsError = {\n            code: \"invalid_argument\",\n            message: \"This page cursor is damaged, so it cannot say where the next page starts. Nothing was read.\",\n            hint,\n          };\n          scream({ code: refusal.code, message: refusal.message, hint, where: \"listKeyset\" });\n          return err(refusal);\n        }\n      }\n      // OWED until `pnpm records:generate` lists it: the door is live, so it is asked; a store without\n      // it answers `door_absent` naming the lane, never an empty page.\n      const door = await owedDoor<{\n        total: number | string | null;\n        limit: number;\n        cursor: unknown;\n        rows: Array<{ id: Uuid; document: unknown; level: string; version: number | null; organization_id: Uuid }> | null;\n        sort_ignored?: unknown;\n        filter_ignored?: unknown;\n      }>(\n        DOORS.readRecordsKeyset,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_filter: filter ?? {},\n          p_search: search ?? null,\n          p_sort: sort ?? [],\n          p_after: pAfter,\n          p_limit: limit,\n          p_ids: ids === undefined ? null : [...ids],\n        },\n        \"listKeyset\",\n      );\n      if (!door.ok) return err(door.error);\n      const answer = door.data;\n      const keyed: KeysetRow[] = (answer?.rows ?? []).map((row) => {\n        const { document, hidden } = unfold(row.document);\n        return {\n          id: row.id,\n          document,\n          level: row.level,\n          hidden,\n          version: row.version == null ? null : Number(row.version),\n          organization_id: row.organization_id,\n        };\n      });\n      // HEADER-ONLY STUBS ARE NOT ROWS (honest-hidden-rows). The live keyset door does not admit\n      // confidential headers; retain a page-local fallback for an older store that does return one.\n      const { rows, locked } = splitLockedRows(keyed);\n      let keysetTotal = answer?.total == null ? null : Number(answer.total);\n      if (locked > 0 && keysetTotal !== null) keysetTotal = Math.max(rows.length, keysetTotal - locked);\n      return ok({\n        rows,\n        ...(locked > 0 ? { locked } : {}),\n        total: keysetTotal,\n        limit: Number(answer?.limit ?? limit),\n        cursor: answer?.cursor != null && typeof answer.cursor === \"object\" ? encodeKeysetCursor(answer.cursor) : null,\n        sort_ignored: Array.isArray(answer?.sort_ignored)\n          ? (answer.sort_ignored as unknown[]).filter((k): k is string => typeof k === \"string\")\n          : [],\n        filter_ignored: Array.isArray(answer?.filter_ignored)\n          ? (answer.filter_ignored as unknown[]).filter((k): k is string => typeof k === \"string\")\n          : [],\n      });\n    },\n\n    async query(input) {\n      const plan = planQuery(input);\n      const sets: Uuid[][] = [];\n      for (const call of plan.relationCalls) {\n        const result = await callDoor<Array<{ relation_targets: Uuid } | Uuid>>(\n          DOORS.relationTargets,\n          { p_organization_id: org, p_record_id: call.record_id, p_via_key: call.via_key },\n          \"query.relations\",\n        );\n        if (!result.ok) return err(result.error);\n        sets.push(\n          (result.data ?? []).map((row) =>\n            typeof row === \"string\" ? row : (row as { relation_targets: Uuid }).relation_targets,\n          ),\n        );\n      }\n      for (const call of plan.promotedCalls) {\n        const result = await callDoor<Array<{ promoted_read: Uuid } | Uuid>>(\n          DOORS.promotedRead,\n          {\n            p_organization_id: org,\n            p_table_id: plan.read.table_id,\n            p_field_key: call.field_key,\n            p_value: call.value,\n          },\n          \"query.promoted\",\n        );\n        if (!result.ok) return err(result.error);\n        sets.push(\n          (result.data ?? []).map((row) =>\n            typeof row === \"string\" ? row : (row as { promoted_read: Uuid }).promoted_read,\n          ),\n        );\n      }\n\n      const ids = plan.intersects ? intersectIds(sets) : null;\n      if (ids !== null && ids.length === 0) {\n        return ok({ rows: [], total: 0 });\n      }\n\n      // DOOR-8: an as-of read is the STORE'S question, on the store's two\n      // clocks — `p_recorded_at` is what the store said at that moment, and\n      // `p_world_on` is what was true of the world on that date. This client\n      // used to answer the record clock itself with `updated_at <= at` and\n      // refuse the world clock by name; both were workarounds for doors that\n      // now exist (`custom.query_table_as_of` / `custom.query_record_as_of`),\n      // and neither ever looked at a dated value.\n      if (plan.read.asOf) {\n        const clock = plan.read.asOf.clock === \"world\"\n          ? { p_world_on: plan.read.asOf.at.slice(0, 10) }\n          : { p_recorded_at: plan.read.asOf.at };\n        if (ids !== null) {\n          const answers = await Promise.all(\n            ids.slice(0, plan.read.limit).map((id) =>\n              callDoor<unknown>(\n                DOORS.queryRecordAsOf,\n                { p_organization_id: org, p_record_id: id, ...clock },\n                \"query.asOf\",\n              ).then((result) => ({ id, result })),\n            ),\n          );\n          const rows: ReadRow[] = [];\n          for (const { id, result } of answers) {\n            if (!result.ok) return err(result.error);\n            // A null answer is the door saying \"not visible to you at that\n            // time\", which is an absence, not an empty record.\n            if (result.data === null) continue;\n            const { document, hidden } = unfold(result.data);\n            rows.push({ id, document, level: \"viewer\", hidden });\n          }\n          return ok({ rows, total: rows.length });\n        }\n        const page = await callDoor<Array<{ record_id: Uuid; data: unknown }>>(\n          DOORS.queryTableAsOf,\n          {\n            p_organization_id: org,\n            p_table_id: plan.read.table_id,\n            ...clock,\n            p_limit: plan.read.limit,\n            p_offset: plan.read.offset,\n          },\n          \"query.asOf\",\n        );\n        if (!page.ok) return err(page.error);\n        const rows: ReadRow[] = (page.data ?? [])\n          .filter((row) => row.data !== null)\n          .map((row) => {\n            const { document, hidden } = unfold(row.data);\n            return { id: row.record_id, document, level: \"viewer\", hidden };\n          });\n        return ok({ rows, total: null });\n      }\n\n      // The live read, through the read door and nothing else. With a planned\n      // id set the door is asked one record at a time (it is keyed by record),\n      // bounded by the page size; without one it is asked for the page.\n      if (ids !== null) {\n        const answers = await Promise.all(\n          ids.slice(0, plan.read.limit).map((id) =>\n            callDoor<unknown>(\n              DOORS.readRecord,\n              { p_organization_id: org, p_record_id: id },\n              \"query\",\n            ).then((result) => ({ id, result })),\n          ),\n        );\n        const rows: ReadRow[] = [];\n        for (const { id, result } of answers) {\n          if (!result.ok) {\n            // `02000` is \"that record is not here (any more)\" — a planned id\n            // that has since been deleted is an absence, not a failed query.\n            if (result.error.sqlstate === \"02000\") continue;\n            return err(result.error);\n          }\n          const { document, hidden } = unfold(result.data);\n          rows.push({ id, document, level: \"viewer\", hidden });\n        }\n        return ok({ rows, total: rows.length });\n      }\n\n      return client.list({\n        table_id: plan.read.table_id,\n        limit: plan.read.limit,\n        offset: plan.read.offset,\n      });\n    },\n\n    async tableRead({ table_id, organization_id }) {\n      if (organization_id && organization_id !== org) {\n        return clientFor(organization_id).tableRead({ table_id, organization_id });\n      }\n      if (readOrgs(organization_id).length > 1) {\n        return openInOwnOrg<Table | null>(\n          table_id,\n          organization_id,\n          (sub) => sub.tableRead({ table_id, organization_id: sub.config.organizationId }),\n          (t) => t !== null,\n        );\n      }\n      const kernel = await tableKernel(\"tableRead.kernel\");\n      if (!kernel.ok) return err(kernel.error);\n      const door = await callDoor<Array<{ id: Uuid; document: unknown; level: string }>>(\n        DOORS.readRecordsByIds,\n        { p_organization_id: org, p_table_id: kernel.data, p_record_ids: [table_id] },\n        \"tableRead\",\n      );\n      if (!door.ok) return err(door.error);\n      const row = (door.data ?? []).find((r) => r.id === table_id);\n      if (!row) return ok(null);\n      const { document } = unfold(row.document);\n      // Same shape as a `tableList` entry; `row.level` is the level on the KERNEL, never carried.\n      return ok({ ...(document as Record<string, unknown>), id: row.id, organization_id: org } as unknown as Table);\n    },\n\n    async tableList(args) {\n      if (args?.organization_id && args.organization_id !== org) {\n        return clientFor(args.organization_id).tableList(args);\n      }\n      if (readOrgs(args?.organization_id).length > 1) {\n        const merged = await acrossOrgs<Table[]>(\n          args?.organization_id,\n          (sub) => sub.tableList({ organization_id: sub.config.organizationId }),\n          (parts) => parts.flat(),\n        );\n        if (merged.ok) merged.data.sort((a, b) => (a.name ?? \"\").localeCompare(b.name ?? \"\"));\n        return merged;\n      }\n      // THROUGH THE READ DOOR, like everything else. A Table is a RECORD in the\n      // Table kernel, so listing this organization's Tables is\n      // `read_records(org, table_kernel_id())` — the store decides which of them\n      // this reader may see. Until 2026-09-18 this method selected\n      // `custom.table` directly, which (a) is the raw table access this package\n      // exists to make impossible and (b) could never have worked from a client:\n      // `authenticated` holds no privilege on ANY table in `custom`, by design.\n      // The browser extension found it on its first real turn (W6-EXT).\n      const kernel = await tableKernel(\"tableList.kernel\");\n      if (!kernel.ok) return err(kernel.error);\n      // EVERY PAGE, UNTIL THE DOOR ANSWERS SHORT. One call at `p_limit: 500` used to be the whole\n      // list: an organization's 501st table vanished from every picker with no sign anything was\n      // cut (a-table-list-past-five-hundred-is-whole.test.ts).\n      const read: Array<{ id: Uuid; document: unknown; level: string }> = [];\n      for (let offset = 0; ; offset += TABLE_LIST_PAGE) {\n        const door = await callDoor<Array<{ id: Uuid; document: unknown; level: string }>>(\n          DOORS.readRecords,\n          { p_organization_id: org, p_table_id: kernel.data, p_limit: TABLE_LIST_PAGE, p_offset: offset },\n          \"tableList\",\n        );\n        if (!door.ok) return err(door.error);\n        const page = door.data ?? [];\n        read.push(...page);\n        if (page.length < TABLE_LIST_PAGE) break;\n      }\n      const tables = read.map((row) => {\n        const { document } = unfold(row.document);\n        // The kernel record IS the Table's declaration; `id` is the Table's id.\n        // `row.level` IS NOT THIS TABLE'S LEVEL AND MUST NOT BE CARRIED AS ONE.\n        // `read_records` answers the caller's level on the table it was ASKED\n        // about, and this call asks about the Table KERNEL — so `row.level` here\n        // is the caller's level on the kernel (viewer, for everybody) and not on\n        // the table the row describes. Carrying it looked free and was measured\n        // wrong within the hour: a table's own owner came back \"viewer\".\n        // The level a screen needs is `custom.my_levels`, asked per subject.\n        // WHERE IT LIVES: the Home is the record the Table sits in (`parent_id` on its kernel record). It is exposed as `home_id`\n        // so a screen never reads `parent_id` off the document by hand.\n        const doc = document as Record<string, unknown>;\n        const home = typeof doc.home_id === \"string\" ? doc.home_id : typeof doc.parent_id === \"string\" ? doc.parent_id : null;\n        return { ...doc, home_id: home, id: row.id, organization_id: org } as unknown as Table;\n      });\n      tables.sort((a, b) => (a.name ?? \"\").localeCompare(b.name ?? \"\"));\n      return ok(tables);\n    },\n\n    async fields({ table_id, recordType, withReverse }) {\n      // FLD-10: the store decides which Fields APPLY, from the record type. The\n      // client asks the door rather than filtering a full list, because the\n      // applicability Rule reads Values this client has not got.\n      //\n      // ONE QUESTION FOR \"NO TYPE\" AND \"EVERY TYPE\" (CLOSE-CORE CD-CORE-15). With no type the store answers the\n      // columns every record has: exactly the columns of its every-type ('*') answer that name no record types.\n      // So both are asked as '*' — the one question the table page's bundle answers and every screen shares —\n      // and \"no type\" is that answer with the typed columns (a Circle's Radius) left out.\n      const applicable = await callDoor<Array<{ id: Uuid; data: unknown }>>(\n        DOORS.applicableFields,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_record_type: recordType === undefined ? EVERY_RECORD_TYPE : recordType,\n        },\n        \"fields\",\n      );\n      if (!applicable.ok) return err(applicable.error);\n      const rows = applicable.data ?? [];\n      const fields = rows\n        .map((row) => ({ id: row.id, ...(row.data as object) }) as Field)\n        .filter((f) => withReverse === true || !isReverseField(f))\n        .filter((f) => recordType !== undefined || fieldAppliesToEveryType(f));\n      // IN THE ORDER A PERSON PUT THEM IN. `custom.applicable_fields` answers a\n      // set, not a sequence — its order is whatever the plan gives it, and it\n      // moves between calls — so a grid that mapped it straight to columns drew\n      // them in an arbitrary order and a reorder in the settings panel appeared\n      // to do nothing. `sort` is the Field's own declared position (and what\n      // `custom.field_update` writes when somebody moves one), so it is applied\n      // ONCE, here, and every consumer of this client inherits it. Measured\n      // 2026-09-20: a table declared Title, Day rate, Due came back Day rate,\n      // Title, Due.\n      fields.sort(\n        (a, b) => (a.sort ?? 0) - (b.sort ?? 0) || (a.label ?? \"\").localeCompare(b.label ?? \"\"),\n      );\n      // A formula column nobody gave a \"Shows as\" reads in the format its formula implies ($ / %), the same\n      // inference the template installer writes onto new formula fields; a rollup or lookup reads in the look of the\n      // column it reads (ROLLUP-FORMAT). A declared format is never touched.\n      return ok(await withLooksFromLinkedTables(table_id, fields, []));\n    },\n\n    async fieldOptions({ field_id }) {\n      return callDoor<StoredRecord[]>(\n        DOORS.fieldOptions,\n        { p_organization_id: org, p_field_id: field_id },\n        \"fieldOptions\",\n      );\n    },\n\n    ...createPickListDoors(callDoor),\n\n    async fieldChoiceUsage({ field_id }) {\n      const result = await callDoor<Record<string, ChoiceUsage> | null>(\n        DOORS.fieldChoiceUsage,\n        { p_organization_id: org, p_field_id: field_id },\n        \"fieldChoiceUsage\",\n      );\n      return result.ok ? ok(result.data ?? {}) : result;\n    },\n\n    async fieldUpdateRehomingChoices({ field_id, patch, rehome, cells_back }) {\n      return structureMoved(null, await callDoor<ChoicesRehomed>(\n        DOORS.fieldUpdateRehomingChoices,\n        {\n          p_organization_id: org,\n          p_field_id: field_id,\n          p_patch: patch,\n          ...(rehome && Object.keys(rehome).length > 0 ? { p_rehome: rehome } : {}),\n          ...(cells_back && cells_back.length > 0 ? { p_cells_back: cells_back } : {}),\n        },\n        \"fieldUpdateRehomingChoices\",\n      ));\n    },\n\n    async tableCapacity({ table_id }) {\n      return callDoor<TableCapacity>(\n        DOORS.tableCapacity,\n        { p_organization_id: org, p_table_id: table_id },\n        \"tableCapacity\",\n      );\n    },\n\n    async fieldDeclare({ table_id, spec }) {\n      return structureMoved(table_id, await callDoor<Uuid>(\n        DOORS.fieldDeclare,\n        { p_organization_id: org, p_table_id: table_id, p_spec: fieldDoorSpec(spec) },\n        \"fieldDeclare\",\n      ));\n    },\n\n    async fieldDeclareMany({ table_id, specs }) {\n      return structureMoved(table_id, await callDoor<Uuid[]>(\n        DOORS.fieldDeclareMany,\n        { p_organization_id: org, p_table_id: table_id, p_specs: specs.map(fieldDoorSpec) },\n        \"fieldDeclareMany\",\n      ));\n    },\n\n    async tableCreate({ spec, fields }) {\n      const made = await callDoor<{ table_id: Uuid; home_id: Uuid; field_ids: Uuid[] }>(\n        DOORS.tableCreate,\n        { p_organization_id: org, p_spec: spec, p_fields: fields.map(fieldDoorSpec) },\n        \"tableCreate\",\n      );\n      if (made.ok) structureMoved(made.data.table_id, made);\n      return made;\n    },\n\n    async entityTable({ token }) {\n      // The door answers one row; `callDoor` hands back the array PostgREST\n      // returns for a set-returning function, so the ONE row is taken here\n      // rather than in every caller.\n      const answer = await callDoor<EntityTableFacts[] | EntityTableFacts>(\n        DOORS.entityTable,\n        { p_token: token },\n        \"entityTable\",\n      );\n      if (!answer.ok) return err(answer.error);\n      const row = Array.isArray(answer.data) ? answer.data[0] : answer.data;\n      if (!row) {\n        return err({\n          code: \"not_found\",\n          message: `The registry answered nothing for the table \"${token}\".`,\n          hint: \"REC-33: a standard table is named by its registry token. Nothing was read.\",\n        });\n      }\n      return ok(row);\n    },\n\n    async entityFields({ token, include_retired }) {\n      // The door's third argument is sent only when asked for, so a live read is the call it always was.\n      const rows = await callDoor<Array<{ id: Uuid; data: unknown; deleted_at?: string | null }>>(\n        DOORS.entityFields,\n        include_retired\n          ? { p_organization_id: org, p_token: token, p_include_retired: true }\n          : { p_organization_id: org, p_token: token },\n        \"entityFields\",\n      );\n      if (!rows.ok) return err(rows.error);\n      return ok(\n        (rows.data ?? []).map(\n          (row) => ({ id: row.id, ...(row.data as object), archived_at: row.deleted_at ?? null }) as Field,\n        ),\n      );\n    },\n\n    async entityFieldsAcross({ token, organization_ids }) {\n      return callDoor<EntityFieldsAcross>(\n        DOORS.entityFieldsAcross,\n        { p_token: token, p_organization_ids: organization_ids },\n        \"entityFieldsAcross\",\n      );\n    },\n\n    async entityFieldDeclare({ token, spec }) {\n      return callDoor<Uuid>(\n        DOORS.entityFieldDeclare,\n        { p_organization_id: org, p_token: token, p_spec: spec },\n        \"entityFieldDeclare\",\n      );\n    },\n\n    async entityFieldUpdate({ field_id, patch }) {\n      return callDoor<Uuid>(\n        DOORS.entityFieldUpdate,\n        { p_organization_id: org, p_field_id: field_id, p_patch: patch },\n        \"entityFieldUpdate\",\n      );\n    },\n\n    async entityFieldRetire({ field_id }) {\n      return callDoor<Uuid>(\n        DOORS.entityFieldRetire,\n        { p_organization_id: org, p_field_id: field_id },\n        \"entityFieldRetire\",\n      );\n    },\n\n    async entityFieldRights({ token }) {\n      return callDoor<EntityFieldRights>(\n        DOORS.entityFieldRights,\n        { p_organization_id: org, p_token: token },\n        \"entityFieldRights\",\n      );\n    },\n\n    async entityRecordRead({ token, record_id }) {\n      return callDoor<EntityRecordRead>(\n        DOORS.entityRecordRead,\n        { p_organization_id: org, p_token: token, p_record_id: record_id },\n        \"entityRecordRead\",\n      );\n    },\n\n    async entityBackLinks({ token, record_id, organization_id, limit, cursor }) {\n      const answered = await callDoor<EntityBackLinks>(\n        DOORS.entityBackLinks,\n        {\n          p_organization_id: organization_id,\n          p_token: token,\n          p_record_id: record_id,\n          p_limit: limit ?? 50,\n          p_cursor: cursor ?? null,\n        },\n        \"entityBackLinks\",\n      );\n      if (!answered.ok) return answered;\n      return ok({ ...answered.data, items: answered.data.items ?? [], next_cursor: answered.data.next_cursor ?? null });\n    },\n\n    async entityRowWrite({ token, record_id, organization_id, custom, columns, expected_version, archive }) {\n      // No organization: a change by id is governed by the row's own (access is personal).\n      // OWED, NOT ASSUMED: lane 7 W3a's door is on the clone and not yet on main, so the generated\n      // catalog (read from main) does not list it. Asked anyway; a store without it answers\n      // `door_absent` naming the owing migration, and records-ui falls back to the older door.\n      return owedDoor<EntityRowWritten>(\n        DOORS.entityRowWrite,\n        {\n          // a new row goes into the organization the call names, else this client's own\n          p_organization_id: record_id == null ? (organization_id ?? org ?? null) : (organization_id ?? null),\n          p_token: token,\n          p_record_id: record_id ?? null,\n          p_columns: columns ?? {},\n          p_custom: custom ?? {},\n          p_expected_version: expected_version ?? null,\n          p_archive: archive ?? null,\n        },\n        \"entityRowWrite\",\n      );\n    },\n\n    async entityRecordsFind({ token, key, value, limit, offset }) {\n      return callDoor<EntityRecordsFound>(\n        DOORS.entityRecordsFind,\n        {\n          p_organization_id: org,\n          p_token: token,\n          p_key: key,\n          p_value: value === undefined ? null : value,\n          ...(limit === undefined ? {} : { p_limit: limit }),\n          ...(offset === undefined ? {} : { p_offset: offset }),\n        },\n        \"entityRecordsFind\",\n      );\n    },\n\n    async migrateRetype({ field_id, to, note }) {\n      return structureMoved(null, await callDoor<FieldRetyped>(\n        DOORS.migrateRetype,\n        { p_organization_id: org, p_id: field_id, p_to: to, ...(note ? { p_note: note } : {}) },\n        \"migrateRetype\",\n      ));\n    },\n\n    async migrateMerge({ winner_id, loser_id, note }) {\n      const result = await callDoor<RecordsMerged>(\n        DOORS.migrateMerge,\n        { p_organization_id: org, p_winner_id: winner_id, p_loser_id: loser_id, p_note: note ?? null },\n        \"migrateMerge\",\n      );\n      // Both records changed: every screen holding either reads it again.\n      if (result.ok) {\n        announceRecordChanged(winner_id);\n        announceRecordChanged(loser_id);\n      }\n      return result;\n    },\n\n    async migrateSplit({ record_id, moved_keys, note }) {\n      const result = await callDoor<RecordSplit>(\n        DOORS.migrateSplit,\n        { p_organization_id: org, p_record_id: record_id, p_moved_keys: moved_keys, p_note: note ?? null },\n        \"migrateSplit\",\n      );\n      if (result.ok) {\n        announceRecordChanged(record_id);\n        announceRecordChanged(result.data.new_record);\n      }\n      return result;\n    },\n\n    async migrateExtractParent({ record_id, parent_table_id, moved_keys, note }) {\n      const result = await callDoor<ParentExtracted>(\n        DOORS.migrateExtractParent,\n        { p_organization_id: org, p_id: record_id, p_parent_table_id: parent_table_id, p_moved_keys: moved_keys, p_note: note ?? null },\n        \"migrateExtractParent\",\n      );\n      if (result.ok) {\n        announceRecordChanged(record_id);\n        announceRecordChanged(result.data.parent);\n      }\n      return result;\n    },\n\n    async migrateMoveRecord({ record_id, to_table_id, note }) {\n      const result = await callDoor<RecordMoved>(\n        DOORS.migrateRetype,\n        { p_organization_id: org, p_id: record_id, p_to: to_table_id, ...(note ? { p_note: note } : {}) },\n        \"migrateMoveRecord\",\n      );\n      if (result.ok) announceRecordChanged(record_id);\n      return result;\n    },\n\n    async migrations({ target_id, limit }) {\n      return callDoor<MigrationEntry[]>(\n        DOORS.migrations,\n        { p_organization_id: org, p_target_id: target_id ?? null, p_limit: limit ?? 100 },\n        \"migrations\",\n      );\n    },\n\n    async historyRetention(args) {\n      return callDoor<HistoryRetention>(\n        DOORS.historyRetention,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"historyRetention\",\n      );\n    },\n\n    async historyRetentionSet({ table_id, days }) {\n      return callDoor<number>(\n        DOORS.historyRetentionSet,\n        { p_organization_id: org, p_table_id: table_id, p_days: days },\n        \"historyRetentionSet\",\n      );\n    },\n\n    async historyRetentionFloorRaise({ days }) {\n      return callDoor<number>(\n        DOORS.historyRetentionFloorRaise,\n        { p_organization_id: org, p_days: days },\n        \"historyRetentionFloorRaise\",\n      );\n    },\n\n    async recordAsOf({ record_id, recorded_at, world_on }) {\n      return callDoor<Record<string, unknown> | null>(\n        DOORS.queryRecordAsOf,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          ...(recorded_at ? { p_recorded_at: recorded_at } : {}),\n          ...(world_on ? { p_world_on: world_on.slice(0, 10) } : {}),\n        },\n        \"recordAsOf\",\n      );\n    },\n\n    async migrateUndo({ migration_id }) {\n      const result = await callDoor<MigrationUndone>(\n        DOORS.migrateUndo,\n        { p_organization_id: org, p_log_id: migration_id },\n        \"migrateUndo\",\n      );\n      if (result.ok && result.data.record_id) announceRecordChanged(result.data.record_id);\n      if (result.ok && result.data.removed) announceRecordChanged(result.data.removed);\n      return result;\n    },\n\n    async fieldUpdate({ field_id, patch }) {\n      return structureMoved(null, await callDoor<Uuid>(\n        DOORS.fieldUpdate,\n        { p_organization_id: org, p_field_id: field_id, p_patch: patch },\n        \"fieldUpdate\",\n      ));\n    },\n\n    async fieldRetypePreview({ field_id, patch }) {\n      return callDoor<FieldRetypePreview>(\n        DOORS.fieldRetypePreview,\n        { p_organization_id: org, p_field_id: field_id, p_patch: patch },\n        \"fieldRetypePreview\",\n      );\n    },\n\n    async fieldRetire({ field_id }) {\n      return structureMoved(null, await callDoor<boolean>(\n        DOORS.fieldRetire,\n        { p_organization_id: org, p_field_id: field_id },\n        \"fieldRetire\",\n      ));\n    },\n\n    async fieldRestore({ field_id }) {\n      return structureMoved(null, await callDoor<boolean>(\n        DOORS.fieldRestore,\n        { p_organization_id: org, p_field_id: field_id },\n        \"fieldRestore\",\n      ));\n    },\n\n    async fieldDuplicate({ field_id }) {\n      return structureMoved(null, await callDoor<FieldDuplicated>(\n        DOORS.fieldDuplicate,\n        { p_organization_id: org, p_field_id: field_id },\n        \"fieldDuplicate\",\n      ));\n    },\n\n    async fieldSourceArchived({ field_id }) {\n      const result = await callDoor<unknown>(\n        DOORS.fieldSourceArchived,\n        { p_organization_id: org, p_field_id: field_id },\n        \"fieldSourceArchived\",\n      );\n      if (!result.ok) return result;\n      return ok(sourceArchivedOf(result.data));\n    },\n\n    async tableKindFacts({ table_id }) {\n      return callDoor<TableKindFacts>(DOORS.tableKindFacts, { p_table_id: table_id }, \"tableKindFacts\");\n    },\n\n    async tableLevelFacts({ table_id }) {\n      return callDoor<TableLevelFacts>(DOORS.tableLevelFacts, { p_table_id: table_id }, \"tableLevelFacts\");\n    },\n\n    async setTableConfidential({ table_id, readers, reason }) {\n      const result = await callDoor<TableLevelSet>(\n        DOORS.setTableConfidential,\n        { p_table_id: table_id, p_readers: readers, p_reason: reason },\n        \"setTableConfidential\",\n      );\n      if (result.ok) announceTableStructureChanged(table_id);\n      return result;\n    },\n\n    async setTableOrganization({ table_id, reason }) {\n      const result = await callDoor<TableLevelSet>(\n        DOORS.setTableOrganization,\n        { p_table_id: table_id, p_reason: reason },\n        \"setTableOrganization\",\n      );\n      if (result.ok) announceTableStructureChanged(table_id);\n      return result;\n    },\n\n    async fieldsRetired({ table_id }) {\n      const kernel = await callDoor<Uuid>(DOORS.fieldKernelId, {}, \"fieldsRetired.kernel\");\n      if (!kernel.ok) return err(kernel.error);\n      const PAGE = 200;\n      const found: ArchivedRow[] = [];\n      for (let page = 0; page < 25; page += 1) {\n        const answered = await this.listArchived({ table_id: kernel.data, lane: \"org\", limit: PAGE, offset: page * PAGE });\n        if (!answered.ok) return err(answered.error);\n        for (const row of answered.data.rows) {\n          if (String((row.document as Record<string, unknown>)[\"entity_definition_id\"] ?? \"\") === table_id) found.push(row);\n        }\n        if (answered.data.rows.length < PAGE) break;\n      }\n      return ok(found);\n    },\n\n    async relationWords({ field_id, value }) {\n      return callDoor<string | null>(\n        DOORS.relationWords,\n        { p_organization_id: org, p_field_id: field_id, p_value: value },\n        \"relationWords\",\n      );\n    },\n\n    async reverseColumns({ table_id }) {\n      // OWED until `pnpm records:generate` lists it: proven on the clone, applied by\n      // migrations/campaign/viewsfields_bl_a_link_shows_on_both_tables.sql.\n      const result = await owedDoor<ReverseColumn[]>(\n        DOORS.reverseColumns,\n        { p_organization_id: org, p_table_id: table_id },\n        \"reverseColumns\",\n      );\n      if (!result.ok) return result;\n      return ok(Array.isArray(result.data) ? result.data : []);\n    },\n\n    async reverseLinksMany(args) {\n      const ids = [...new Set(args.record_ids.filter((id) => typeof id === \"string\" && id.length > 0))];\n      const out: Record<string, ReverseLinks> = {};\n      for (let at = 0; at < ids.length; at += REVERSE_LINKS_RECORDS_PER_CALL) {\n        const result = await owedDoor<Array<{ record_id: Uuid; total: number | null; links: ReverseLinks[\"links\"] | null }>>(\n          DOORS.reverseLinksMany,\n          {\n            p_organization_id: org,\n            p_table_id: args.table_id,\n            p_field_id: args.source_field_id,\n            p_record_ids: ids.slice(at, at + REVERSE_LINKS_RECORDS_PER_CALL),\n            p_limit: args.limit ?? 10,\n            p_offset: args.offset ?? 0,\n          },\n          \"reverseLinksMany\",\n        );\n        if (!result.ok) return result;\n        for (const row of result.data ?? []) {\n          if (!row?.record_id) continue;\n          out[row.record_id] = {\n            total: typeof row.total === \"number\" ? row.total : 0,\n            links: Array.isArray(row.links) ? row.links : [],\n          };\n        }\n      }\n      return ok(out);\n    },\n\n    async reverseLinksFields(args) {\n      const ids = [...new Set(args.record_ids.filter((id) => typeof id === \"string\" && id.length > 0))];\n      const fieldIds = [...new Set(args.source_field_ids)];\n      const out: Record<string, Record<string, ReverseLinks>> = Object.fromEntries(fieldIds.map((id) => [id, {}]));\n      for (let f = 0; f < fieldIds.length || f === 0; f += 20) {\n        for (let at = 0; at < ids.length; at += REVERSE_LINKS_RECORDS_PER_CALL) {\n          const result = await owedDoor<Array<{ field_id: Uuid; record_id: Uuid; total: number | null; links: ReverseLinks[\"links\"] | null }>>(\n            DOORS.reverseLinksManyFields,\n            {\n              p_organization_id: org,\n              p_table_id: args.table_id,\n              p_field_ids: fieldIds.slice(f, f + 20),\n              p_record_ids: ids.slice(at, at + REVERSE_LINKS_RECORDS_PER_CALL),\n              p_limit: args.limit ?? 10,\n              p_offset: args.offset ?? 0,\n            },\n            \"reverseLinksFields\",\n          );\n          if (!result.ok) return result;\n          for (const row of result.data ?? []) {\n            if (!row?.record_id || !row.field_id) continue;\n            (out[row.field_id] ??= {})[row.record_id] = {\n              total: typeof row.total === \"number\" ? row.total : 0,\n              links: Array.isArray(row.links) ? row.links : [],\n            };\n          }\n        }\n        if (fieldIds.length === 0) break;\n      }\n      return ok(out);\n    },\n\n    async relationReverseField({ field_id, label }) {\n      const made = await owedDoor<Uuid>(\n        DOORS.relationReverseField,\n        { p_organization_id: org, p_field_id: field_id, p_label: label ?? null },\n        \"relationReverseField\",\n      );\n      if (made.ok) announceTableStructureChanged(null);\n      return made;\n    },\n\n    async relationReverseSet({ record_id, field_id, add, remove }) {\n      const done = await owedDoor<number>(\n        DOORS.relationReverseSet,\n        { p_organization_id: org, p_record_id: record_id, p_field_id: field_id, p_add: [...(add ?? [])], p_remove: [...(remove ?? [])] },\n        \"relationReverseSet\",\n      );\n      if (done.ok) for (const id of [record_id, ...(add ?? []), ...(remove ?? [])]) announceRecordChanged(id);\n      return done;\n    },\n\n    async relationNamesMatch(args) {\n      // One call per 5,000 distinct names (the door's own cap), answers joined in order.\n      const distinct: string[] = [];\n      const seen = new Set<string>();\n      for (const name of args.names) {\n        const key = name.trim().replace(/\\s+/g, \" \").toLowerCase();\n        if (key === \"\" || seen.has(key)) continue;\n        seen.add(key);\n        distinct.push(name.trim());\n      }\n      const joined: RelationNamesAnswer = { table_id: args.table_id, table_name: null, names: [] };\n      for (let at = 0; at === 0 || at < distinct.length; at += 5000) {\n        // OWED until `pnpm records:generate` lists it: proven on the clone, applied by\n        // migrations/campaign/visionreach_g1_a_relation_is_filled_by_its_name.sql.\n        const result = await owedDoor<RelationNamesAnswer>(\n          DOORS.relationNamesMatch,\n          { p_organization_id: org, p_table_id: args.table_id, p_names: distinct.slice(at, at + 5000) },\n          \"relationNamesMatch\",\n        );\n        if (!result.ok) return result;\n        joined.table_name = result.data?.table_name ?? joined.table_name;\n        joined.title_field = result.data?.title_field ?? joined.title_field ?? null;\n        joined.names.push(...(result.data?.names ?? []));\n        if (distinct.length === 0) break;\n      }\n      return { ok: true, data: joined } as RecordsResult<RelationNamesAnswer>;\n    },\n\n    async relationWordsMany(args) {\n      // The door returns one row per id — `(record_id, words)` — and a caller wants a lookup, so\n      // the shape is turned here rather than in every screen. An id the store answered nothing for\n      // is simply ABSENT from the map, and the caller decides what an absent chip says; inventing\n      // \"Untitled\" here would hide the difference between \"no answer yet\" and \"no words\".\n      // ICONS RIDE THE SAME CALL (CHAIR-EMBEDDED-FIDELITY 14): the with-icons door wraps the words\n      // door, so the ladder is the same; a database without it falls back to the plain door.\n      const doorArgs = { p_organization_id: org, p_field_id: args.field_id, p_record_ids: args.record_ids };\n      // A host whose data source throws on a door it does not know is answered by the plain door.\n      const withIcons: RecordsResult<Array<{ record_id: Uuid; words: string | null }>> = await owedDoor<Array<{ record_id: Uuid; words: string | null }>>(\n        DOORS.relationWordsWithIconsMany,\n        doorArgs,\n        \"relationWordsMany\",\n      ).catch(() => err({ code: \"door_absent\", message: \"relation_words_with_icons_many is not answered here.\" } as RecordsError));\n      // The real door answers one row per id asked; an empty answer to a non-empty ask is a store that\n      // does not speak it (a stub, an older database), so the plain door answers instead.\n      const result = withIcons.ok && (!Array.isArray(withIcons.data) || withIcons.data.length > 0 || args.record_ids.length === 0)\n        ? withIcons\n        : await callDoor<Array<{ record_id: Uuid; words: string | null }>>(DOORS.relationWordsMany, doorArgs, \"relationWordsMany\");\n      if (!result.ok) return result;\n      const icons: Record<string, RelationIcons> = {};\n      const map: Record<string, string> = {};\n      // ARCHIVED (lane REFERENCE-KEEPS-ARCHIVED, chair ruling B3-21): an archive keeps every\n      // reference to what it archived, and the store's words door says which of these ids are in\n      // Archived items (`archived`, true only for a record this reader may see). A door without\n      // that column (a database before the column) answers none.\n      const archived: string[] = [];\n      for (const row of (result.data ?? []) as Array<{\n        record_id?: Uuid;\n        words: string | null;\n        archived?: boolean | null;\n        icon?: string | null;\n        table_icon?: string | null;\n      }>) {\n        const id = row?.record_id;\n        if (id && typeof row.words === \"string\") map[id] = row.words;\n        if (id && row.archived === true) archived.push(id);\n        if (id && (row.icon || row.table_icon)) icons[id] = { icon: row.icon ?? null, tableIcon: row.table_icon ?? null };\n      }\n      return { ok: true, data: map, archived, icons };\n    },\n\n    async tableFind(args) {\n      const slug = \"slug\" in args && typeof args.slug === \"string\" ? args.slug.trim() : \"\";\n      const name = \"name\" in args && typeof args.name === \"string\" ? args.name.trim() : \"\";\n      const keptFor = typeof args.keptFor === \"string\" ? args.keptFor.trim() : \"\";\n      const found = await owedDoor<\n        { id: Uuid; document?: unknown; level?: string; archived?: boolean; archived_at?: string } | null\n      >(\n        DOORS.tableFind,\n        {\n          p_organization_id: org,\n          p_slug: slug || null,\n          p_name: slug ? null : name || null,\n          // Only when asked: a store whose table_find predates kept_for still answers a plain find.\n          ...(keptFor ? { p_kept_for: keptFor } : {}),\n        },\n        \"tableFind\",\n      );\n      if (!found.ok) return err(found.error);\n      if (!found.data) return ok(null);\n      if (found.data.archived === true) {\n        return ok({ id: found.data.id, organization_id: org, archived_at: found.data.archived_at ?? null } as unknown as Table);\n      }\n      const { document } = unfold(found.data.document);\n      // Same shape as a `tableList` / `tableRead` entry; the level is the kernel's, never carried.\n      return ok({ ...(document as Record<string, unknown>), id: found.data.id, organization_id: org } as unknown as Table);\n    },\n\n    async tableFindMany({ organizationIds, slug, keptFor }) {\n      const orgs = [...new Set(organizationIds.filter(Boolean))];\n      if (orgs.length === 0) return ok({ tables: [], refused: [] });\n      const found = await owedDoor<Array<{\n        organization_id: Uuid;\n        table?: { id: Uuid; document?: unknown; archived?: boolean } | null;\n        refused?: { code?: string; message?: string };\n      }> | null>(\n        DOORS.tableFindMany,\n        { p_organization_ids: orgs, p_slug: slug.trim(), p_kept_for: keptFor?.trim() || null },\n        \"tableFindMany\",\n      );\n      if (!found.ok) return err(found.error);\n      const tables: Table[] = [];\n      const refused: Array<{ organization_id: Uuid; error: RecordsError }> = [];\n      for (const entry of found.data ?? []) {\n        if (entry.refused) {\n          refused.push({\n            organization_id: entry.organization_id,\n            error: mapPgError({ code: entry.refused.code ?? \"\", message: entry.refused.message ?? \"\" }, \"tableFindMany\"),\n          });\n          continue;\n        }\n        // An archived match (kept_for given, no live one) is no table to read rows from.\n        if (!entry.table?.id || entry.table.archived === true) continue;\n        const { document } = unfold(entry.table.document);\n        tables.push({ ...(document as Record<string, unknown>), id: entry.table.id, organization_id: entry.organization_id } as unknown as Table);\n      }\n      return ok({ tables, refused });\n    },\n\n    async tableEnsure({ spec }) {\n      const ensured = await owedDoor<{ table_id: Uuid; home_id: Uuid | null; created: boolean; drift?: unknown }>(\n        DOORS.tableEnsure,\n        { p_organization_id: org, p_spec: spec },\n        \"tableEnsure\",\n      );\n      if (!ensured.ok) return ensured;\n      return ok({ ...ensured.data, drift: parseFieldDrift(ensured.data.drift) });\n    },\n\n    async recordUpsert({ table_id, key, data, expectedVersion }) {\n      const keys = (Array.isArray(key) ? key : [key]).map((k) => k.trim()).filter((k) => k.length > 0);\n      const result = await owedDoor<Uuid>(\n        DOORS.recordUpsert,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_key: keys,\n          // The op id rides the envelope, as `recordWrite` / `recordUpdate` send it; each door takes it off.\n          p_data: { ...data, _op_id: mintOp() },\n          ...(expectedVersion === undefined ? {} : { p_expected_version: expectedVersion }),\n        },\n        \"recordUpsert\",\n      );\n      if (result.ok) announceRecordChanged(result.data);\n      return result;\n    },\n\n    async tableDeclare({ spec, homeId }) {\n      return callDoor<Uuid>(\n        DOORS.tableDeclare,\n        { p_organization_id: org, p_spec: { ...spec, parent_id: homeId } },\n        \"tableDeclare\",\n      );\n    },\n\n    async personKernelId() {\n      // A CONSTANT (`custom.person_kernel_id` is IMMUTABLE): asked once per client, never per birth.\n      if (personKernelOnce) return ok(personKernelOnce);\n      const answer = await callDoor<Uuid>(DOORS.personKernelId, {}, \"personKernelId\");\n      if (answer.ok) personKernelOnce = answer.data;\n      return answer;\n    },\n\n    async fieldKernelId() {\n      return callDoor<Uuid>(DOORS.fieldKernelId, {}, \"fieldKernelId\");\n    },\n\n    async ruleKernelId() {\n      return callDoor<Uuid>(DOORS.ruleKernelId, {}, \"ruleKernelId\");\n    },\n\n    async pipelineRead({ table_id }) {\n      return callDoor<Pipeline>(\n        DOORS.pipelineRead,\n        { p_organization_id: org, p_table_id: table_id },\n        \"pipelineRead\",\n      );\n    },\n\n    async pipelineBoard({ table_id, measure, filter }) {\n      // With a question, the four-argument door; without one, exactly the call it always was.\n      const asked = filter && stableFilterKey(filter) !== \"{}\";\n      return callDoor<PipelineColumn[]>(\n        DOORS.pipelineBoard,\n        asked\n          ? { p_organization_id: org, p_table_id: table_id, p_measure: measure ?? null, p_filter: filter }\n          : { p_organization_id: org, p_table_id: table_id, p_measure: measure ?? null },\n        \"pipelineBoard\",\n      );\n    },\n\n    async pipelineTransitionRefusal({ record_id, to }) {\n      return callDoor<PipelineVerdict>(\n        DOORS.pipelineTransitionRefusal,\n        { p_organization_id: org, p_record_id: record_id, p_to: to },\n        \"pipelineTransitionRefusal\",\n      );\n    },\n\n    async pipelineMove({ record_id, to, also, expected_version }) {\n      return callDoor<PipelineMoveResult>(\n        DOORS.pipelineMove,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_to: to,\n          p_also: also ?? {},\n          p_expected_version: expected_version ?? null,\n        },\n        \"pipelineMove\",\n      );\n    },\n\n    async pipelineMoveMany({ moves }) {\n      return callDoor<PipelineMoveMany>(\n        DOORS.pipelineMoveMany,\n        { p_organization_id: org, p_moves: moves },\n        \"pipelineMoveMany\",\n      );\n    },\n\n    async pipelineDeclare({ table_id, spec }) {\n      return callDoor<PipelineDeclared>(\n        DOORS.pipelineDeclare,\n        { p_organization_id: org, p_table_id: table_id, p_spec: spec },\n        \"pipelineDeclare\",\n      );\n    },\n\n    async tableStageField({ table_id }) {\n      return callDoor<string | null>(\n        DOORS.tableStageField,\n        { p_organization_id: org, p_table_id: table_id },\n        \"tableStageField\",\n      );\n    },\n\n    async stageRuleOnFailKinds() {\n      return callDoor<{ behaviour: StageRuleOnFail; note: string }[]>(\n        DOORS.stageRuleOnFailKinds,\n        {},\n        \"stageRuleOnFailKinds\",\n      );\n    },\n\n    async stageRuleEnforcement() {\n      return callDoor<StageRuleEnforcement>(\n        DOORS.stageRuleEnforcement,\n        { p_organization_id: org },\n        \"stageRuleEnforcement\",\n      );\n    },\n\n    async recordStagePending({ record_id }) {\n      return callDoor<StagePending[]>(\n        DOORS.recordStagePending,\n        { p_organization_id: org, p_record_id: record_id },\n        \"recordStagePending\",\n      );\n    },\n\n    async pipelinePending({ table_id }) {\n      return callDoor<StagePendingOnBoard[]>(\n        DOORS.pipelinePending,\n        { p_organization_id: org, p_table_id: table_id },\n        \"pipelinePending\",\n      );\n    },\n\n    async pipelineGatePreview({ table_id, stage, gate }) {\n      return callDoor<PipelineGatePreview>(\n        DOORS.pipelineGatePreview,\n        { p_organization_id: org, p_table_id: table_id, p_stage: stage, p_gate: gate },\n        \"pipelineGatePreview\",\n      );\n    },\n\n    async ruleMembersVisible({ rule_id, limit = 200, offset = 0 }) {\n      const door = await callDoor<Array<{ id: Uuid; document: unknown; level: string }>>(\n        DOORS.ruleMembersVisible,\n        { p_organization_id: org, p_rule_id: rule_id, p_limit: limit, p_offset: offset },\n        \"ruleMembersVisible\",\n      );\n      if (!door.ok) return err(door.error);\n      return ok((door.data ?? []).map((row) => {\n        const { document, hidden } = unfold(row.document);\n        return { id: row.id, document, level: row.level, hidden, ...waitingMark(row) } as ReadRow;\n      }));\n    },\n\n    async ruleMembers({ rule_id }) {\n      return callDoor<StoredRecord[]>(\n        DOORS.ruleMembers,\n        { p_organization_id: org, p_rule_id: rule_id },\n        \"ruleMembers\",\n      );\n    },\n\n    async ruleMembership({ rule_id, record_id }) {\n      return callDoor<unknown>(\n        DOORS.ruleMembership,\n        { p_organization_id: org, p_rule_id: rule_id, p_record_id: record_id },\n        \"ruleMembership\",\n      );\n    },\n\n    async forms(args) {\n      return callDoor<FormSummary[]>(\n        DOORS.forms,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"forms\",\n      );\n    },\n\n    async bookings(args) {\n      return callDoor<BookingSummary[]>(\n        DOORS.bookings,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"bookings\",\n      );\n    },\n\n    async bookingDeclare(args) {\n      return callDoor<BookingDeclared>(\n        DOORS.bookingDeclare,\n        {\n          p_organization_id: org,\n          p_table_id: args.table_id,\n          p_title: args.title,\n          p_questions: args.questions,\n          // AN EMPTY OBJECT IS NOT A MISTAKE. The store owns every default, so a\n          // page declared with no availability comes back Monday-to-Friday,\n          // nine-to-five, in the organization's own zone — and the screen draws\n          // what came BACK rather than what it sent.\n          p_availability: args.availability ?? {},\n          p_presentation: args.presentation ?? {},\n          p_submission_cap: args.submission_cap ?? null,\n          p_quarantine_rule_id: args.quarantine_rule_id ?? null,\n          p_notify_rule_id: args.notify_rule_id ?? null,\n          p_form_id: args.form_id ?? null,\n          p_slug: args.slug ?? null,\n          p_home_id: args.home_id ?? null,\n        },\n        \"bookingDeclare\",\n      );\n    },\n\n    async formPreviewAsks({ table_id, questions, values }) {\n      return callDoor<Array<{ field_key: string; asked: boolean; decided: boolean; said: string | null }>>(\n        DOORS.formPreviewAsks,\n        { p_organization_id: org, p_table_id: table_id, p_questions: questions, p_values: values },\n        \"formPreviewAsks\",\n      );\n    },\n\n    async formPreviewRoute({ table_id, questions, endings, values }) {\n      return callDoor<FormRoute>(\n        DOORS.formPreviewRoute,\n        { p_organization_id: org, p_table_id: table_id, p_questions: questions, p_endings: endings ?? [], p_values: values },\n        \"formPreviewRoute\",\n      );\n    },\n\n    async formResults({ form_id }) {\n      return callDoor<FormResults>(\n        DOORS.formResults,\n        { p_organization_id: org, p_form_id: form_id },\n        \"formResults\",\n      );\n    },\n\n    async formKnobs() {\n      return callDoor<{ show_owner_header: boolean; choice_auto_advance: boolean }>(\n        DOORS.formKnobs,\n        { p_organization_id: org },\n        \"formKnobs\",\n      );\n    },\n\n    async formSetPassword({ form_id, password }) {\n      return callDoor<{ has_password: boolean }>(\n        DOORS.formSetPassword,\n        { p_organization_id: org, p_form_id: form_id, p_password: password },\n        \"formSetPassword\",\n      );\n    },\n\n    async formLookOptions(args) {\n      return callDoor<FormLookOptions>(\n        DOORS.formLookOptions,\n        { p_organization_id: org, p_presentation: args?.presentation ?? {} },\n        \"formLookOptions\",\n      );\n    },\n\n    async formDeclare(args) {\n      return callDoor<Uuid>(\n        DOORS.formDeclare,\n        {\n          p_organization_id: org,\n          p_table_id: args.table_id,\n          p_title: args.title,\n          p_questions: args.questions,\n          p_presentation: args.presentation ?? {},\n          p_submission_cap: args.submission_cap ?? null,\n          p_quarantine_rule_id: args.quarantine_rule_id ?? null,\n          p_notify_rule_id: args.notify_rule_id ?? null,\n          p_form_id: args.form_id ?? null,\n          p_slug: args.slug ?? null,\n        },\n        \"formDeclare\",\n      );\n    },\n\n    async importPlan(args) {\n      return callDoor<ImportPlan>(\n        DOORS.importPlan,\n        { p_organization_id: org, p_table_id: args.table_id, p_columns: args.columns },\n        \"importPlan\",\n      );\n    },\n\n    async importBegin(args) {\n      return callDoor<ImportOpened>(\n        DOORS.importBegin,\n        {\n          p_organization_id: org,\n          p_table_id: args.table_id,\n          p_format: args.format ?? \"csv\",\n          p_source_name: args.source_name ?? null,\n          p_source_columns: args.source_columns ?? [],\n          p_file_hash: args.file_hash ?? null,\n          p_policy: args.policy ?? {},\n          p_dedupe_key: args.dedupe_key ?? null,\n          p_file_bytes: args.file_bytes ?? null,\n          p_force: args.force ?? false,\n        },\n        \"importBegin\",\n      );\n    },\n\n    async importDeclareColumns(args) {\n      return callDoor<ImportColumnsDeclared>(\n        DOORS.importDeclareColumns,\n        {\n          p_organization_id: org,\n          p_table_id: args.table_id,\n          p_rows: args.rows,\n          p_mapping: args.mapping ?? {},\n        },\n        \"importDeclareColumns\",\n      );\n    },\n\n    async importRows(args) {\n      return callDoor<ImportBatchResult>(\n        DOORS.importRows,\n        {\n          p_organization_id: org,\n          p_import_id: args.import_id,\n          p_rows: args.rows,\n          p_mapping: args.mapping ?? {},\n        },\n        \"importRows\",\n      );\n    },\n\n    async importFinish(args) {\n      return callDoor<ImportFinished>(\n        DOORS.importFinish,\n        { p_organization_id: org, p_import_id: args.import_id, p_unmapped: args.unmapped ?? null },\n        \"importFinish\",\n      );\n    },\n\n    async importReport(args) {\n      return callDoor<ImportReport>(\n        DOORS.importReport,\n        {\n          p_organization_id: org,\n          p_import_id: args.import_id,\n          p_state: args.state ?? \"refused\",\n          p_limit: args.limit ?? 100,\n          p_offset: args.offset ?? 0,\n        },\n        \"importReport\",\n      );\n    },\n\n    async imports(args) {\n      return callDoor<ImportRun[]>(\n        DOORS.imports,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null, p_limit: args?.limit ?? 25 },\n        \"imports\",\n      );\n    },\n\n    async importForget(args) {\n      return callDoor<boolean>(\n        DOORS.importForget,\n        { p_organization_id: org, p_import_id: args.import_id },\n        \"importForget\",\n      );\n    },\n\n    async inboundDeclare(args) {\n      return callDoor<InboundDeclared>(\n        DOORS.inboundDeclare,\n        { p_organization_id: org, p_table_id: args.table_id, p_label: args.label ?? null },\n        \"inboundDeclare\",\n      );\n    },\n\n    async inboundAddresses(args) {\n      return callDoor<InboundAddress[]>(\n        DOORS.inboundAddresses,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"inboundAddresses\",\n      );\n    },\n\n    async inboundSet(args) {\n      return callDoor<{ inbound_id: Uuid; address: string; enabled: boolean; message: string }>(\n        DOORS.inboundSet,\n        { p_organization_id: org, p_inbound_id: args.inbound_id, p_enabled: args.enabled },\n        \"inboundSet\",\n      );\n    },\n\n    async portals() {\n      return callDoor<PortalSummary[]>(DOORS.portals, { p_organization_id: org }, \"portals\");\n    },\n\n    async listPortals(args) {\n      return callDoor<PortalSummary[]>(\n        DOORS.listPortals,\n        { p_organization_id: org, p_archived: args?.archived ?? \"active\" },\n        \"listPortals\",\n      );\n    },\n\n    async portalArchive(args) {\n      return callDoor<PortalArchiveAnswer>(\n        DOORS.portalArchive,\n        {\n          p_organization_id: org,\n          p_portal_id: args.portal_id,\n          p_confirm_title: args.confirm_title,\n          p_reason: args.reason ?? null,\n        },\n        \"portalArchive\",\n      );\n    },\n\n    async portalRestore(args) {\n      return callDoor<PortalArchiveAnswer>(\n        DOORS.portalRestore,\n        {\n          p_organization_id: org,\n          p_portal_id: args.portal_id,\n          p_confirm_title: args.confirm_title,\n        },\n        \"portalRestore\",\n      );\n    },\n\n    async formArchive({ form_id }) {\n      return callDoor<FormArchiveAnswer>(\n        DOORS.formArchive,\n        { p_organization_id: org, p_form_id: form_id },\n        \"formArchive\",\n      );\n    },\n\n    async formRestore({ form_id }) {\n      return callDoor<FormArchiveAnswer>(\n        DOORS.formRestore,\n        { p_organization_id: org, p_form_id: form_id },\n        \"formRestore\",\n      );\n    },\n\n    async formsArchived(args) {\n      return callDoor<ArchivedForm[]>(\n        DOORS.formsArchived,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null, p_limit: args?.limit ?? 100 },\n        \"formsArchived\",\n      );\n    },\n\n    async checklistTemplatesArchived(args) {\n      return callDoor<ArchivedChecklistTemplate[]>(\n        DOORS.checklistTemplatesArchived,\n        { p_organization_id: org, p_about_table_id: args?.about_table_id ?? null, p_limit: args?.limit ?? 100 },\n        \"checklistTemplatesArchived\",\n      );\n    },\n\n    async tableRowLabel({ table_id }) {\n      return callDoor<TableRowLabel>(\n        DOORS.tableRowLabel,\n        { p_organization_id: org, p_table_id: table_id },\n        \"tableRowLabel\",\n      );\n    },\n\n    async tableRowLabelSet({ table_id, formula }) {\n      return callDoor<TableRowLabel>(\n        DOORS.tableRowLabelSet,\n        { p_organization_id: org, p_table_id: table_id, p_formula: clearsRowLabel(formula) ? null : formula },\n        \"tableRowLabelSet\",\n      );\n    },\n\n    async tableRowDefaults({ table_id }) {\n      return callDoor<TableRowDefaults>(\n        DOORS.tableRowDefaults,\n        { p_organization_id: org, p_table_id: table_id },\n        \"tableRowDefaults\",\n      );\n    },\n\n    async tableRowDefaultsSet({ table_id, defaults }) {\n      return callDoor<TableRowDefaults>(\n        DOORS.tableRowDefaultsSet,\n        { p_organization_id: org, p_table_id: table_id, p_defaults: defaults },\n        \"tableRowDefaultsSet\",\n      );\n    },\n\n    async tableRowDefaultsApply({ table_id, after }) {\n      return callDoor<RowDefaultsApplied>(\n        DOORS.tableRowDefaultsApply,\n        { p_organization_id: org, p_table_id: table_id, p_after: after ?? null },\n        \"tableRowDefaultsApply\",\n      );\n    },\n\n    async rowDefaultsApplyAll({ table_id, maxPasses }) {\n      // EVERY PASS, SUMMED. The door stops at its time budget and says where; a screen that showed\n      // one pass's count would under-report a big table. The cap keeps a runaway loop finite.\n      const cap = Math.max(1, maxPasses ?? 200);\n      let after: Uuid | null = null;\n      let total: RowDefaultsApplied | null = null;\n      for (let pass = 0; pass < cap; pass += 1) {\n        const step: RecordsResult<RowDefaultsApplied> = await callDoor<RowDefaultsApplied>(\n          DOORS.tableRowDefaultsApply,\n          { p_organization_id: org, p_table_id: table_id, p_after: after },\n          \"tableRowDefaultsApply\",\n        );\n        if (!step.ok) return step;\n        total = total\n          ? {\n              ...step.data,\n              seen: total.seen + step.data.seen,\n              changed: total.changed + step.data.changed,\n              kept_by_hand: total.kept_by_hand + step.data.kept_by_hand,\n            }\n          : step.data;\n        if (step.data.done || !step.data.next_after) break;\n        after = step.data.next_after;\n      }\n      return ok(total as RowDefaultsApplied);\n    },\n\n    async recordRowControls({ record_id }) {\n      return callDoor<RecordRowControls>(\n        DOORS.recordRowControls,\n        { p_organization_id: org, p_record_id: record_id },\n        \"recordRowControls\",\n        // A person with table-level access only has no row controls: the door says so, the record's\n        // header draws nothing, and that is not a failure.\n        { quiet: true },\n      );\n    },\n\n    async recordRowControlsSet({ record_id, controls }) {\n      const result = await callDoor<RecordRowControls>(\n        DOORS.recordRowControlsSet,\n        { p_organization_id: org, p_record_id: record_id, p_controls: controls },\n        \"recordRowControlsSet\",\n      );\n      if (result.ok) announceRecordChanged(record_id);\n      return result;\n    },\n\n    async portalTables() {\n      return callDoor<PortalTableRef[]>(DOORS.portalTables, { p_organization_id: org }, \"portalTables\");\n    },\n\n    async portalCard({ portal_id }) {\n      return callDoor<PortalCard>(\n        DOORS.portalCard,\n        { p_organization_id: org, p_portal_id: portal_id },\n        \"portalCard\",\n      );\n    },\n\n    async portalDeclare(args) {\n      return callDoor<Uuid>(\n        DOORS.portalDeclare,\n        {\n          p_organization_id: org,\n          p_title: args.title,\n          p_client_table_id: args.client_table_id,\n          p_tables: args.tables,\n          p_portal_id: args.portal_id ?? null,\n          p_slug: args.slug ?? null,\n          p_sign_in_method: args.sign_in_method ?? \"magic_link\",\n          // S6: sent only when given, so a caller that says nothing about the look keeps it.\n          ...(args.config !== undefined ? { p_config: args.config } : {}),\n        },\n        \"portalDeclare\",\n      );\n    },\n\n    async portalForm({ portal_id, form_id }) {\n      return callDoor<PortalFormSpec>(\n        DOORS.portalForm,\n        { p_organization_id: org, p_portal_id: portal_id, p_form_id: form_id },\n        \"portalForm\",\n      );\n    },\n\n    async portalFormSubmit({ portal_id, form_id, answers, client_key }) {\n      return callDoor<PortalFormAnswer>(\n        DOORS.portalFormSubmit,\n        {\n          p_organization_id: org,\n          p_portal_id: portal_id,\n          p_form_id: form_id,\n          p_payload: answers,\n          p_client_key: client_key ?? null,\n        },\n        \"portalFormSubmit\",\n      );\n    },\n\n    async portalInvite(args) {\n      return callDoor<PortalInvitation>(\n        DOORS.portalInvite,\n        {\n          p_organization_id: org,\n          p_portal_id: args.portal_id,\n          p_client_record_id: args.client_record_id,\n          p_email: args.email,\n          // ALWAYS null from a client. See the interface comment: an invitation\n          // confers nothing until the person follows their own sign-in link.\n          p_user_id: null,\n        },\n        \"portalInvite\",\n      );\n    },\n\n    async portalRevoke({ portal_id, principal_id }) {\n      return callDoor<PortalRevocation>(\n        DOORS.portalRevoke,\n        { p_organization_id: org, p_portal_id: portal_id, p_principal_id: principal_id },\n        \"portalRevoke\",\n      );\n    },\n\n    async portalPreview({ portal_id, principal_id, table_id }) {\n      return callDoor<PortalPreviewRow[]>(\n        DOORS.portalPreview,\n        {\n          p_organization_id: org,\n          p_portal_id: portal_id,\n          p_principal_id: principal_id,\n          p_table_id: table_id,\n        },\n        \"portalPreview\",\n      );\n    },\n\n    async ruleRun({ rule_id, values, context }) {\n      return callDoor<unknown>(\n        DOORS.ruleRun,\n        {\n          p_organization_id: org,\n          p_rule_id: rule_id,\n          p_values: values,\n          ...(context === undefined ? {} : { p_context: context }),\n        },\n        \"ruleRun\",\n      );\n    },\n\n    async ruleEval({ expr, values, context }) {\n      return callDoor<unknown>(\n        DOORS.ruleEval,\n        {\n          p_organization_id: org,\n          p_expr: expr,\n          p_values: values,\n          ...(context === undefined ? {} : { p_context: context }),\n        },\n        \"ruleEval\",\n      );\n    },\n\n    async captureSheetDeclare(args) {\n      return callDoor<Uuid>(\n        DOORS.captureSheetDeclare,\n        {\n          p_organization_id: org,\n          p_table_id: args.table_id,\n          p_title: args.title,\n          p_questions: args.questions,\n          p_presentation: args.presentation ?? {},\n          p_sheet_id: args.sheet_id ?? null,\n          p_notify_rule_id: args.notify_rule_id ?? null,\n        },\n        \"captureSheetDeclare\",\n      );\n    },\n\n    async capturePublish(args) {\n      return callDoor<string | null>(\n        DOORS.capturePublish,\n        { p_organization_id: org, p_sheet_id: args.sheet_id, p_open: args.open ?? true },\n        \"capturePublish\",\n      );\n    },\n\n    async captureSheets(args) {\n      return callDoor<CaptureSheetSummary[]>(\n        DOORS.captureSheets,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"captureSheets\",\n      );\n    },\n\n    async captureOpen(args) {\n      const out = await callDoor<CaptureSheetFace[] | CaptureSheetFace | null>(\n        DOORS.captureOpen,\n        { p_organization_id: org, p_sheet_id: args.sheet_id },\n        \"captureOpen\",\n      );\n      if (!out.ok) return out as RecordsResult<CaptureSheetFace | null>;\n      const rows = Array.isArray(out.data) ? out.data : out.data ? [out.data] : [];\n      // NO ROW is the answer for a sheet below `viewer` AND for a sheet that is not\n      // there — the same answer the Table itself gives. It is not an error.\n      return { ...out, data: rows[0] ?? null } as RecordsResult<CaptureSheetFace | null>;\n    },\n\n    async captureSubmit(args) {\n      const out = await callDoor<CaptureOutcome[] | CaptureOutcome | null>(\n        DOORS.captureSubmit,\n        {\n          p_organization_id: org,\n          p_sheet_id: args.sheet_id,\n          p_client_key: args.client_key,\n          p_payload: args.answers ?? {},\n          p_files: args.files ?? [],\n          p_device: args.device ?? null,\n          p_captured_at: args.captured_at ?? null,\n          p_location: args.location ?? null,\n        },\n        \"captureSubmit\",\n      );\n      if (!out.ok) return out as RecordsResult<CaptureOutcome | null>;\n      const rows = Array.isArray(out.data) ? out.data : out.data ? [out.data] : [];\n      return { ...out, data: rows[0] ?? null } as RecordsResult<CaptureOutcome | null>;\n    },\n\n    async enrichments(args) {\n      return callDoor<EnrichmentSummary[]>(\n        DOORS.enrichments,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"enrichments\",\n      );\n    },\n\n    async enrichDeclare(args) {\n      return callDoor<EnrichDeclared>(\n        DOORS.enrichDeclare,\n        { p_organization_id: org, p_field_id: args.field_id, p_spec: args.spec },\n        \"enrichDeclare\",\n      );\n    },\n\n    async enrichDue(args) {\n      return callDoor<EnrichDueRow[]>(\n        DOORS.enrichDue,\n        {\n          p_organization_id: org,\n          p_field_id: args.field_id,\n          p_limit: args.limit ?? 50,\n          p_include_fresh: args.include_fresh ?? false,\n        },\n        \"enrichDue\",\n      );\n    },\n\n    async enrichCells(args) {\n      return callDoor<EnrichCell[]>(\n        DOORS.enrichCells,\n        {\n          p_organization_id: org,\n          p_table_id: args.table_id,\n          p_field_keys: args.field_keys ?? null,\n          p_record_ids: args.record_ids ?? null,\n        },\n        \"enrichCells\",\n      );\n    },\n\n    async enrichPin(args) {\n      return callDoor<{ pinned: boolean; says: string }>(\n        DOORS.enrichPin,\n        {\n          p_organization_id: org,\n          p_record_id: args.record_id,\n          p_field_key: args.field_key,\n          p_pinned: args.pinned ?? true,\n        },\n        \"enrichPin\",\n      );\n    },\n\n    async enrichRuns(args) {\n      return callDoor<EnrichRun[]>(\n        DOORS.enrichRuns,\n        {\n          p_organization_id: org,\n          p_field_id: args?.field_id ?? null,\n          p_limit: args?.limit ?? 50,\n        },\n        \"enrichRuns\",\n      );\n    },\n\n    async interfaceRead({ interface_id }) {\n      return callDoor<InterfaceRead | null>(DOORS.interfaceRead, { p_interface_id: interface_id }, \"interfaceRead\");\n    },\n\n    async interfaceRows({ interface_id, element_id, record_id, limit, offset }) {\n      return callDoor<InterfaceRows | null>(\n        DOORS.interfaceRows,\n        {\n          p_interface_id: interface_id,\n          p_element_id: element_id,\n          p_record_id: record_id ?? null,\n          p_limit: limit ?? 200,\n          p_offset: offset ?? 0,\n        },\n        \"interfaceRows\",\n      );\n    },\n\n    async interfaceChart({ interface_id, chart_id }) {\n      return callDoor<DashboardBlockResult | null>(\n        DOORS.interfaceChart,\n        { p_interface_id: interface_id, p_chart_id: chart_id },\n        \"interfaceChart\",\n      );\n    },\n\n    async dashboards(args) {\n      return callDoor<DashboardSummary[]>(\n        DOORS.dashboards,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"dashboards\",\n      );\n    },\n\n    async dashboardDeclare(args) {\n      return callDoor<Uuid>(\n        DOORS.dashboardDeclare,\n        {\n          p_organization_id: org,\n          p_table_id: args.table_id,\n          p_name: args.name,\n          p_blocks: args.blocks ?? [],\n          p_presentation: args.presentation ?? {},\n          p_dashboard_id: args.dashboard_id ?? null,\n        },\n        \"dashboardDeclare\",\n      );\n    },\n\n    async dashboardRun({ dashboard_id, filter, compare, grain }) {\n      return callDoor<DashboardRunResult>(\n        DOORS.dashboardRun,\n        {\n          p_organization_id: org,\n          p_dashboard_id: dashboard_id,\n          p_filter: filter ?? {},\n          // Sent only when asked, so a caller that never compares calls exactly what it did.\n          ...(compare ? { p_compare: compare } : {}),\n          ...(grain ? { p_grain: grain } : {}),\n        },\n        \"dashboardRun\",\n      );\n    },\n\n    async dashboardStuck({ table_id, state_key, days, filter, limit }) {\n      return callDoor<StuckRow[]>(\n        DOORS.dashboardStuck,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_state_key: state_key,\n          p_days: days ?? 14,\n          p_filter: filter ?? {},\n          p_limit: limit ?? 50,\n        },\n        \"dashboardStuck\",\n      );\n    },\n\n    async dashboardDelete({ dashboard_id }) {\n      return callDoor<boolean>(\n        DOORS.dashboardDelete,\n        { p_organization_id: org, p_dashboard_id: dashboard_id },\n        \"dashboardDelete\",\n      );\n    },\n\n    async recordAggregate({ table_id, organization_id, groupBy, measures, bucket, filter, limit, compare, search, time_zone, splitMulti }) {\n      if (spans(organization_id)) {\n        // The aggregate runs in the organization that OWNS the table (never the active one by\n        // default). Not found in any ⇒ asked in the page's / own organization anyway, so the\n        // refusal is the store's own sentence for a table that is not there.\n        const owner = await client.ownerOrganization({ table_id, ...(organization_id ? { organization_id } : {}) });\n        const target = owner.ok && owner.data ? owner.data : (organization_id ?? org);\n        if (target !== org) {\n          const answered = await clientFor(target).recordAggregate({\n            table_id,\n            ...(groupBy ? { groupBy } : {}),\n            ...(measures ? { measures } : {}),\n            ...(bucket !== undefined ? { bucket } : {}),\n            ...(filter ? { filter } : {}),\n            ...(limit !== undefined ? { limit } : {}),\n            ...(compare !== undefined ? { compare } : {}),\n            ...(search ? { search } : {}),\n            ...(time_zone ? { time_zone } : {}),\n            ...(splitMulti ? { splitMulti } : {}),\n          });\n          return answered.ok\n            ? ok(answered.data.map((row) => ({ ...row, organization_id: target })) as AggregateRow[])\n            : answered;\n        }\n      }\n      const asked = await callDoor<AggregateRow[]>(\n        DOORS.recordAggregate,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_group_by: groupBy ?? [],\n          p_measures: measures ?? [],\n          p_bucket: bucket ?? null,\n          p_filter: filter ?? {},\n          p_limit: limit ?? 200,\n          ...(compare ? { p_compare: compare } : {}),\n          ...(search && search.trim() !== \"\" ? { p_search: search } : {}),\n          ...(time_zone ? { p_time_zone: time_zone } : {}),\n          ...(splitMulti ? { p_split_multi: true } : {}),\n        },\n        \"recordAggregate\",\n      );\n      // AGG-WITHHELD: the store answers a column this reader may not read as a state, not an error.\n      return asked.ok ? ok(liftWithheld(asked.data)) : asked;\n    },\n\n    async recordAggregateAsOf({ table_id, recorded_at, measure, field_key, group_by, match }) {\n      if (spans()) {\n        const owner = await client.ownerOrganization({ table_id });\n        if (!owner.ok) return err(owner.error);\n        if (owner.data && owner.data !== org) {\n          return clientFor(owner.data).recordAggregateAsOf({\n            table_id,\n            recorded_at,\n            ...(measure ? { measure } : {}),\n            ...(field_key ? { field_key } : {}),\n            ...(group_by ? { group_by } : {}),\n            ...(match ? { match } : {}),\n          });\n        }\n      }\n      return callDoor<Array<{\n        bucket: string | null;\n        result: number | null;\n        row_count: number;\n        not_numbers: number;\n        a_non_number: string | null;\n      }>>(\n        DOORS.recordAggregateAsOf,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_recorded_at: recorded_at,\n          p_measure: measure ?? \"count\",\n          p_field_key: field_key ?? null,\n          p_group_by: group_by ?? null,\n          p_match: match ?? {},\n        },\n        \"recordAggregateAsOf\",\n      );\n    },\n\n    async aggOperations() {\n      return callDoor<string[]>(DOORS.aggOperations, {}, \"aggOperations\");\n    },\n\n    async aggBuckets() {\n      return callDoor<string[]>(DOORS.aggBuckets, {}, \"aggBuckets\");\n    },\n\n    async aggCalendar() {\n      return callDoor<{ time_zone: string; week_start: string }>(DOORS.aggCalendar, { p_organization_id: org }, \"aggCalendar\");\n    },\n\n    async drillDescribe({ source }) {\n      return drillDoor<DrillDefinition>(DRILL_DOORS.describe, { p_organization_id: org, p_source: source }, \"drillDescribe\");\n    },\n\n    async drillAsk({ source, question }) {\n      const answer = await drillDoor<DrillAnswerRow[]>(\n        DRILL_DOORS.ask,\n        { p_organization_id: org, p_source: source, p_question: question ?? {} },\n        \"drillAsk\",\n      );\n      return answer.ok ? ok(drillAnswerOf(answer.data ?? [])) : answer;\n    },\n\n    async drillRows({ source, where, window, sort, lane, columns, limit, offset, search }) {\n      const question: Record<string, unknown> = {};\n      if (where) question.where = where;\n      if (window) question.window = window;\n      if (sort) question.sort = sort;\n      if (lane) question.lane = lane;\n      if (columns) question.columns = columns;\n      if (limit !== undefined) question.limit = limit;\n      if (offset !== undefined) question.offset = offset;\n      if (search !== undefined && search.trim() !== \"\") {\n        // The door asks a search together with a scope (`platform._drill_compile`); the Table API\n        // sends \"all\" (every row this person may read) — never narrower than the unsearched read.\n        question.search = search.trim();\n        question.scope = \"all\";\n      }\n      return drillDoor<DrillRowsPage>(\n        DRILL_DOORS.rows,\n        { p_organization_id: org, p_source: source, p_question: question },\n        \"drillRows\",\n      );\n    },\n\n    async aggSubscriptions(args) {\n      return callDoor<Subscription[]>(\n        DOORS.aggSubscriptions,\n        {\n          p_organization_id: org,\n          p_saved_view_id: args?.saved_view_id ?? null,\n          p_cadence: args?.cadence ?? null,\n        },\n        \"aggSubscriptions\",\n      );\n    },\n\n    async aggSubscriptionCadences() {\n      return callDoor<string[]>(DOORS.aggSubscriptionCadences, {}, \"aggSubscriptionCadences\");\n    },\n\n    async subscriptionCadences() {\n      return callDoor<string[]>(\n        DOORS.subscriptionCadences,\n        { p_organization_id: org },\n        \"subscriptionCadences\",\n      );\n    },\n\n    async subscriptions(args) {\n      return callDoor<MySubscription[]>(\n        DOORS.subscriptions,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"subscriptions\",\n      );\n    },\n\n    async subscriptionDeclare({ table_id, spec }) {\n      return callDoor<Uuid>(\n        DOORS.subscriptionDeclare,\n        // The schedule is read in the owner's clock, never silently in UTC (`withCallersClock`).\n        { p_organization_id: org, p_table_id: table_id, p_spec: withCallersClock(spec) },\n        \"subscriptionDeclare\",\n      );\n    },\n\n    async subscriptionPreview({ rule_id }) {\n      return callDoor<DigestPreview>(\n        DOORS.subscriptionPreview,\n        { p_organization_id: org, p_rule_id: rule_id },\n        \"subscriptionPreview\",\n      );\n    },\n\n    async views(args) {\n      return callDoor<SavedViewRow[]>(\n        DOORS.views,\n        { p_organization_id: org, p_table_id: args?.table_id ?? null },\n        \"views\",\n      );\n    },\n\n    async rowTemplates({ table_id }) {\n      return callDoor<RowTemplateRow[]>(\n        DOORS.rowTemplates,\n        { p_organization_id: org, p_table_id: table_id },\n        \"rowTemplates\",\n      );\n    },\n\n    async rowTemplateDeclare({ table_id, spec }) {\n      return callDoor<Uuid>(\n        DOORS.rowTemplateDeclare,\n        { p_organization_id: org, p_table_id: table_id, p_spec: spec },\n        \"rowTemplateDeclare\",\n      );\n    },\n\n    async viewDeclare({ table_id, spec }) {\n      return callDoor<Uuid>(\n        DOORS.viewDeclare,\n        { p_organization_id: org, p_table_id: table_id, p_spec: spec },\n        \"viewDeclare\",\n      );\n    },\n\n    async viewArchive({ view_id }) {\n      return publicDoor<Record<string, unknown> | null>(\n        \"saved_view_archive\",\n        { p_surface_key: SAVED_VIEW_SURFACE, p_id: view_id },\n        \"viewArchive\",\n        \"platform\",\n      );\n    },\n\n    async viewRestore({ view_id }) {\n      return publicDoor<boolean>(\"entity_undelete\", { p_token: \"platform_saved_view\", p_id: view_id }, \"viewRestore\", \"platform\");\n    },\n\n    async viewDesignate({ table_id, view_id, layout }) {\n      return callDoor<Uuid>(\n        DOORS.viewDesignate,\n        { p_organization_id: org, p_table_id: table_id, p_view_id: view_id, p_layout: layout ?? null },\n        \"viewDesignate\",\n      );\n    },\n\n    async viewLookRead({ table_id }) {\n      const answered = await callDoor<Record<string, { look: Record<string, unknown>; updated_at: string }> | null>(\n        DOORS.viewLookRead,\n        { p_organization_id: org, p_table_id: table_id },\n        \"viewLookRead\",\n      );\n      return answered.ok ? ok(answered.data ?? {}) : answered;\n    },\n\n    async viewLookSet({ table_id, view_id, look }) {\n      return callDoor<Record<string, unknown> | null>(\n        DOORS.viewLookSet,\n        { p_organization_id: org, p_table_id: table_id, p_view_id: view_id, p_look: look },\n        \"viewLookSet\",\n      );\n    },\n\n    async subscriptionMute({ rule_id, muted }) {\n      return callDoor<boolean>(\n        DOORS.subscriptionMute,\n        { p_organization_id: org, p_rule_id: rule_id, p_muted: muted },\n        \"subscriptionMute\",\n      );\n    },\n\n    async docTemplateSave({ table_id, name, body, template_id }) {\n      return callDoor<Uuid>(\n        DOORS.docTemplateSave,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_name: name,\n          p_body: body,\n          p_template_id: template_id ?? null,\n        },\n        \"docTemplateSave\",\n      );\n    },\n\n    async docRenderBody({ template_id, record_id }) {\n      return callDoor<string>(\n        DOORS.docRenderBody,\n        { p_organization_id: org, p_template_id: template_id, p_record_id: record_id },\n        \"docRenderBody\",\n      );\n    },\n\n    async docRenderDocument({ template_id, record_id }) {\n      return callDoor<Uuid>(\n        DOORS.docRenderDocument,\n        { p_organization_id: org, p_template_id: template_id, p_record_id: record_id },\n        \"docRenderDocument\",\n      );\n    },\n\n    async docTokens({ body }) {\n      return callDoor<DocToken[]>(DOORS.docTokens, { p_body: body }, \"docTokens\");\n    },\n\n    async docUnresolvedTokens({ table_id, body }) {\n      return callDoor<DocUnresolvedToken[]>(\n        DOORS.docUnresolvedTokens,\n        { p_organization_id: org, p_table_id: table_id, p_body: body },\n        \"docUnresolvedTokens\",\n      );\n    },\n\n    async docSign({ render_id, field_key, signer_name, signer_user_id }) {\n      return callDoor<Uuid>(\n        DOORS.docSign,\n        {\n          p_organization_id: org,\n          p_render_id: render_id,\n          p_field_key: field_key,\n          p_signer_name: signer_name,\n          p_signer_user_id: signer_user_id ?? null,\n        },\n        \"docSign\",\n      );\n    },\n\n    // A LIST IS A DOOR, NEVER A GRANT ON THE THING BEHIND IT. These three used to\n    // read `custom.doc_template`, `custom.doc_render` and `custom.doc_signature`\n    // with a direct PostgREST `.from()`, and none of the three holds a client\n    // SELECT — so a person could save a template they could never list and\n    // render a document they could never find again, and every document screen\n    // opened on \"permission denied for view doc_template\". The doors below\n    // narrow inside the definer, after the ladder has spoken (DOORS-TWO).\n    async docTemplates({ table_id }) {\n      // The door names its key `template_id`, because a door answers about the\n      // thing it is a door to. The package's row keeps `id`, which is what every\n      // screen already holds — one rename, here, rather than in four screens.\n      const answered = await callDoor<Array<Record<string, unknown>>>(\n        DOORS.docTemplates,\n        { p_organization_id: org, p_table_id: table_id },\n        \"docTemplates\",\n      );\n      if (!answered.ok) return answered;\n      return ok(\n        answered.data.map((row) => ({ ...row, id: row[\"template_id\"] })) as unknown as DocTemplateRow[],\n      );\n    },\n\n    async docTemplateDelete({ template_id }) {\n      return callDoor<boolean>(\n        DOORS.docTemplateDelete,\n        { p_organization_id: org, p_template_id: template_id },\n        \"docTemplateDelete\",\n      );\n    },\n\n    async docTemplateRestore({ template_id }) {\n      return callDoor<boolean>(\n        DOORS.docTemplateRestore,\n        { p_organization_id: org, p_template_id: template_id },\n        \"docTemplateRestore\",\n      );\n    },\n\n    async docRenderDelete({ render_id }) {\n      return callDoor<boolean>(\n        DOORS.docRenderDelete,\n        { p_organization_id: org, p_render_id: render_id },\n        \"docRenderDelete\",\n      );\n    },\n\n    async docRenderRestore({ render_id }) {\n      return callDoor<boolean>(\n        DOORS.docRenderRestore,\n        { p_organization_id: org, p_render_id: render_id },\n        \"docRenderRestore\",\n      );\n    },\n\n    async docRenders({ record_id }) {\n      const answered = await callDoor<Array<Record<string, unknown>>>(\n        DOORS.docRenders,\n        { p_organization_id: org, p_record_id: record_id },\n        \"docRenders\",\n      );\n      if (!answered.ok) return answered;\n      return ok(\n        answered.data.map((row) => ({ ...row, id: row[\"render_id\"] })) as unknown as DocRenderRow[],\n      );\n    },\n\n    async docSignatures({ record_id }) {\n      const answered = await callDoor<Array<Record<string, unknown>>>(\n        DOORS.docSignatures,\n        { p_organization_id: org, p_record_id: record_id },\n        \"docSignatures\",\n      );\n      if (!answered.ok) return answered;\n      return ok(\n        answered.data.map((row) => ({ ...row, id: row[\"signature_id\"] })) as unknown as DocSignatureRow[],\n      );\n    },\n\n    async recordValuesVersioned({ record_id, organization_id }) {\n      if (organization_id && organization_id !== org) {\n        return clientFor(organization_id).recordValuesVersioned({ record_id, organization_id });\n      }\n      if (readOrgs(organization_id).length > 1) {\n        return openInOwnOrg<ReadValue[]>(\n          record_id,\n          organization_id,\n          (sub) => sub.recordValuesVersioned({ record_id, organization_id: sub.config.organizationId }),\n          (values) => values.length > 0,\n        );\n      }\n      return readValues(record_id);\n    },\n\n    async revisions({ record_id }) {\n      return callDoor<RecordRevision[]>(\n        DOORS.ioRevisions,\n        { p_organization_id: org, p_record_id: record_id },\n        \"revisions\",\n      );\n    },\n\n    async recordScopeContext({ record_id, relations, history, siblings }) {\n      return callDoor<RecordScopeContext>(\n        DOORS.recordScopeContext,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_relations: relations ?? 12,\n          p_history: history ?? 15,\n          p_siblings: siblings ?? 8,\n        },\n        \"recordScopeContext\",\n      );\n    },\n\n    async conversationScope({ conversation_id }) {\n      return callDoor<ConversationScope>(\n        DOORS.conversationScope,\n        { p_organization_id: org, p_conversation_id: conversation_id },\n        \"conversationScope\",\n      );\n    },\n\n    async conversationScopeBind({ conversation_id, record_id }) {\n      return callDoor<ConversationScope>(\n        DOORS.conversationScopeBind,\n        {\n          p_organization_id: org,\n          p_conversation_id: conversation_id,\n          p_record_id: record_id,\n        },\n        \"conversationScopeBind\",\n      );\n    },\n\n    async conversationScopeUnbind({ conversation_id }) {\n      return callDoor<ConversationScope>(\n        DOORS.conversationScopeUnbind,\n        { p_organization_id: org, p_conversation_id: conversation_id },\n        \"conversationScopeUnbind\",\n      );\n    },\n\n    async conversationScopeContext({ conversation_id, relations, history, siblings }) {\n      return callDoor<ConversationScopeContext>(\n        DOORS.conversationScopeContext,\n        {\n          p_organization_id: org,\n          p_conversation_id: conversation_id,\n          p_relations: relations ?? 12,\n          p_history: history ?? 15,\n          p_siblings: siblings ?? 8,\n        },\n        \"conversationScopeContext\",\n      );\n    },\n\n    async recordHistory({ record_id, limit, offset }) {\n      return callDoor<RecordHistoryEntry[]>(\n        DOORS.recordHistory,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_limit: limit ?? 200,\n          p_offset: offset ?? 0,\n        },\n        \"recordHistory\",\n      );\n    },\n\n    async fieldHistory({ table_id, field_key, limit, offset, record_id }) {\n      return callDoor<FieldHistoryEntry[]>(\n        DOORS.fieldHistory,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_field_key: field_key,\n          p_limit: limit ?? 100,\n          p_offset: offset ?? 0,\n          p_record_id: record_id ?? null,\n        },\n        \"fieldHistory\",\n      );\n    },\n\n    async formulaHistory({ record_id, field_key, limit }) {\n      return callDoor<FormulaHistoryEntry[]>(\n        DOORS.formulaHistory,\n        { p_organization_id: org, p_record_id: record_id, p_field_key: field_key, p_limit: limit ?? 100 },\n        \"formulaHistory\",\n      );\n    },\n\n    async restorePreview({ record_id, version, field_key }) {\n      return callDoor<RestorePreview>(\n        DOORS.restorePreview,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_version: version,\n          p_field_key: field_key ?? null,\n        },\n        \"restorePreview\",\n      );\n    },\n\n    async restoreVersion({ record_id, version }) {\n      const result = await callDoor<RestoreResult>(\n        DOORS.restoreVersion,\n        { p_organization_id: org, p_record_id: record_id, p_version: version },\n        \"restoreVersion\",\n      );\n      if (result.ok) announceRecordChanged(record_id);\n      return result;\n    },\n\n    async valueRestore({ record_id, field_key, version }) {\n      const answered = await callDoor<RestoreResult>(\n        DOORS.valueRestore,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_field_key: field_key,\n          p_version: version,\n        },\n        \"valueRestore\",\n      );\n      if (answered.ok) announceRecordChanged(record_id);\n      return answered;\n    },\n\n    async commentThread({ record_id, include_resolved }) {\n      return callDoor<CommentThreadRead>(\n        DOORS.commentThread,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_include_resolved: include_resolved ?? false,\n        },\n        \"commentThread\",\n      );\n    },\n\n    async commentCounts({ record_ids }) {\n      if (record_ids.length === 0) return { ok: true, data: {} };\n      return callDoor<Record<string, number>>(\n        DOORS.commentCounts,\n        { p_organization_id: org, p_record_ids: [...record_ids] },\n        \"commentCounts\",\n      );\n    },\n\n    async commentWrite({ record_id, body, field_key, parent_comment_id, mentions }) {\n      return callDoor<CommentWritten>(\n        DOORS.commentWrite,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_body: body,\n          // THE ANCHOR IS WHERE A FIELD COMMENT LIVES. `custom.io_comment` has\n          // always carried it; nothing was ever putting a Field in it.\n          p_anchor: field_key ? { field_key } : {},\n          p_parent_comment_id: parent_comment_id ?? null,\n          p_mentions: mentions && mentions.length > 0 ? mentions : null,\n        },\n        \"commentWrite\",\n      );\n    },\n\n    async commentResolve({ comment_id, resolved }) {\n      return callDoor<boolean>(\n        DOORS.commentResolve,\n        {\n          p_organization_id: org,\n          p_comment_id: comment_id,\n          p_resolved: resolved ?? true,\n        },\n        \"commentResolve\",\n      );\n    },\n\n    async recordFollowSet({ record_id, follow }) {\n      return callDoor<RecordFollowSet>(\n        DOORS.recordFollowSet,\n        { p_organization_id: org, p_record_id: record_id, p_follow: follow ?? true },\n        \"recordFollowSet\",\n      );\n    },\n\n    async recordFollowers({ record_id }) {\n      return callDoor<RecordFollowers>(\n        DOORS.recordFollowers,\n        { p_organization_id: org, p_record_id: record_id },\n        \"recordFollowers\",\n      );\n    },\n\n    async docSignatureRead({ signature_id }) {\n      return callDoor<unknown>(\n        DOORS.docSignatureRead,\n        { p_organization_id: org, p_signature_id: signature_id },\n        \"docSignatureRead\",\n      );\n    },\n\n    // ── the anonymous lane ───────────────────────────────────────────────\n    async anonTokenIssue({ mode, allowedOrigins, formId, savedViewId, recordId, expiresAt }) {\n      // The door answers a one-row TABLE, so the array is unwrapped here rather\n      // than in every caller. An empty answer is impossible — the door either\n      // returns the pair or raises — so `[0]` is not a guess.\n      const answered = await callDoor<Array<{ token_id: Uuid; secret: string }>>(\n        DOORS.anonTokenIssue,\n        {\n          p_organization_id: org,\n          p_mode: mode,\n          p_allowed_origins: allowedOrigins,\n          p_form_id: formId ?? null,\n          p_saved_view_id: savedViewId ?? null,\n          p_record_id: recordId ?? null,\n          p_expires_at: expiresAt ?? null,\n        },\n        \"anonTokenIssue\",\n      );\n      if (!answered.ok) return answered;\n      const pair = answered.data[0];\n      if (!pair) {\n        return err({\n          code: \"internal\",\n          message: \"custom.anon_token_issue returned no token, which it cannot do — it either mints one or raises.\",\n          hint: \"Nothing was issued. Do not retry blindly: something between this client and the store changed the answer's shape.\",\n        });\n      }\n      return ok(pair);\n    },\n\n    async anonTokenVerify({ secret, origin, requiredMode }) {\n      const answered = await callDoor<AnonTokenBinding[]>(\n        DOORS.anonTokenVerify,\n        { p_secret: secret, p_origin: origin, p_required_mode: requiredMode ?? null },\n        \"anonTokenVerify\",\n      );\n      if (!answered.ok) return answered;\n      const binding = answered.data[0];\n      if (!binding) {\n        return err({\n          code: \"internal\",\n          message: \"custom.anon_token_verify returned no binding, which it cannot do — it either answers or raises.\",\n          hint: \"Treat this as unverified. It is reported rather than read as 'not valid', because those are different sentences.\",\n        });\n      }\n      return ok(binding);\n    },\n\n    async anonTokenRevoke({ token_id }) {\n      return callDoor<boolean>(\n        DOORS.anonTokenRevoke,\n        { p_organization_id: org, p_token_id: token_id },\n        \"anonTokenRevoke\",\n      );\n    },\n\n    async anonWrite({ secret, origin, payload, clientKey, rawPayload }) {\n      // No `p_organization_id`: the TOKEN supplies the organization. A stranger\n      // naming one would be choosing which tenant to write into.\n      return callDoor<Uuid>(\n        DOORS.anonWrite,\n        {\n          p_secret: secret,\n          p_origin: origin,\n          p_payload: payload,\n          p_client_key: clientKey ?? null,\n          p_raw_payload: rawPayload ?? {},\n        },\n        \"anonWrite\",\n      );\n    },\n\n    async anonCapture({ table_id, clientKey, payload, device, capturedAt }) {\n      return callDoor<Uuid>(\n        DOORS.anonCapture,\n        {\n          p_organization_id: org,\n          p_client_key: clientKey,\n          p_table_id: table_id,\n          p_payload: payload,\n          p_device: device ?? null,\n          p_captured_at: capturedAt ?? null,\n        },\n        \"anonCapture\",\n      );\n    },\n\n    async anonPublish({ form_id, published = true }) {\n      return callDoor<Timestamp | null>(\n        DOORS.anonPublish,\n        { p_organization_id: org, p_form_id: form_id, p_published: published },\n        \"anonPublish\",\n      );\n    },\n\n    // ── work ─────────────────────────────────────────────────────────────\n    async workStates() {\n      return callDoor<WorkState[]>(DOORS.workStates, {}, \"workStates\");\n    },\n\n    async workTemplateRefusal({ graph }) {\n      return callDoor<string | null>(DOORS.workTemplateRefusal, { p_graph: graph }, \"workTemplateRefusal\");\n    },\n\n    async workTemplateDeclare({ name, graph }) {\n      return callDoor<Uuid>(\n        DOORS.workTemplateDeclare,\n        { p_organization_id: org, p_name: name, p_graph: graph },\n        \"workTemplateDeclare\",\n      );\n    },\n\n    async workTemplateInstantiate({ template_id, overrides }) {\n      return callDoor<WorkInstantiation>(\n        DOORS.workTemplateInstantiate,\n        { p_organization_id: org, p_template_id: template_id, p_overrides: overrides ?? {} },\n        \"workTemplateInstantiate\",\n      );\n    },\n\n    async workTemplateShape({ template_id }) {\n      return callDoor<unknown>(\n        DOORS.workTemplateShape,\n        { p_organization_id: org, p_template_id: template_id },\n        \"workTemplateShape\",\n      );\n    },\n\n    async workInstantiationShape({ instantiation_id }) {\n      return callDoor<unknown>(\n        DOORS.workInstantiationShape,\n        { p_organization_id: org, p_instantiation_id: instantiation_id },\n        \"workInstantiationShape\",\n      );\n    },\n\n    async workWhoseTurn({ table_id, includeFinished = false }) {\n      return callDoor<WorkTurn[]>(\n        DOORS.workWhoseTurn,\n        { p_organization_id: org, p_table_id: table_id, p_include_finished: includeFinished },\n        \"workWhoseTurn\",\n      );\n    },\n\n    async workHasAssignment({ table_id }) {\n      return callDoor<boolean>(\n        DOORS.workHasAssignment,\n        { p_organization_id: org, p_table_id: table_id },\n        \"workHasAssignment\",\n      );\n    },\n\n    async workAssignmentFields(args) {\n      return callDoor<WorkAssignmentField[]>(\n        DOORS.workAssignmentFields,\n        { p_options_table_id: args?.options_table_id ?? null },\n        \"workAssignmentFields\",\n      );\n    },\n\n    async workTakeAssignment({ table_id }) {\n      return callDoor<unknown>(\n        DOORS.workTakeAssignment,\n        { p_organization_id: org, p_table_id: table_id },\n        \"workTakeAssignment\",\n      );\n    },\n\n    async workTransitionRefusal({ from_state_id, to_state_id }) {\n      return callDoor<string | null>(\n        DOORS.workTransitionRefusal,\n        { p_organization_id: org, p_from_state_id: from_state_id, p_to_state_id: to_state_id },\n        \"workTransitionRefusal\",\n      );\n    },\n\n    async workSlotsDeclare({ name, slug, homeId }) {\n      return callDoor<unknown>(\n        DOORS.workSlotsDeclare,\n        { p_organization_id: org, p_name: name, p_slug: slug, p_home_id: homeId ?? null },\n        \"workSlotsDeclare\",\n      );\n    },\n\n    async workSlotHold({ table_id, slotKey, holder, ttl }) {\n      return callDoor<unknown>(\n        DOORS.workSlotHold,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_slot_key: slotKey,\n          p_holder: holder,\n          ...(ttl ? { p_ttl: ttl } : {}),\n        },\n        \"workSlotHold\",\n      );\n    },\n\n    async workSlotRelease({ hold_id }) {\n      return callDoor<boolean>(\n        DOORS.workSlotRelease,\n        { p_organization_id: org, p_hold_id: hold_id },\n        \"workSlotRelease\",\n      );\n    },\n\n    async workSlotHolds({ table_id }) {\n      return callDoor<WorkSlotHold[]>(\n        DOORS.workSlotHolds,\n        { p_organization_id: org, p_table_id: table_id },\n        \"workSlotHolds\",\n      );\n    },\n\n    async workSlotExpire({ table_id }) {\n      return callDoor<number>(\n        DOORS.workSlotExpire,\n        { p_organization_id: org, p_table_id: table_id },\n        \"workSlotExpire\",\n      );\n    },\n\n    // ── checklists and SOP runs ──────────────────────────────────────────\n    async checklistRefusal({ spec }) {\n      return callDoor<string | null>(\n        DOORS.checklistRefusal,\n        { p_spec: spec },\n        \"checklistRefusal\",\n      );\n    },\n\n    async checklistDeclare({ spec, template_id = null }) {\n      return callDoor<ChecklistDeclared>(\n        DOORS.checklistDeclare,\n        { p_organization_id: org, p_spec: spec, p_template_id: template_id },\n        \"checklistDeclare\",\n      );\n    },\n\n    async checklistTemplates(args) {\n      return callDoor<ChecklistTemplateSummary[]>(\n        DOORS.checklistTemplates,\n        {\n          p_organization_id: org,\n          p_about_table_id: args?.about_table_id ?? null,\n          p_limit: args?.limit ?? 100,\n        },\n        \"checklistTemplates\",\n      );\n    },\n\n    async checklistTemplateShape({ template_id }) {\n      return callDoor<ChecklistTemplateShape>(\n        DOORS.checklistTemplateShape,\n        { p_organization_id: org, p_template_id: template_id },\n        \"checklistTemplateShape\",\n      );\n    },\n\n    async checklistStart({ template_id, about_record_id = null, roles = {}, startingAt = null }) {\n      return callDoor<ChecklistRunStarted>(\n        DOORS.checklistStart,\n        {\n          p_organization_id: org,\n          p_template_id: template_id,\n          p_about_record_id: about_record_id,\n          p_roles: roles,\n          p_starting_at: startingAt,\n        },\n        \"checklistStart\",\n      );\n    },\n\n    async checklistRun({ run_id }) {\n      return callDoor<ChecklistRunStep[]>(\n        DOORS.checklistRun,\n        { p_organization_id: org, p_run_id: run_id },\n        \"checklistRun\",\n      );\n    },\n\n    async checklistRuns(args) {\n      return callDoor<ChecklistRunSummary[]>(\n        DOORS.checklistRuns,\n        {\n          p_organization_id: org,\n          p_about_table_id: args?.about_table_id ?? null,\n          p_about_record_id: args?.about_record_id ?? null,\n          p_include_closed: args?.includeClosed ?? true,\n          p_limit: args?.limit ?? 100,\n        },\n        \"checklistRuns\",\n      );\n    },\n\n    async checklistStepComplete({ step_id, evidence = {} }) {\n      return callDoor<ChecklistStepCompleted>(\n        DOORS.checklistStepComplete,\n        { p_organization_id: org, p_step_id: step_id, p_evidence: evidence },\n        \"checklistStepComplete\",\n      );\n    },\n\n    async checklistStepRefusal({ step_id }) {\n      return callDoor<string | null>(\n        DOORS.checklistStepRefusal,\n        { p_organization_id: org, p_step_id: step_id },\n        \"checklistStepRefusal\",\n      );\n    },\n\n    // ── the work layer a person actually uses ────────────────────────────\n    async workInbox(args) {\n      return callDoor<WorkInboxItem[]>(\n        DOORS.workInbox,\n        {\n          p_organization_id: org,\n          p_limit: args?.limit ?? 50,\n          p_offset: args?.offset ?? 0,\n          p_include_decided: args?.includeDecided ?? false,\n          p_view: args?.view ?? \"inbox\",\n        },\n        \"workInbox\",\n      );\n    },\n\n    async inboxSnooze({ item_id, until }) {\n      return callDoor<InboxStateChange>(\n        DOORS.inboxSnooze,\n        { p_organization_id: org, p_item_id: item_id, p_until: until },\n        \"inboxSnooze\",\n      );\n    },\n\n    async inboxUnsnooze({ item_id }) {\n      return callDoor<InboxStateChange>(\n        DOORS.inboxUnsnooze,\n        { p_organization_id: org, p_item_id: item_id },\n        \"inboxUnsnooze\",\n      );\n    },\n\n    async inboxClear({ item_id }) {\n      return callDoor<InboxStateChange>(\n        DOORS.inboxClear,\n        { p_organization_id: org, p_item_id: item_id },\n        \"inboxClear\",\n      );\n    },\n\n    async inboxUnclear({ item_id }) {\n      return callDoor<InboxStateChange>(\n        DOORS.inboxUnclear,\n        { p_organization_id: org, p_item_id: item_id },\n        \"inboxUnclear\",\n      );\n    },\n\n    async inboxCounts(args) {\n      return callDoor<InboxCounts[]>(\n        DOORS.inboxCounts,\n        { p_organization_id: args?.everyOrganization ? null : org },\n        \"inboxCounts\",\n      );\n    },\n\n    async workList(args) {\n      return callDoor<WorkListItem[]>(\n        DOORS.workList,\n        {\n          p_organization_id: org,\n          p_flavour: args?.flavour ?? \"mine\",\n          p_include_finished: args?.includeFinished ?? false,\n          p_limit: args?.limit ?? 100,\n          p_offset: args?.offset ?? 0,\n        },\n        \"workList\",\n      );\n    },\n\n    async workAssign({ record_id, user_id = null, dueDate = null, clearDue = false }) {\n      return callDoor<WorkAssignment>(\n        DOORS.workAssign,\n        {\n          p_organization_id: org,\n          p_record_id: record_id,\n          p_assignee_user_id: user_id,\n          p_due_date: dueDate,\n          p_clear_due: clearDue,\n        },\n        \"workAssign\",\n      );\n    },\n\n    async workRecordStates({ record_id }) {\n      return callDoor<WorkRecordState[]>(\n        DOORS.workRecordStates,\n        { p_organization_id: org, p_record_id: record_id },\n        \"workRecordStates\",\n      );\n    },\n\n    async workSetState({ record_id, state_id }) {\n      return callDoor<unknown>(\n        DOORS.workSetState,\n        { p_organization_id: org, p_record_id: record_id, p_state_id: state_id },\n        \"workSetState\",\n      );\n    },\n\n    async workPerson({ user_id, create = true }) {\n      return callDoor<Uuid | null>(\n        DOORS.workPerson,\n        { p_organization_id: org, p_user_id: user_id, p_create: create },\n        \"workPerson\",\n      );\n    },\n\n    async workTemplates(args) {\n      return callDoor<Array<{\n        template_id: Uuid;\n        name: string;\n        nodes: number;\n        relations: number;\n        created_at: string;\n      }>>(\n        DOORS.workTemplates,\n        { p_organization_id: org, p_limit: args?.limit ?? 100 },\n        \"workTemplates\",\n      );\n    },\n\n    async workApprovalApprovers({ subject_id, approver_id = null }) {\n      return callDoor<WorkApprover[]>(\n        DOORS.workApprovalApprovers,\n        { p_organization_id: org, p_subject_id: subject_id, p_approver_id: approver_id },\n        \"workApprovalApprovers\",\n      );\n    },\n\n    async workApprovalRequest({\n      subject_id,\n      change,\n      note = null,\n      approver_id = null,\n      origin = \"person\",\n      conversation_id = null,\n    }) {\n      return callDoor<WorkApprovalFiled>(\n        DOORS.workApprovalRequest,\n        {\n          p_organization_id: org,\n          p_subject_id: subject_id,\n          p_change: change,\n          p_note: note,\n          p_approver_id: approver_id,\n          p_origin: origin,\n          p_conversation_id: conversation_id,\n        },\n        \"workApprovalRequest\",\n      );\n    },\n\n    async workApprovalMayDecide({ approval_id }) {\n      return callDoor<boolean>(\n        DOORS.workApprovalMayDecide,\n        { p_organization_id: org, p_approval_id: approval_id },\n        \"workApprovalMayDecide\",\n      );\n    },\n\n    async workApprovalDecide({ approval_id, approve, note = null }) {\n      return callDoor<WorkApprovalDecision>(\n        DOORS.workApprovalDecide,\n        {\n          p_organization_id: org,\n          p_approval_id: approval_id,\n          p_approve: approve,\n          p_note: note,\n        },\n        \"workApprovalDecide\",\n      );\n    },\n\n    async workDecideMany({ decisions }) {\n      return callDoor<WorkDecideMany>(\n        DOORS.workDecideMany,\n        { p_organization_id: org, p_decisions: decisions },\n        \"workDecideMany\",\n      );\n    },\n\n    async workApprovalRead({ approval_id }) {\n      return callDoor<Record<string, unknown>>(\n        DOORS.workApprovalRead,\n        { p_organization_id: org, p_approval_id: approval_id },\n        \"workApprovalRead\",\n      );\n    },\n\n    // ── the trust doors ──────────────────────────────────────────────────\n    async isExternalPrincipal(args) {\n      return trustDoor<boolean>(\n        TRUST_DOORS.isExternalPrincipal,\n        { p_user_id: args?.user_id ?? null },\n        \"isExternalPrincipal\",\n      );\n    },\n\n    async externalPrincipalCard(args) {\n      return trustDoor<ExternalPrincipalCard>(\n        TRUST_DOORS.externalPrincipalCard,\n        { p_user_id: args?.user_id ?? null },\n        \"externalPrincipalCard\",\n      );\n    },\n\n    async externalPrincipalReach({ resourceType, user_id }) {\n      return trustDoor<Array<{ resource_id: Uuid }>>(\n        TRUST_DOORS.externalPrincipalReach,\n        { p_resource_type: resourceType, p_user_id: user_id ?? null },\n        \"externalPrincipalReach\",\n      );\n    },\n\n    async publishBindingCreate({ slug, resourceType, resource_id, renderMode = \"page\" }) {\n      return trustDoor<PublishBinding>(\n        TRUST_DOORS.publishBindingCreate,\n        {\n          p_slug: slug,\n          p_resource_type: resourceType,\n          p_resource_id: resource_id,\n          p_organization_id: org,\n          p_render_mode: renderMode,\n        },\n        \"publishBindingCreate\",\n      );\n    },\n\n    async publishBindingRevoke({ slug }) {\n      return trustDoor<unknown>(TRUST_DOORS.publishBindingRevoke, { p_slug: slug }, \"publishBindingRevoke\");\n    },\n\n    async resolvePublishBinding({ slug }) {\n      return trustDoor<ResolvedPublishBinding[]>(\n        TRUST_DOORS.resolvePublishBinding,\n        { p_slug: slug },\n        \"resolvePublishBinding\",\n      );\n    },\n\n    async resolvePublishBindingKind({ slug }) {\n      return trustDoor<ResolvedPublishBindingKind[]>(\n        TRUST_DOORS.resolvePublishBindingKind,\n        { p_slug: slug },\n        \"resolvePublishBindingKind\",\n      );\n    },\n\n    async worldPublishGapNotice() {\n      return trustDoor<string>(TRUST_DOORS.worldPublishGapNotice, {}, \"worldPublishGapNotice\");\n    },\n\n    async publishToWorld({ resourceType, resource_id, discoverable = false }) {\n      return trustDoor<unknown>(\n        TRUST_DOORS.publishToWorld,\n        {\n          p_resource_type: resourceType,\n          p_resource_id: resource_id,\n          p_organization_id: org,\n          p_discoverable: discoverable,\n        },\n        \"publishToWorld\",\n      );\n    },\n\n    async ruleDeclare({ spec, rule_id }) {\n      // THE DOOR LANDED (lane FORMS, 2026-09-20). This used to be a refusing\n      // stub, and the refusal was right: until `custom.rule_declare` existed\n      // there was NO way to write a Rule that the store's own rule doors could\n      // see, and pretending otherwise would have been the silent failure the\n      // comment on the interface describes.\n      return callDoor<Uuid>(\n        DOORS.ruleDeclare,\n        { p_organization_id: org, p_spec: spec, p_rule_id: rule_id ?? null },\n        \"ruleDeclare\",\n      );\n    },\n\n    // The words reach the read door in every organization asked (`structureSearchIn`).\n    async metadataSearch({ text, organization_id }) {\n      if (spans(organization_id) && readOrgs(organization_id).length > 0) {\n        const targets = readOrgs(organization_id).filter((t): t is Uuid => t !== null);\n        const unavailable: OrganizationUnavailable[] = [];\n        const answers = await Promise.all(\n          targets.map(async (t) => {\n            // No store switch is asked first: the store is never off (2026-10-03). A refusal of\n            // the read door itself is what makes an organization unavailable.\n            // ONE organization's door — never `sub.metadataSearch` (for the client's own\n            // organization `sub` is this very client, which would span again).\n            const found = await structureSearchIn(t, text);\n            if (!found.ok) {\n              unavailable.push({ organization_id: t, reason: unavailableReason(found.error) });\n              return { t, found };\n            }\n            return { t, found };\n          }),\n        );\n        const matches: MetadataSearchAnswer[\"matches\"] = [];\n        const covered: Uuid[] = [];\n        let firstRefusal: RecordsError | null = null;\n        for (const answer of answers) {\n          if (!answer) continue;\n          if (!answer.found.ok) {\n            firstRefusal ??= answer.found.error;\n            continue;\n          }\n          covered.push(answer.t);\n          for (const m of answer.found.data.matches) matches.push({ ...m, organization_id: answer.t });\n        }\n        const inOrder = (a: OrganizationUnavailable, b: OrganizationUnavailable) =>\n          targets.indexOf(a.organization_id) - targets.indexOf(b.organization_id);\n        unavailable.sort(inOrder);\n        // One organization's refusal never hides the rest; only when NOTHING answered is it a failure.\n        if (covered.length === 0 && firstRefusal) return err(firstRefusal);\n        return ok({ matches, organizations_covered: covered, unavailable });\n      }\n      return structureSearchIn(org, text);\n    },\n\n    async organizationsOpen(args) {\n      const targets = readOrgs(args?.organization_id).filter((t): t is Uuid => t !== null);\n      const open: Uuid[] = [];\n      const unavailable: OrganizationUnavailable[] = [];\n      await Promise.all(\n        targets.map(async (t) => {\n          const result = await clientFor(t).storeIsOpen();\n          // Only a REFUSAL makes an organization unavailable. No organization is \"switched off\":\n          // the store is never off (2026-10-03).\n          if (!result.ok) unavailable.push({ organization_id: t, reason: unavailableReason(result.error) });\n          else open.push(t);\n        }),\n      );\n      const position = (id: Uuid) => targets.indexOf(id);\n      open.sort((a, b) => position(a) - position(b));\n      unavailable.sort((a, b) => position(a.organization_id) - position(b.organization_id));\n      return ok({ open, unavailable });\n    },\n\n    async ownerOrganization({ table_id, record_id, organization_id }) {\n      if (table_id) {\n        const read = await client.tableRead({ table_id, ...(organization_id ? { organization_id } : {}) });\n        if (!read.ok) return err(read.error);\n        return ok(read.data ? (read.data.organization_id ?? null) : null);\n      }\n      if (record_id) {\n        const read = await client.recordRead({ record_id, ...(organization_id ? { organization_id } : {}) });\n        if (!read.ok) return ok(null);\n        const targets = readOrgs(organization_id);\n        return ok(recordOrgs.get(record_id) ?? organization_id ?? (targets.length === 1 ? targets[0] ?? null : null));\n      }\n      return ok(null);\n    },\n\n    async fieldPropose() {\n      const refusal = doorAbsent(DOORS.fieldPropose);\n      scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where: \"fieldPropose\" });\n      return err(refusal);\n    },\n\n    async tablePropose() {\n      const refusal = doorAbsent(DOORS.tablePropose);\n      scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), where: \"tablePropose\" });\n      return err(refusal);\n    },\n\n    async promoteTable({ table_id }) {\n      return callDoor<unknown>(\n        DOORS.promoteTable,\n        { p_organization_id: org, p_table_id: table_id },\n        \"promoteTable\",\n      );\n    },\n\n    async promoteField({ table_id, field_id }) {\n      return callDoor<unknown>(\n        DOORS.promoteField,\n        { p_organization_id: org, p_table_id: table_id, p_field_id: field_id },\n        \"promoteField\",\n      );\n    },\n\n    async storeIsOpen() {\n      // The store is never off (2026-10-03): `custom.store_is_open` answers true for every\n      // organization, and this method answers true whenever the door answers at all. A refusal\n      // still comes back as a refusal — that is \"could not reach\", never \"off\".\n      const reached = await callDoor<boolean>(DOORS.storeIsOpen, { p_organization_id: org }, \"storeIsOpen\");\n      return reached.ok ? ok(true) : reached;\n    },\n\n    // ── THE GRID (lane GRID-PRIMITIVES) ──────────────────────────────────────\n    async tableDecorate({ table_id, path, value }) {\n      return callDoor<TableDecorations>(\n        DOORS.tableDecorate,\n        { p_organization_id: org, p_table_id: table_id, p_path: path, p_value: value ?? null },\n        \"tableDecorate\",\n      );\n    },\n\n    async tableDecorations({ table_id }) {\n      return callDoor<TableDecorations>(\n        DOORS.tableDecorations,\n        { p_organization_id: org, p_table_id: table_id },\n        \"tableDecorations\",\n      );\n    },\n\n    async gridLayout({ table_id, view_id }) {\n      return callDoor<GridLayout>(\n        DOORS.gridLayout,\n        { p_organization_id: org, p_table_id: table_id, p_view_id: view_id ?? null },\n        \"gridLayout\",\n      );\n    },\n\n    async formulaPreview({ table_id, record_id, text }) {\n      return owedDoor<FormulaPreview>(\n        DOORS.formulaPreview,\n        { p_organization_id: org, p_table_id: table_id, p_record_id: record_id, p_text: text },\n        \"formulaPreview\",\n      );\n    },\n\n    async formulaParse({ table_id, text }) {\n      return callDoor<FormulaParse>(\n        DOORS.formulaParse,\n        { p_organization_id: org, p_table_id: table_id, p_text: text },\n        \"formulaParse\",\n      );\n    },\n\n    async actionDeclare({ table_id, actions }) {\n      return callDoor<RowAction[]>(\n        DOORS.actionDeclare,\n        { p_organization_id: org, p_table_id: table_id, p_actions: actions },\n        \"actionDeclare\",\n      );\n    },\n\n    async rowActions({ table_id }) {\n      return callDoor<{ actions: RowAction[]; stale: unknown[] }>(\n        DOORS.rowActions,\n        { p_organization_id: org, p_table_id: table_id },\n        \"rowActions\",\n      );\n    },\n\n    async actionRun({ action_id, record_ids }) {\n      const result = await callDoor<ActionRunResult>(\n        DOORS.actionRun,\n        { p_organization_id: org, p_action_id: action_id, p_record_ids: record_ids },\n        \"actionRun\",\n      );\n      // A button that changed records changed THOSE records: every screen holding one re-reads.\n      if (result.ok) for (const ran of result.data?.records ?? []) if (ran?.record_id) announceRecordChanged(ran.record_id);\n      return result;\n    },\n\n    async automationDeclare({ table_id, spec, automation_id }) {\n      return callDoor<AutomationDeclared>(\n        DOORS.automationDeclare,\n        { p_organization_id: org, p_table_id: table_id, p_spec: spec, p_automation_id: automation_id ?? null },\n        \"automationDeclare\",\n      );\n    },\n\n    async automations({ table_id, include_archived }) {\n      return callDoor<AutomationList>(\n        DOORS.automations,\n        { p_table_id: table_id, p_organization_id: org, p_include_archived: include_archived ?? false },\n        \"automations\",\n      );\n    },\n\n    async automationArchive({ automation_id }) {\n      return callDoor<AutomationFlipped>(\n        DOORS.automationArchive,\n        { p_organization_id: org, p_automation_id: automation_id },\n        \"automationArchive\",\n      );\n    },\n\n    async automationRestore({ automation_id }) {\n      return callDoor<AutomationFlipped>(\n        DOORS.automationRestore,\n        { p_organization_id: org, p_automation_id: automation_id },\n        \"automationRestore\",\n      );\n    },\n\n    async automationSetEnabled({ automation_id, enabled }) {\n      return callDoor<AutomationFlipped>(\n        DOORS.automationSetEnabled,\n        { p_organization_id: org, p_automation_id: automation_id, p_enabled: enabled },\n        \"automationSetEnabled\",\n      );\n    },\n\n    async automationRuns({ automation_id, limit, cursor }) {\n      return callDoor<AutomationRuns>(\n        DOORS.automationRuns,\n        { p_automation_id: automation_id, p_limit: limit ?? 50, p_cursor: cursor ?? null, p_organization_id: org },\n        \"automationRuns\",\n      );\n    },\n\n    async automationTest({ automation_id, record_id }) {\n      const result = await callDoor<AutomationTested>(\n        DOORS.automationTest,\n        { p_organization_id: org, p_automation_id: automation_id, p_record_id: record_id ?? null },\n        \"automationTest\",\n      );\n      // A test run that set properties changed that row: every screen holding it re-reads.\n      if (result.ok && record_id) announceRecordChanged(record_id);\n      return result;\n    },\n\n    async automationRevisions({ automation_id }) {\n      return callDoor<AutomationRevisions>(\n        DOORS.automationRevisions,\n        { p_organization_id: org, p_automation_id: automation_id },\n        \"automationRevisions\",\n      );\n    },\n\n    async automationRevisionRestore({ automation_id, revision_id }) {\n      return callDoor<AutomationDeclared>(\n        DOORS.automationRevisionRestore,\n        { p_organization_id: org, p_automation_id: automation_id, p_revision_id: revision_id },\n        \"automationRevisionRestore\",\n      );\n    },\n\n    async tableWebhookDeclare({ table_id, target_url, events, description }) {\n      return callDoor<TableWebhookDeclared>(\n        DOORS.tableWebhookDeclare,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_target_url: target_url,\n          p_events: events ?? null,\n          p_description: description ?? null,\n        },\n        \"tableWebhookDeclare\",\n      );\n    },\n\n    async tableWebhooks({ table_id }) {\n      return callDoor<TableWebhook[]>(\n        DOORS.tableWebhooks,\n        { p_organization_id: org, p_table_id: table_id },\n        \"tableWebhooks\",\n      );\n    },\n\n    async tableWebhookArchive({ webhook_id }) {\n      return callDoor<boolean>(\n        DOORS.tableWebhookArchive,\n        { p_organization_id: org, p_webhook_id: webhook_id },\n        \"tableWebhookArchive\",\n      );\n    },\n\n    async tableListEverywhere(args) {\n      return callDoor<{ success: boolean; tables: TableListEntry[] }>(\n        DOORS.tableListEverywhere,\n        // The two-argument overload is chosen by naming both arguments (CHAIR-DOORS-2, N-C8).\n        args?.include_platform_tables ? { p_organization_id: org, p_include_platform_tables: true } : { p_organization_id: org },\n        \"tableListEverywhere\",\n      );\n    },\n\n    async dataHomeTables({ organization_id, include_platform_tables }) {\n      // THE ROW CAP (CLOSE-LINK, 2026-10-23; the data home's own fix of 2026-10-17): `custom.data_home_tables` returns a\n      // SET, and PostgREST cuts a set at its max-rows (1,000) in no order, so a person past 1,000 tables silently lost\n      // the rest from every list (\"CL Bookings\" was missing from Move under…'s table picker). `custom.data_home` answers\n      // the SAME rows as ONE jsonb value, which no cap touches. It is asked for everything and the two placement words\n      // the set door leaves out by default are dropped here, so the answer is exactly the set door's, whole.\n      const answered = await callDoor<{ tables?: DataHomeTable[] } | null>(\n        DOORS.dataHome,\n        { p_organization_id: organization_id, p_include_platform_tables: true },\n        \"dataHomeTables\",\n      );\n      if (!answered.ok) return answered;\n      const rows = (answered.data && !Array.isArray(answered.data) ? answered.data.tables : null) ?? [];\n      return { ok: true, data: include_platform_tables ? rows : rows.filter((t) => !DATA_HOME_KEPT_OUT_OF_LISTS.has(t.kind ?? \"\")) };\n    },\n\n    async adminAllTables() {\n      return callDoor<AdminTable[]>(DOORS.adminAllTables, {}, \"adminAllTables\");\n    },\n\n    async tableSync({ home_id, spec }) {\n      return callDoor<TableSyncResult>(\n        DOORS.tableSync,\n        { p_organization_id: org, p_home_id: home_id, p_spec: spec },\n        \"tableSync\",\n      );\n    },\n\n    async tableCopySync(spec) {\n      return callDoor<TableSyncAnswer>(\n        DOORS.tableCopySync,\n        { p_organization_id: org, p_spec: spec },\n        \"tableCopySync\",\n      );\n    },\n\n    async tableSyncSettingsSet({ table_id, settings }) {\n      return callDoor<TableSyncSourceDocument>(\n        DOORS.tableSyncSettingsSet,\n        { p_organization_id: org, p_table_id: table_id, p_settings: settings },\n        \"tableSyncSettingsSet\",\n      );\n    },\n\n    async scopeTableProvision({ home_id, item_id, scope_id }) {\n      return scopes.tableProvision({ organization_id: org, item_id, scope_id, home_id: home_id ?? null });\n    },\n\n    async tableRowCounts({ table_ids }) {\n      return callDoor<TableRowCount[]>(\n        DOORS.tableRowCounts,\n        { p_organization_id: org, p_table_ids: table_ids },\n        \"tableRowCounts\",\n      );\n    },\n\n    async recordHeaders({ ids }) {\n      return callDoor<RecordHeader[]>(\n        DOORS.recordHeaders,\n        { p_organization_id: org, p_ids: ids },\n        \"recordHeaders\",\n      );\n    },\n\n    async tableShareOutsideGrant({ table_id, person, level }) {\n      return callDoor<OutsideShareAnswer>(\n        DOORS.tableShareOutsideGrant,\n        { p_organization_id: org, p_table_id: table_id, p_person: person, p_level: level ?? \"viewer\" },\n        \"tableShareOutsideGrant\",\n      );\n    },\n\n    async viewRecordOrderSet({ view_id, record_ids }) {\n      return callDoor<ViewOrderSet>(\n        DOORS.viewRecordOrderSet,\n        { p_organization_id: org, p_view_id: view_id, p_record_ids: record_ids },\n        \"viewRecordOrderSet\",\n      );\n    },\n\n    async readInViewOrder({ view_id, filter, limit, offset }) {\n      // ORDER-FILTER: the filter goes INTO the order door (one WHERE clause, the ladder inside),\n      // never onto a page of positions afterwards — that read the first 500 positions of the\n      // whole table and misplaced every matching row past them. Sent only when asked.\n      const asked = filter && Object.keys(filter).length > 0 ? filter : null;\n      const door = await callDoor<Array<{ id: Uuid; document: unknown; level: string; position: number | null }>>(\n        DOORS.readRecordsInViewOrder,\n        {\n          p_organization_id: org,\n          p_view_id: view_id,\n          p_by_id: false,\n          p_limit: limit ?? 200,\n          p_offset: offset ?? 0,\n          ...(asked ? { p_filter: asked } : {}),\n        },\n        \"readInViewOrder\",\n      );\n      if (!door.ok) return err(door.error);\n      return ok(\n        (door.data ?? [])\n          .map((row) => {\n            const { document, hidden } = unfold(row.document);\n            return { id: row.id, document, level: row.level, hidden, position: row.position ?? null };\n          })\n          .filter((row) => !isLockedStub(row)),\n      );\n    },\n\n    async buttonPress({ record_id, field_id }) {\n      const result = await callDoor<ButtonPressed>(\n        DOORS.buttonPress,\n        { p_organization_id: org, p_record_id: record_id, p_field_id: field_id },\n        \"buttonPress\",\n      );\n      // A press that changed records changed THOSE records (a row action), or this one (an automation).\n      if (result.ok && result.data?.do === \"run_action\") {\n        for (const ran of result.data.result?.records ?? []) if (ran?.record_id) announceRecordChanged(ran.record_id);\n      }\n      if (result.ok && result.data?.do === \"run_automation\") announceRecordChanged(record_id);\n      if (result.ok && result.data?.do === \"add_row\") announceRecordChanged(result.data.record_id);\n      return result;\n    },\n\n    recordsLimits() {\n      return askLimits();\n    },\n\n    async timelineDependencyShift() {\n      const result = await callDoor<boolean>(DOORS.timelineDependencyShift, { p_organization_id: org }, \"timelineDependencyShift\");\n      if (!result.ok) return result;\n      return ok(result.data !== false);\n    },\n\n    async fieldNotifyOnAssign({ field_id, on }) {\n      return callDoor<FieldNotifyOnAssign>(\n        DOORS.fieldNotifyOnAssign,\n        { p_organization_id: org, p_field_id: field_id, p_on: on },\n        \"fieldNotifyOnAssign\",\n      );\n    },\n\n    async autonumberBackfill({ field_id }) {\n      return callDoor<{ numbered: number; highest: number | null; says: string }>(\n        DOORS.autonumberBackfill,\n        { p_organization_id: org, p_field_id: field_id },\n        \"autonumberBackfill\",\n      );\n    },\n\n    async ioExport({ table_id, columns, limit }) {\n      return callDoor<IoExportPage>(\n        DOORS.ioExport,\n        {\n          p_organization_id: org,\n          p_table_id: table_id,\n          p_columns: columns ?? null,\n          p_limit: limit ?? null,\n          p_required: \"viewer\",\n        },\n        \"ioExport\",\n      );\n    },\n\n    async exportXlsx({ table_id, columns, limit, labels, sheetLabel }) {\n      const page = await client.ioExport({\n        table_id,\n        ...(columns !== undefined ? { columns } : {}),\n        ...(limit !== undefined ? { limit } : {}),\n      });\n      if (!page.ok) return err(page.error);\n      return ok(await exportPageXlsx(page.data, labels ?? {}, sheetLabel ?? \"Records\"));\n    },\n\n    async myLevels({ ids, subject }) {\n      if (ids.length === 0) return ok([]);\n      const answered = await callDoor<Array<{ id: Uuid; level: string | null }>>(\n        DOORS.myLevels,\n        { p_organization_id: org, p_ids: ids, p_type: subject ?? \"record\" },\n        \"myLevels\",\n      );\n      if (!answered.ok) return err(answered.error);\n      return ok(\n        (answered.data ?? []).map((row) => ({ id: row.id, level: asPermissionLevel(row.level) })),\n      );\n    },\n  };\n\n  return client;\n}\n\n/**\n * Turn a refusal into the conflict a screen can SHOW: which version you wrote\n * against, which one won, and every field you touched as it stands now. Returns\n * null when the refusal was not a stale write.\n */\nexport function asWriteConflict(error: RecordsError, recordId: Uuid): WriteConflict | null {\n  const detail = staleWriteDetail(error);\n  if (!detail) return null;\n  return {\n    ...detail,\n    record_id: recordId,\n    message: error.message,\n    hint: error.hint ?? \"\",\n  };\n}\n","// RELATIVE DAYS ARE THE READER'S DAYS (ADVERSARIAL-11 F3).\n//\n// A saved view that says \"Today\", \"Overdue\" or \"This week\" (`{ due_on: { relative: \"today\" } }`, or a\n// `within` Rule node) used to be worked out in the DATABASE from the reader's SAVED zone. A saved zone\n// that was one browser behind (a new device, a trip, the first page of a session read before the zone\n// was written) made a person in Los Angeles at 23:05 see tomorrow's items under \"Today\".\n//\n// The client now works the window out itself, in the zone it is actually being read in (the person's\n// zone the host mirrored with `setReadersTimeZone`, else this browser's), and sends exact bounds. The\n// database still accepts and works out a relative window it is handed (older callers keep working);\n// this only means a relative window never reaches it from this client.\n//\n// Mirrors custom.relative_window_for_reader: same kinds, same half-open [from, to), same week start.\n\nexport const RELATIVE_DAY_KINDS = [\n  \"today\", \"tomorrow\", \"yesterday\",\n  \"this_week\", \"next_week\", \"last_week\",\n  \"this_month\", \"next_month\", \"last_month\",\n  \"before_today\", \"next_days\", \"past_days\",\n] as const;\n\nexport type RelativeDayKind = (typeof RELATIVE_DAY_KINDS)[number];\n\nlet readersZone: string | null = null;\n\nfunction validZone(z: unknown): z is string {\n  if (typeof z !== \"string\" || !z.trim()) return false;\n  try {\n    new Intl.DateTimeFormat(\"en-US\", { timeZone: z });\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/** The zone the host reads this person's day in (their saved zone, or the browser's while it follows). `null` clears. */\nexport function setReadersTimeZone(zone: string | null | undefined): void {\n  readersZone = validZone(zone) ? zone : null;\n}\n\n/** The zone a relative day is worked out in: the host's mirrored zone, else this browser's, else UTC. */\nexport function readersTimeZone(): string {\n  if (readersZone) return readersZone;\n  try {\n    const device = Intl.DateTimeFormat().resolvedOptions().timeZone;\n    if (validZone(device)) return device;\n  } catch {\n    /* fall through */\n  }\n  return \"UTC\";\n}\n\n/** Calendar parts of `at` on a wall clock in `zone`. */\nfunction partsIn(zone: string, at: Date): { y: number; m: number; d: number } {\n  const p = new Intl.DateTimeFormat(\"en-US\", { timeZone: zone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\" }).formatToParts(at);\n  const n = (t: string) => Number(p.find((x) => x.type === t)?.value ?? 0);\n  return { y: n(\"year\"), m: n(\"month\"), d: n(\"day\") };\n}\n\nconst ymd = (t: Date) =>\n  `${t.getUTCFullYear()}-${String(t.getUTCMonth() + 1).padStart(2, \"0\")}-${String(t.getUTCDate()).padStart(2, \"0\")}`;\n\n/** The instant at which the wall clock in `zone` first reads midnight of civil day `day` (a UTC-midnight Date standing for it). */\nfunction midnightInstant(zone: string, day: Date): Date {\n  const y = day.getUTCFullYear();\n  const m = day.getUTCMonth();\n  const d = day.getUTCDate();\n  // Start from the UTC guess, then correct by how far the zone's wall clock is from the wanted one (twice: DST-safe).\n  let guess = Date.UTC(y, m, d);\n  for (let i = 0; i < 3; i += 1) {\n    const f = new Intl.DateTimeFormat(\"en-US\", {\n      timeZone: zone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\", hour: \"2-digit\", minute: \"2-digit\", second: \"2-digit\", hourCycle: \"h23\",\n    }).formatToParts(new Date(guess));\n    const n = (t: string) => Number(f.find((x) => x.type === t)?.value ?? 0);\n    const wall = Date.UTC(n(\"year\"), n(\"month\") - 1, n(\"day\"), n(\"hour\"), n(\"minute\"), n(\"second\"));\n    const diff = Date.UTC(y, m, d) - wall;\n    if (diff === 0) break;\n    guess += diff;\n  }\n  return new Date(guess);\n}\n\nexport interface RelativeWindowOptions {\n  zone?: string;\n  now?: Date;\n  /** First day of the week, Sunday 0 ... Saturday 6. Monday (1) by default, the organization knob's default. */\n  weekStart?: number;\n  /** A moment column (created_at, a datetime): the window is the reader's local midnights as instants. */\n  instants?: boolean;\n}\n\n/**\n * One relative window as exact bounds, half-open [from, to), or `null` when `window` is not a relative\n * window this knows (it is then left for the store to judge). A date-only column gets calendar days.\n */\nexport function relativeWindowBounds(window: unknown, opts: RelativeWindowOptions = {}): { from?: string; to?: string } | null {\n  if (!window || typeof window !== \"object\" || Array.isArray(window)) return null;\n  const w = window as { relative?: unknown; n?: unknown };\n  const kind = w.relative as RelativeDayKind;\n  if (typeof kind !== \"string\" || !(RELATIVE_DAY_KINDS as readonly string[]).includes(kind)) return null;\n  const zone = opts.zone && validZone(opts.zone) ? opts.zone : readersTimeZone();\n  const n = typeof w.n === \"number\" && Number.isFinite(w.n) ? Math.min(Math.max(Math.trunc(w.n), 0), 3660) : null;\n  if ((kind === \"next_days\" || kind === \"past_days\") && n === null) return null;\n\n  const p = partsIn(zone, opts.now ?? new Date());\n  const t = new Date(Date.UTC(p.y, p.m - 1, p.d));\n  const add = (base: Date, days: number) => new Date(base.getTime() + days * 86_400_000);\n  const first = opts.weekStart !== undefined ? ((opts.weekStart % 7) + 7) % 7 : 1;\n  const ws = add(t, -((t.getUTCDay() - first + 7) % 7));\n  const ms = new Date(Date.UTC(p.y, p.m - 1, 1));\n  const month = (k: number) => new Date(Date.UTC(ms.getUTCFullYear(), ms.getUTCMonth() + k, 1));\n\n  let from: Date | undefined;\n  let to: Date | undefined;\n  switch (kind) {\n    case \"today\": from = t; to = add(t, 1); break;\n    case \"tomorrow\": from = add(t, 1); to = add(t, 2); break;\n    case \"yesterday\": from = add(t, -1); to = t; break;\n    case \"this_week\": from = ws; to = add(ws, 7); break;\n    case \"next_week\": from = add(ws, 7); to = add(ws, 14); break;\n    case \"last_week\": from = add(ws, -7); to = ws; break;\n    case \"this_month\": from = ms; to = month(1); break;\n    case \"next_month\": from = month(1); to = month(2); break;\n    case \"last_month\": from = month(-1); to = ms; break;\n    case \"before_today\": to = t; break;\n    case \"next_days\": from = t; to = add(t, n!); break;\n    case \"past_days\": from = add(t, -n!); to = t; break;\n  }\n  const out = (d: Date | undefined) =>\n    d === undefined ? undefined : opts.instants ? midnightInstant(zone, d).toISOString().replace(/\\.\\d{3}Z$/, \"Z\") : ymd(d);\n  const f = out(from);\n  const e = out(to);\n  return { ...(f === undefined ? {} : { from: f }), ...(e === undefined ? {} : { to: e }) };\n}\n\n/** What the filter needs to know about a column to cut its window: the key and whether it holds moments. */\nexport interface RelativeFieldLookup {\n  byKey(key: string): { instants: boolean } | null;\n  byId(id: string): { instants: boolean } | null;\n}\n\n/** A lookup over the table's Fields (a moment column is `created_at` / `updated_at` or `config.kind === \"datetime\"`). */\nexport function lookupFromFields(fields: ReadonlyArray<{ id: string; key: string; config?: Record<string, unknown> | null }>): RelativeFieldLookup {\n  const info = (f: { key: string; config?: Record<string, unknown> | null }) => ({\n    instants: f.key === \"created_at\" || f.key === \"updated_at\" || f.config?.[\"kind\"] === \"datetime\",\n  });\n  return {\n    byKey: (key) => {\n      const f = fields.find((x) => x.key === key);\n      return f ? info(f) : key === \"created_at\" || key === \"updated_at\" ? { instants: true } : null;\n    },\n    byId: (id) => {\n      const f = fields.find((x) => x.id === id);\n      return f ? info(f) : null;\n    },\n  };\n}\n\n/** Does this filter hold a relative window anywhere? (Cheap test so a filter without one never loads Fields.) */\nexport function holdsRelativeDays(filter: unknown): boolean {\n  if (!filter || typeof filter !== \"object\") return false;\n  if (Array.isArray(filter)) return filter.some(holdsRelativeDays);\n  const o = filter as Record<string, unknown>;\n  if (typeof o[\"relative\"] === \"string\") return true;\n  return Object.values(o).some(holdsRelativeDays);\n}\n\n/**\n * The filter with every relative window worked out for THIS reader, now. Flat filters (`{ due_on: { relative } }`) and\n * Rule `within` nodes, at any depth. A window it cannot place (an unknown column, an unknown kind) is left as it was.\n * Never mutates its input.\n */\nexport function resolveRelativeDays(filter: unknown, lookup: RelativeFieldLookup, opts: Omit<RelativeWindowOptions, \"instants\"> = {}): unknown {\n  if (!holdsRelativeDays(filter)) return filter;\n  const walk = (node: unknown, flatTop: boolean): unknown => {\n    if (Array.isArray(node)) return node.map((x) => walk(x, false));\n    if (!node || typeof node !== \"object\") return node;\n    const o = node as Record<string, unknown>;\n    if (o[\"op\"] === \"within\" && Array.isArray(o[\"args\"]) && o[\"args\"].length === 2) {\n      const [a, b] = o[\"args\"] as Array<Record<string, unknown> | undefined>;\n      const id = a && typeof a[\"field\"] === \"string\" ? (a[\"field\"] as string) : null;\n      const win = b && typeof b === \"object\" ? (b[\"const\"] as unknown) : null;\n      const col = id ? lookup.byId(id) : null;\n      const bounds = col ? relativeWindowBounds(win, { ...opts, instants: col.instants }) : null;\n      return bounds ? { ...o, args: [a, { const: bounds }] } : node;\n    }\n    const out: Record<string, unknown> = {};\n    for (const [k, v] of Object.entries(o)) {\n      if (flatTop && v && typeof v === \"object\" && !Array.isArray(v) && typeof (v as { relative?: unknown }).relative === \"string\") {\n        const col = lookup.byKey(k);\n        const bounds = col ? relativeWindowBounds(v, { ...opts, instants: col.instants }) : null;\n        out[k] = bounds ?? v;\n      } else {\n        out[k] = walk(v, false);\n      }\n    }\n    return out;\n  };\n  const isRule = !!filter && typeof filter === \"object\" && typeof (filter as { op?: unknown }).op === \"string\";\n  return walk(filter, !isRule);\n}\n\n/** `\"sunday\"` .. `\"saturday\"` as `Date.getUTCDay()` counts; anything else is Monday, the knob's default. */\nexport function weekStartIndexOf(word: string | null | undefined): number {\n  const days = [\"sunday\", \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\"];\n  const at = days.indexOf(String(word ?? \"\").trim().toLowerCase());\n  return at < 0 ? 1 : at;\n}\n","// src/core/errors.ts — @ai-matrx/records/entity\n//\n// THE ERROR MAP (PHASE-B-APPLETS §4). The entity doors raise their own `MX0xx` class; this turns it\n// into the `RecordsError` every other door of the records package answers, carrying THE STORE'S\n// SENTENCE VERBATIM (message and hint are never rewritten here). Anything that is not an `MX` code\n// (a timeout, a dropped connection, a revoked schema) goes through records' own `mapPgError`.\n\nimport { mapPgError } from \"../../core/pgError\";\nimport type { PgError, RecordsError, RecordsErrorCode } from \"../../results\";\n\n/**\n * Every MX code a read door raises, and the engine code a screen branches on. A code the doors learn\n * later and this map lacks comes back `internal` with `unmapped: true` (never silently \"handled\").\n */\nexport const ENTITY_REFUSALS: Readonly<Record<string, RecordsErrorCode>> = {\n  /** conflict_version: somebody else's write won. */\n  MX001: \"stale_write\",\n  /** organization_required: the call needs an organization and carried none. */\n  MX002: \"organization_required\",\n  /** forbidden. */\n  MX003: \"door\",\n  /** not_found (also: not visible to this person). */\n  MX004: \"not_found\",\n  /** validation_refused (detail.reason required / bad_value / ambiguous_word / constraint; `not_supported` is read apart below). */\n  MX005: \"invalid_argument\",\n  /** system_column: a write named a column the store owns. */\n  MX008: \"invalid_argument\",\n  /** unknown_identifier: a column that is not there or not usable here. */\n  MX012: \"invalid_argument\",\n  /** cursor_invalid: the page cursor belongs to another list; the engine restarts the page. */\n  MX013: \"invalid_argument\",\n  /** view_not_offered. */\n  MX015: \"invalid_argument\",\n  /** invalid_argument: a parameter the door refuses by name. */\n  MX016: \"invalid_argument\",\n};\n\nexport function mapEntityError(error: PgError, where: string): RecordsError {\n  const mapped = mapPgError(error, where);\n  const state = mapped.sqlstate;\n  if (state && /^MX\\d{3}$/.test(state)) {\n    const code = ENTITY_REFUSALS[state];\n    if (code) {\n      // MX005 that says the store does not offer this yet is a different question for a screen than a bad value.\n      const reason = (mapped.detail as { reason?: unknown } | undefined)?.reason;\n      const known: RecordsError = { ...mapped, code: state === \"MX005\" && reason === \"not_supported\" ? \"not_supported\" : code };\n      delete known.unmapped;\n      delete known.diagnostic;\n      return known;\n    }\n  }\n  return mapped;\n}\n\n/** A refusal this package itself raises (an alias nobody declared, a write not offered yet). */\nexport function refusal(code: RecordsErrorCode, message: string, hint?: string): { ok: false; error: RecordsError } {\n  return { ok: false, error: { code, message, ...(hint ? { hint } : {}) } };\n}\n","// src/core/client.ts — @ai-matrx/records/entity\n//\n// THE THIN TYPED CLIENT over the live INVOKER doors in `platform`: reads (`entity_list_scoped`,\n// `entity_get`, `entity_columns`) and, since 0.3, writes (`entity_insert`, `entity_update`,\n// `entity_archive`, `entity_unarchive`). Every call answers a `RecordsResult` and\n// never throws; every refusal is the store's own sentence (see `errors.ts`). The caller's seat is the\n// one on the supabase client handed in — nothing here widens or narrows what the store lets her see.\n\nimport { asRecordsDataSource } from \"../../core/supabase\";\nimport type { RecordsDataSource } from \"../../ports\";\nimport type { RecordsResult } from \"../../results\";\nimport type { Uuid } from \"../../record\";\nimport { mapEntityError } from \"./errors\";\nimport type { EntityColumnsAnswer, EntityGetAnswer, EntityListAnswer, EntityWireQuery, EntityWriteAnswer } from \"./types\";\n\n/**\n * THE ECHO HEADER (U6). The entity doors take no `_op_id` argument: the writer's op id rides the request\n * as this header, PostgREST hands it to `request.headers`, and `platform._entity_org_notice` puts it on\n * the notice as `op_id`, so the browser that wrote drops its own echo (`@ai-matrx/records` `isOwnOp`).\n */\nexport const OP_ID_HEADER = \"x-matrx-op-id\";\n\n/** What a write takes beyond its arguments: the op id minted for it (`mintOpId`). */\nexport interface EntityWriteOptions {\n  opId?: string;\n}\n\n/** The schema every entity door lives in. */\nexport const ENTITY_DOOR_SCHEMA = \"platform\";\n\nexport interface CreateEntityClientOptions {\n  /** A supabase-js v2 client for the signed-in person, or anything with `rpc(fn, args, {schema})`. */\n  dataSource?: unknown;\n  /** Same thing, spelled the way the plan names it. Give one of the two. */\n  supabase?: unknown;\n}\n\nexport interface EntityListRequest extends EntityWireQuery {\n  token: string;\n  /** Keyset cursor from the previous answer's `next_after`. */\n  after?: string | null;\n  /** Ask the door to skip the count. Default: counted. */\n  withTotal?: boolean;\n  archived?: \"active\" | \"archived\" | \"all\";\n}\n\nexport interface EntityClient {\n  list(request: EntityListRequest): Promise<RecordsResult<EntityListAnswer>>;\n  get(request: { token: string; ids: readonly Uuid[] }): Promise<RecordsResult<EntityGetAnswer>>;\n  /** `organizationId` null reads the custom fields of every organization the person belongs to. */\n  columns(request: { token: string; organizationId?: Uuid | null }): Promise<RecordsResult<EntityColumnsAnswer>>;\n  /** One `entity_data` knob as `platform.knob_resolve` answers it for an organization (live updates read three). */\n  knob(request: { key: string; organizationId?: Uuid | null }): Promise<RecordsResult<unknown>>;\n  /** `platform.entity_insert`: rows into the organization the host names (never guessed). */\n  insert(request: { token: string; organizationId: Uuid; rows: readonly Record<string, unknown>[] } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n  /** `platform.entity_update`: one row, refused as stale (`MX001`) unless `baseVersion` is still current. */\n  update(request: { token: string; id: Uuid; baseVersion: number; patch: Record<string, unknown> } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n  /** `platform.entity_archive` (on these types, the trash). */\n  archive(request: { token: string; ids: readonly Uuid[] } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n  /** `platform.entity_unarchive`. */\n  unarchive(request: { token: string; ids: readonly Uuid[] } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n  /** The organizations the person belongs to, as row security counts them (`iam.my_orgs()`: archived ones closed). */\n  memberOrganizations(): Promise<RecordsResult<Uuid[]>>;\n}\n\nexport function createEntityClient(options: CreateEntityClientOptions): EntityClient {\n  const source: RecordsDataSource = asRecordsDataSource(options.dataSource ?? options.supabase);\n\n  let warnedHeaderless = false;\n\n  /**\n   * A per-call header rides the request builder supabase-js hands back (`PostgrestBuilder.setHeader`, set\n   * before the builder is awaited). `@ai-matrx/records`' adapter returns that builder unwrapped, so the\n   * header reaches PostgREST on this one call only — never on the client every other caller shares.\n   * A data seam whose answer has no `setHeader` (a host's own adapter, a test double) cannot carry it:\n   * the write still lands, the writer re-reads its own echo once, and the console says why.\n   */\n  function withHeaders(pending: PromiseLike<unknown>, headers: Record<string, string> | undefined): void {\n    if (!headers) return;\n    const builder = pending as { setHeader?: (name: string, value: string) => unknown };\n    if (typeof builder.setHeader === \"function\") {\n      for (const [name, value] of Object.entries(headers)) builder.setHeader(name, value);\n      return;\n    }\n    if (!warnedHeaderless) {\n      warnedHeaderless = true;\n      console.warn(\n        `[@ai-matrx/records/entity] This data source cannot carry a per-call header (${Object.keys(headers).join(\", \")}), so this browser re-reads the notice of its own writes once.`,\n      );\n    }\n  }\n\n  async function call<T>(\n    fn: string,\n    args: Record<string, unknown>,\n    schema: string = ENTITY_DOOR_SCHEMA,\n    headers?: Record<string, string>,\n  ): Promise<RecordsResult<T>> {\n    try {\n      const pending = source.rpc(fn, args, { schema });\n      withHeaders(pending, headers);\n      const answer = await pending;\n      if (answer.error) return { ok: false, error: mapEntityError(answer.error, `${schema}.${fn}`) };\n      return { ok: true, data: answer.data as T };\n    } catch (thrown) {\n      // supabase-js answers failures; a throw here is a transport that never reached the store.\n      return {\n        ok: false,\n        error: mapEntityError({ code: \"\", message: thrown instanceof Error ? thrown.message : String(thrown) }, `${schema}.${fn}`),\n      };\n    }\n  }\n\n  return {\n    list(request) {\n      const args: Record<string, unknown> = {\n        p_entity_type: request.token,\n        p_scope: request.scope ?? null,\n        p_filter: request.filter ?? {},\n        p_search: request.search ?? null,\n        p_sort: request.sort ?? null,\n        p_archived: request.archived ?? \"active\",\n        p_page_size: request.pageSize ?? null,\n        p_after: request.after ?? null,\n        p_with_total: request.withTotal ?? true,\n      };\n      return call<EntityListAnswer>(\"entity_list_scoped\", args);\n    },\n    get(request) {\n      return call<EntityGetAnswer>(\"entity_get\", { p_entity_type: request.token, p_ids: [...request.ids] });\n    },\n    columns(request) {\n      return call<EntityColumnsAnswer>(\"entity_columns\", { p_organization_id: request.organizationId ?? null, p_token: request.token });\n    },\n    insert(request) {\n      return call<EntityWriteAnswer>(\n        \"entity_insert\",\n        { p_entity_type: request.token, p_organization_id: request.organizationId, p_rows: request.rows.map((r) => ({ ...r })) },\n        ENTITY_DOOR_SCHEMA,\n        opHeader(request.opId),\n      );\n    },\n    update(request) {\n      return call<EntityWriteAnswer>(\n        \"entity_update\",\n        { p_entity_type: request.token, p_id: request.id, p_base_version: request.baseVersion, p_patch: request.patch },\n        ENTITY_DOOR_SCHEMA,\n        opHeader(request.opId),\n      );\n    },\n    archive(request) {\n      return call<EntityWriteAnswer>(\"entity_archive\", { p_entity_type: request.token, p_ids: [...request.ids] }, ENTITY_DOOR_SCHEMA, opHeader(request.opId));\n    },\n    unarchive(request) {\n      return call<EntityWriteAnswer>(\"entity_unarchive\", { p_entity_type: request.token, p_ids: [...request.ids] }, ENTITY_DOOR_SCHEMA, opHeader(request.opId));\n    },\n    knob(request) {\n      return call<unknown>(\"knob_resolve\", { p_feature: \"entity_data\", p_key: request.key, p_organization_id: request.organizationId ?? null });\n    },\n    async memberOrganizations() {\n      const answer = await call<unknown>(\"my_orgs\", {}, \"iam\");\n      if (!answer.ok) return answer;\n      const rows = Array.isArray(answer.data) ? answer.data : [];\n      // A SETOF uuid comes back as bare strings; a row shape (`{my_orgs}`) is read the same way.\n      const ids = rows\n        .map((row) => (typeof row === \"string\" ? row : row && typeof row === \"object\" ? Object.values(row as Record<string, unknown>)[0] : null))\n        .filter((id): id is string => typeof id === \"string\");\n      return { ok: true, data: ids };\n    },\n  };\n}\n\nfunction opHeader(opId: string | undefined): Record<string, string> | undefined {\n  return opId ? { [OP_ID_HEADER]: opId } : undefined;\n}\n","// src/port/port.ts — @ai-matrx/records/entity\n//\n// THE HOST'S DATAPORT FOR ENTITY ALIASES (Applets CONTRACTS §4; PHASE-B-APPLETS U5, read-only).\n//\n// One port per mounted Applet, scoped to the aliases its record declares: `{kind:\"entity\", token}`.\n// Every call goes through the store's entity doors under the signed-in person's seat — the store\n// decides what she may see; nothing here widens or narrows it.\n//\n//   · sources  — canCreate / canUpdate are `entity_columns`' own answer for the person.\n//   · columns  — live: platform columns plus the organizations' custom fields (`origin`), the identity\n//                columns left to `_id` / `_version` / `_organization_id`.\n//   · list     — KEYSET: the cursor is the door's `next_after`; the lane defaults to the type's own\n//                landing lane (decided by the door, never here); `org` is a filter, never a lock.\n//   · get      — by id, through the same door every list row opens through. Every id asked in the same\n//                tick (the engine re-reading the rows a notice named) is ONE `entity_get(ids)`.\n//   · create   — `entity_insert` into the organization the HOST names (`activeOrganizationId()`), never\n//                guessed; with none, refused `organization_required` before anything is sent.\n//   · update   — `entity_update` with the `baseVersion` the person saw; a link (`EntityRef[]`) goes back\n//                as its id, `_custom` as `{key: value}`. Stale → `stale_write` with the store's sentence.\n//   · archive / restore — `entity_archive` / `entity_unarchive` (on these types, the trash).\n//                Every write mints an op id (`mintOpId`) and sends it as header `x-matrx-op-id`, so the\n//                notice of the writer's own change comes back marked and is dropped.\n//   · subscribe — LIVE (U6): `rows:<alias>` hears the organization topics `mx:entity-org:<org>:<token>`\n//                through the host's `realtime` (core/realtime.ts). An alias with an organization hears\n//                that one; otherwise the active organization, then the organizations of the rows this\n//                port has handed out (most rows first), then the person's other memberships — capped by\n//                knob entity_data.realtime_max_org_topics. `{ids}` names rows to re-read; `{ids: null}`\n//                re-reads all. With no `realtime` bound it says so out loud and stays a no-op.\n\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport type {\n  Column,\n  DataPortEventName,\n  DataSource,\n  HostDataPort,\n  Page,\n  Query,\n  Row,\n  RowsEvent,\n  Uuid,\n  Values,\n} from \"../../data\";\nimport { defaultOpLedger, type OpLedger } from \"../../ops\";\nimport type { RecordsResult } from \"../../results\";\nimport { createEntityClient, type EntityClient } from \"../core/client\";\nimport { refusal } from \"../core/errors\";\nimport { DEFAULT_MAX_ORG_TOPICS, orderOrganizationTopics, type EntityRealtime } from \"../core/realtime\";\nimport type { EntityColumnsAnswer, EntityGetAnswer, EntityWriteAnswer, EntityWireRow } from \"../core/types\";\nimport { toWire } from \"../core/wire\";\nimport { toColumns, toRow } from \"./rows\";\n\n/** An alias as the Applet record declares it for an entity: one token (a `platform.entity_types` word). */\nexport interface EntityAlias {\n  kind: \"entity\";\n  token: string;\n  /** Whose custom fields `columns()` reads. Left out: every organization the person belongs to. */\n  organizationId?: Uuid;\n  /** Shown in `sources()`; the type's own name when left out. */\n  label?: string;\n}\n\nexport interface CreateEntityDataPortOptions {\n  /** A client from `createEntityClient` … */\n  client?: EntityClient;\n  /** … or the supabase-js client (or `rpc` source) to build one from. Give one of the two. */\n  dataSource?: unknown;\n  aliases: Readonly<Record<string, EntityAlias>>;\n  /**\n   * TOKEN-FIRST (the `/react` layer): an alias nobody declared is read as a type token —\n   * `list(\"party\")` is `{kind:\"entity\", token:\"party\"}`. `sources()` still lists only the declared\n   * aliases. Off by default: an Applet's port answers only what its record declares.\n   */\n  tokensAreAliases?: boolean;\n  /**\n   * The active organization (CONTRACTS §4: `viewer().activeOrganizationId`), read at the moment it is\n   * needed: where `create` saves, and the first live topic joined. The host's own answer, never guessed;\n   * null/undefined means none is chosen and `create` is refused `organization_required`.\n   */\n  activeOrganizationId?: () => Uuid | null | undefined;\n  /** A fixed active organization, for a host whose port lives no longer than its choice. `activeOrganizationId` wins. */\n  organization?: Uuid | null;\n  /** The host's live-notice layer (`createEntityRealtime`). Left out, lists are as fresh as their last read. */\n  realtime?: EntityRealtime;\n  /** This port's own-write memory (`createOpLedger()`); absent ⇒ the realm's default ledger. */\n  opLedger?: OpLedger;\n}\n\n/** A value as rows carry it → as the write doors take it: a link (`EntityRef[]` or one ref) becomes its id. */\nexport function toWireValue(value: unknown): unknown {\n  if (isRef(value)) return value.id;\n  if (Array.isArray(value) && value.length > 0 && value.every(isRef)) {\n    // One link is one id; none is null; several are sent as ids and the door refuses a one-record column by name.\n    return value.length === 1 ? (value[0] as { id: string }).id : value.map((ref) => (ref as { id: string }).id);\n  }\n  return value;\n}\n\nfunction isRef(value: unknown): value is { token: string; id: string } {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    && typeof (value as { token?: unknown }).token === \"string\" && typeof (value as { id?: unknown }).id === \"string\";\n}\n\n/** `Values` → the doors' `{column: value, _custom: {key: value}}`: links back to ids at both levels. */\nexport function toWireValues(values: Values): Record<string, unknown> {\n  const out: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(values)) {\n    if (value === undefined) continue;\n    if (key === \"_custom\" && value && typeof value === \"object\" && !Array.isArray(value)) {\n      out._custom = Object.fromEntries(Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined).map(([k, v]) => [k, toWireValue(v)]));\n      continue;\n    }\n    // A link column emptied in a grid arrives as [] and means \"no link\".\n    out[key] = Array.isArray(value) && value.length === 0 && key !== \"_custom\" ? null : toWireValue(value);\n  }\n  return out;\n}\n\n/** A type as the person may use it: its name and whether she may add or change rows (`entity_columns`' own answer). */\nexport interface EntityTypeFacts {\n  token: string;\n  label: string;\n  canCreate: boolean;\n  canUpdate: boolean;\n}\n\n/** The host's entity port: the DataPort, plus `describe` for a token-first screen that has no `sources()` entry. */\nexport interface EntityDataPort extends HostDataPort {\n  /** The type behind an alias, from the same one `entity_columns` read `columns()` uses. */\n  describe(alias: string): Promise<RecordsResult<EntityTypeFacts>>;\n}\n\nexport function createEntityDataPort(options: CreateEntityDataPortOptions): EntityDataPort {\n  const client: EntityClient = options.client ?? createEntityClient({ dataSource: options.dataSource });\n  const ledger = options.opLedger ?? defaultOpLedger;\n  const activeOrganization = (): Uuid | null => (options.activeOrganizationId ? options.activeOrganizationId() : options.organization) ?? null;\n  /** Ids asked by `get` in this tick, per alias: answered by one `entity_get`. */\n  const gets = new Map<string, Map<Uuid, ((answer: RecordsResult<Row | null>) => void)[]>>();\n  const aliases = options.aliases;\n  const shapes = new Map<string, Promise<RecordsResult<EntityColumnsAnswer>>>();\n  let warnedNotLive = false;\n  /** Which organization each row this port handed out belongs to, per alias: the \"held rows\" topic order. */\n  const held = new Map<string, Map<Uuid, Uuid>>();\n  const replans = new Map<string, Set<() => void>>();\n  let memberships: Promise<Uuid[] | null> | null = null;\n  let maxOrgTopics: Promise<number> | null = null;\n\n  function hold(alias: string, rows: readonly { id?: unknown; organization_id?: unknown }[]) {\n    const byId = held.get(alias) ?? new Map<Uuid, Uuid>();\n    held.set(alias, byId);\n    const before = new Set(byId.values());\n    for (const r of rows) {\n      if (typeof r.id === \"string\" && typeof r.organization_id === \"string\") byId.set(r.id, r.organization_id);\n    }\n    // A row from an organization this alias did not hold yet may move it into the joined topics.\n    if ([...byId.values()].some((org) => !before.has(org))) for (const replan of replans.get(alias) ?? []) replan();\n  }\n\n  function heldCounts(alias: string): Map<Uuid, number> {\n    const counts = new Map<Uuid, number>();\n    for (const org of held.get(alias)?.values() ?? []) counts.set(org, (counts.get(org) ?? 0) + 1);\n    return counts;\n  }\n\n  function membershipsOnce(): Promise<Uuid[] | null> {\n    memberships ??= client.memberOrganizations().then((answer) => {\n      if (answer.ok) return answer.data;\n      memberships = null; // a refusal is never kept for the next asker\n      console.warn(`[@ai-matrx/records/entity] Could not read your organizations for live updates: ${answer.error.message}`);\n      return null;\n    });\n    return memberships;\n  }\n\n  function maxOrgTopicsOnce(): Promise<number> {\n    maxOrgTopics ??= client.knob({ key: \"realtime_max_org_topics\", organizationId: activeOrganization() }).then((answer) => {\n      const value = answer.ok ? Number(answer.data) : Number.NaN;\n      if (Number.isFinite(value) && value >= 0) return value;\n      console.warn(`[@ai-matrx/records/entity] knob entity_data.realtime_max_org_topics did not resolve; joining at most ${DEFAULT_MAX_ORG_TOPICS} organizations.`);\n      return DEFAULT_MAX_ORG_TOPICS;\n    });\n    return maxOrgTopics;\n  }\n\n  const tokenBindings = new Map<string, EntityAlias>();\n  function bindingOf(alias: string): EntityAlias | null {\n    if (Object.prototype.hasOwnProperty.call(aliases, alias)) return aliases[alias]!;\n    if (!options.tokensAreAliases || !/^[a-z][a-z0-9_]*$/.test(alias)) return null;\n    let bound = tokenBindings.get(alias);\n    if (!bound) {\n      bound = { kind: \"entity\", token: alias };\n      tokenBindings.set(alias, bound);\n    }\n    return bound;\n  }\n\n  function noSuchAlias(alias: string) {\n    return refusal(\"not_found\", `This Applet has no data source called \"${alias}\".`, \"Use one of the aliases sources() lists.\");\n  }\n\n  /** One read of a type's columns per port; a refusal is never kept for the next asker. */\n  function shapeOf(alias: string, binding: EntityAlias): Promise<RecordsResult<EntityColumnsAnswer>> {\n    let held = shapes.get(alias);\n    if (!held) {\n      held = client.columns({ token: binding.token, organizationId: binding.organizationId ?? null }).then((answer) => {\n        if (!answer.ok) shapes.delete(alias);\n        return answer;\n      });\n      shapes.set(alias, held);\n    }\n    return held;\n  }\n\n  /** Ask for one row; every id asked for the alias before the tick ends goes in the same `entity_get`. */\n  function getCoalesced(alias: string, token: string, id: Uuid): Promise<RecordsResult<Row | null>> {\n    return new Promise((resolve) => {\n      let batch = gets.get(alias);\n      if (!batch) {\n        batch = new Map();\n        gets.set(alias, batch);\n        const asked = batch;\n        queueMicrotask(() => {\n          gets.delete(alias);\n          void flushGets(alias, token, asked);\n        });\n      }\n      const waiting = batch.get(id) ?? [];\n      waiting.push(resolve);\n      batch.set(id, waiting);\n    });\n  }\n\n  async function flushGets(alias: string, token: string, asked: Map<Uuid, ((answer: RecordsResult<Row | null>) => void)[]>) {\n    const answer: RecordsResult<EntityGetAnswer> = await client.get({ token, ids: [...asked.keys()] });\n    if (answer.ok) hold(alias, answer.data.rows);\n    const byId = new Map<string, EntityWireRow>(answer.ok ? answer.data.rows.map((r) => [r.id, r]) : []);\n    for (const [id, waiting] of asked) {\n      // A row in the trash is not a row of this port: the DataPort's lists are active rows only (a Query has no\n      // archived option), so a re-read that finds one trashed answers null and the engine takes it off the list.\n      // `entity_get` itself opens trashed rows by id (`_state.archived`) for screens that read the doors directly.\n      const found = byId.get(id);\n      const wire = found && (found[\"_state\"] as { archived?: unknown } | undefined)?.archived === true ? undefined : found;\n      const result: RecordsResult<Row | null> = answer.ok ? { ok: true, data: wire ? toRow(wire) : null } : answer;\n      for (const resolve of waiting) resolve(result);\n    }\n  }\n\n  /** The one row a write door read back (with its new `version`). */\n  function readBack(alias: string, answer: RecordsResult<EntityWriteAnswer>, what: string): RecordsResult<Row> {\n    if (!answer.ok) return answer;\n    hold(alias, answer.data.rows);\n    const wire = answer.data.rows[0];\n    if (!wire) {\n      return refusal(\n        \"not_found\",\n        `${what} was saved, but you cannot open it now, so it is not shown here.`,\n        \"The row is in the store; who may open it decides whether it appears in this list.\",\n      );\n    }\n    return { ok: true, data: toRow(wire) };\n  }\n\n  function done(answer: RecordsResult<EntityWriteAnswer>): RecordsResult<void> {\n    return answer.ok ? { ok: true, data: undefined } : answer;\n  }\n\n  return {\n    async sources() {\n      const out: DataSource[] = [];\n      for (const [alias, binding] of Object.entries(aliases)) {\n        const shape = await shapeOf(alias, binding);\n        if (!shape.ok) return shape;\n        out.push({\n          alias,\n          label: binding.label ?? shape.data.label ?? alias,\n          kind: \"entity\",\n          canCreate: Boolean(shape.data.can_create),\n          canUpdate: Boolean(shape.data.can_update),\n        });\n      }\n      return { ok: true, data: out };\n    },\n\n    async describe(alias) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      const shape = await shapeOf(alias, binding);\n      if (!shape.ok) return shape;\n      return {\n        ok: true,\n        data: {\n          token: binding.token,\n          label: binding.label ?? shape.data.label ?? binding.token,\n          canCreate: Boolean(shape.data.can_create),\n          canUpdate: Boolean(shape.data.can_update),\n        },\n      };\n    },\n\n    async columns(alias) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      const shape = await shapeOf(alias, binding);\n      return shape.ok ? { ok: true, data: toColumns(shape.data.columns) satisfies Column[] } : shape;\n    },\n\n    async list(alias, q: Query = {}, cursor) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      // A custom field's key is only known from the columns; ask for them only when the query names a column.\n      let customKeys: ReadonlySet<string> = new Set();\n      if ((q.where && q.where.length > 0) || (q.sort && q.sort.length > 0)) {\n        const shape = await shapeOf(alias, binding);\n        if (!shape.ok) return shape;\n        customKeys = new Set(shape.data.columns.filter((c) => c.origin === \"custom\").map((c) => c.key));\n      }\n      const wire = toWire(q, customKeys);\n      // A SOURCE DECLARED IN ONE ORGANIZATION reads that organization only (an Applet's own source scope,\n      // CONTRACTS v2.11): the alias's organization replaces any per-query org filter — it is the source's\n      // definition, not the person's list filter. Without one, the query's filter (or none) stands.\n      if (binding.organizationId) wire.scope = { ...wire.scope, organization_id: binding.organizationId };\n      // The archive (`archived: true`) is the same door's own archived lane, never a client-side sieve.\n      const answer = await client.list({ token: binding.token, ...wire, after: cursor ?? null, ...(q.archived === true ? { archived: \"archived\" as const } : {}) });\n      if (!answer.ok) return answer;\n      const { data } = answer;\n      if (data.sort_ignored.length > 0) {\n        // SAID OUT LOUD: the door keeps one sort key today; the rest were dropped, not silently reordered.\n        console.warn(`[@ai-matrx/records/entity] \"${alias}\" sorts by one column for now; ignored: ${data.sort_ignored.join(\", \")}.`);\n      }\n      hold(alias, data.rows);\n      const page: Page = {\n        rows: data.rows.map(toRow),\n        // A count that stopped at the store's cap is a floor, not a count: unknown beats a wrong number.\n        total: data.total === null || data.total === undefined || data.total_is_capped ? null : data.total,\n        cursor: data.has_more ? data.next_after : null,\n      };\n      return { ok: true, data: page };\n    },\n\n    async get(alias, id: Uuid) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n      return getCoalesced(alias, binding.token, id);\n    },\n\n    async create(alias, values: Values) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      // A source declared in one organization saves there; otherwise the host's active organization.\n      const organizationId = binding.organizationId ?? activeOrganization();\n      if (!organizationId) {\n        // MX002, said before anything is sent: a new row's organization is the person's choice, never ours.\n        return refusal(\n          \"organization_required\",\n          \"Choose the organization this new record belongs to.\",\n          \"Pick an organization, then add the row again. Nothing was saved.\",\n        );\n      }\n      const answer = await client.insert({ token: binding.token, organizationId, rows: [toWireValues(values)], opId: ledger.mint() });\n      return readBack(alias, answer, \"The new row\");\n    },\n\n    async update(alias, id: Uuid, patch: Values, baseVersion: number) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n      const answer = await client.update({ token: binding.token, id, baseVersion, patch: toWireValues(patch), opId: ledger.mint() });\n      return readBack(alias, answer, \"The change\");\n    },\n\n    async archive(alias, id: Uuid) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n      return done(await client.archive({ token: binding.token, ids: [id], opId: ledger.mint() }));\n    },\n\n    async restore(alias, id: Uuid) {\n      const binding = bindingOf(alias);\n      if (!binding) return noSuchAlias(alias);\n      if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n      return done(await client.unarchive({ token: binding.token, ids: [id], opId: ledger.mint() }));\n    },\n\n    subscribe(event: DataPortEventName, listener: (event: RowsEvent) => void) {\n      const alias = event.startsWith(\"rows:\") ? event.slice(5) : null;\n      const binding = alias ? bindingOf(alias) : null;\n      if (!alias || !binding) {\n        throw new Error(`DataPort.subscribe: \"${event}\" is not an event this Applet's port carries. Use rows:<alias>.`);\n      }\n      const realtime = options.realtime;\n      if (!realtime) {\n        // NOT LIVE, SAID OUT LOUD: a host that bound no realtime layer goes stale, and the console says why.\n        if (!warnedNotLive) {\n          warnedNotLive = true;\n          console.warn(\"[@ai-matrx/records/entity] This host bound no realtime layer, so other people's changes appear on the next read.\");\n        }\n        return () => {};\n      }\n\n      let stopped = false;\n      let joined: string[] = [];\n      let stopLive: (() => void) | null = null;\n      const sink = { rows: (ids: string[] | null) => listener({ ids: ids === null ? null : [...ids] }) };\n\n      const plan = async () => {\n        const organizationIds = binding.organizationId\n          ? [binding.organizationId]\n          : orderOrganizationTopics({\n              active: activeOrganization(),\n              held: heldCounts(alias),\n              members: await membershipsOnce(),\n              max: await maxOrgTopicsOnce(),\n            });\n        if (stopped) return;\n        if (organizationIds.length === joined.length && organizationIds.every((org, i) => org === joined[i])) return;\n        // Join the new set before leaving the old, so a topic in both never closes and reopens.\n        const previous = stopLive;\n        joined = organizationIds;\n        stopLive = realtime.subscribe({ token: binding.token, organizationIds }, sink);\n        previous?.();\n      };\n      const replan = () => void plan();\n      const set = replans.get(alias) ?? new Set<() => void>();\n      replans.set(alias, set);\n      set.add(replan);\n      replan();\n\n      return () => {\n        stopped = true;\n        set.delete(replan);\n        stopLive?.();\n        stopLive = null;\n      };\n    },\n  };\n}\n\n/**\n * THE PORT A SERVER ASKS THROUGH, AND THE PAGE READS THROUGH WHILE IT HYDRATES (lane SEED-ENTITY).\n * One construction for both, so the doors' arguments are the same on either side: a token is its own\n * alias, nothing is bound to an organization, and nothing is live. `dataSource` is the person's own\n * (server), a recording one, or one that answers from a page seed.\n */\nexport function createSeedPort(dataSource: unknown): EntityDataPort {\n  return createEntityDataPort({ client: createEntityClient({ dataSource }), aliases: {}, tokensAreAliases: true, activeOrganizationId: () => null });\n}\n","// src/core/realtime.ts — @ai-matrx/records/entity\n//\n// LIVE NOTICES FOR PLATFORM LISTS (PHASE-B-APPLETS R4 / U6).\n//\n// The database announces every statement on the five Table-API tables (party, crm_deal, project, task,\n// hr_employee) with ONE broadcast per organization it touched, on the PRIVATE topic\n// `mx:entity-org:<organization>:<token>`, event `entity_bump`, payload\n// `{id, entity_type, organization_id, op, op_id, ids | null, at}` — ids, never values. It is written by\n// `platform.entity_org_notice_stmt` and admitted by `platform.entity_org_topic_admits` through the one RLS\n// policy on `realtime.messages`: a signed-in member of that organization (her own memberships, never the\n// admin route) whose role may read the table. The subscriber re-reads the ids through the read door, so\n// row security decides what she sees at read time.\n//\n// This file joins those topics through `@ai-matrx/data/realtime` — the ONE realtime layer, never a hand-written\n// `.channel(` — so the socket, `setAuth` before a private join, backoff, dedupe and wake backfill are the\n// manager's.\n//\n//   · ONE CHANNEL PER (organization, token), HOWEVER MANY READERS — opened by the first, closed by the last.\n//   · BURSTS COALESCED per reader: the first notice starts a `batchMs` timer, later ones join it, and\n//     `maxWaitMs` caps how long a steady stream can hold a re-read back (knobs entity_data.realtime_batch_ms\n//     / realtime_max_wait_ms).\n//   · `ids: null` PASSES THROUGH — above knob entity_data.realtime_max_ids the database stops naming ids.\n//   · ECHO DROPPED — a write that carried header `x-matrx-op-id` comes back with that `op_id`; a notice whose\n//     op id this client minted (`@ai-matrx/records` `isOwnOp`) is our own write and is dropped.\n//   · NO REPLAY ON A WAKE OR RECONNECT — the answer is `ids: null` (read again).\n\nimport {\n  defineChannelNamespace,\n  subscribeToRealtimeManager,\n  type ChannelSpec,\n  type RealtimeManager,\n} from \"@ai-matrx/data/realtime\";\nimport { isOwnOp } from \"../../ops\";\n\nimport type { EntityClient } from \"./client\";\n\n/** The topic is a CONTRACT WITH THE DATABASE (a trigger writes it, an RLS policy parses it): built once, here. */\nexport const entityOrgChannel = defineChannelNamespace({\n  namespace: \"entity-org\",\n  foreignTopic: \"mx:entity-org\",\n  parts: [\"organizationId\", \"token\"],\n  description:\n    \"One organization's changes to one platform type (contacts, deals, projects, tasks, employees). Carries NOTICES written by platform.entity_org_notice_stmt — which ids moved, never a value. Admitted by the one RLS policy on realtime.messages to members of that organization.\",\n});\n\n/** The broadcast event the database sends on an organization topic. */\nexport const ENTITY_NOTICE_EVENT = \"entity_bump\";\n\n/** Starting values of the knobs the runtime coalesces with (entity_data.realtime_batch_ms / _max_wait_ms). */\nexport const DEFAULT_BATCH_MS = 150;\nexport const DEFAULT_MAX_WAIT_MS = 1000;\n/** Starting value of knob entity_data.realtime_max_org_topics. */\nexport const DEFAULT_MAX_ORG_TOPICS = 20;\n\nexport interface EntityNotice {\n  id?: string;\n  entity_type?: string;\n  organization_id?: string;\n  op?: \"created\" | \"updated\" | \"deleted\";\n  /** The client operation that caused it (header `x-matrx-op-id`), or null for any other writer. */\n  op_id?: string | null;\n  /** `null` MEANS \"more changed than the database lists: re-read\". */\n  ids?: string[] | null;\n  at?: string;\n}\n\n/** A redelivered notice is the same notice: the database mints one id per send. */\nexport function entityNoticeKey(notice: EntityNotice): string | undefined {\n  return notice.id ?? (notice.at ? `${notice.organization_id ?? \"\"}:${notice.entity_type ?? \"\"}:${notice.at}` : undefined);\n}\n\nexport function entityOrgTopic(organizationId: string, token: string): string {\n  return entityOrgChannel.topic({ organizationId, token });\n}\n\n/** The channel spec for one (organization, token): private, echo-guarded, deduped, backfilled. */\nexport function entityOrgChannelSpec(\n  organizationId: string,\n  token: string,\n  onNotice: (notice: EntityNotice) => void,\n  onBackfill: () => void,\n): ChannelSpec {\n  return {\n    topic: entityOrgTopic(organizationId, token),\n    // Database Broadcast is authorized by RLS on realtime.messages; the manager awaits setAuth() first.\n    private: true,\n    // The sender is Postgres: no Matrx envelope. Our own write is known by the op id it carried.\n    wire: { mode: \"raw\", isOwnMessage: (payload) => isOwnOp((payload as EntityNotice | null)?.op_id) },\n    eventKey: (_source, payload) => entityNoticeKey((payload ?? {}) as EntityNotice),\n    broadcast: [\n      {\n        event: ENTITY_NOTICE_EVENT,\n        onMessage: (message) => {\n          const notice = (message.data ?? {}) as EntityNotice;\n          if (isOwnOp(notice.op_id)) return; // belt and braces: the manager's test ran first\n          onNotice(notice);\n        },\n      },\n    ],\n    // Realtime has no replay: a channel back from a gap re-reads.\n    onBackfill: () => onBackfill(),\n  };\n}\n\n/**\n * Which organization topics to join, in order, until `max`: the active organization, the alias's `org`\n * filter, then the organizations of held rows by number of held rows (descending; organization id\n * ascending on ties), then the person's remaining memberships by id. Only memberships are kept when they\n * are known — any other topic is refused by the database anyway. Deterministic for the same input.\n */\nexport function orderOrganizationTopics(input: {\n  active?: string | null;\n  filter?: string | null;\n  held?: ReadonlyMap<string, number>;\n  members?: readonly string[] | null;\n  max: number;\n}): string[] {\n  const members = input.members ? new Set(input.members) : null;\n  const out: string[] = [];\n  const push = (org: string | null | undefined) => {\n    if (!org || out.includes(org)) return;\n    if (members && !members.has(org)) return;\n    out.push(org);\n  };\n  push(input.active);\n  push(input.filter);\n  const held = [...(input.held ?? new Map<string, number>()).entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n  for (const [org] of held) push(org);\n  for (const org of [...(input.members ?? [])].sort()) push(org);\n  return out.slice(0, Math.max(0, input.max));\n}\n\nexport interface EntityNoticeSink {\n  /** `ids` to re-read, or `null` to re-read everything this reader shows. */\n  rows(ids: string[] | null): void;\n}\n\nexport interface EntityRealtime {\n  /** Hear `token` across `organizationIds`; the sink gets one coalesced call per burst. Returns the stop. */\n  subscribe(target: { token: string; organizationIds: readonly string[] }, sink: EntityNoticeSink): () => void;\n}\n\nexport interface CreateEntityRealtimeOptions {\n  /** The host's realtime manager. Left out, the AMBIENT manager the app mounted — never a socket of our own. */\n  manager?: RealtimeManager;\n  /** Knob entity_data.realtime_batch_ms (starting value 150). */\n  batchMs?: number;\n  /** Knob entity_data.realtime_max_wait_ms (starting value 1000). */\n  maxWaitMs?: number;\n}\n\ninterface OrgListener {\n  notice(notice: EntityNotice): void;\n  backfill(): void;\n}\n\ninterface OrgChannel {\n  listeners: Set<OrgListener>;\n  stop: (() => void) | null;\n}\n\n/** The live-notice layer for platform lists, bound to a realtime manager. One per host is enough. */\nexport function createEntityRealtime(options: CreateEntityRealtimeOptions = {}): EntityRealtime {\n  const batchMs = options.batchMs ?? DEFAULT_BATCH_MS;\n  const maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;\n  const channels = new Map<string, OrgChannel>();\n\n  const open = (organizationId: string, token: string): OrgChannel => {\n    const channel: OrgChannel = { listeners: new Set(), stop: null };\n    const spec = entityOrgChannelSpec(\n      organizationId,\n      token,\n      (notice) => {\n        for (const listener of channel.listeners) listener.notice(notice);\n      },\n      () => {\n        for (const listener of channel.listeners) listener.backfill();\n      },\n    );\n    if (options.manager) {\n      const handle = options.manager.open(spec);\n      channel.stop = () => handle.close();\n    } else {\n      channel.stop = subscribeToRealtimeManager(() => spec);\n    }\n    return channel;\n  };\n\n  return {\n    subscribe({ token, organizationIds }, sink) {\n      let timer: ReturnType<typeof setTimeout> | null = null;\n      let firstAt = 0;\n      let pending = new Set<string>();\n      let wholeList = false;\n\n      const flush = () => {\n        if (timer !== null) clearTimeout(timer);\n        timer = null;\n        const ids = [...pending];\n        const all = wholeList;\n        pending = new Set();\n        wholeList = false;\n        // THE IDS ARE USED AS IDS. `null` costs a whole re-read; three ids re-read three rows.\n        if (all) sink.rows(null);\n        else if (ids.length > 0) sink.rows(ids);\n      };\n      const nudge = () => {\n        const now = Date.now();\n        if (timer === null) firstAt = now;\n        else clearTimeout(timer);\n        // Wait `batchMs` after the latest notice, never past `maxWaitMs` after the first one.\n        const wait = Math.max(0, Math.min(batchMs, firstAt + maxWaitMs - now));\n        timer = setTimeout(flush, wait);\n      };\n\n      const listener: OrgListener = {\n        notice(notice) {\n          if (notice.entity_type && notice.entity_type !== token) return;\n          if (notice.ids == null) wholeList = true;\n          else for (const id of notice.ids) pending.add(id);\n          nudge();\n        },\n        backfill() {\n          wholeList = true;\n          flush();\n        },\n      };\n\n      const keys = [...new Set(organizationIds)].map((org) => {\n        const key = entityOrgTopic(org, token);\n        const channel = channels.get(key) ?? open(org, token);\n        channels.set(key, channel);\n        channel.listeners.add(listener);\n        return key;\n      });\n\n      return () => {\n        if (timer !== null) clearTimeout(timer);\n        for (const key of keys) {\n          const channel = channels.get(key);\n          if (!channel) continue;\n          channel.listeners.delete(listener);\n          if (channel.listeners.size > 0) continue;\n          // The last reader of this (organization, token) left: its one subscription goes with it.\n          channel.stop?.();\n          channels.delete(key);\n        }\n      };\n    },\n  };\n}\n\n/** The three live-update knobs as the store answers them for an organization (starting values when unset). */\nexport async function readEntityRealtimeKnobs(\n  client: Pick<EntityClient, \"knob\">,\n  organizationId?: string | null,\n): Promise<{ batchMs: number; maxWaitMs: number; maxOrgTopics: number }> {\n  const read = async (key: string, fallback: number) => {\n    const answer = await client.knob({ key, organizationId: organizationId ?? null });\n    const value = answer.ok ? Number(answer.data) : Number.NaN;\n    if (!Number.isFinite(value)) {\n      // SAID OUT LOUD: the starting value stands in for a knob the store did not answer.\n      console.warn(`[@ai-matrx/records/entity] knob entity_data.${key} did not resolve; using its starting value ${fallback}.`);\n      return fallback;\n    }\n    return value;\n  };\n  const [batchMs, maxWaitMs, maxOrgTopics] = await Promise.all([\n    read(\"realtime_batch_ms\", DEFAULT_BATCH_MS),\n    read(\"realtime_max_wait_ms\", DEFAULT_MAX_WAIT_MS),\n    read(\"realtime_max_org_topics\", DEFAULT_MAX_ORG_TOPICS),\n  ]);\n  return { batchMs, maxWaitMs, maxOrgTopics };\n}\n","// src/core/wire.ts — @ai-matrx/records/entity\n//\n// `toWire`: the Applets `Query` (§4) → the door's arguments (scope, filter, sort). Pure.\n//\n// What the doors do not offer yet is NOT filtered, reordered or emulated here: the clause is sent as\n// asked and the door refuses it BY NAME (`\"contains\" filters are not offered yet.`), so the day the\n// door learns it the port already speaks it, and until then the person reads the store's sentence.\n// A browser-side filter would silently drop everything the browser was not shown.\n\nimport type { Query, WhereClause } from \"../../data\";\nimport type { EntityWirePredicate, EntityWireQuery, EntityWireSort } from \"./types\";\n\n/** The runtime's underscore names for the three identity columns the doors call `id`, `version`, `organization_id`. */\nconst IDENTITY: Readonly<Record<string, string>> = {\n  _id: \"id\",\n  _version: \"version\",\n  _organization_id: \"organization_id\",\n};\n\nexport const CUSTOM_PREFIX = \"_custom.\";\n\n/**\n * Applets column key → the door's identifier. A custom field is `_custom.<key>` (the key as\n * `columns()` answered it — the same plain key for every viewer; `<key>@<organization_id>` is accepted, never produced).\n */\nexport function wireColumn(column: string, customKeys: ReadonlySet<string>): string {\n  const identity = IDENTITY[column];\n  if (identity) return identity;\n  if (column.startsWith(CUSTOM_PREFIX)) return column;\n  return customKeys.has(column) ? `${CUSTOM_PREFIX}${column}` : column;\n}\n\nfunction predicate(clause: WhereClause, customKeys: ReadonlySet<string>): EntityWirePredicate {\n  const column = wireColumn(clause.column, customKeys);\n  const v = clause.value;\n  switch (clause.op) {\n    case \"eq\":\n      // The store reads \"equals nothing\" as empty (the table port's rule, so both kinds of source agree).\n      return v === null || v === undefined ? { column, op: \"empty\" } : { column, op: \"eq\", value: v };\n    case \"neq\":\n      return v === null || v === undefined ? { column, op: \"empty\", negated: true } : { column, op: \"neq\", value: v };\n    case \"lt\":\n    case \"lte\":\n    case \"gt\":\n    case \"gte\":\n      return { column, op: clause.op, value: v };\n    case \"in\":\n      return { column, op: \"in\", values: Array.isArray(v) ? v : [] };\n    case \"empty\":\n      return v === false ? { column, op: \"empty\", negated: true } : { column, op: \"empty\" };\n    case \"contains\":\n      return { column, op: \"contains\", value: v };\n    default:\n      // An op this version does not know is still SENT, so the door names it, instead of vanishing here.\n      return { column, op: String((clause as WhereClause).op), value: v };\n  }\n}\n\nexport function toWire(query: Query | undefined, customKeys: ReadonlySet<string> = new Set()): EntityWireQuery {\n  const q = query ?? {};\n  const out: EntityWireQuery = {};\n  const scope: NonNullable<EntityWireQuery[\"scope\"]> = {};\n  if (q.lane) scope.kind = q.lane; // absent = the type's own landing lane, decided by the door\n  if (q.org && q.org !== \"all\") scope.organization_id = q.org; // a filter, never a lock\n  if (scope.kind || scope.organization_id) out.scope = scope;\n  if (q.where && q.where.length > 0) out.filter = { all: q.where.map((c) => predicate(c, customKeys)) };\n  const search = q.search?.trim();\n  if (search) out.search = search;\n  if (q.sort && q.sort.length > 0) {\n    out.sort = q.sort.map<EntityWireSort>((s) => ({\n      column: wireColumn(s.column, customKeys),\n      dir: s.direction === \"desc\" ? \"desc\" : \"asc\",\n      nulls: \"last\",\n    }));\n  }\n  if (typeof q.pageSize === \"number\" && Number.isFinite(q.pageSize)) out.pageSize = Math.max(1, Math.floor(q.pageSize));\n  return out;\n}\n","// src/port/rows.ts — @ai-matrx/records/entity\n//\n// ROW AND COLUMN SHAPING (Applets CONTRACTS §0): the door's wire row → `Row`, its columns → `Column`.\n// Pure; every case is pinned against recorded door answers (`__fixtures__`).\n\nimport type { Column, EntityRef, Row } from \"../../data\";\nimport type { EntityColumnWire, EntityWireRow } from \"../core/types\";\n\n/** The door's identity columns become the runtime's own underscore keys on a Row; they are never plain columns. */\nconst IDENTITY_COLUMNS = new Set([\"id\", \"version\", \"organization_id\"]);\n/** The compiler's own presentation markers; not data. */\nconst PRESENTATION_KEYS = new Set([\"_state\", \"_k\"]);\n\nfunction isRefList(value: unknown): value is { token: string; id: string; label?: unknown }[] {\n  return (\n    Array.isArray(value) &&\n    value.length > 0 &&\n    value.every((item) => item !== null && typeof item === \"object\" && typeof (item as { token?: unknown }).token === \"string\" && typeof (item as { id?: unknown }).id === \"string\")\n  );\n}\n\n/** Every link reads as `EntityRef[]` — `{token, id, label}`, the label null when the store had no words for it. */\nexport function toRefs(value: unknown): EntityRef[] {\n  if (!isRefList(value)) return [];\n  return value.map<EntityRef>((item) => ({ token: item.token, id: item.id, label: typeof item.label === \"string\" ? item.label : null }));\n}\n\nexport function toRow(wire: EntityWireRow): Row {\n  const row: Row = {\n    _id: wire.id,\n    _version: wire.version,\n    _organization_id: wire.organization_id,\n    _custom: wire._custom && typeof wire._custom === \"object\" ? { ...wire._custom } : {},\n  };\n  for (const [key, value] of Object.entries(wire)) {\n    if (IDENTITY_COLUMNS.has(key) || PRESENTATION_KEYS.has(key) || key === \"_custom\") continue;\n    row[key] = isRefList(value) ? toRefs(value) : value === undefined ? null : value;\n  }\n  return row;\n}\n\nexport function toColumn(wire: EntityColumnWire): Column {\n  const column: Column = {\n    key: wire.key,\n    label: wire.label || wire.key,\n    type: wire.type,\n    origin: wire.origin === \"custom\" ? \"custom\" : \"platform\",\n    required: Boolean(wire.required),\n    readOnly: Boolean(wire.readOnly),\n  };\n  if (wire.choices && wire.choices.length > 0) column.choices = [...wire.choices];\n  if (wire.linksTo && wire.linksTo.length > 0) column.linksTo = [...wire.linksTo];\n  return column;\n}\n\n/** The columns a person sees: the door's own list minus the identity columns a Row carries as `_id` / `_version` / `_organization_id`. */\nexport function toColumns(wire: readonly EntityColumnWire[]): Column[] {\n  return wire.filter((c) => !IDENTITY_COLUMNS.has(c.key)).map(toColumn);\n}\n","// src/objectOrganization.ts — @ai-matrx/records (HEADLESS)\n//\n// WHICH ORGANIZATION OWNS THIS RECORD — READ FROM THE OBJECT, NEVER FROM THE PERSON (lane ACCESS-IS-PERSONAL;\n// moved from the website's features/unified-data/objectOrganization.ts, step 10, 2026-10-08).\n//\n// Every store door takes an organization and checks it first. An object page must hand the doors the\n// organization the OBJECT lives in, never the one the person picked: `custom.where_id_opens(p_id)` — the\n// store's one door that reads an object's organization from its own id (table, record, dashboard, digest,\n// form, booking, portal, rendered document) — answers only when the person could already open it.\n//\n// IT IS A PORT. `RecordOrganizationPort` is what `createRecords` accepts; `whereIdOpensPort(dataSource)` is\n// the default (one door call per ask). A host that keeps answers across remounts or seeds them from a server\n// render (the website's kept-answer store) supplies its own implementation over the same reader.\n//\n// THE ANSWER IS THE PERSON'S. Zero rows means \"not given to you\" and \"not there\" alike; \"we could not ask\"\n// is a third answer and is never folded into either. No stand-in: a miss says so and the page holds.\n\nimport type { RecordsDataSource } from \"./ports\";\nimport { mapPgError, mapThrownError } from \"./core/pgError\";\n\n/** What kind of object the id is, as `custom.where_id_opens` names it — carried as the door's own word. */\nexport type ObjectKind = string;\n\nexport type ObjectOrganizationAnswer =\n  /** The store named the object's organization, and the person may open the object. */\n  | {\n      state: \"found\";\n      organizationId: string;\n      kind: ObjectKind;\n      /** The screen the store says opens it (`/data/<table>?record=…`), or null for a part with none. */\n      path: string | null;\n      /** False when it is in the trash — the person may still open it, to bring it back. */\n      live: boolean;\n      /** The id it answers as — a merged record's survivor. */\n      resolvedId: string;\n      /** A table only: how many rows THIS person sees, capped at `rows_visible_cap` (200) — a loading frame's height. Absent when not asked/known. */\n      rowsVisible?: number;\n      /**\n       * A table only: the layout it opens in and, when that view groups by a Field (a board), the cards each group\n       * holds (largest first; counted over at most `cap` rows, a several-choice card in each of its groups).\n       */\n      opening?: OpeningViewShape;\n    }\n  /** Not given to this person — or not there at all. The store does not say which, on purpose. */\n  | { state: \"not-given\" }\n  /** We could not ask. NOT an answer about the person's access. */\n  | { state: \"unavailable\"; why: string };\n\n/** Which organization owns an object — the port `createRecords({ organizationOf })` accepts. */\nexport interface RecordOrganizationPort {\n  organizationOf(id: string): Promise<ObjectOrganizationAnswer>;\n}\n\n/** What the store says of the layout a table opens in — enough to size a board's or a gallery's loading frame. */\nexport interface OpeningViewShape {\n  layout?: string;\n  groupField?: string;\n  /** Cards per group, largest first. */\n  groups?: number[];\n  cap: number;\n}\n\n/** Reads `opening_view` of the door's answer; anything malformed is no shape at all. */\nexport function readOpeningViewShape(raw: unknown): OpeningViewShape | undefined {\n  if (!raw || typeof raw !== \"object\") return undefined;\n  const o = raw as { layout?: unknown; group_field?: unknown; groups?: unknown; cap?: unknown };\n  const groups = Array.isArray(o.groups) ? o.groups.filter((n): n is number => typeof n === \"number\" && Number.isFinite(n) && n >= 0) : undefined;\n  const shape: OpeningViewShape = {\n    cap: typeof o.cap === \"number\" && o.cap > 0 ? o.cap : 200,\n    ...(typeof o.layout === \"string\" ? { layout: o.layout } : {}),\n    ...(typeof o.group_field === \"string\" ? { groupField: o.group_field } : {}),\n    ...(groups ? { groups } : {}),\n  };\n  return shape.layout === undefined && shape.groupField === undefined && shape.groups === undefined ? undefined : shape;\n}\n\ninterface WhereIdOpens {\n  kind?: unknown;\n  organization_id?: unknown;\n  path?: unknown;\n  live?: unknown;\n  resolved_id?: unknown;\n  rows_visible?: unknown;\n  opening_view?: unknown;\n}\n\nexport const WHERE_ID_OPENS_DOOR = \"where_id_opens\";\n\nfunction doorIsAbsent(error: { code?: string | null; message?: string | null }): boolean {\n  if (error.code === \"PGRST202\" || error.code === \"42883\") return true;\n  return /could not find the function/i.test(error.message ?? \"\");\n}\n\nconst DOOR_ABSENT_WHY =\n  \"custom.where_id_opens is missing from this database, so this page cannot tell which \" +\n  \"organization the record lives in and holds instead of guessing. Remedy: the chair applies \" +\n  \"migrations/campaign/openbyid_one_address_opens_any_id.sql and openbyid_the_resolver_can_be_reached.sql.\";\n/** What a person reads when the door is absent (the remedy above goes to the console, never the page). */\nconst DOOR_ABSENT_SAYS = \"This page cannot ask the record store where this is yet.\";\n\n/** Ask the store which organization `id` lives in — the one call an object page makes before any other door. */\nexport async function resolveObjectOrganization(dataSource: Pick<RecordsDataSource, \"rpc\">, id: string): Promise<ObjectOrganizationAnswer> {\n  let answered: { data: unknown; error: { code?: string | null; message?: string | null } | null };\n  try {\n    answered = (await dataSource.rpc(WHERE_ID_OPENS_DOOR, { p_id: id }, { schema: \"custom\" })) as typeof answered;\n  } catch (thrown) {\n    // A PERSON READS PLAIN WORDS (CLOSE-PERF 2026-10-21): \"TypeError: Failed to fetch\" is the transport, not a sentence.\n    return { state: \"unavailable\", why: mapThrownError(thrown, WHERE_ID_OPENS_DOOR).message };\n  }\n  return readObjectOrganizationAnswer(answered, id);\n}\n\n/** Read one `custom.where_id_opens` answer — asked here, or asked by a server render as the same person. */\nexport function readObjectOrganizationAnswer(\n  answered: { data: unknown; error: { code?: string | null; message?: string | null } | null },\n  id: string,\n): ObjectOrganizationAnswer {\n  if (answered.error) {\n    if (doorIsAbsent(answered.error)) {\n      // The remedy is for whoever runs the store; the person reads what happened.\n      console.warn(`[@ai-matrx/records] ${DOOR_ABSENT_WHY}`);\n      return { state: \"unavailable\", why: DOOR_ABSENT_SAYS };\n    }\n    // A PERSON READS PLAIN WORDS, NEVER THE API'S (CLOSE-PERF 2026-10-21, live at 768 as test@test.com): PostgREST's\n    // \"Could not query the database for the schema cache. Retrying.\" reached the page word for word, and the page\n    // does not retry. The package's one mapping (mapPgError) says the store being away, a timeout and the store's\n    // own refusals in a person's words.\n    return {\n      state: \"unavailable\",\n      why: answered.error.message ? mapPgError({ ...answered.error, message: answered.error.message }, WHERE_ID_OPENS_DOOR).message : \"The record store refused to say where this is.\",\n    };\n  }\n  const row = answered.data as WhereIdOpens | null;\n  if (row === null || row === undefined) return { state: \"not-given\" };\n  // READ STRICTLY. An answer this module cannot read is \"could not ask\", never a guess.\n  if (typeof row !== \"object\" || typeof row.organization_id !== \"string\" || typeof row.kind !== \"string\") {\n    return { state: \"unavailable\", why: \"The record store answered something this page cannot read.\" };\n  }\n  return {\n    state: \"found\",\n    organizationId: row.organization_id,\n    kind: row.kind,\n    path: typeof row.path === \"string\" ? row.path : null,\n    live: row.live !== false,\n    resolvedId: typeof row.resolved_id === \"string\" ? row.resolved_id : id,\n    ...(typeof row.rows_visible === \"number\" && row.rows_visible >= 0 ? { rowsVisible: row.rows_visible } : {}),\n    ...(readOpeningViewShape(row.opening_view) ? { opening: readOpeningViewShape(row.opening_view) as OpeningViewShape } : {}),\n  };\n}\n\n/** The default port: one `custom.where_id_opens` call per ask, nothing kept. */\nexport function whereIdOpensPort(dataSource: Pick<RecordsDataSource, \"rpc\">): RecordOrganizationPort {\n  return { organizationOf: (id) => resolveObjectOrganization(dataSource, id) };\n}\n","// src/realtime/index.ts — @ai-matrx/records/realtime\n//\n// THE STORE'S LIVE-UPDATES PORT, ONCE, FOR EVERY HOST (Applets AP-3, 2026-10-06).\n//\n// Until now `RecordsRealtimePort` was a contract with no implementation in the package: matrx-frontend\n// wrote its own (features/unified-data/realtime/recordsRealtimePort.ts) and every other host — the\n// Applets platform host first — would have had to write a second, or go without and never fire a\n// `rows:<alias>` event. This is that implementation, moved here so every host binds the same one.\n//\n// HOW THE STORE GOES LIVE. Schema `custom` is doors-only (zero table grants) and `custom.record` is\n// hash-partitioned, so `postgres_changes` cannot serve it. The database BROADCASTS a notice instead,\n// on a PRIVATE topic per Table — `custom:table:<table_id>`, event `records.changed`, written by\n// `custom.io_outbox_broadcast_stmt` and admitted by the one RLS policy on `realtime.messages`, which\n// asks the store's own ladder (`custom.assert_may_know_table`). This file joins that topic through\n// `@ai-matrx/data/realtime` — the ONE realtime layer (never a hand-written `.channel(`) — so the socket,\n// `setAuth` before a private join, backoff, dedupe and wake/reconnect backfill are the manager's.\n//\n// WHAT COMES DOWN THE WIRE IS NOT DATA: `{table_id, kind, op, op_id, record_ids, fields_changed, at}`\n// — ids, never values. The hooks re-read the named ids through the read door, which applies the ladder.\n//\n//   · ECHO SUPPRESSION BY OP ID — every write through this package mints `_op_id`; the store returns it\n//     as the notice's `op_id`; `isOwnOp` drops our own write's echo before anything else.\n//   · ONE CHANNEL PER TABLE, HOWEVER MANY READERS — opened by the first listener, closed by the last;\n//     each listener coalesces its own bursts.\n//   · A COLUMN IS NOT A ROW — a `field` / `table` notice calls `sink.shape()`.\n//   · NO REPLAY ON A WAKE OR RECONNECT — the only correct answer is `sink.records(null)` (read again).\n\nimport {\n  defineChannelNamespace,\n  subscribeToRealtimeManager,\n  type ChannelSpec,\n  type RealtimeManager,\n} from \"@ai-matrx/data/realtime\";\n\nimport { defaultOpLedger, type OpLedger } from \"../ops\";\nimport type { RecordsChangeSink, RecordsRealtimePort } from \"../ports\";\nimport type { Uuid } from \"../record\";\n\n/**\n * The topic is a CONTRACT WITH THE DATABASE (a Postgres trigger writes it, an RLS policy parses it),\n * so it is built in one place through the realtime package's foreign-topic door.\n */\nexport const storeTableChannel = defineChannelNamespace({\n  namespace: \"records-store-table\",\n  foreignTopic: \"custom:table\",\n  parts: [\"tableId\"],\n  description:\n    \"One Table in the record store. Carries NOTICES written by custom.io_outbox_broadcast_stmt — which record ids moved and whether the table's shape moved — never any value. Authorized by the one RLS policy on realtime.messages, which asks the store's own ladder.\",\n});\n\n/** The broadcast event the store sends on a table's topic. */\nexport const STORE_NOTICE_EVENT = \"records.changed\";\n\n/** Coalesce a burst into one re-read. A statement is already one notice; this catches two. */\nexport const NUDGE_DEBOUNCE_MS = 150;\n\nexport interface StoreNotice {\n  table_id?: string;\n  kind?: \"record\" | \"field\" | \"table\";\n  op?: \"created\" | \"updated\" | \"deleted\";\n  /** The client operation that caused it (`_op_id`), or null for a server, agent or foreign write. */\n  op_id?: string | null;\n  /** `null` MEANS \"re-read the page\" — above the cap the database stops listing ids. */\n  record_ids?: string[] | null;\n  fields_changed?: boolean;\n  at?: string;\n}\n\n/** The notice's own identity: a redelivered notice is the same statement at the same instant. */\nexport function noticeKey(notice: StoreNotice): string | undefined {\n  if (!notice.at) return undefined;\n  const ids = notice.record_ids == null ? \"*\" : [...notice.record_ids].sort().join(\",\");\n  return `${notice.table_id ?? \"\"}:${notice.kind ?? \"\"}:${notice.op ?? \"\"}:${notice.op_id ?? \"\"}:${notice.at}:${ids}`;\n}\n\ninterface TableListener {\n  notice(notice: StoreNotice): void;\n  backfill(): void;\n}\n\ninterface TableChannel {\n  listeners: Set<TableListener>;\n  stop: (() => void) | null;\n}\n\nexport interface CreateRecordsRealtimePortOptions {\n  /**\n   * The host's realtime manager (`@ai-matrx/data/realtime`). Left out, the AMBIENT manager is used — the one\n   * the app mounted (`setAmbientRealtimeManager` / `<RealtimeProvider>`); the port joins when one is\n   * mounted and follows it if it is replaced. Never a second socket of the port's own.\n   */\n  manager?: RealtimeManager;\n  /**\n   * The own-write memory of the client this port listens for (`createOpLedger()`, the same one handed\n   * to `createRecordsClient({ opLedger })`). Absent ⇒ the realm's default ledger.\n   */\n  ledger?: OpLedger;\n}\n\n/** The channel spec for one table: private, echo-guarded, deduped, backfilled. */\nexport function storeTableChannelSpec(\n  tableId: string,\n  onNotice: (notice: StoreNotice) => void,\n  onBackfill: () => void,\n  ledger: OpLedger = defaultOpLedger,\n): ChannelSpec {\n  return {\n    topic: storeTableChannel.topic({ tableId }),\n    // Database Broadcast is authorized by RLS on realtime.messages — that is what `private` means here;\n    // the manager awaits `setAuth()` before subscribing (its absence is a channel that looks healthy and\n    // delivers nothing forever).\n    private: true,\n    // The sender is Postgres: no Matrx envelope. OUR OWN WRITE is known by the op id the write door carried.\n    wire: { mode: \"raw\", isOwnMessage: (payload) => ledger.isOwn((payload as StoreNotice | null)?.op_id) },\n    eventKey: (_source, payload) => noticeKey((payload ?? {}) as StoreNotice),\n    broadcast: [\n      {\n        event: STORE_NOTICE_EVENT,\n        onMessage: (message) => {\n          const notice = (message.data ?? {}) as StoreNotice;\n          if (ledger.isOwn(notice.op_id)) return; // belt and braces: the manager's test ran first\n          onNotice(notice);\n        },\n      },\n    ],\n    // A CHANNEL WITH NO RECONCILIATION IS A SCREEN THAT WILL EVENTUALLY LIE: realtime has no replay.\n    onBackfill: () => onBackfill(),\n  };\n}\n\n/**\n * The store's live-updates port, bound to a realtime manager. Hand it to `RecordsConfig.realtime`; the\n * `@ai-matrx/records/data` port turns its sink calls into `rows:<alias>` events.\n */\nexport function createRecordsRealtimePort(options: CreateRecordsRealtimePortOptions = {}): RecordsRealtimePort {\n  const channels = new Map<string, TableChannel>();\n\n  const open = (tableId: string): TableChannel => {\n    const channel: TableChannel = { listeners: new Set(), stop: null };\n    const spec = storeTableChannelSpec(\n      tableId,\n      (notice) => {\n        for (const listener of channel.listeners) listener.notice(notice);\n      },\n      () => {\n        for (const listener of channel.listeners) listener.backfill();\n      },\n      options.ledger,\n    );\n    if (options.manager) {\n      const handle = options.manager.open(spec);\n      channel.stop = () => handle.close();\n    } else {\n      channel.stop = subscribeToRealtimeManager(() => spec);\n    }\n    return channel;\n  };\n\n  return {\n    subscribeRecords({ table_id }, sink: RecordsChangeSink) {\n      let timer: ReturnType<typeof setTimeout> | null = null;\n      let pending = new Set<Uuid>();\n      let wholePage = false;\n\n      const flush = () => {\n        timer = null;\n        const ids = [...pending];\n        const all = wholePage;\n        pending = new Set();\n        wholePage = false;\n        // THE IDS ARE USED AS IDS. `null` is reserved for \"the store could not name them\" or \"the socket\n        // was away\" and costs a whole read; a nudge naming three records re-reads three records.\n        if (all) sink.records(null);\n        else if (ids.length > 0) sink.records(ids);\n      };\n      const nudge = () => {\n        if (timer === null) timer = setTimeout(flush, NUDGE_DEBOUNCE_MS);\n      };\n\n      const listener: TableListener = {\n        notice(notice) {\n          if (notice.kind === \"field\" || notice.kind === \"table\") sink.shape();\n          if (notice.kind === \"field\") return;\n          if (notice.record_ids == null) wholePage = true;\n          else for (const id of notice.record_ids) pending.add(id);\n          nudge();\n        },\n        backfill() {\n          wholePage = true;\n          flush();\n        },\n      };\n\n      const channel = channels.get(table_id) ?? open(table_id);\n      channels.set(table_id, channel);\n      channel.listeners.add(listener);\n\n      return () => {\n        if (timer !== null) clearTimeout(timer);\n        channel.listeners.delete(listener);\n        if (channel.listeners.size > 0) return;\n        // The last reader of this table left: the table's one subscription goes with it.\n        channel.stop?.();\n        channels.delete(table_id);\n      };\n    },\n  };\n}\n\n// WHO ELSE IS LOOKING AT THIS TABLE (row 183): the presence port, on the same realtime layer.\nexport {\n  createRecordsPresencePort,\n  peopleOf,\n  presenceColor,\n  storeTablePresenceChannel,\n  type CreateRecordsPresencePortOptions,\n  type PresenceCell,\n  type PresenceSelf,\n  type RecordsPresencePort,\n  type TablePresencePerson,\n  type TablePresenceSession,\n} from \"./presence\";\n","// @ai-matrx/records/search — search across every table a person can see (moved from the website's\n// `features/unified-data/storeRecordCandidates.ts`, 2026-10-08; the body is the same, the client is\n// the host's data source instead of the website's).\n//\n// The store's own search door, `custom.records_search`, answers across EVERY organization the person\n// belongs to — the active organization is never passed (access-ladder: it is not a list filter) —\n// and names each record by its table's title field. Narrowing to tables or organizations is the\n// caller's visible choice (`tableIds`, `organizationIds`).\n//\n// The door costs ~200–450 ms, so a single typed character is not sent: a picker already waits for a\n// pause, and this answers a one-character search with nothing rather than a slow broad read.\n\nimport { asRecordsDataSource } from \"../core/supabase\";\nimport { mapPgError } from \"../core/pgError\";\nimport type { Uuid } from \"../record\";\nimport type { PgError, RecordsResult } from \"../results\";\n\nexport const STORE_RECORD_SEARCH_MIN_CHARS = 2;\n\n/** One record the search door found. */\nexport interface RecordSearchHit {\n  recordId: Uuid;\n  tableId: Uuid;\n  tableName: string;\n  /** The record's title-field value; null when the record has none yet. */\n  name: string | null;\n  organizationId: Uuid;\n  updatedAt: string;\n}\n\nexport interface RecordSearchRequest {\n  search?: string;\n  limit?: number;\n  offset?: number;\n  /** Only these tables (a visible filter the person chose). */\n  tableIds?: readonly Uuid[];\n  /** Only these organizations (a visible filter the person chose; never the active one by default). */\n  organizationIds?: readonly Uuid[];\n}\n\ninterface SearchRow {\n  record_id: Uuid;\n  table_id: Uuid;\n  table_name: string;\n  name: string | null;\n  organization_id: Uuid;\n  updated_at: string;\n}\n\n/** Records across every table the person can see whose name matches `search`. */\nexport async function searchRecords(dataSource: unknown, request: RecordSearchRequest = {}): Promise<RecordsResult<RecordSearchHit[]>> {\n  const search = request.search?.trim() ?? \"\";\n  if (search.length > 0 && search.length < STORE_RECORD_SEARCH_MIN_CHARS) return { ok: true, data: [] };\n  const args: Record<string, unknown> = { p_search: search, p_limit: request.limit ?? 25, p_offset: request.offset ?? 0 };\n  if (request.tableIds && request.tableIds.length > 0) args[\"p_table_ids\"] = [...request.tableIds];\n  if (request.organizationIds && request.organizationIds.length > 0) args[\"p_organization_ids\"] = [...request.organizationIds];\n  try {\n    const answer = await asRecordsDataSource(dataSource).rpc(\"records_search\", args, { schema: \"custom\" });\n    if (answer.error) return { ok: false, error: mapPgError(answer.error as PgError, \"custom.records_search\") };\n    const rows = (answer.data ?? []) as SearchRow[];\n    return {\n      ok: true,\n      data: rows.map((row) => ({\n        recordId: row.record_id,\n        tableId: row.table_id,\n        tableName: row.table_name,\n        name: row.name,\n        organizationId: row.organization_id,\n        updatedAt: row.updated_at,\n      })),\n    };\n  } catch (thrown) {\n    return { ok: false, error: mapPgError({ code: \"\", message: thrown instanceof Error ? thrown.message : String(thrown) } as PgError, \"custom.records_search\") };\n  }\n}\n\n/**\n * Candidates for the `record` entity token in a record picker (\"Link a record…\"). Two tables often\n * hold a record of the same name (\"UnitedHealthcare\" in two choice lists), so each candidate says\n * which table it is in; the same words label the link.\n */\nexport async function listStoreRecordCandidates(\n  dataSource: unknown,\n  args: { search?: string; limit?: number },\n): Promise<{ ok: true; data: { id: string; title: string }[] } | { ok: false; error: string }> {\n  const found = await searchRecords(dataSource, { ...(args.search !== undefined ? { search: args.search } : {}), limit: args.limit ?? 25 });\n  if (!found.ok) {\n    console.error(\"[listStoreRecordCandidates] failed\", found.error);\n    return { ok: false, error: found.error.message || \"Could not search records\" };\n  }\n  return { ok: true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Q,UAAU;AACrB,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,OAAO,EAAE,MAAM,iBAAiB,SAAS,uFAAuF;AAAA,QAClI;AAAA,MACF;AACA,YAAM,QAAQ,SAAS,IAAI,MAAM;AACjC,aAAO,EAAE,IAAI,MAAM,MAAM,OAAU;AAAA,IACrC;AAAA,IACA,QAAQ;AACN,UAAI,aAAc,WAAU,QAAQ;AAAA,IACtC;AAAA,EACF;AACF;","names":["import_realtime","registry","doorReady","refusal","import_global_slot","import_uuid","isRef","refusal","import_uuid","predicate","flight","refusal","copyId","schema","rows","siblings","import_uuid","held","import_realtime","organizationId"]}