{"version":3,"sources":["../../src/core/index.ts","../../src/vocabulary.ts","../../src/record.ts","../../src/archive.ts","../../src/level.ts","../../src/table.ts","../../src/field.ts","../../src/recordType.ts","../../src/formulaLook.ts","../../src/choice.ts","../../src/retype.ts","../../src/button.ts","../../src/newerKinds.ts","../../src/typedDate.ts","../../src/typedNumber.ts","../../src/coerce.ts","../../src/autonumber.ts","../../src/typedMatch.ts","../../src/pipeline.ts","../../src/rule.ts","../../src/portal.ts","../../src/rowControls.ts","../../src/rowLabel.ts","../../src/aggregate.ts","../../src/relativeDays.ts","../../src/drill.ts","../../src/grid.ts","../../src/automation.ts","../../src/placement.ts","../../src/base.ts","../../src/capture-queue.ts","../../src/subscription.ts","../../src/results.ts","../../src/core/pgError.ts","../../src/relation.ts","../../src/objectOrganization.ts","../../src/ops.ts","../../src/store.generated.ts","../../src/record-scope.ts","../../src/table-kind.ts","../../src/table-kind-mapping.json","../../src/alternates.ts","../../src/datedValues.ts","../../src/ai-field-presets.ts","../../src/core/primedBundle.ts","../../src/core/transient.ts","../../src/core/doorCall.ts","../../src/core/recordChanges.ts","../../src/scopes/types.ts","../../src/scopes/codec.ts","../../src/scopes/rules.ts","../../src/scopes/doors.ts","../../src/core/pickListDoors.ts","../../src/core/keysetCursor.ts","../../src/core/doors.ts","../../src/core/supabase.ts","../../src/core/query.ts","../../src/core/client.ts","../../src/core/clientInOrganization.ts","../../src/core/declareTable.ts","../../src/core/tableKindFacts.ts","../../src/core/landingOutcomes.ts","../../src/core/storeDoors.ts","../../src/core/validation.ts","../../../design-system/src/field-formats/registry.ts","../../../design-system/src/field-formats/display-zone.ts","../../../design-system/src/field-formats/design-tokens.ts","../../../design-system/src/field-formats/format.ts","../../src/core/io.ts","../../src/core/wholeValue.ts","../../src/core/seed.ts","../../src/core/table-logic.ts"],"sourcesContent":["// src/core/index.ts — @ai-matrx/records (HEADLESS)\n//\n// Zero React, zero DOM. Everything here runs in a node script, a worker, a\n// server component and a browser alike.\n\nexport * from \"../index\";\nexport { createRecordsClient, asWriteConflict, isAPersonsRefusal, A_PERSONS_REFUSAL, withTableFacts, type RecordsClient, type TableFact, type TableLiveLocation, type FieldNotifyOnAssign, RECORDS_LIMITS_DEFAULTS, recordsLimitsFrom, type RecordsLimits } from \"./client\";\nexport { clientInOrganization } from \"./clientInOrganization\";\nexport { DOORS, doorExists, doorReady, doorAbsent, doorCensus, type DoorKey } from \"./doors\";\nexport {\n  declareTable,\n  ensureTable,\n  addFields,\n  fieldDeclarationFor,\n  tokenFor,\n  DEFAULT_FIELDS,\n  type NewTableSpec,\n  type NewFieldSpec,\n  type DeclareResult,\n  type EnsureResult,\n} from \"./declareTable\";\nexport { announceRecordChanged, onRecordChanged, markRecordRemoved, markRecordRestored, isRecordRemoved, announceTableStructureChanged, onTableStructureChanged } from \"./recordChanges\";\nexport { tableKindFacts } from \"./tableKindFacts\";\nexport {\n  landingOutcomesFor,\n  landingContentsOf,\n  outcomeForBlock,\n  blockLandedInStore,\n  valuesAreUnconfirmed,\n  outputIsKept,\n  OUTPUT_KEPT_KEY,\n  PRODUCED_BY_LABEL,\n  LANDING_SOURCE_TYPE,\n  LANDING_TARGET_TYPES,\n  type Landing,\n  type LandingBlock,\n  type LandingContents,\n  type LandingOutcomes,\n  type LandingState,\n  type LandingStore,\n  type BlockOutcome,\n} from \"./landingOutcomes\";\nexport { primeTablePageBundle, primeRecordPageBundle, takePrimedTablePageBundle, forgetPrimedTablePageBundles, dropPrimedDoorAnswers, primeDoorAnswer, PRIMED_DOOR_TTL_MS, type PrimedBundleAnswer } from \"./primedBundle\";\nexport { supabaseDataSource, asRecordsDataSource, type SupabaseLike } from \"./supabase\";\nexport { storeDoors, STORE_SCHEMA, type StoreDoors, type StoreCaller, type StoreDoorAnswer, type StoreDoorError } from \"./storeDoors\";\nexport { mapPgError, mapThrownError, staleWriteDetail, archivedOrganizationId, MAPPED_SQLSTATES, TIMED_OUT_MESSAGE } from \"./pgError\";\nexport {\n  planQuery,\n  intersectIds,\n  DEFAULT_PAGE_SIZE,\n  type RecordQuery,\n  type QueryPlan,\n  type AsOf,\n  type PromotedPredicate,\n} from \"./query\";\nexport {\n  predictWriteRefusals,\n  predictValueRefusals,\n  predictSizeRefusal,\n  predictEnvelopeRefusal,\n  DEFAULT_VALUE_MAX_BYTES,\n  DEFAULT_DOCUMENT_MAX_BYTES,\n  type MirrorLimits,\n} from \"./validation\";\nexport {\n  exportCsv,\n  exportMarkdown,\n  exportXlsx,\n  importCsv,\n  importXlsx,\n  parseCsv,\n  toAoa,\n  cellText,\n  exportCellText,\n  type ExportRow,\n  type ParsedImport,\n} from \"./io\";\nexport {\n  WHOLE_VALUE_SOURCE_KIND,\n  wholeValueOf,\n  wholeValueOfRead,\n  wholeValueSize,\n  wholeValueNotRead,\n  withWholeValues,\n  type WholeValuePointer,\n  type ReadFileText,\n} from \"./wholeValue\";\nexport { recordingDataSource, seededDataSource, seedIndex, seedKey, type RecordsSeed, type RecordsSeedAnswer } from \"./seed\";\nexport {\n  inferDataType,\n  sanitizeFieldName,\n  validateFieldName,\n  isBulkOpError,\n  describeBulkFailures,\n  isServiceFailure,\n  type Json,\n  type FieldDataType,\n  type DatasetField,\n  type DatasetRow,\n  type BulkInsertOp,\n  type BulkUpdateOp,\n  type BulkMergeOp,\n  type BulkCellOp,\n  type BulkDeleteOp,\n  type BulkOp,\n  type BulkOpError,\n  type BulkOpResult,\n  type BulkWriteResponse,\n  type ServiceOk,\n  type ServiceErr,\n  type ServiceResult,\n} from \"./table-logic\";\n","// src/vocabulary.ts — @ai-matrx/records\n//\n// THE CLOSED VOCABULARIES. Every list here is a word set the STORE enforces,\n// and the store is the only place any of them is decided. The literal values\n// are not typed by hand: `src/store.generated.ts` is regenerated from the live\n// catalog by `pnpm records:generate`, and `pnpm check:store-registry` fails\n// the build the moment this package and the database disagree. What lives HERE\n// is the type layer over those literals, so a wrong word is a compile error in\n// a consumer rather than a `23514` at three in the morning.\n\nimport {\n  ACTOR_VOCABULARY,\n  ABSENCE_REASONS,\n  VALUE_ENVELOPE_KEYS,\n  VALUE_ALTERNATE_KEYS,\n  STORAGE_MODES,\n  RULE_USES,\n  PER_VALUE_ACCESS_WORDS,\n  PARITY_FIELD_TYPES,\n  DECLARABLE_FIELD_KINDS,\n  RULE_NODE_KINDS,\n  RETIRED_ACTOR_WORDS,\n} from \"./store.generated\";\n\n/**\n * VAL-8. Who wrote a value. `user`, `agent`, `system` — enforced by every write\n * door, and the three retired words (`human`, `ai`, `code`) are translated by\n * the store's own `custom.actor_word`, never by a caller.\n */\nexport type Actor = (typeof ACTOR_VOCABULARY)[number];\n\n/** The words the store still accepts and rewrites, mapped to what they become. */\nexport type RetiredActorWord = keyof typeof RETIRED_ACTOR_WORDS;\n\n/**\n * VAL-2. Why a value is missing. A value is never blank for an unexplained\n * reason: it either holds something or it says one of these four words.\n */\nexport type AbsenceReason = (typeof ABSENCE_REASONS)[number];\n\n/** The closed key set of one value envelope (VAL-1 … VAL-4). */\nexport type ValueEnvelopeKey = (typeof VALUE_ENVELOPE_KEYS)[number];\n\n/** The closed key set of one ranked alternate (VAL-3). */\nexport type ValueAlternateKey = (typeof VALUE_ALTERNATE_KEYS)[number];\n\n/**\n * REC-4. `heavy` is indexed storage with Rules on write; `light` is\n * whole-document storage with Rules on read. Per Table, one store.\n */\nexport type StorageMode = (typeof STORAGE_MODES)[number];\n\n/** REC-15. One Rule object, four uses. */\nexport type RuleUse = (typeof RULE_USES)[number];\n\n/**\n * VAL-5 / VAL-6. The words that may NOT appear inside a value envelope:\n * Visibility and access belong to a Field and to a Record, never to a value.\n * The store refuses each of them by name and so does this package's mirror.\n */\nexport type PerValueAccessWord = (typeof PER_VALUE_ACCESS_WORDS)[number];\n\n/** FLD-11. The parity floor: the field type a person picks in the UI. */\nexport type ParityFieldType = (typeof PARITY_FIELD_TYPES)[number][\"parity_type\"];\n\n/**\n * THE ONE REGISTRY, as a type: every kind a column can be DECLARED as.\n *\n * `ParityFieldType` above is the parity FLOOR — the answer to \"which of the fourteen\n * is this field\". It is not the answer to \"what may somebody pick\", and reading it as\n * though it were is exactly how `signature` came to be a field shape the store accepted\n * (`custom.doc_sign` takes no other) and no screen could offer: VERIFIER-10, F6.\n * `custom.field_kinds()` is the registry, and this is generated from it.\n */\nexport type DeclarableFieldKind = (typeof DECLARABLE_FIELD_KINDS)[number][\"kind\"];\n\n/** FLD-1. The five behaviors a Field can have. One, exactly, and closed. */\nexport type FieldBehavior = (typeof PARITY_FIELD_TYPES)[number][\"behavior\"];\n\n/** The node kinds `custom.rule_eval` evaluates. */\nexport type RuleNodeKind = (typeof RULE_NODE_KINDS)[number][\"node\"];\n\n/**\n * REC-32. The seven table types, closed. The parenthesised names are the\n * retired ones the doctrine records; never coin an eighth.\n */\nexport const TABLE_TYPES = [\n  \"entity\",\n  \"detail\",\n  \"reference\",\n  \"ledger\",\n  \"restricted\",\n  \"system\",\n  \"deprecated\",\n] as const;\nexport type TableType = (typeof TABLE_TYPES)[number];\n\n/** REC-33. The two origins. A table we ship in schema `custom` is `standard`. */\nexport const TABLE_ORIGINS = [\"standard\", \"custom\"] as const;\nexport type TableOrigin = (typeof TABLE_ORIGINS)[number];\n\n/** REL-1. Ownership is one fact, stored once, read from the field's side. */\nexport const RELATION_FLAVORS = [\"owned\", \"referenced\"] as const;\nexport type RelationFlavor = (typeof RELATION_FLAVORS)[number];\n\n/** REL-2. What happens to the far side, separate from flavour. */\nexport const ON_DELETE = [\"cascade\", \"set_null\", \"restrict\"] as const;\nexport type OnDelete = (typeof ON_DELETE)[number];\n\n/** REL-3. A snapshot is a frozen copy in the relation's payload, never a pointer. */\nexport const RELATION_BINDINGS = [\"live\", \"snapshot\"] as const;\nexport type RelationBinding = (typeof RELATION_BINDINGS)[number];\n\n/** REL-7. */\nexport const RELATION_CARDINALITIES = [\"one\", \"many\"] as const;\nexport type RelationCardinality = (typeof RELATION_CARDINALITIES)[number];\n\n/** FLD-7. Where a Field's values come from. */\nexport const FIELD_SOURCES = [\"manual\", \"formula\", \"agent\", \"synced\"] as const;\nexport type FieldSource = (typeof FIELD_SOURCES)[number];\n\n/** FLD-9. A Formula declares whether it computes on read or on write. */\nexport const COMPUTE_ON = [\"read\", \"write\"] as const;\nexport type ComputeOn = (typeof COMPUTE_ON)[number];\n\n/**\n * AGT-7 / FLD-12. A Field's sensitivity sets a ceiling a merge field can never\n * widen — and these are THE STORE'S four words, checked against its own guard.\n *\n * This list used to read `standard · sensitive · secret`, which the store has\n * never accepted: writing a Field with `sensitivity: \"standard\"` is refused\n * with \"the field <name> has to say how sensitive its values are, and it says\n * standard\". The knob `custom/field_sensitivity_levels` keys off these same\n * four words to decide which level may read and edit each one, so a package\n * carrying three different words could never have agreed with it. Corrected\n * against the live store, 2026-09-18.\n */\nexport const FIELD_SENSITIVITIES = [\"public\", \"internal\", \"confidential\", \"restricted\"] as const;\nexport type FieldSensitivity = (typeof FIELD_SENSITIVITIES)[number];\n\n/** DYN-17 / §D. Which tier a MERGE FIELD's value is delivered in. */\nexport const DELIVERIES = [\"inline\", \"on_demand\", \"auto\"] as const;\nexport type Delivery = (typeof DELIVERIES)[number];\n\n/**\n * FLD-12. WHETHER AN AGENT MAY SEE A FIELD'S VALUES, and these are the STORE'S\n * four words — not the merge field's delivery tiers.\n *\n * `Field.context_policy` used to be typed as `Delivery` here, which is a\n * different question with a different vocabulary: writing a Field with\n * `context_policy: \"inline\"` is refused with \"the field <name> has to say\n * whether an agent may see its values, and it says inline\". Delivery is about\n * HOW MUCH of a value a merge field carries into a turn; this is about WHETHER\n * the value reaches an agent at all, and conflating them let a screen offer a\n * word the store has never accepted. Corrected against the live store,\n * 2026-09-18.\n */\nexport const CONTEXT_POLICIES = [\"include\", \"summarize\", \"exclude\", \"on_request\"] as const;\nexport type ContextPolicy = (typeof CONTEXT_POLICIES)[number];\n\n/** DYN-3. The eight sources, closed. Relationships and rules are not sources. */\nexport const MERGE_FIELD_SOURCES = [\n  \"literal\",\n  \"record\",\n  \"state\",\n  \"actor\",\n  \"platform\",\n  \"user_input\",\n  \"tool\",\n  \"derived\",\n] as const;\nexport type MergeFieldSource = (typeof MERGE_FIELD_SOURCES)[number];\n\n/** DYN-4. What a merge field resolves INTO. The consumer never learns which. */\nexport const MERGE_FIELD_SEMANTIC_TYPES = [\n  \"value\",\n  \"reference\",\n  \"resolver\",\n  \"computed\",\n  \"collection\",\n] as const;\nexport type MergeFieldSemanticType = (typeof MERGE_FIELD_SEMANTIC_TYPES)[number];\n\n/** DYNAMIC-VALUES §A. Any number of these; never fused into the source. */\nexport const MERGE_FIELD_MODIFIERS = [\n  \"scoped\",\n  \"temporal\",\n  \"collection\",\n  \"live\",\n  \"fallback\",\n  \"formatted\",\n  \"required\",\n] as const;\nexport type MergeFieldModifier = (typeof MERGE_FIELD_MODIFIERS)[number];\n\n/** DYN-12. The five override policies. Exactly one, and it outranks the ladder. */\nexport const OVERRIDE_POLICIES = [\n  \"must_supply\",\n  \"shown_overridable\",\n  \"shown_locked\",\n  \"server_fixed\",\n  \"derived\",\n] as const;\nexport type OverridePolicy = (typeof OVERRIDE_POLICIES)[number];\n\n/** DYNAMIC-VALUES §C. What a resolved merge field's freshness was. */\nexport const FRESHNESS = [\"live\", \"cached\", \"snapshot\"] as const;\nexport type Freshness = (typeof FRESHNESS)[number];\n\n/** REC-1. How a Table shows itself. */\nexport const TABLE_DISPLAYS = [\"list\", \"grid\", \"board\", \"calendar\", \"timeline\"] as const;\nexport type TableDisplay = (typeof TABLE_DISPLAYS)[number];\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/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/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/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/field.ts — @ai-matrx/records\n//\n// THE FIELD. FLD-1 … FLD-13, FLD-N-1.\n//\n// One behavior from a closed set of five; modifiers SEPARATE from behavior; a\n// constraint is a Rule and never a behavior; a parity type on top that says\n// which of the thirteen things a person picked in the UI and what it is MADE OF.\n// Unit and format live here and not in presentation, because they change what\n// the value MEANS and they reach the agent's context (FLD-N-1).\n\nimport type { NewerFieldKind } from \"./newerKinds\";\nimport type { Timestamp, Uuid } from \"./record\";\nimport type {\n  ComputeOn,\n  ContextPolicy,\n  DeclarableFieldKind,\n  FieldBehavior,\n  FieldSensitivity,\n  FieldSource,\n  OnDelete,\n  ParityFieldType,\n} from \"./vocabulary\";\n\n/** FLD-3. A constraint attached to a Field. A Rule, never a behavior. */\nexport interface FieldRule {\n  /**\n   * `unique` (FLD-3 / B1): no two live records of the Table hold the same value, compared\n   * case- and outer-space-blind. The store enforces it under an advisory lock\n   * (`custom._unique_rule_holds`); it is also what lets `recordUpsert` find \"the\" record by a key.\n   * The mirror never predicts it — it needs a query.\n   */\n  kind: \"min\" | \"max\" | \"length\" | \"pattern\" | \"equals_field\" | \"differs_from_field\" | \"unique\";\n  /**\n   * The rule's own number or word: the least / the most for `min` / `max`, the\n   * LONGEST for `length`, the pattern for `pattern`, the other column's key for\n   * `equals_field` / `differs_from_field`. A `length` rule that only says how\n   * SHORT a value may be carries `min` and no `value`.\n   */\n  value?: string | number;\n  /**\n   * STORE-RULE-GAPS (the older grid's `patternHint`). On a `pattern` rule only:\n   * how a person writes it, e.g. `\"949-555-0142\"`. The store refuses an example\n   * its own pattern would refuse, and a refused value is told \"Enter it like\n   * 949-555-0142.\" (the hint, and `detail.example`).\n   */\n  example?: string;\n  /**\n   * STORE-RULE-GAPS (the older grid's `minLength`). On a `length` rule only: the\n   * fewest characters. A blank is `required`'s question, never \"too short\".\n   */\n  min?: number;\n  /** FLD-10. Empty means \"wherever the Field applies\". */\n  applies_to_types?: string[];\n}\n\n/**\n * `custom.field` — the ONE definitions table (FLD-8), organization-scoped, so\n * two organizations add different fields to the same standard table.\n */\n/**\n * WHICH OF THE OTHER RECORD'S COLUMNS A RELATION SHOWS (REL-DISP, 2026-09-21).\n *\n * A Table has ONE stored default reference column — its `title_field` — and until\n * this existed every relation pointing at that Table could display that column and\n * nothing else. A Jobs board could read \"Maria Chen\" but never \"Maria Chen —\n * Rincon\", and two columns could not be joined into one string at all.\n *\n * ABSENT MEANS THE TABLE'S OWN COLUMN. A field with no `display` resolves exactly\n * as it did before, so nothing changes for a column nobody has given a spec to.\n *\n * The store judges it once, in `custom._display_spec_for`: every column named must\n * exist on the target Table, and the refusal names the one that does not. It is\n * resolved by ONE body, `custom._words_for`, which `custom.record_words`,\n * `custom._card_words`, `custom.relation_words` and `custom.relation_words_many`\n * are all one-liners onto — so the thirteen store-side readers inherit it too.\n *\n * A display column that is itself a relation resolves ONE hop and never a second.\n */\nexport interface RelationDisplay {\n  /** The target's columns, in the order they are shown. */\n  columns: string[];\n  /** What goes between them. Defaults to a single space. */\n  separator: string;\n}\n\nexport interface Field {\n  id: Uuid;\n  organization_id: Uuid;\n  /** Set when this Field extends a standard entity rather than a custom Table. */\n  entity_definition_id: Uuid | null;\n  /** The token of the Table this Field belongs to. */\n  table_token: string | null;\n  key: string;\n  label: string;\n  name: string | null;\n  /**\n   * When this Field was taken away (retired / archived), or null while it is live. Filled by the reads that\n   * can answer a retired Field — `entityFields({ include_retired: true })`; absent from reads that never do.\n   */\n  archived_at?: string | null;\n\n  // ── behavior and modifiers, which are different questions ────────────────\n  /** FLD-1. Exactly one of five. */\n  type: FieldBehavior;\n  /** FLD-2. The shape of the value, never a second behavior. */\n  multi: boolean;\n  /** FLD-2. The values carry their own dates — the world clock, not History. */\n  dated: boolean;\n  /** FLD-3. Any number of attached validation Rules. */\n  rules: FieldRule[];\n  config: Record<string, unknown>;\n  required: boolean;\n  default: unknown;\n  sort: number | null;\n\n  // ── relation properties (REL-1 … REL-8), on the field's side ──────────────\n  /** The Table this relation points at. */\n  relation_target: Uuid | null;\n  relation_max: number | null;\n  on_target_delete: OnDelete | null;\n  /** REL-9. The reverse is visible from both ends and is NOT a second Field. */\n  inverse_key: string | null;\n  /** REL-DISP. Which of the target's columns this one shows. Null = the Table's own. */\n  display: RelationDisplay | null;\n\n  // ── where values come from (FLD-7, FLD-9) ─────────────────────────────────\n  source: FieldSource;\n  source_config: Record<string, unknown>;\n  /** FLD-9. A Formula declares whether it computes on read or on write. */\n  compute_on: ComputeOn | null;\n\n  // ── what the value MEANS (FLD-N-1) ────────────────────────────────────────\n  /** The unit, on the Field, because it changes the meaning. Never presentation. */\n  unit: string | null;\n  format: string | null;\n\n  // ── the agent-facing properties (FLD-12, AGT-6, AGT-7) ────────────────────\n  /** AGT-7. A ceiling a merge field's delivery can never widen. */\n  sensitivity: FieldSensitivity | null;\n  /** FLD-12. Whether an agent may see this Field's values: include · summarize · exclude · on_request. */\n  context_policy: ContextPolicy | null;\n  /** AGT-6. How often a `source = agent` Field is refilled. */\n  review_interval_days: number | null;\n  /**\n   * §D says this is on the wrong object and moves to the merge field. It is\n   * still carried here because the live column is, and the client reads what\n   * the store holds — never what the plan wishes it held.\n   */\n  depends_on: Uuid[] | null;\n\n  /** FLD-10. Which record types this Field applies to. Empty means all of them. */\n  applies_to_types: string[];\n  /** FLD-5 / FLD-6. A list field's choices are the records of THIS Table. */\n  options_table_id: Uuid | null;\n\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  visibility: string;\n}\n\n/**\n * FLD-11. What the person picked, and what the store says it is made of. The\n * list itself is generated from `custom.parity_field_types()`; this is its type.\n */\nexport interface ParityFieldTypeDescriptor {\n  parity_type: ParityFieldType;\n  behavior: FieldBehavior;\n  made_of: string;\n}\n\n/** AGT-8 / AGT-4. What an agent (or a person) proposes when a Field is missing. */\nexport interface FieldProposal {\n  table_id: Uuid;\n  key: string;\n  label: string;\n  type: FieldBehavior;\n  multi?: boolean;\n  required?: boolean;\n  config?: Record<string, unknown>;\n  relation_target?: Uuid;\n  /** Why this Field should exist — what an approver reads before approving. */\n  because: string;\n}\n\n/** AGT-8. What a table proposal looks like, same shape of question. */\nexport interface TableProposal {\n  name: string;\n  slug: string;\n  title_field: string;\n  fields: Array<Omit<FieldProposal, \"table_id\" | \"because\">>;\n  because: string;\n}\n\n/**\n * WHAT A PERSON SAYS WHEN THEY ADD A COLUMN — the argument of\n * `custom.field_declare`, and deliberately NOT a `Field`.\n *\n * A `Field` is what the store STORES: a behavior from a closed set of five,\n * modifiers beside it, a format, a unit, a relation target, a relation maximum,\n * an on-delete word, a compute_on, and the attached Rules that make a format\n * enforceable. A person adding a column knows none of that. They know they want\n * a date, or a person, or a list with these three choices in it.\n *\n * Every client that tried to bridge that gap itself got it wrong — the field\n * panel picked \"Person\" and the store read a Formula — so the bridge is the\n * STORE's, once, and this is the shape it takes.\n */\nexport interface NewFieldDeclaration {\n  /** What a person reads on the column. The only thing that is always required. */\n  label: string;\n  /** One of the thirteen. Absent means one of the three plain behaviors below. */\n  parity_type?: ParityFieldType;\n  /** Plain text, a long text or a plain number — the three that carry no parity type. */\n  plain?: \"text\" | \"long_text\" | \"number\";\n  /**\n   * THE ONE WORD EVERY OTHER CALLER REACHES FOR. An agent, a script, an import\n   * and this package's own table-declaring path all say `type`, and until\n   * 2026-09-20 `custom._field_document_for` threw it away — a `number` became a\n   * text column in silence. It now resolves all three vocabularies, so this is\n   * named here rather than left as a shape only the store knows about.\n   */\n  type?: FieldTypeWord;\n  /** Derived from the label when absent, which is why the panel never asks for it. */\n  key?: string;\n  /** T8 / CD-CORE-15. The record types this column applies to (its table's type field's choices). Absent: every record. */\n  applies_to_types?: string[];\n  required?: boolean;\n  multi?: boolean;\n  dated?: boolean;\n  sort?: number;\n  sensitivity?: FieldSensitivity;\n  context_policy?: ContextPolicy;\n  rules?: FieldRule[];\n  /** DEFECTS 7: `true` is the plain way to say `rules: [{ kind: \"unique\" }]`; the store adds the rule once. */\n  unique?: boolean;\n  /** A choice list's choices, as words. The store keeps them as a Table (FLD-5 / FLD-6). */\n  options?: string[];\n  /** …or the Table they already come from, when a person picked an existing list. */\n  options_table_id?: Uuid;\n  /** The currency symbol or code a currency field's numbers are in (FLD-N-1). */\n  unit?: string;\n  /** A date field: a day, or a day and a time. */\n  kind?: \"date\" | \"datetime\";\n  /** A lookup or a rollup: the key of the relation Field on THIS table it travels along. */\n  via?: string;\n  /** A lookup: the key of the value it reads on the far side. */\n  pick?: string;\n  /** A rollup: what it works out, and of which far-side field (`count` needs none). */\n  agg?:\n    | \"sum\" | \"count\" | \"min\" | \"max\" | \"avg\"\n    | \"countall\" | \"counta\" | \"and\" | \"or\" | \"xor\" | \"arrayjoin\" | \"concatenate\" | \"arrayunique\" | \"arraycompact\";\n  of?: string;\n  /**\n   * A rollup: WHICH linked records it adds up (CHAIR-MATH b, 2026-10-03). The same shape a saved\n   * view's `filters` carries, written against the far table — a flat map of far-side column keys\n   * (`{ status: \"open\" }`, choice columns by their words, windows as a view writes them) or a Rule\n   * expression over far-side field IDs (`{ op: \"eq\", args: [{ field: \"<id>\" }, { const: false }] }`).\n   * The store validates it against the far table on declare and update; absent or `null` means\n   * every linked record. Kept in `config.filter`.\n   */\n  filter?: Record<string, unknown> | null;\n  /** A formula: the expression, in the same shape a Rule uses (REC-15). */\n  expr?: Record<string, unknown>;\n  /**\n   * A formula IN THE LANGUAGE A PERSON TYPES — `{Visit fee} - {Deposit taken}` (GRID-PRIMITIVES\n   * G3). The store parses it (`custom.formula_parse`), keeps the text in `config.formula_text`\n   * and the expression it parses to in `config.expr`; send this OR `expr`, never both.\n   */\n  formula_text?: string;\n  /**\n   * LANE SC-R — an `entity_reference` column's kinds: the platform entity tokens it may point at\n   * (`note`, `site`, `agent` …), kept by the store in `config.allowed_types`.\n   */\n  allowed_types?: string[];\n  compute_on?: ComputeOn;\n  relation_max?: number;\n  /**\n   * REL / FLD-11. The Table this column points at, when it is neither a Person\n   * (`member`) nor a File (`attachment`). The store has taken it since\n   * 2026-09-20 and no client type named it, so a person with an Invoice table\n   * and a Line table could not declare the link through this package at all.\n   */\n  relation_target?: Uuid;\n  /** REL-2. What happens to this record when the thing it points at goes. */\n  on_target_delete?: OnDelete;\n  /**\n   * REL-DISP. Which of the target's columns this one shows, and what joins them.\n   * A bare column name and a plain list are both accepted by the door and\n   * normalized; leaving it out keeps the target Table's own reference column.\n   */\n  display?: RelationDisplay | string[] | string;\n  /**\n   * Presentation and behavior settings the store carries verbatim — a long\n   * text's `multiline`, a list's existing options table. The door has always\n   * read it (`p_spec -> 'config'`) and this interface never offered it, so a\n   * package-owned table could not declare its own multi-line column.\n   */\n  config?: Record<string, unknown>;\n  /** A text column that holds a signature (`custom.doc_sign` accepts no other). */\n  format?: string;\n  /**\n   * STORE-RULE-GAPS (the older grid's `allowOther`). A choice list only: a value\n   * that is none of the choices is ADDED to the list as typed instead of\n   * refused. Stored as `config.allow_other`; absent means off.\n   */\n  allow_other?: boolean;\n  /** LANE 10 P4 — a rating's top star, 1 to 10 (5 when absent); the store keeps it as a max Rule. */\n  max?: number;\n  /** LANE 10 P4 — a status's groups: choice words → `todo`, `in_progress` or `done`. */\n  status_groups?: Record<string, \"todo\" | \"in_progress\" | \"done\">;\n  /** LANE 10 P4 — a barcode's symbology, one of `BARCODE_SYMBOLOGIES`; absent takes any code. */\n  symbology?: string;\n}\n\n/**\n * Every word `custom._field_document_for` resolves for `type`: any parity type\n * in `PARITY_FIELD_TYPES`, any behavior those types are made of, or one of the\n * plain synonyms a person or an agent actually writes. No count is written down\n * here on purpose — the parity floor is regenerated from\n * `custom.parity_field_types()` and grew from thirteen to fourteen the day\n * `checkbox` landed, which is how the store's own refusals came to name a list\n * that no longer matched it.\n */\nexport type FieldTypeWord =\n  // THE ONE REGISTRY (FIX-10B-F6). Every kind `custom.field_kinds()` publishes: the parity\n  // floor plus plain text, long text, number, a person-aimed relation and a signature. This\n  // union named only the parity floor and three plain synonyms, so `signature` — the one\n  // shape `custom.doc_sign` accepts — was not a word any typed caller could send, which is\n  // half of why no screen offered it.\n  | DeclarableFieldKind\n  | FieldBehavior\n  | \"number\"\n  | \"integer\"\n  | \"decimal\"\n  | \"float\"\n  | \"long_text\"\n  | \"string\"\n  // GRID-PRIMITIVES G5: the store's own stamps, each made a formula Field over its system node\n  // (`fx.autonumber`, `fx.created_time`, `fx.modified_time`). `custom.field_kinds()` does not\n  // publish them (each is a formula, not a behaviour), but `custom.field_declare` takes the word.\n  | \"autonumber\"\n  | \"created_time\"\n  | \"modified_time\"\n  // LANE SC-R: a column that points at a platform thing; published by `custom.field_kinds()` once\n  // the chair's apply lands, and named here so a typed caller can send it before that generate.\n  | \"entity_reference\"\n  // LANE 10 P4: the nine newer kinds (`newerKinds.ts`), the same way.\n  | NewerFieldKind;\n\n/**\n * What `custom.field_update` accepts.\n *\n * THE SETTINGS **AND** THE BEHAVIOR. The door has had a behavior arm since\n * T12 — say `parity_type`, `plain` or `type` and every value of the column is\n * converted (or kept in `_retired` with its reason) by\n * `custom._field_type_converts_values`. This interface named only the settings,\n * so the one client that needed to move a field back onto the behavior it is\n * written against had no door and reached for `custom.record_update` instead,\n * which writes the document under the guards rather than through them.\n */\n/** One existing choice of a list, re-worded in place (`FieldPatch.options`). */\nexport interface FieldOptionEdit {\n  /** The option record's id, as `fieldOptions` answers it. */\n  id: string;\n  /** What the choice reads as from now on. */\n  words: string;\n}\n\nexport interface FieldPatch {\n  label?: string;\n  /** T8 / CD-CORE-15. The record types this column applies to; `[]` makes it apply to every record. */\n  applies_to_types?: string[];\n  required?: boolean;\n  dated?: boolean;\n  sort?: number;\n  sensitivity?: FieldSensitivity;\n  context_policy?: ContextPolicy;\n  unit?: string;\n  rules?: FieldRule[];\n  /**\n   * The choices of a choice list, rewritten, IN ORDER (lane CHOICE-COLUMN-EDIT, 2026-09-27).\n   *\n   * Each entry is either `{ id, words }` — `id` is the option record's id as `fieldOptions`\n   * answers it — which RE-WORDS that choice in place (its key never changes, so every cell\n   * holding it now reads the new words), or plain words: the live choice with the same words\n   * (any case), else a retired one brought back, else a new choice. Every choice takes the\n   * position it has in this array. A live choice the array does not name is RETIRED (never\n   * deleted): cells holding it keep it and read as its words. All in one transaction.\n   */\n  options?: Array<string | FieldOptionEdit>;\n  /**\n   * Words ADDED to a choice list's choices without touching the others: a live same-words\n   * choice adds nothing, a retired one is brought back, the rest are appended. Refused by name\n   * beside `type` / `parity_type` / `plain`.\n   */\n  options_add?: string[];\n  /** One of the thirteen — a change of what this column HOLDS, not of a setting. */\n  parity_type?: ParityFieldType;\n  /** …or one of the three plain behaviors, …*/\n  plain?: \"text\" | \"long_text\" | \"number\";\n  /** …or the one word every other caller reaches for (see `NewFieldDeclaration`). */\n  type?: FieldTypeWord;\n  /**\n   * FLD-2. The shape of the value — one, or several.\n   *\n   * This comment used to say that a patch moving `multi` ALONE changed nothing\n   * and that the behavior word had to be sent with it. That was true, and it\n   * was a description of a silent failure rather than a contract: the door\n   * answered \"saved\" and the column still held one. `custom.field_update` has\n   * had a real settings arm for it since 2026-09-20 (matrx-frontend\n   * `migrations/campaign/fix7b_field_multi_arm.sql`), which also moves a\n   * relation's `relation_max` beside it — `custom.validate_values` counts links\n   * against that number, so moving `multi` without it would tick a box and\n   * still refuse the second record.\n   *\n   * A CHOICE LIST IS THE ONE EXCEPTION, and it is refused by name rather than\n   * ignored: for `select` / `multi_select`, \"one answer or several\" IS the\n   * parity type, so send the type instead.\n   */\n  multi?: boolean;\n  /** REL / FLD-11: re-point the column. The old edges are withdrawn by the door. */\n  relation_target?: Uuid;\n  on_target_delete?: OnDelete;\n  /**\n   * REL-DISP. Which of the target's columns this one shows. `null` REMOVES the\n   * spec and the column goes back to whatever the table it points at is titled by;\n   * the door refuses it by name on a column that points at nothing.\n   */\n  display?: RelationDisplay | string[] | string | null;\n  /** SEAT-SUITES: whether the store builds an index for this column, and a unique one. */\n  promoted?: boolean;\n  unique?: boolean;\n  /**\n   * STORE-RULE-GAPS. A choice list's \"other values allowed\" setting — see\n   * `NewFieldDeclaration.allow_other`. Refused by name on any other column; a\n   * retype that stays a list keeps it.\n   */\n  allow_other?: boolean;\n  /** LANE 10 P4 — a status's groups, changed in place: choice words or keys → `todo` | `in_progress` | `done`. */\n  status_groups?: Record<string, \"todo\" | \"in_progress\" | \"done\">;\n  /** LANE 10 P4 — a barcode's symbology; null takes any code again. */\n  symbology?: string | null;\n  /** LANE 10 P4 round 3 — a rating's new top star, 1 to 10; scores above it are set aside in `_retired`. */\n  max?: number;\n  /** NOTION-PROPS-3 — a button column's settings, whole (`config.button`); refused on any other column. */\n  button?: import(\"./button\").ButtonSettings;\n  /** NOTION-PROPS-3 — a link to its own table says one record waits on another (a timeline draws it). */\n  dependency?: boolean;\n  /** W2-A 4 — a Last changed time column watches only these field keys (`config.only_fields`); null = the whole record. */\n  only_fields?: string[] | null;\n  /** NOTION-PROPS-3 — a one-record link to its own table names each record's parent: the table nests sub-items. */\n  sub_items?: boolean;\n  /** CLOSE-LINK (CD-LINK-03) — a link's picker offers only this saved view's records (`config.limit_to_view`); null takes it off. */\n  limit_to_view?: string | null;\n  /** CLOSE-LINK (CD-LINK-05) — a link follows the linked record (`live`, the default) or keeps a copy of it from when it was linked (`snapshot`, `config.binding`); turning snapshot on takes a copy for every link already there. */\n  binding?: \"live\" | \"snapshot\";\n  /** CLOSE-LINK (CD-LINK-08) — a link carries access: whoever can see a linked record can see this one (`config.carries`), at most at `carries_max`. */\n  carries?: boolean;\n  /** CLOSE-LINK (CD-LINK-08) — the most a carrying link conveys: `viewer` (the default) or `editor`. */\n  carries_max?: \"viewer\" | \"editor\";\n  /** CLOSE-LINK (CD-LINK-09) — two records may point at each other along this link (`config.loops`). */\n  loops?: boolean;\n  /** CLOSE-LINK (CD-LINK-04) — the other tables a link also points at (`config.target_tables`, its own table always first); null or [] = only its own table. */\n  target_tables?: readonly string[] | null;\n  /** §D / T7: which fields a worked-out column reads. */\n  depends_on?: Uuid[];\n  /**\n   * A rollup: WHICH linked records it adds up — the same shape as `NewFieldDeclaration.filter`\n   * (a saved view's filter written against the far table). `null` removes it, and the rollup adds\n   * up every linked record again. `custom.field_update` validates it against the far table.\n   */\n  filter?: Record<string, unknown> | null;\n  /**\n   * FLD-9. WHEN a worked-out column works its answer out: when somebody reads the record,\n   * or when somebody saves it.\n   *\n   * This door accepted the word, answered success and threw it away until 2026-09-21\n   * (matrx-frontend `migrations/campaign/tails2_a_formula_says_when_it_works_itself_out.sql`)\n   * — its spec builder used a fixed key list that did not carry it, so a person declaring a\n   * write-stamped formula through this door silently got a read-time one. It is applied now,\n   * in both arms, and the records already saved are brought with it.\n   *\n   * TWO THINGS IT REFUSES BY NAME rather than forcing quietly: a column that is not worked\n   * out by the store has no moment to be worked out at, and a ROLL-UP adds up OTHER records,\n   * so an answer stamped when this record was last saved would be wrong the moment one of\n   * them changed — a roll-up is always `read`.\n   */\n  compute_on?: ComputeOn;\n  /**\n   * FLD-11 / REC-15. RE-AIMING A WORKED-OUT COLUMN: the expression, in the same\n   * shape a Rule uses and read by the same evaluator — `{\"op\":\"concat\",\"args\":\n   * [{\"field\":\"note\"}]}`. Every `{\"field\": …}` in it names a live Field of this\n   * organization, or `custom._field_document_for` refuses the whole patch by\n   * name and writes nothing.\n   *\n   * `custom.field_update` carries this in its BEHAVIOR arm — the arm a type\n   * word opens — so send it WITH the word for what the column is\n   * (`type: \"formula\"`, or `parity_type` / `plain`). The door's spec builder\n   * reads `coalesce(p_patch -> 'expr', v_old -> 'config' -> 'expr')`, so a\n   * re-type that does not carry one deliberately keeps the expression the\n   * column already had; the settings arm has no `expr` key at all, so `expr`\n   * alone is not a change this door makes. `STORE-TAILS-2` asked for the field\n   * because the one client that needed to re-aim an existing formula had no\n   * typed way to say it and reached for `custom.record_update`, which writes the\n   * Field document under the guards rather than through them.\n   */\n  expr?: Record<string, unknown>;\n  /**\n   * RE-AIMING A FORMULA IN THE LANGUAGE A PERSON TYPES (GRID-PRIMITIVES G3). Same arm as\n   * `expr` — send it with `type: \"formula\"`; the store parses it and keeps both the text and\n   * the expression. Measured on the dev clone 2026-09-23: `{\"type\":\"formula\",\"formula_text\":\n   * \"{Visit fee} * 2\"}` re-aims the column and keeps its other settings.\n   */\n  formula_text?: string;\n}\n\n/**\n * Whether a choice column takes values that are not one of its choices\n * (`config.allow_other`, STORE-RULE-GAPS). Off unless the column says so.\n */\nexport function allowsOtherValues(field: Pick<Field, \"type\" | \"config\">): boolean {\n  return field.type === \"list\" && field.config?.[\"allow_other\"] === true;\n}\n\n/**\n * What `custom.field_duplicate` answers (DUPLICATE PROPERTY, Notion N5): the copy's id, key and name, and\n * how many records had a value copied into it. `values` is `not_a_value` for a link, formula, lookup or\n * roll-up column, whose copy holds no document values of its own.\n */\nexport interface FieldDuplicated {\n  field_id: string;\n  key: string;\n  label: string;\n  values_copied: number;\n  values: \"copied\" | \"not_a_value\";\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/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","// 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/retype.ts — @ai-matrx/records\n//\n// CHANGING WHAT A COLUMN HOLDS (FLD-4 / T12; merged-grid review 2, 2026-09-27, C3).\n//\n// `custom.migrate_retype` changes a Field's behavior word and the store's own trigger converts\n// every value already written: what converts is converted, what does not is kept in that record's\n// `_retired` with its reason — neither coerced nor deleted. A person deciding whether to do that\n// deserves the honest count BEFORE it happens (Airtable's \"N cells will be cleared\" warning,\n// bettered: nothing is cleared here, it is kept aside). The store's conversion is\n// `custom.field_value_convert(p_to, p_value)`, which is not reachable from a client, so this is\n// its MIRROR — the same rules, word for word, used only to say what will happen. The store still\n// decides, and its own answer (`FieldRetyped`) is what the screen reports afterwards.\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n/** The store's behavior words a column can be changed to. */\nexport type RetypeBehaviour = \"text\" | \"range\" | \"boolean\";\n\n/** `custom.migrate_retype`'s answer for a Field. */\nexport interface FieldRetyped {\n  verb: \"retype\";\n  field_id: string;\n  was: string | null;\n  now: string;\n  changed: boolean;\n  migration_id?: string;\n  /** Records that hold a value for this column after the change. */\n  records_still_holding_a_value?: number;\n  /** Values of this column now kept aside in `_retired`, with their reason. */\n  values_in_retired_for_this_field?: number;\n  at?: string;\n}\n\n/**\n * `custom.field_retype_preview`'s answer: what a change of a column's kind WILL do, counted by the store\n * running the change itself in a subtransaction it rolls back (lane F2, D11). It cannot disagree with the\n * change, because it is the change.\n */\nexport interface FieldRetypePreview {\n  /** Records holding a value before the change. */\n  held_before: number;\n  /** Records still holding a value after it (converted, or already fitting). Null when `limited`. */\n  converts: number | null;\n  /** Values the change keeps aside in `_retired`, with their reason. Null when `limited`. */\n  kept_aside: number | null;\n  /**\n   * The column holds too many values to run the change ahead of time without holding the table (ADV-1 F8),\n   * or another editor held it. No counts then; `held_before` is still the number of values held.\n   */\n  limited?: boolean;\n  /** Why it is limited: \"large\" (too many values) or \"busy\" (another editor holds the table). */\n  why?: string;\n  /** Up to five of the values kept aside, as words. */\n  examples: string[];\n  /** Choices the change makes from the column's words (a change to Choice or Multi-choice). */\n  choices_added: number;\n}\n\n/**\n * `custom.migrate_merge`'s answer (T5 / REC-21): the other record merged into the survivor. Its\n * values the survivor did not hold moved across; the ones that differed are kept as ranked\n * alternates with their source (or in `_retired` when the key is not a declared field); every\n * link and child pointing at it now points at the survivor; it is archived and its id resolves to\n * the survivor. `migration_id` is what `migrateUndo` takes.\n */\nexport interface RecordsMerged {\n  verb: \"merge\";\n  winner: string;\n  loser: string;\n  migration_id: string;\n  values_taken: number;\n  values_copied: number;\n  alternates_added: number;\n  values_retired: number;\n  relations_retargeted: number;\n  relations_detached_as_duplicates: number;\n  resolves_to?: string | null;\n  at?: string;\n}\n\n/** `custom.migrate_split`'s answer. The original keeps its id; the moved values live on `new_record`. */\nexport interface RecordSplit {\n  verb: \"split\";\n  kept_the_id: string;\n  new_record: string;\n  migration_id: string;\n  moved: string[];\n  old_id_resolves_to?: string | null;\n  at?: string;\n}\n\n/** `custom.migrate_extract_parent`'s answer. The named values were COPIED up into `parent`, and the record now sits under it. */\nexport interface ParentExtracted {\n  verb: \"extract_parent\";\n  record_id: string;\n  parent: string;\n  was_under: string | null;\n  migration_id: string;\n  at?: string;\n}\n\n/**\n * `custom.migrate_retype`'s answer for a RECORD (test 9 / REC-N-18): the record moved to another table of\n * the same organization and KEPT ITS ID, so every link to it still resolves. The values whose column the\n * new table lacks are `misfits`: taken off the record and kept in History on `migration_id`, with the\n * reason — neither coerced nor deleted. `migrateUndo(migration_id)` puts the record back on its table\n * with every value it held.\n */\nexport interface RecordMoved {\n  verb: \"retype\";\n  record_id: string;\n  kept_the_id: boolean;\n  from_table: string;\n  to_table: string;\n  migration_id: string;\n  /** The values that did not fit, by key, exactly as they were. */\n  misfits: Record<string, unknown>;\n  misfits_are?: string;\n  at?: string;\n}\n\n/** One row of `custom.migrations`: a recorded Migration on one target, and whether it was put back. */\n/** `custom.history_retention`'s answer: the organization's floor and (when asked) one table's days. */\nexport interface HistoryRetention {\n  organization_id: string;\n  table_id: string | null;\n  floor_days: number;\n  table_days: number | null;\n  /** The store's own sentence. */\n  says: string;\n}\n\nexport interface MigrationEntry {\n  id: string;\n  verb: string;\n  target_kind: string;\n  target_id: string;\n  note: string | null;\n  applied_at: string;\n  applied_by: string | null;\n  undone_at: string | null;\n}\n\n/** `custom.migrate_undo`'s answer: the Migration it put back. */\nexport interface MigrationUndone {\n  undone: string;\n  verb: string;\n  kind: string;\n  record_id: string | null;\n  version_after?: number | null;\n  also_restored?: number;\n  ids_unaliased?: number;\n  /** A split or an extracted parent: the record the Migration made, archived by the undo. */\n  removed?: string | null;\n  at?: string;\n}\n\nconst TRUE_WORDS = new Set([\"true\", \"t\", \"yes\", \"y\", \"1\", \"on\", \"x\", \"✓\", \"✔\"]);\nconst FALSE_WORDS = new Set([\"false\", \"f\", \"no\", \"n\", \"0\", \"off\", \"☐\"]);\n\n/**\n * THE MIRROR OF `custom.field_value_convert`: does `value` survive the change to `to` (the\n * behavior word, and for `range` the kind — `number`, `date`, `datetime`)? An absence always\n * survives; a list survives only when every member does.\n */\nexport function valueConverts(to: { type: string; kind?: string | null }, value: unknown): boolean {\n  if (value === null || value === undefined) return true;\n  if (Array.isArray(value)) return value.every((v) => valueConverts(to, v));\n  if (typeof value === \"object\") return false;\n  const text = String(value);\n  const kind = to.kind ?? \"number\";\n  switch (to.type) {\n    case \"boolean\":\n      if (typeof value === \"boolean\") return true;\n      return TRUE_WORDS.has(text.trim().toLowerCase()) || FALSE_WORDS.has(text.trim().toLowerCase());\n    case \"text\":\n      return true;\n    case \"range\":\n      if (kind === \"date\" || kind === \"datetime\") return typeof value === \"string\" && !Number.isNaN(Date.parse(text));\n      if (typeof value === \"number\") return true;\n      return text.trim() !== \"\" && /^[+-]?(\\d+\\.?\\d*|\\.\\d+)(e[+-]?\\d+)?$/i.test(text.trim());\n    case \"list\":\n    case \"relation\":\n      return typeof value === \"string\" && isUuidShape(text);\n    default:\n      return false;\n  }\n}\n\n/** What a retype will do to the values already written, counted before anything is changed. */\nexport interface RetypePreview {\n  /** Records holding a value that will be converted and stay in the column. */\n  converts: number;\n  /** Records holding a value that will be kept aside (in `_retired`, with the reason). */\n  keptAside: number;\n  /** Up to five of the values that will be kept aside, to show the person. */\n  examples: string[];\n  /** The count covers only the groups the store answered (a ceiling was reached). */\n  partial: boolean;\n}\n\n/** Count a column's distinct values (value → how many records hold it) against the change. */\nexport function previewRetype(\n  to: { type: string; kind?: string | null },\n  groups: ReadonlyArray<{ value: unknown; count: number }>,\n  partial = false,\n): RetypePreview {\n  let converts = 0;\n  let keptAside = 0;\n  const examples: string[] = [];\n  for (const group of groups) {\n    if (group.value === null || group.value === undefined || group.value === \"\") continue;\n    if (valueConverts(to, group.value)) converts += group.count;\n    else {\n      keptAside += group.count;\n      if (examples.length < 5) examples.push(Array.isArray(group.value) ? group.value.join(\", \") : String(group.value));\n    }\n  }\n  return { converts, keptAside, examples, partial };\n}\n\n// ── A RULE THAT TIGHTENS (lane 10 P4c / V13 #4) ─────────────────────────────────────────────\n//\n// Changing a column's checks (a smallest, a largest, a longest, a pattern) or a rating's top star\n// sets aside every value already written that the new checks refuse: `custom.field_update` keeps\n// each one in its record's `_retired` with the reason, in one statement. The person deserves the\n// same honest count a retype gets, BEFORE pressing Save. This is the mirror of the rule branch of\n// `custom.validate_values`, word for word: `min` / `max` judge numbers only, `length` judges text\n// only (an empty text is a blank, never \"too short\"), `pattern` is the store's unanchored regex\n// match. Rules that need other columns or other records (`equals_field`, `differs_from_field`,\n// `unique`) are never judged against values already written, so they set nothing aside.\n\n/** The checks the mirror can judge on one value. */\ntype JudgedRule = { kind: string; value?: string | number | undefined; min?: number | undefined };\n\n/** The first check `value` fails, or null when every check keeps it. An absence always passes. */\nexport function ruleThatRefuses(rules: ReadonlyArray<JudgedRule>, value: unknown): JudgedRule | null {\n  if (value === null || value === undefined) return null;\n  if (Array.isArray(value)) {\n    for (const member of value) {\n      const failed = ruleThatRefuses(rules, member);\n      if (failed) return failed;\n    }\n    return null;\n  }\n  for (const rule of rules) {\n    const bound = typeof rule.value === \"number\" ? rule.value : rule.value === undefined || rule.value === \"\" ? NaN : Number(rule.value);\n    if (rule.kind === \"min\" && typeof value === \"number\" && Number.isFinite(bound) && value < bound) return rule;\n    if (rule.kind === \"max\" && typeof value === \"number\" && Number.isFinite(bound) && value > bound) return rule;\n    if (rule.kind === \"length\" && typeof value === \"string\") {\n      const chars = Array.from(value).length;\n      if (Number.isInteger(bound) && chars > bound) return rule;\n      if (typeof rule.min === \"number\" && value !== \"\" && chars < rule.min) return rule;\n    }\n    if (rule.kind === \"pattern\" && typeof value === \"string\" && typeof rule.value === \"string\" && rule.value !== \"\") {\n      let pattern: RegExp | null = null;\n      try {\n        pattern = new RegExp(rule.value, \"u\");\n      } catch {\n        pattern = null; // A pattern JavaScript cannot read is the store's to judge; it is not guessed here.\n      }\n      if (pattern && !pattern.test(value)) return rule;\n    }\n  }\n  return null;\n}\n\n/** A rating's checks with its top star as the `max` (the store writes the top star as that Rule). */\nexport function rulesWithTopStar<R extends JudgedRule>(rules: ReadonlyArray<R>, topStar: number): Array<R | { kind: \"max\"; value: number }> {\n  return [...rules.filter((r) => r.kind !== \"max\"), { kind: \"max\" as const, value: topStar }];\n}\n\n/** What new checks will do to the values already written, counted before anything is saved. */\nexport function previewRuleChange(\n  rules: ReadonlyArray<JudgedRule>,\n  groups: ReadonlyArray<{ value: unknown; count: number }>,\n  partial = false,\n): RetypePreview {\n  let converts = 0;\n  let keptAside = 0;\n  const examples: string[] = [];\n  for (const group of groups) {\n    if (group.value === null || group.value === undefined || group.value === \"\") continue;\n    if (ruleThatRefuses(rules, group.value) === null) converts += group.count;\n    else {\n      keptAside += group.count;\n      if (examples.length < 5) examples.push(Array.isArray(group.value) ? group.value.join(\", \") : String(group.value));\n    }\n  }\n  return { converts, keptAside, examples, partial };\n}\n","// src/button.ts — @ai-matrx/records\n//\n// A BUTTON COLUMN (lanes NOTION-PROPS-2/3; champions: Notion's and Airtable's Button). The store keeps it as\n// behavior text wearing the format `button`; it holds no value, and `config.button` says what a press does\n// through `custom.button_press`:\n//\n//   open_url        answers `url` with every {{field id}} filled from the row; the screen opens it\n//   run_action      one of the table's row actions on this row (which is how a button sets fields)\n//   run_automation  one of the table's automations on this row, for an editor of the row\n//\n// A button with no `do` (what Notion's importer brings — Notion's API hides a button's steps) is a label\n// only, and a press is refused by name. Its settings change through `custom.field_update`'s `button` key.\n\nimport type { CoercibleField } from \"./coerce\";\nimport type { Uuid } from \"./record\";\n\nexport const BUTTON_DOES = [\"open_url\", \"run_action\", \"run_automation\", \"add_row\"] as const;\nexport type ButtonDoes = (typeof BUTTON_DOES)[number];\n\n/** What `config.button` holds. */\nexport interface ButtonSettings {\n  label: string;\n  /** One of the table's color names (blue, green, …); absent, the button wears the neutral look. */\n  color?: string | undefined;\n  /** Absent: nothing is set up yet, and a press says so. */\n  do?: ButtonDoes | undefined;\n  url?: string | undefined;\n  action_id?: Uuid | undefined;\n  automation_id?: Uuid | undefined;\n  /** W2-A `add_row`: the table the new row goes in; absent = this table. */\n  table_id?: Uuid | undefined;\n  /** W2-A `add_row`: the new row's field key → this row's field key, or \"@row\" for this row's id (a link back). */\n  prefill?: Record<string, string> | undefined;\n  /** TEMPLATE-GAPS R3 `add_row`: the target table's row template the new row starts from (its values under prefill). */\n  template_id?: Uuid | undefined;\n}\n\n/** What `custom.button_press` answers. */\nexport type ButtonPressed =\n  | { do: \"open_url\"; label: string; url: string }\n  /** W2-A: the row the press added (through custom.record_write), for the screen to open. */\n  | { do: \"add_row\"; label: string; table_id: Uuid; record_id: Uuid; template_id?: Uuid }\n  | { do: \"run_action\"; label: string; result: { ran?: number; records?: Array<{ record_id: Uuid; version: number }> } & Record<string, unknown> }\n  | {\n      do: \"run_automation\";\n      label: string;\n      /** null when no automation this button starts met its conditions (status \"skipped\"). */\n      run_id: Uuid | null;\n      automation: string | null;\n      status: string | null;\n      says: string | null;\n      /** AUTOMATIONS-AIRTABLE: every automation whose trigger is this button, as each ran on the press. */\n      runs?: Array<{ run_id: Uuid; automation: string | null; status: string | null; says: string | null }>;\n    };\n\n/** Whether a Field is a button column — `custom.field_kind_of`'s mirror for this one kind. */\nexport function isButtonField(field: CoercibleField | null | undefined): boolean {\n  return field?.type === \"text\" && String(field.format ?? \"\") === \"button\";\n}\n\n/** A button column's settings, read off its declaration; null for any other column. */\nexport function buttonOf(field: (CoercibleField & { label?: string | null }) | null | undefined): ButtonSettings | null {\n  if (!field || !isButtonField(field)) return null;\n  const raw = ((field.config ?? {}) as Record<string, unknown>)[\"button\"];\n  const b = raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : {};\n  const text = (v: unknown) => (typeof v === \"string\" && v.trim() !== \"\" ? v.trim() : undefined);\n  const does = text(b[\"do\"]);\n  return {\n    label: text(b[\"label\"]) ?? text(field.label) ?? \"Button\",\n    color: text(b[\"color\"]),\n    do: (BUTTON_DOES as readonly string[]).includes(does ?? \"\") ? (does as ButtonDoes) : undefined,\n    url: text(b[\"url\"]),\n    action_id: text(b[\"action_id\"]) as Uuid | undefined,\n    automation_id: text(b[\"automation_id\"]) as Uuid | undefined,\n    table_id: text(b[\"table_id\"]) as Uuid | undefined,\n    prefill: b[\"prefill\"] && typeof b[\"prefill\"] === \"object\" && !Array.isArray(b[\"prefill\"]) ? (b[\"prefill\"] as Record<string, string>) : undefined,\n    template_id: text(b[\"template_id\"]) as Uuid | undefined,\n  };\n}\n\n/** The `{{field id}}` placeholders a link names, in order — so a settings screen can show them as names. */\nexport function buttonUrlPlaceholders(url: string): string[] {\n  return Array.from(url.matchAll(/\\{\\{([^{}]+)\\}\\}/g), (m) => m[1]!.trim());\n}\n\n/**\n * What a button's settings are missing before a press can work, in words; null when it is set up.\n * The store refuses the same cases (`custom._field_kind_shape_ok`, `custom.button_press`).\n */\nexport function buttonNeeds(b: ButtonSettings): string | null {\n  if (!b.do) return `${b.label} has nothing set up to do yet.`;\n  if (b.do === \"open_url\" && !/^(https?:\\/\\/|mailto:|tel:|\\{\\{)/i.test(b.url ?? \"\")) return `${b.label} needs a link that starts with https://.`;\n  if (b.do === \"run_action\" && !b.action_id) return `${b.label} needs a row action to run.`;\n  if (b.do === \"run_automation\" && !b.automation_id) return `${b.label} needs an automation to run.`;\n  return null;\n}\n","// src/newerKinds.ts — @ai-matrx/records\n//\n// THE NINE NEWER KINDS OF COLUMN (lane 10 VIEWS-AND-FIELDS, sublane P4; champions: Airtable's and\n// SmartSuite's field types). The store keeps each as an EXISTING behavior wearing a format —\n// FLD-1's six behaviors stay six — and `custom.field_kind_of` reads each back. This file is the\n// client's mirror of that one reader, plus the few words each kind needs wherever only words fit\n// (a card, an export cell, a typed answer):\n//\n//   kind         behavior  format     value\n//   rating       range      rating     whole number 0..max (max Rule 1–10, default 5)\n//   duration     range      duration   seconds (unit \"seconds\"), never below zero\n//   created_by   formula    —          {id, name}; config.system created_by, worked out on read\n//   modified_by  formula    —          {id, name}; config.system modified_by, worked out on read\n//   status       list       status     the choice's key; config.status_groups key → todo | in_progress | done\n//   address      text       address    {street, city, region, postal_code, country}\n//   barcode      text       barcode    one printable line; config.symbology optional\n//   rich_text    text       rich_text  Markdown, no raw HTML\n//   count        formula    count      how many linked records (a roll-up whose agg is count)\n//\n// `fieldKindFor` (coerce.ts) still answers the BASE kind — a rating is a number, a status a\n// select, a count a roll-up — because every editor, sort and aggregate keyed on those keeps\n// working for them. What is particular to each newer kind asks `newerKindOf` here.\n\nimport { formatDurationSeconds } from \"@ai-matrx/kit/format\";\nimport type { CoercibleField } from \"./coerce\";\n\nexport const NEWER_FIELD_KINDS = [\n  \"rating\",\n  \"duration\",\n  \"created_by\",\n  \"modified_by\",\n  \"status\",\n  \"address\",\n  \"barcode\",\n  \"rich_text\",\n  \"count\",\n] as const;\n\nexport type NewerFieldKind = (typeof NEWER_FIELD_KINDS)[number];\n\ntype WithRules = CoercibleField & { rules?: ReadonlyArray<{ kind?: string; value?: unknown }> | null };\n\n/** Which of the nine newer kinds a Field is, read off its declaration — `custom.field_kind_of`'s mirror. */\nexport function newerKindOf(field: CoercibleField): NewerFieldKind | null {\n  const format = String(field.format ?? \"\");\n  const config = (field.config ?? {}) as Record<string, unknown>;\n  switch (field.type) {\n    case \"range\":\n      if (format === \"rating\") return \"rating\";\n      if (format === \"duration\") return \"duration\";\n      return null;\n    case \"text\":\n      if (format === \"address\") return \"address\";\n      if (format === \"barcode\") return \"barcode\";\n      if (format === \"rich_text\") return \"rich_text\";\n      return null;\n    case \"list\":\n      return format === \"status\" ? \"status\" : null;\n    case \"formula\":\n      if (format === \"count\" && config[\"agg\"] === \"count\") return \"count\";\n      if (config[\"system\"] === \"created_by\") return \"created_by\";\n      if (config[\"system\"] === \"modified_by\") return \"modified_by\";\n      return null;\n    default:\n      return null;\n  }\n}\n\n// ── RATING ─────────────────────────────────────────────────────────────────────────────────\n\n/** A rating's top star: its max Rule (1–10), else 5 — the store's own default. */\nexport function ratingMaxOf(field: CoercibleField): number {\n  const rules = (field as WithRules).rules ?? [];\n  const max = rules.find((r) => r?.kind === \"max\")?.value;\n  const n = typeof max === \"number\" ? max : typeof max === \"string\" ? Number(max) : NaN;\n  return Number.isInteger(n) && n >= 1 && n <= 10 ? n : 5;\n}\n\n// ── DURATION ───────────────────────────────────────────────────────────────────────────────\n\n/** Seconds as h:mm — and h:mm:ss only when there are seconds to show. 2700 → \"0:45\". */\nexport function durationText(seconds: unknown): string | null {\n  const n = typeof seconds === \"number\" ? seconds : typeof seconds === \"string\" && seconds.trim() !== \"\" ? Number(seconds) : NaN;\n  if (!Number.isFinite(n)) return null;\n  return formatDurationSeconds(Math.round(n), { granularity: \"minute\", signed: true });\n}\n\n/**\n * A length of time as a person types it, in seconds. \"45\" and \"45 min\" are 45 minutes (the column\n * reads in h:mm, so a bare number is minutes, as in Airtable); \"1:30\" is an hour and a half;\n * \"1:30:15\" has seconds; \"1h 30m\", \"2 hours\", \"90s\" read as written. Null: not a length of time.\n */\nexport function readTypedDuration(text: string): number | null {\n  const t = text.trim().toLowerCase();\n  if (t === \"\") return null;\n  const clock = /^(\\d+):([0-5]?\\d)(?::([0-5]?\\d))?$/.exec(t);\n  if (clock) return Number(clock[1]) * 3600 + Number(clock[2]) * 60 + Number(clock[3] ?? 0);\n  if (/^\\d+(\\.\\d+)?$/.test(t)) return Math.round(Number(t) * 60);\n  const unitRe = /(\\d+(?:\\.\\d+)?)\\s*(h|hr|hrs|hour|hours|m|min|mins|minute|minutes|s|sec|secs|second|seconds)\\b/g;\n  let total = 0;\n  let matched = \"\";\n  for (const m of t.matchAll(unitRe)) {\n    const n = Number(m[1]);\n    const u = m[2]!;\n    total += u.startsWith(\"h\") ? n * 3600 : u.startsWith(\"m\") ? n * 60 : n;\n    matched += m[0];\n  }\n  if (matched === \"\" || t.replace(unitRe, \"\").replace(/[\\s,and]+/g, \"\") !== \"\") return null;\n  return Math.round(total);\n}\n\n// ── ADDRESS ────────────────────────────────────────────────────────────────────────────────\n\nexport const ADDRESS_PARTS = [\"street\", \"city\", \"region\", \"postal_code\", \"country\"] as const;\nexport type AddressPart = (typeof ADDRESS_PARTS)[number];\nexport type AddressValue = Partial<Record<AddressPart, string | null>>;\n\nexport function isAddressValue(value: unknown): value is AddressValue {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    && Object.keys(value as object).every((k) => (ADDRESS_PARTS as readonly string[]).includes(k));\n}\n\n/** An address on one line, the way an envelope reads: \"1420 Cedar Ridge Pkwy, Boulder, CO 80301, US\". */\nexport function addressValueText(value: unknown): string | null {\n  if (typeof value === \"string\") return value.trim() === \"\" ? null : value.trim();\n  if (!isAddressValue(value)) return null;\n  const part = (k: AddressPart) => (typeof value[k] === \"string\" ? (value[k] as string).trim() : \"\");\n  const regionLine = [part(\"region\"), part(\"postal_code\")].filter(Boolean).join(\" \");\n  const words = [part(\"street\"), part(\"city\"), regionLine, part(\"country\")].filter(Boolean).join(\", \");\n  return words === \"\" ? null : words;\n}\n\n/**\n * One typed line as an address in parts. \"street, city, region postal, country\" is read into its\n * parts when it has that shape; anything else is kept whole as the street, so nothing typed is lost.\n */\nexport function addressFromText(text: string): AddressValue | null {\n  const t = text.trim();\n  if (t === \"\") return null;\n  const bits = t.split(\",\").map((b) => b.trim()).filter(Boolean);\n  if (bits.length >= 3) {\n    const [street, city, regionPostal, ...rest] = bits;\n    const rp = /^(.*?)\\s*([A-Za-z0-9-]*\\d[A-Za-z0-9 -]*)?$/.exec(regionPostal ?? \"\");\n    const out: AddressValue = { street: street!, city: city! };\n    if (rp?.[1]) out.region = rp[1];\n    if (rp?.[2]) out.postal_code = rp[2].trim();\n    if (rest.length > 0) out.country = rest.join(\", \");\n    return out;\n  }\n  return { street: t };\n}\n\n/** A maps search for an address, opened in a new tab. */\nexport function addressMapUrl(value: unknown): string | null {\n  const words = addressValueText(value);\n  return words ? `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(words)}` : null;\n}\n\n// ── CREATED BY / LAST MODIFIED BY ──────────────────────────────────────────────────────────\n\n/**\n * `{id, name, actor}` as the store works it out (`custom.formula_value`). `actor` is the kind of\n * writer — a person (`user`), an agent (`agent`, with `id`/`name` the person it wrote for) or the\n * platform itself (`system`, with no id and no name). `name` is null for somebody outside the\n * organization. A value written before the store said `actor` is a person's.\n */\nexport type PersonStamp = { id: string | null; name: string | null; actor?: \"user\" | \"agent\" | \"system\" };\n\nexport function isPersonStamp(value: unknown): value is PersonStamp {\n  if (value === null || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const v = value as { id?: unknown; actor?: unknown };\n  return typeof v.id === \"string\" || v.actor === \"system\" || v.actor === \"agent\";\n}\n\n/** The words for who made or changed a record. */\nexport const NOT_A_MEMBER_WORDS = \"Not in this organization\";\nexport const SYSTEM_WRITER_WORDS = \"System\";\nexport const AGENT_WRITER_WORDS = \"Agent\";\nexport function personStampText(value: unknown): string | null {\n  if (!isPersonStamp(value)) return null;\n  const name = value.name && value.name.trim() !== \"\" ? value.name : null;\n  // V11 #6: a system write names the person who set it going, when the store knows who.\n  if (value.actor === \"system\") return name ? `${SYSTEM_WRITER_WORDS} for ${name}` : SYSTEM_WRITER_WORDS;\n  if (value.actor === \"agent\") return name ? `${AGENT_WRITER_WORDS} for ${name}` : AGENT_WRITER_WORDS;\n  return name ?? NOT_A_MEMBER_WORDS;\n}\n\n// ── STATUS ─────────────────────────────────────────────────────────────────────────────────\n\nexport const STATUS_GROUPS = [\"todo\", \"in_progress\", \"done\"] as const;\nexport type StatusGroup = (typeof STATUS_GROUPS)[number];\nexport const STATUS_GROUP_WORDS: Record<StatusGroup, string> = { todo: \"To do\", in_progress: \"In progress\", done: \"Done\" };\n\n/** Which group a status choice sits in; a choice the column names no group for is To do. */\nexport function statusGroupOf(field: CoercibleField, choiceKey: string): StatusGroup {\n  const groups = ((field.config ?? {}) as Record<string, unknown>)[\"status_groups\"];\n  const g = groups && typeof groups === \"object\" ? (groups as Record<string, unknown>)[choiceKey] : undefined;\n  return g === \"in_progress\" || g === \"done\" ? g : \"todo\";\n}\n\n// ── BARCODE ────────────────────────────────────────────────────────────────────────────────\n\nexport const BARCODE_SYMBOLOGIES = [\"code128\", \"code39\", \"ean13\", \"ean8\", \"upc_a\", \"upc_e\", \"itf\", \"qr\", \"data_matrix\", \"pdf417\"] as const;\n\n// ── RICH TEXT ──────────────────────────────────────────────────────────────────────────────\n\n/** Markdown read as plain words on one line — what a card title or a sentence shows. */\nexport function richTextPlain(text: string): string {\n  return text\n    .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, \"$1\")\n    .replace(/(\\*\\*|__|`)/g, \"\")\n    .replace(/(^|\\s)[*_]([^*_\\s][^*_]*)[*_](?=\\s|$|[.,;:!?])/g, \"$1$2\")\n    .replace(/^\\s*(#{1,3}|[-*+]|\\d+[.)])\\s+/gm, \"\")\n    .replace(/\\s*\\n+\\s*/g, \" · \")\n    .trim();\n}\n\n/**\n * A link destination as a browser would follow it: HTML entities and backslash escapes decoded,\n * spaces and control characters removed (`custom._entity_decoded`'s rules). Then only a web page,\n * an email address or a phone number is a link here; everything else is drawn as words.\n */\nexport function safeLinkHref(raw: string): string | null {\n  let t = raw\n    .replace(/&#[xX]([0-9a-fA-F]{1,8});?/g, (_, h: string) => codePoint(parseInt(h, 16)))\n    .replace(/&#([0-9]{1,8});?/g, (_, d: string) => codePoint(parseInt(d, 10)))\n    .replace(/&colon;/g, \":\").replace(/&Tab;/g, \"\\t\").replace(/&NewLine;/g, \"\\n\").replace(/&sol;/g, \"/\")\n    .replace(/&lpar;/g, \"(\").replace(/&rpar;/g, \")\").replace(/&period;/g, \".\").replace(/&nbsp;/g, \" \")\n    .replace(/&lt;/g, \"<\").replace(/&gt;/g, \">\").replace(/&quot;/g, '\"').replace(/&apos;/g, \"'\").replace(/&amp;/g, \"&\")\n    .replace(/\\\\([!-/:-@[-`{-~])/g, \"$1\");\n  t = t.replace(/[\\s\\u0000-\\u001f\\u007f]/g, \"\");\n  return /^(https?:\\/\\/|mailto:|tel:)/i.test(t) ? t : null;\n}\n\nfunction codePoint(n: number): string {\n  return Number.isFinite(n) && n >= 1 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : \"\\ufffd\";\n}\n\n// ── ONE VALUE IN WORDS ─────────────────────────────────────────────────────────────────────\n\n/**\n * The words one value of a newer kind reads as wherever only words fit — an export cell, a card,\n * a sentence. Null: not a newer kind, or nothing particular to say (the caller's own words apply).\n */\nexport function newerKindWords(field: CoercibleField, value: unknown): string | null {\n  if (value === null || value === undefined || value === \"\") return null;\n  switch (newerKindOf(field)) {\n    case \"duration\":\n      return durationText(value);\n    case \"address\":\n      return addressValueText(value);\n    case \"created_by\":\n    case \"modified_by\":\n      return personStampText(value);\n    case \"rich_text\":\n      return typeof value === \"string\" ? richTextPlain(value) : null;\n    case \"rating\": {\n      const n = typeof value === \"number\" ? value : Number(value);\n      return Number.isFinite(n) ? `${n} / ${ratingMaxOf(field)}` : null;\n    }\n    default:\n      return null;\n  }\n}\n\n/**\n * The words one value of a newer kind is EXPORTED or COPIED as: an address on one line, a length of\n * time as h:mm, who by name. A rating, a count and a barcode stay what they are, and rich text\n * stays its Markdown. Null: the value is written as it is stored.\n */\nexport function newerKindExportWords(field: CoercibleField, value: unknown): string | null {\n  const kind = newerKindOf(field);\n  if (kind === \"address\" || kind === \"duration\" || kind === \"created_by\" || kind === \"modified_by\") {\n    return newerKindWords(field, value);\n  }\n  return null;\n}\n","// src/typedDate.ts — @ai-matrx/records\n//\n// A DATE A PERSON TYPED, READ THE WAY THEIR SPREADSHEET READS IT — OR REFUSED.\n//\n// 🚨 WHY THIS EXISTS (merged-grid cold review, 2026-09-26). A person selected a Visit Date cell\n// and typed `10/03/2026`; the store kept **Jan 31, 0026**. `2026-10-03` became **Feb 6, 1003**.\n// The keystrokes after the first landed in the browser's segmented date control one segment at a\n// time and every half-typed segment was a \"valid\" date. The reading that replaces that is this\n// one, and it is the ONE reading every typed-date door uses (`coerceTypedAnswer` — the grid's\n// type-to-edit, a paste, a public form, an import).\n//\n// THE RULES (Google Sheets and Airtable are the bar):\n//   · `2026-10-03` (and `2026/10/03`) is year-month-day, everywhere.\n//   · `10/03/2026` is read in the reader's own LOCALE order — Oct 3 in en-US, 10 March in en-GB —\n//     exactly as their spreadsheet would. The locale is the caller's to pass; the default is the\n//     runtime's.\n//   · A month may be a word: `Oct 3, 2026`, `3 October 2026`, `Saturday, October 3, 2026`.\n//   · A TWO-DIGIT YEAR IS READ THE WAY GOOGLE SHEETS READS IT (grids review 3, 2026-09-30):\n//     `10/03/26` is Oct 3, 2026 — 00–29 is 2000–2029 and 30–99 is 1930–1999, Sheets' and Excel's\n//     own window, so a birthday typed `5/12/85` is 1985 and a visit typed `10/03/26` is this year.\n//     Airtable and Sheets both take it; refusing it was the one place this reader was stricter\n//     than every spreadsheet a person has used.\n//   · NOTHING ELSE IS GUESSED. A missing year (which year?), a one- or three-digit year, a\n//     month 0 or 13, a 31 September, a year before 1000 (that is a half-typed year, not a date\n//     anybody means) — each is REFUSED with a sentence saying how to write it.\n//   · A time of day may follow (`10/03/2026 2:30 PM`, `2026-10-03T14:30`, an ISO instant with its\n//     zone). A day-only column keeps the DAY that was written; a date-and-time column keeps the\n//     instant, read in the reader's own zone unless the text names one.\n\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\n// THE PERSON'S ZONE, read from the ONE slot design-system's `setDisplayTimeZone` writes (the host sets it\n// once at boot through records-ui `setPersonTimeZone`). Same key, same shape: this file only READS it, so a\n// typed `10/03/2026 9:30 AM` is placed at 9:30 in the zone the cell, the panel and the calendar show it in.\n// Without a saved zone the device's zone applies, exactly as before (AT-FIX-J2, 2026-10-20).\nconst zoneSlot = globalSlot<{ zone: string | null }>(\"ai-matrx.design-system.display-time-zone\", () => ({ zone: null }));\n\nexport type WallParts = { year: number; month: number; day: number; hour: number; minute: number; second: number };\n\n/** The wall clock `at` shows in the person's zone (the device's when none is saved). */\nexport function wallPartsInZone(at: Date): WallParts {\n  const zone = zoneSlot.zone;\n  if (!zone) {\n    return { year: at.getFullYear(), month: at.getMonth() + 1, day: at.getDate(), hour: at.getHours(), minute: at.getMinutes(), second: at.getSeconds() };\n  }\n  const parts = 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(at);\n  const n = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0);\n  return { year: n(\"year\"), month: n(\"month\"), day: n(\"day\"), hour: n(\"hour\"), minute: n(\"minute\"), second: n(\"second\") };\n}\n\n/** The instant at which the person's wall clock reads these fields (the device's clock when no zone is saved). */\nexport function instantFromWallInZone(year: number, month: number, day: number, hour = 0, minute = 0, second = 0): Date {\n  const zone = zoneSlot.zone;\n  if (!zone) return new Date(year, month - 1, day, hour, minute, second);\n  const target = Date.UTC(year, month - 1, day, hour, minute, second);\n  let guess = target;\n  for (let i = 0; i < 3; i += 1) {\n    const w = wallPartsInZone(new Date(guess));\n    guess -= Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - target;\n  }\n  return new Date(guess);\n}\n\nexport type TypedDate =\n  | { ok: true; day: string; /** ISO instant, only when a time of day was read or asked for. */ instant: string | null }\n  | { ok: false; why: string };\n\nconst MONTHS: Record<string, number> = {\n  jan: 1, january: 1, feb: 2, february: 2, mar: 3, march: 3, apr: 4, april: 4, may: 5, jun: 6, june: 6,\n  jul: 7, july: 7, aug: 8, august: 8, sep: 9, sept: 9, september: 9, oct: 10, october: 10,\n  nov: 11, november: 11, dec: 12, december: 12,\n};\nconst WEEKDAYS = /\\b(mon|tue|tues|wed|thu|thur|thurs|fri|sat|sun)(day|nesday|sday|urday)?\\b\\.?,?/gi;\n\n/** The order a locale writes a numeric date in: \"mdy\", \"dmy\" or \"ymd\". */\nexport function localeDateOrder(locale?: string): \"mdy\" | \"dmy\" | \"ymd\" {\n  try {\n    const parts = new Intl.DateTimeFormat(locale, { year: \"numeric\", month: \"2-digit\", day: \"2-digit\" }).formatToParts(\n      new Date(2026, 10, 22),\n    );\n    const order = parts\n      .filter((p) => p.type === \"year\" || p.type === \"month\" || p.type === \"day\")\n      .map((p) => p.type.charAt(0))\n      .join(\"\");\n    if (order === \"mdy\" || order === \"dmy\" || order === \"ymd\") return order;\n  } catch {\n    // An unknown locale reads like the runtime's own.\n  }\n  return \"mdy\";\n}\n\nfunction pad(n: number, width = 2): string {\n  return String(n).padStart(width, \"0\");\n}\n\nfunction daysIn(year: number, month: number): number {\n  return new Date(Date.UTC(year, month, 0)).getUTCDate();\n}\n\nconst HOW = \"Write it as 2026-10-03, or with the year in full the way your spreadsheet writes dates.\";\n\n/** Sheets' and Excel's two-digit-year window: 00–29 → 2000–2029, 30–99 → 1930–1999. */\nexport function twoDigitYear(yy: number): number {\n  return yy < 30 ? 2000 + yy : 1900 + yy;\n}\n\nfunction checkDay(year: number, month: number, day: number, raw: string): string | null {\n  if (year < 1000 || year > 9999) return `“${raw}” has no four-digit year. ${HOW}`;\n  if (month < 1 || month > 12) return `“${raw}” names no month (month ${month}). ${HOW}`;\n  if (day < 1 || day > daysIn(year, month)) return `“${raw}” is not a day on the calendar. ${HOW}`;\n  return null;\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// A TIME OF DAY A PERSON TYPED (Arman, 2026-09-28: \"if I type 1200PM, I get 2:00PM because the\n// one isn't recorded\"). The grid opens a plain text box holding every key typed; this reads it\n// ONCE, on commit — for a time column and for the time after a date-and-time column's day.\n//\n//   · 12-hour with a meridiem, any spelling: `1200PM`, `12pm`, `12:00 PM`, `9:30a`, `9:30 a.m.`,\n//     `930am`, `2 PM`.\n//   · 24-hour with minutes: `14:30`, `14:30:05`, and the four-digit clock `1200`, `0930`.\n//   · NOTHING IS GUESSED. A bare hour (`9` — morning or evening?), three bare digits (`200`),\n//     `13pm`, `0am`, `25:00`, `12:60`, `2400` — each is refused with the way to write it.\n// ───────────────────────────────────────────────────────────────────────────\n\nexport type TypedTime = { ok: true; /** 24-hour `HH:MM`, or `HH:MM:SS` when seconds were typed. */ value: string } | { ok: false; why: string };\n\nconst TIME_HOW = \"Write it like 2:30 PM or 14:30.\";\nconst MERIDIEM = String.raw`([ap])\\.?\\s*(?:m\\.?)?`;\nconst CLOCK = new RegExp(String.raw`^(\\d{1,2})(?::(\\d{2})(?::(\\d{2}))?)?\\s*(?:${MERIDIEM})?$`, \"i\");\nconst COMPACT = new RegExp(String.raw`^(\\d{3,4})\\s*(?:${MERIDIEM})?$`, \"i\");\n\n/** Read one typed time of day. Never throws; never guesses. */\nexport function readTypedTime(raw: string): TypedTime {\n  const text = raw.trim();\n  if (text === \"\") return { ok: false, why: \"Nothing was typed.\" };\n  let h: number;\n  let m: number;\n  let s: number | null = null;\n  let meridiem: string | undefined;\n  const clock = CLOCK.exec(text);\n  const compact = clock ? null : COMPACT.exec(text);\n  if (clock) {\n    h = Number(clock[1]);\n    meridiem = clock[4]?.toLowerCase();\n    if (clock[2] === undefined && !meridiem) {\n      return { ok: false, why: `“${raw}” could be in the morning or the evening. ${TIME_HOW}` };\n    }\n    m = clock[2] === undefined ? 0 : Number(clock[2]);\n    if (clock[3] !== undefined) s = Number(clock[3]);\n  } else if (compact) {\n    const digits = compact[1]!;\n    meridiem = compact[2]?.toLowerCase();\n    if (digits.length === 3 && !meridiem) {\n      return { ok: false, why: `“${raw}” could be in the morning or the evening. ${TIME_HOW}` };\n    }\n    h = Number(digits.slice(0, digits.length - 2));\n    m = Number(digits.slice(-2));\n  } else {\n    return { ok: false, why: `“${raw}” is not a time of day. ${TIME_HOW}` };\n  }\n  if (meridiem) {\n    if (h < 1 || h > 12) return { ok: false, why: `“${raw}” is not a time of day. ${TIME_HOW}` };\n    if (meridiem === \"p\" && h !== 12) h += 12;\n    if (meridiem === \"a\" && h === 12) h = 0;\n  }\n  if (h > 23 || m > 59 || (s !== null && s > 59)) return { ok: false, why: `“${raw}” is not a time of day. ${TIME_HOW}` };\n  return { ok: true, value: [h, m, ...(s === null ? [] : [s])].map((n) => pad(n)).join(\":\") };\n}\n\n/**\n * A time of day at the END of the text: `14:30`, `2:30 pm`, `2 PM`, `1200PM`, `14:30:05`. A bare\n * number (`2026` after `Oct 3`) is never a time — only one with a colon or a meridiem is.\n */\nfunction splitTime(text: string): { date: string; time: { h: number; m: number; s: number } | null; bad: boolean } {\n  const match = /(?:^|[\\sT,]+)(?:at\\s+)?(\\d{1,4}(?::\\d{2}){0,2}\\s*(?:[ap]\\.?\\s*(?:m\\.?)?)?)$/i.exec(text);\n  if (!match) return { date: text, time: null, bad: false };\n  const token = match[1]!;\n  if (!/:|[ap]\\.?\\s*(?:m\\.?)?$/i.test(token)) return { date: text, time: null, bad: false };\n  const read = readTypedTime(token);\n  if (!read.ok) return { date: text, time: null, bad: true };\n  const [h, m, s] = read.value.split(\":\").map(Number);\n  return { date: text.slice(0, match.index).replace(/[\\s,]+$/, \"\"), time: { h: h!, m: m!, s: s ?? 0 }, bad: false };\n}\n\n/**\n * Read one typed date. `withTime` is true for a date-and-time column. Never throws; never guesses.\n */\nexport function readTypedDate(raw: string, opts: { withTime?: boolean; locale?: string } = {}): TypedDate {\n  const text = raw.trim();\n  if (text === \"\") return { ok: false, why: \"Nothing was typed.\" };\n\n  // AN ISO INSTANT WITH ITS ZONE (`…Z`, `…+02:00`) is a moment, placed exactly.\n  const iso = /^(\\d{4})-(\\d{2})-(\\d{2})[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})$/i.exec(text);\n  if (iso) {\n    const bad = checkDay(Number(iso[1]), Number(iso[2]), Number(iso[3]), raw);\n    if (bad) return { ok: false, why: bad };\n    const at = new Date(Date.parse(text));\n    if (Number.isNaN(at.getTime())) return { ok: false, why: `“${raw}” is not a moment this can read. ${HOW}` };\n    const w = wallPartsInZone(at);\n    const day = `${pad(w.year, 4)}-${pad(w.month)}-${pad(w.day)}`;\n    return { ok: true, day, instant: opts.withTime ? at.toISOString() : null };\n  }\n\n  const split = splitTime(text.replace(/(\\d)T(\\d)/, \"$1 $2\"));\n  if (split.bad) return { ok: false, why: `“${raw}” has a time of day that is not one. Write it as 14:30 or 2:30 PM.` };\n  const dateText = split.date.replace(WEEKDAYS, \" \").replace(/\\s+/g, \" \").trim();\n\n  let year: number | null = null;\n  let month: number | null = null;\n  let day: number | null = null;\n\n  const numeric = /^(\\d{1,4})[/.\\-](\\d{1,2})[/.\\-](\\d{1,4})$/.exec(dateText);\n  // DIGITS WITH NO SEPARATORS (Arman 2026-10-08: typing `10142026` did nothing): MMDDYYYY / DDMMYYYY by\n  // the locale's order, MMDDYY (the two-digit-year window), and YYYYMMDD when that is the only reading.\n  const compact = /^(\\d{8}|\\d{6})$/.exec(dateText);\n  if (compact) {\n    const digits = compact[1]!;\n    const order = localeDateOrder(opts.locale);\n    const first2 = Number(digits.slice(0, 2));\n    const mid2 = Number(digits.slice(2, 4));\n    if (digits.length === 6) {\n      year = twoDigitYear(Number(digits.slice(4)));\n      if (order === \"dmy\") {\n        day = first2;\n        month = mid2;\n      } else {\n        month = first2;\n        day = mid2;\n      }\n    } else {\n      const yearLast = Number(digits.slice(4));\n      const yearFirst = Number(digits.slice(0, 4));\n      const localeReading = (): [number, number, number] =>\n        order === \"dmy\" ? [yearLast, mid2, first2] : [yearLast, first2, mid2];\n      const [ly, lm, ld] = localeReading();\n      const isoReading: [number, number, number] = [yearFirst, Number(digits.slice(4, 6)), Number(digits.slice(6))];\n      const fits = (y: number, m: number, d: number) => checkDay(y, m, d, raw) === null;\n      const useIso = order === \"ymd\" || (!fits(ly, lm, ld) && fits(...isoReading));\n      [year, month, day] = useIso ? isoReading : [ly, lm, ld];\n    }\n  } else if (numeric) {\n    const [a, b, c] = [numeric[1]!, numeric[2]!, numeric[3]!];\n    if (a.length === 4) {\n      year = Number(a);\n      month = Number(b);\n      day = Number(c);\n    } else {\n      if (c.length !== 4 && c.length !== 2) {\n        return { ok: false, why: `“${raw}” has no four-digit year. ${HOW}` };\n      }\n      const order = localeDateOrder(opts.locale);\n      year = c.length === 2 ? twoDigitYear(Number(c)) : Number(c);\n      if (order === \"dmy\") {\n        day = Number(a);\n        month = Number(b);\n      } else {\n        month = Number(a);\n        day = Number(b);\n      }\n    }\n  } else {\n    // A MONTH WRITTEN AS A WORD, in any order with a day and a four-digit year.\n    const tokens = dateText.toLowerCase().replace(/,/g, \" \").split(/[\\s/.\\-]+/).filter(Boolean);\n    const numbers: string[] = [];\n    for (const token of tokens) {\n      const word = token.replace(/\\.$/, \"\");\n      if (/^\\d+(st|nd|rd|th)?$/.test(word)) numbers.push(word.replace(/\\D/g, \"\"));\n      else if (word in MONTHS) {\n        if (month !== null) return { ok: false, why: `“${raw}” names two months. ${HOW}` };\n        month = MONTHS[word]!;\n      } else if (word !== \"of\" && word !== \"the\") {\n        return { ok: false, why: `“${raw}” is not a date this can read. ${HOW}` };\n      }\n    }\n    if (month === null) return { ok: false, why: `“${raw}” is not a date this can read. ${HOW}` };\n    const years = numbers.filter((n) => n.length === 4);\n    const days = numbers.filter((n) => n.length <= 2);\n    if (years.length === 0) {\n      return {\n        ok: false,\n        why: numbers.some((n) => n.length === 3)\n          ? `“${raw}” has no four-digit year. ${HOW}`\n          : `“${raw}” has no year, and which year it means is a guess. Write the year too (${\n              days[0] ?? \"3\"\n            } ${Object.keys(MONTHS).find((k) => MONTHS[k] === month && k.length > 3) ?? \"October\"} 2026).`,\n      };\n    }\n    if (years.length > 1 || days.length !== 1 || numbers.length !== 2) {\n      return { ok: false, why: `“${raw}” is not a date this can read. ${HOW}` };\n    }\n    year = Number(years[0]);\n    day = Number(days[0]);\n  }\n\n  const bad = checkDay(year!, month!, day!, raw);\n  if (bad) return { ok: false, why: bad };\n  const dayText = `${pad(year!, 4)}-${pad(month!)}-${pad(day!)}`;\n  if (!opts.withTime) return { ok: true, day: dayText, instant: null };\n  const t = split.time ?? { h: 0, m: 0, s: 0 };\n  const local = instantFromWallInZone(year!, month!, day!, t.h, t.m, t.s);\n  return { ok: true, day: dayText, instant: local.toISOString() };\n}\n\n/**\n * THE TEXT AN EDITOR OPENS WITH for a stored day or instant — the inverse of `readTypedDate`, so\n * a cell opened by Enter or a double-click shows words this reader reads back to the SAME value\n * (grids review 3, 2026-09-30: those paths used to open the browser's own date picker, which lost\n * the time and saved \"now\"). The day is numeric in the locale's own order with a four-digit year;\n * a time of day follows as `2:30 PM` (a 12-hour locale) or `14:30` (a 24-hour one). An unreadable\n * stored value opens as the stored characters, untouched.\n */\nexport function typedDateText(value: unknown, opts: { withTime?: boolean; locale?: string } = {}): string {\n  if (value === null || value === undefined || value === \"\") return \"\";\n  const text = String(value).trim();\n  const bare = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(text);\n  let y: number;\n  let mo: number;\n  let d: number;\n  let at: Date | null = null;\n  let wall: WallParts | null = null;\n  if (bare) {\n    y = Number(bare[1]);\n    mo = Number(bare[2]);\n    d = Number(bare[3]);\n  } else {\n    const parsed = value instanceof Date ? value : new Date(Date.parse(text));\n    if (Number.isNaN(parsed.getTime())) return text;\n    at = parsed;\n    wall = wallPartsInZone(parsed);\n    y = wall.year;\n    mo = wall.month;\n    d = wall.day;\n  }\n  const order = localeDateOrder(opts.locale);\n  const day =\n    order === \"ymd\" ? `${pad(y, 4)}-${pad(mo)}-${pad(d)}` : order === \"dmy\" ? `${pad(d)}/${pad(mo)}/${pad(y, 4)}` : `${pad(mo)}/${pad(d)}/${pad(y, 4)}`;\n  if (!opts.withTime || !at || !wall) return day;\n  return `${day} ${typedTimeText(wall.hour, wall.minute, opts.locale)}`;\n}\n\n/** A time of day in the words `readTypedTime` reads back: `2:30 PM` or `14:30`, by the locale's clock. */\nexport function typedTimeText(hours: number, minutes: number, locale?: string): string {\n  let twelve = true;\n  try {\n    twelve = new Intl.DateTimeFormat(locale, { hour: \"numeric\" }).resolvedOptions().hour12 !== false;\n  } catch {\n    // An unknown locale reads like the runtime's own.\n  }\n  if (!twelve) return `${pad(hours)}:${pad(minutes)}`;\n  const h = hours % 12 === 0 ? 12 : hours % 12;\n  return `${h}:${pad(minutes)} ${hours < 12 ? \"AM\" : \"PM\"}`;\n}\n","// src/typedNumber.ts — @ai-matrx/records\n//\n// A NUMBER A PERSON TYPED, READ THE WAY THEY WROTE IT — OR REFUSED.\n//\n// PEOPLE WRITE NUMBERS THE WAY PEOPLE WRITE NUMBERS. \"$1,250.50\", \"(300)\" for a negative, \"12%\",\n// \"2019\" — all of them are the number that was meant, and refusing them makes the column people use\n// most the one the product cannot take. A MINUS IS A MINUS WHEREVER THE SYMBOL SITS (merged-grid\n// review 2, A9): \"-$150\", \"$-150\" and \"(150)\" are all −150 — Sheets and Airtable read every one of\n// them. Everything before the first digit is symbols and signs; an odd number of minus signs there\n// is a negative.\n//\n// This is the ONE reading: `coerceTypedAnswer` (every record-store door) and the older `/data` grid's\n// typed cells both call it, so a number typed into any grid is read the same way.\n\nexport type TypedNumber = { ok: true; value: number } | { ok: false; why: string };\n\nexport function readTypedNumber(raw: string): TypedNumber {\n  const text = raw.trim();\n  if (text === \"\") return { ok: false, why: \"Nothing was typed.\" };\n  const bracketed = /^\\(.*\\)$/.test(text);\n  const inner = (bracketed ? text.slice(1, -1) : text).replace(/[\\s,]/g, \"\");\n  const head = /^[^\\d.]*/.exec(inner)?.[0] ?? \"\";\n  const bare = inner.slice(head.length).replace(/[^\\d.eE+-]+$/, \"\");\n  const minus = (head.match(/[-−]/g) ?? []).length % 2 === 1;\n  const n = Number(bare);\n  if (bare === \"\" || Number.isNaN(n) || /[\\d]/.test(head)) {\n    return {\n      ok: false,\n      why: `“${raw}” is not a number. Write digits, like 1,250.50 — a currency symbol, a percent sign, commas and a minus sign or brackets for a negative are all fine.`,\n    };\n  }\n  return { ok: true, value: bracketed !== minus ? -n : n };\n}\n","// src/coerce.ts — @ai-matrx/records\n//\n// WHAT A TYPED-IN ANSWER MEANS TO A FIELD, WORKED OUT IN ONE PLACE.\n//\n// Every door into this store that a person types into hands over STRINGS. A\n// browser input is a string. A clipboard cell is a string. A CSV column is a\n// string. A public form's answer is a string. A Field does not take strings —\n// it takes a number, a tick, a day, the id of an option — and until the string\n// has been turned into one of those, the store refuses it.\n//\n// 🚨 WHY THIS FILE EXISTS (AGENT-BUILDS-2's closing walk, 2026-09-21). A real\n// customer picked a time on Ironclad Mobile Mechanic's public booking page,\n// typed their name, phone, email and vehicle, pressed \"Book it\", and the page\n// answered:\n//\n//     \"Vehicle Year takes a number, and it was given a string\"\n//\n// The appointment was not made. `BookingPicker` kept its answers as\n// `Record<string, string>` and the confirm route passed them through\n// uncoerced, so a booking page over ANY table with a number field was\n// unbookable by anybody. The store was right and said so plainly; nothing\n// between the person and the store had done the one job that stood between\n// them.\n//\n// AND IT WAS ALREADY SOLVED, TWICE, IN THE WRONG PLACE. The grid's paste\n// (`@ai-matrx/records-ui` `valueFromPastedText`) and the import wizard each\n// carried their own coercion — good ones — while the two PUBLIC doors, the\n// ones a stranger uses, carried none. That is the shape the platform-primitive\n// rule exists to stop: a capability scoped to the feature that surfaced it.\n// So the coercion lives HERE, headless, in the package both the screens and\n// the servers already depend on, and every one of those five doors calls it.\n//\n// THREE RULES IT KEEPS:\n//\n//   1. A VALUE IS COERCED, NEVER GUESSED. Writing 0 for \"about twelve\" or\n//      today's date for \"soon\" is how a table quietly becomes untrue. A string\n//      that is not the thing is REFUSED, by name, in words the person can act\n//      on — \"Vehicle Year holds a number, and “twenty nineteen” is not one\".\n//   2. THE REFUSAL NAMES THE FIELD IN PLAIN WORDS, never its key, because the\n//      person reading it is looking at a label on a screen.\n//   3. IT DECIDES NOTHING ELSE. Required, the Rules, the cap, the rate window\n//      and every wall are the store's. This turns a string into a value and\n//      stops.\n\nimport { isButtonField } from \"./button\";\nimport { addressFromText, newerKindOf, ratingMaxOf, readTypedDuration } from \"./newerKinds\";\nimport { readTypedDate } from \"./typedDate\";\nimport { readTypedNumber } from \"./typedNumber\";\nimport type { Field } from \"./field\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n/**\n * EVERYTHING THIS FILE NEEDS TO KNOW ABOUT A FIELD, AND NOTHING ELSE.\n *\n * A full `Field` satisfies it, and so does every narrower shape the store\n * hands to a screen — `CaptureField` on a phone with no network, the Field\n * documents `custom.form_public` and `custom.booking_public` publish to a\n * stranger. Asking for the whole `Field` would have meant the capture sheet\n * keeping its own `Number(raw)`, which is exactly the duplication this file\n * exists to end.\n */\nexport interface CoercibleField {\n  /** Named so the doc above is checkable: a full {@link Field} satisfies this. */\n  key: string;\n  label?: string | null;\n  name?: string | null;\n  /** FLD-1. One of five behaviors; an unknown word is treated as text. */\n  type?: string | null;\n  multi?: boolean | null;\n  unit?: string | null;\n  format?: string | null;\n  config?: Record<string, unknown> | null | undefined;\n  relation_target?: string | null;\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// WHICH KIND OF THING A FIELD HOLDS\n// ───────────────────────────────────────────────────────────────────────────\n\n/**\n * The kind of value one Field holds, resolved from its DECLARATION only — the\n * behavior, the modifiers, the format, the relation target and the config,\n * because those are what the store stores. A screen that guessed from a value\n * would answer differently for an empty record.\n *\n * `plain_text`, `long_text`, `number` and `boolean` are behaviors that carry\n * no parity type of their own; every other word here is a parity type.\n */\nexport const FIELD_KINDS = [\n  \"attachment\",\n  \"checkbox\",\n  \"currency\",\n  \"datetime\",\n  \"email\",\n  \"entity_reference\",\n  \"formula\",\n  \"json\",\n  \"long_text\",\n  \"lookup\",\n  \"member\",\n  \"multi_select\",\n  \"number\",\n  \"percent\",\n  \"phone\",\n  \"relation\",\n  \"rollup\",\n  \"select\",\n  \"text\",\n  \"url\",\n] as const;\n\n/**\n * 🚨 THE UNION IS DERIVED FROM THE LIST ABOVE, and the list is what the\n * coverage test walks. Add a kind here and the test drives it; give it no arm\n * in `coerceTypedAnswer` and the test says so, instead of the new kind falling\n * quietly through `default:` and a value of the wrong shape reaching the store\n * — which is the whole defect this file closes.\n */\nexport type FieldKind = (typeof FIELD_KINDS)[number];\n\n/** The kernel Table ids REC-31 pins the two special relations to. */\nexport interface KernelTargets {\n  /** The kernel `File` Table — a relation pointing here is an attachment. */\n  file?: string | undefined;\n  /** The kernel `Person` Table — a relation pointing here names a person. */\n  person?: string | undefined;\n}\n\n/**\n * Which kind of value this Field holds.\n *\n * This is the ONE classifier. `@ai-matrx/records-ui`'s `editorKindFor` — which\n * decides which editor to DRAW — delegates to it, so the editor a person types\n * into and the coercion applied to what they typed can never disagree about\n * the same column. They did disagree before this moved here; that is the whole\n * class of grid defect September was spent closing.\n */\nexport function fieldKindFor(field: CoercibleField, kernel?: KernelTargets): FieldKind {\n  const format = (field.format ?? \"\").toLowerCase();\n  const config = field.config ?? {};\n  switch (field.type) {\n    case \"boolean\":\n      return \"checkbox\";\n    case \"text\":\n      if (format === \"email\") return \"email\";\n      if (format === \"phone\") return \"phone\";\n      if (format === \"url\") return \"url\";\n      if (format === \"json\" || config[\"json\"] === true) return \"json\";\n      if (format === \"long\" || config[\"multiline\"] === true) return \"long_text\";\n      return \"text\";\n    case \"range\": {\n      const kind = String(config[\"kind\"] ?? \"number\");\n      if (kind === \"date\" || kind === \"datetime\") return \"datetime\";\n      // THE FORMAT, AND ONLY THE FORMAT. A unit is not a currency: a quantity\n      // in `units` drawn as money is how three of something rendered \"units3\".\n      if (format === \"currency\") return \"currency\";\n      if (format === \"percent\" || field.unit === \"%\") return \"percent\";\n      return \"number\";\n    }\n    case \"list\":\n      return field.multi ? \"multi_select\" : \"select\";\n    case \"relation\": {\n      // SC-R / P12: a relation whose target mode is `any`, restricted by\n      // `config.allowed_types` to the platform kinds it may name (notes, web\n      // sites, agents …). Its value is `{token, id}`, never a record id.\n      if (isEntityReferenceConfig(config)) return \"entity_reference\";\n      const parity = String(config[\"parity\"] ?? \"\");\n      if (parity === \"attachment\" || parity === \"member\") return parity;\n      if (kernel?.file && field.relation_target === kernel.file) return \"attachment\";\n      if (kernel?.person && field.relation_target === kernel.person) return \"member\";\n      return \"relation\";\n    }\n    case \"formula\": {\n      const via = config[\"via\"];\n      if (via && config[\"agg\"]) return \"rollup\";\n      if (via) return \"lookup\";\n      return \"formula\";\n    }\n    default:\n      return \"text\";\n  }\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// THE COERCION\n// ───────────────────────────────────────────────────────────────────────────\n\n/** One Field's options, indexed the way a typed word has to be looked up. */\nexport interface ChoiceOptions {\n  /**\n   * Lower-cased label, option key and option id, each pointing at the OPTION\n   * RECORD'S ID — which is what a list Field stores (FLD-5/FLD-6).\n   */\n  byWord: Map<string, string>;\n  /** The labels, in order, so a refusal can say what is on offer. */\n  labels: string[];\n}\n\n/** What one answer became, or the sentence saying why it did not. */\nexport type Coerced =\n  | { value: unknown; words?: string }\n  | { refusal: string; unmatched?: string[]; unmatchedNames?: string[]; ambiguousNames?: string[] };\n\n// ───────────────────────────────────────────────────────────────────────────\n// A RELATION FILLED BY NAME (VISION-REACH G1, 2026-10-02)\n// ───────────────────────────────────────────────────────────────────────────\n//\n// A spreadsheet names the record a row points at — \"Dr. Marisol Gutierrez\" —\n// and Airtable fills a linked-record cell from exactly that: the primary\n// field's text. Until this lane every door here refused it (\"chosen rather than\n// typed\"), and the sitting's clinic file needed 264 hand picks. The store now\n// matches a name through ONE matcher (`custom._relation_names_resolve`); a\n// screen asks it in one call per column (`relationNamesMatch`) and hands the\n// answer to the coercion below as a `RelationNameIndex`, exactly as a choice\n// column hands its `ChoiceOptions`. One match is that record; none, or two\n// records of one name, is REFUSED and named — never guessed.\n\n/** One record a name matched. */\nexport interface RelationNameMatch {\n  id: string;\n  /** What its name column holds. */\n  words: string;\n}\n\n/** A relation's target Table, indexed by the names a column holds. */\nexport interface RelationNameIndex {\n  /** `relationNameKey(name)` → the records of that name the reader may see. */\n  byName: ReadonlyMap<string, readonly RelationNameMatch[]>;\n  /** The target Table's name, for the sentence. */\n  tableName: string;\n  /** The target Table's name column, so a screen can make a record a name matched nothing. */\n  titleField: string | null;\n}\n\n/** The answer of `custom.relation_names_match`. */\nexport interface RelationNamesAnswer {\n  table_id: string;\n  table_name: string | null;\n  title_field?: string | null;\n  names: Array<{ name: string; matches: RelationNameMatch[] }>;\n}\n\n/**\n * How two spellings of one name are told apart: case and runs of spacing do not\n * count. The store's `custom.relation_name_key` is the same rule.\n */\nexport function relationNameKey(name: string): string {\n  return name.trim().replace(/\\s+/g, \" \").toLowerCase();\n}\n\n/** How an import splits a cell that holds several values: `;`, `,` or `|` — the store's own rule. */\nexport function splitListCell(text: string): string[] {\n  return text\n    .split(/\\s*[;,|]\\s*/)\n    .map((w) => w.trim())\n    .filter((w) => w.length > 0);\n}\n\n/** Index the store's answer the way the coercion reads it. */\nexport function relationNameIndexOf(answer: RelationNamesAnswer): RelationNameIndex {\n  const byName = new Map<string, RelationNameMatch[]>();\n  for (const entry of answer.names ?? []) {\n    const key = relationNameKey(entry.name ?? \"\");\n    if (key !== \"\" && !byName.has(key)) byName.set(key, entry.matches ?? []);\n  }\n  return { byName, tableName: answer.table_name ?? \"that table\", titleField: answer.title_field ?? null };\n}\n\n/** Every name a relation cell carries, split the way the column reads it. */\nexport function relationNamesIn(field: Pick<CoercibleField, \"multi\">, text: string): string[] {\n  const t = text.trim();\n  if (t === \"\") return [];\n  const parts = field.multi ? splitListCell(t) : [t];\n  return parts.filter((p) => !isUuidShape(p));\n}\n\nexport interface CoerceOptions {\n  /** This Field's choices, when the caller has loaded them. */\n  options?: ChoiceOptions | undefined;\n  /** The kernel File/Person Table ids, for classifying relations. */\n  kernel?: KernelTargets | undefined;\n  /**\n   * The Field's name as this caller writes it. Defaults to the Field's own\n   * label. A screen passes the same words it printed above the box.\n   */\n  label?: string | undefined;\n  /**\n   * A relation column's target, indexed by name (`relationNameIndexOf`). Without it a name in a\n   * relation column is refused as before, and only ids pass.\n   */\n  relationNames?: RelationNameIndex | undefined;\n  /** The reader's locale, for the order of a numeric date (10/03/2026). Defaults to the runtime's. */\n  locale?: string | undefined;\n  /**\n   * The column SHOWS AS a percent (its \"Shows as\" format, which this package does not read), so a\n   * typed `45%` is a percent here even on a number column. The caller scales it to the column's\n   * own percent scale.\n   */\n  showsAsPercent?: boolean | undefined;\n}\n\n/** The money symbols people type, and the currency each one names. `¥` names two, so it names none. */\nconst MONEY_SYMBOLS: Record<string, string> = { $: \"USD\", \"€\": \"EUR\", \"£\": \"GBP\", \"₹\": \"INR\", \"₩\": \"KRW\", \"₪\": \"ILS\", \"₺\": \"TRY\", \"₽\": \"RUB\" };\n\n/** The currency a money column keeps (`unit` holds a symbol or an ISO code), or null when it names none. */\nfunction columnCurrency(unit: string | null | undefined): string | null {\n  const u = (unit ?? \"\").trim();\n  if (u === \"\") return null;\n  if (MONEY_SYMBOLS[u]) return MONEY_SYMBOLS[u]!;\n  return /^[A-Za-z]{3}$/.test(u) ? u.toUpperCase() : null;\n}\n\n/**\n * A UNIT THAT DOES NOT BELONG TO THE COLUMN IS REFUSED, NEVER DROPPED (grids review 3,\n * 2026-09-30): `45%` typed into a Number column was kept as 45 and into a Money column as $45.00 —\n * the percent sign silently thrown away, a value off by a hundred times. Sheets reads `45%` as the\n * percent it is; a column that does not keep percents says so, with the way to write its own kind.\n */\nfunction foreignUnit(kind: \"number\" | \"currency\" | \"percent\", text: string, label: string, raw: string, unit: string | null | undefined, showsAsPercent: boolean): string | null {\n  const hasPercent = /%/.test(text);\n  const symbols = [...text].filter((ch) => ch in MONEY_SYMBOLS);\n  if (kind === \"percent\" || showsAsPercent) {\n    if (symbols.length > 0) return `${label} holds a percent, and “${raw}” is an amount of money. Write it like 45%.`;\n    return null;\n  }\n  if (hasPercent) {\n    return kind === \"currency\"\n      ? `${label} holds an amount of money, and “${raw}” is a percent. Write the amount, like $1,250.50.`\n      : `${label} holds a number, and “${raw}” is a percent, which this column does not show. Write 45 or 0.45 — or make the column show as a percent.`;\n  }\n  if (kind === \"currency\") {\n    const own = columnCurrency(unit);\n    const typed = symbols.map((ch) => MONEY_SYMBOLS[ch]!);\n    if (own && typed.some((code) => code !== own)) {\n      return `${label} holds an amount in ${own}, and “${raw}” is written in ${typed.find((code) => code !== own)}. Write the amount in ${own}.`;\n    }\n  }\n  return null;\n}\n\n/** One id, written the way the store writes one (REC-51's shape test). */\n\n/**\n * SC-R / P12. Whether a relation's config makes it an ENTITY REFERENCE: target\n * mode `any` (REL-8) restricted by a non-empty `allowed_types`.\n */\nexport function isEntityReferenceConfig(config: Record<string, unknown> | null | undefined): boolean {\n  const allowed = config?.[\"allowed_types\"];\n  return Array.isArray(allowed) && allowed.length > 0;\n}\n\n/** The platform kinds an entity-reference Field may name, lower-cased, in its own order. */\nexport function entityReferenceKindsOf(field: Pick<CoercibleField, \"config\">): string[] {\n  const allowed = field.config?.[\"allowed_types\"];\n  return Array.isArray(allowed) ? allowed.map((k) => String(k).trim().toLowerCase()).filter(Boolean) : [];\n}\n\nconst TRUE_WORDS = new Set([\"true\", \"yes\", \"y\", \"1\", \"✓\", \"x\", \"checked\", \"on\"]);\nconst FALSE_WORDS = new Set([\"false\", \"no\", \"n\", \"0\", \"\", \"unchecked\", \"off\"]);\n\n/** The Field's name in plain words — never its key on a screen. */\nexport function coercionLabel(field: CoercibleField): string {\n  const label = (field.label ?? \"\").trim();\n  if (label !== \"\") return label;\n  const name = (field.name ?? \"\").trim();\n  if (name !== \"\") return name;\n  return field.key\n    .replace(/[_-]+/g, \" \")\n    .replace(/\\b\\w/g, (c) => c.toUpperCase())\n    .trim();\n}\n\n/**\n * Turn ONE typed-in string into the value this Field holds — or say, in a\n * sentence a person can act on, why it is not one.\n *\n * An empty answer is `null` for every kind: a blank means \"no answer here\",\n * and clearing a value is a thing a person means to do. Whether the Field may\n * be blank is the store's question, asked with the Field's `required` and its\n * Rules, not this one's.\n */\n/**\n * The choices a public question was handed (`public_choices`: `{key, label}` in order), as the\n * options a typed answer is matched against — by its key or by its label, either case — and each\n * answering with its KEY, which is what the public picker sends. Null when the question carries none.\n */\nfunction optionsFromPublicChoices(field: CoercibleField): ChoiceOptions | null {\n  const offered = (field as { public_choices?: unknown }).public_choices;\n  if (!Array.isArray(offered) || offered.length === 0) return null;\n  const byWord = new Map<string, string>();\n  const labels: string[] = [];\n  for (const c of offered) {\n    const key = typeof (c as { key?: unknown })?.key === \"string\" ? (c as { key: string }).key : null;\n    if (!key) continue;\n    const words = (c as { label?: unknown }).label;\n    const choiceLabel = typeof words === \"string\" && words.trim() !== \"\" ? words.trim() : key;\n    byWord.set(key.toLowerCase(), key);\n    byWord.set(choiceLabel.toLowerCase(), key);\n    labels.push(choiceLabel);\n  }\n  return labels.length > 0 ? { byWord, labels } : null;\n}\n\nexport function coerceTypedAnswer(\n  field: CoercibleField,\n  raw: string,\n  opts: CoerceOptions = {},\n): Coerced {\n  const label = opts.label ?? coercionLabel(field);\n  const text = raw.trim();\n  const kind = fieldKindFor(field, opts.kernel);\n\n  if (text === \"\" && kind !== \"checkbox\") return { value: null };\n\n  // LANE 10 P4: the newer kinds a format makes more exact (`newerKinds.ts`) read their own way;\n  // everything else about them (a status's choices, a count's refusal) is their base kind's.\n  // NOTION-PROPS-3: a button holds no value — it is pressed, never typed or pasted into.\n  if (isButtonField(field)) return { refusal: `${label} is a button: it is pressed, and holds nothing to type.` };\n  const newer = newerKindOf(field);\n  if (newer === \"rating\") {\n    const max = ratingMaxOf(field);\n    const n = Number(text);\n    if (Number.isInteger(n) && n >= 0 && n <= max) return { value: n };\n    return { refusal: `${label} is a whole number of stars from 0 to ${max}, and “${raw}” is not one.` };\n  }\n  if (newer === \"duration\") {\n    const seconds = readTypedDuration(text);\n    if (seconds === null || seconds < 0) {\n      return { refusal: `${label} is a length of time, and “${raw}” is not one. Write it like 45 min, 1:30 or 1h 30m.` };\n    }\n    // The store's own ceiling (custom._kind_value_ok): ten years of 365.25 days.\n    if (seconds > 315_576_000) return { refusal: `${label} is longer than ten years, and a length of time here is at most ten years.` };\n    return { value: seconds };\n  }\n  if (newer === \"address\") return { value: addressFromText(text) };\n  if (newer === \"barcode\") return { value: text };\n\n  switch (kind) {\n    case \"checkbox\": {\n      const word = text.toLowerCase();\n      if (TRUE_WORDS.has(word)) return { value: true };\n      if (FALSE_WORDS.has(word)) return { value: word === \"\" ? null : false };\n      return {\n        refusal: `${label} is a tick box, so it takes yes or no — “${raw}” is neither. Write TRUE/FALSE, yes/no or 1/0.`,\n      };\n    }\n    case \"number\":\n    case \"currency\":\n    case \"percent\": {\n      // The ONE number reading (`typedNumber.ts`): \"$1,250.50\", \"(300)\", \"-$150\", \"12%\".\n      const read = readTypedNumber(text);\n      if (!read.ok) {\n        return {\n          refusal: `${label} holds a number, and “${raw}” is not one. Write digits, like 1,250.50 — a currency symbol, a percent sign, commas and a minus sign or brackets for a negative are all fine.`,\n        };\n      }\n      const foreign = foreignUnit(kind, text, label, raw, field.unit, opts.showsAsPercent === true);\n      if (foreign) return { refusal: foreign };\n      return { value: read.value };\n    }\n    case \"datetime\": {\n      // A DAY IS NOT AN INSTANT, AND TREATING IT AS ONE MOVES IT. `2026-09-01`\n      // parsed as an instant is midnight UTC, and a screen west of Greenwich\n      // then draws it as 31 August — measured on fifty pasted invoice dates,\n      // all one day early, systematically. A date Field holds a DAY.\n      const wantsTime = String(field.config?.[\"kind\"] ?? \"date\") === \"datetime\";\n      // 🚨 READ, NEVER GUESSED (merged-grid review 2026-09-26): `Date.parse` read \"10/3\" as\n      // 2001 and a half-typed year as a real one. `readTypedDate` reads the person's locale\n      // order and refuses a two-digit or missing year, a month 13, a 31 September.\n      const read = readTypedDate(text, { withTime: wantsTime, ...(opts.locale ? { locale: opts.locale } : {}) });\n      if (!read.ok) return { refusal: `${label} holds a date, and ${read.why}` };\n      return { value: wantsTime ? read.instant : read.day };\n    }\n    case \"json\": {\n      try {\n        return { value: JSON.parse(text) };\n      } catch {\n        return {\n          refusal: `${label} holds a document, and “${raw}” is not valid JSON. Write the whole object, braces and all.`,\n        };\n      }\n    }\n    case \"select\":\n    case \"multi_select\": {\n      // A LIST IS AN IDENTITY, AND A WORD IS HOW A PERSON NAMES ONE. The store\n      // keeps the option's id; the person types its label. Matching the two is\n      // the whole job, and it is case-insensitive because \"COMPLETED\" and\n      // \"Completed\" are one option.\n      // A PUBLIC QUESTION CARRIES ITS OWN CHOICES (lane HANDOVER, 2026-09-29). A stranger's page\n      // never reads the column's options, and the form and booking doors hand each choice question\n      // its choices as `public_choices` instead. Cedar Ridge's booking page sent the Visit type's\n      // key (\"follow_up\") and this answered \"its options have not been read yet\", so every booking\n      // that answered a choice was refused, on the page and again at the confirm route.\n      const options = opts.options ?? optionsFromPublicChoices(field);\n      if (!options) {\n        return {\n          refusal: `${label} is a list and its options have not been read yet, so nothing can be matched to “${raw}”. Try again once the column's choices have loaded.`,\n        };\n      }\n      const wanted = kind === \"multi_select\"\n        ? text.split(/[,;]/).map((w) => w.trim()).filter((w) => w.length > 0)\n        : [text];\n      if (wanted.length === 0) return { value: kind === \"multi_select\" ? [] : null };\n      const matched: string[] = [];\n      const unmatched: string[] = [];\n      for (const word of wanted) {\n        const hit = options.byWord.get(word.toLowerCase());\n        if (hit === undefined) unmatched.push(word);\n        else matched.push(hit);\n      }\n      if (unmatched.length > 0) {\n        const offered = options.labels.length > 0\n          ? options.labels.join(\", \")\n          : \"it has none yet\";\n        return {\n          refusal:\n            `${label} does not have ${unmatched.map((w) => `“${w}”`).join(\" or \")} among its options. ` +\n            `It offers: ${offered}.`,\n          unmatched,\n        };\n      }\n      return { value: kind === \"multi_select\" ? matched : matched[0] };\n    }\n    // AN IDENTITY IS NOT A WORD. Writing the word would put a string where an\n    // id belongs, and every filter, color and rollup built on that column\n    // would stop agreeing with it. So it is refused and the person is told\n    // which control does hold it.\n    //\n    // BUT AN ID IS AN IDENTITY (RELATION-TARGETS, 2026-09-23). A Person or File\n    // column holds the kernel Person / File record, and the store itself now\n    // turns the id a writer actually holds — a member's user id, an uploaded\n    // file's id, or the record's own id — into that record at every write door\n    // (`custom.relation_kernel_record`), refusing anything else in its own\n    // words (\"… names someone who is not a member of …\"). So an import column\n    // of member ids, or an agent handing over the file it just uploaded, is a\n    // value and not a refusal; the store, not this mirror, decides whether the\n    // id is somebody here.\n    case \"member\":\n      if (isUuidShape(text)) return { value: text.toLowerCase() };\n      return {\n        refusal: `${label} names a person in this organization, so it is chosen rather than typed. Open it and pick them.`,\n      };\n    case \"attachment\":\n      if (isUuidShape(text)) return { value: text.toLowerCase() };\n      return {\n        refusal: `${label} holds a file, which cannot arrive as typed-in text. Open it and attach the file.`,\n      };\n    case \"relation\": {\n      // VISION-REACH G1: a record's id, or its NAME read through the index the caller asked the\n      // store for. A several-records column splits the cell the way an import splits any list.\n      const parts = field.multi ? splitListCell(text) : [text];\n      const ids: string[] = [];\n      const words: string[] = [];\n      const none: string[] = [];\n      const many: string[] = [];\n      for (const part of parts) {\n        if (isUuidShape(part)) {\n          if (!ids.includes(part.toLowerCase())) ids.push(part.toLowerCase());\n          continue;\n        }\n        if (!opts.relationNames) {\n          return {\n            refusal: `${label} points at another record, so it is chosen rather than typed. Open it and pick the record.`,\n          };\n        }\n        const hits = opts.relationNames.byName.get(relationNameKey(part)) ?? [];\n        if (hits.length === 0) none.push(part);\n        else if (hits.length > 1) many.push(part);\n        else if (!ids.includes(hits[0]!.id)) {\n          ids.push(hits[0]!.id);\n          words.push(hits[0]!.words);\n        }\n      }\n      if (none.length > 0 || many.length > 0) {\n        const table = opts.relationNames?.tableName ?? \"that table\";\n        const said = many.length > 0\n          ? `${many.map((w) => `“${w}”`).join(\", \")} names more than one record in ${table}.`\n          : `${table} has no record called ${none.map((w) => `“${w}”`).join(\" or \")}.`;\n        return { refusal: `${label}: ${said}`, unmatchedNames: none, ambiguousNames: many };\n      }\n      if (ids.length === 0) return { value: field.multi ? [] : null };\n      return { value: field.multi ? ids : ids[0], ...(words.length > 0 ? { words: words.join(\", \") } : {}) };\n    }\n    // SC-R / P12. An entity reference names a platform thing by kind and id.\n    // An import or an agent may hand over `note:<id>` — or a bare id when the\n    // column allows exactly one kind; the store then decides whether the thing\n    // is there and whether the writer may open it. Words are chosen, not typed.\n    case \"entity_reference\": {\n      const allowed = entityReferenceKindsOf(field);\n      const [maybeToken, maybeId] = text.includes(\":\") ? text.split(/:(.*)/s, 2) : [\"\", text];\n      const token = (maybeToken ?? \"\").trim().toLowerCase() || (allowed.length === 1 ? allowed[0] : \"\");\n      const id = (maybeId ?? \"\").trim();\n      if (token && isUuidShape(id)) {\n        const ref = { token, id: id.toLowerCase() };\n        return { value: field.multi ? [ref] : ref };\n      }\n      return {\n        refusal: `${label} points at something on the platform, so it is chosen rather than typed. Open it and pick it.`,\n      };\n    }\n    case \"formula\":\n    case \"lookup\":\n    case \"rollup\":\n      return {\n        refusal: `${label} is worked out by the system, so nothing can be written into it.`,\n      };\n    // A LINK AND AN EMAIL ARE READ, THE WAY AIRTABLE READS THEM (merged-grid review 2, A9).\n    // \"company.com\" is a link a person meant: it is kept as https://company.com. Words that\n    // cannot be one are refused NAMING THE KIND, WITH ONE EXAMPLE — never \"not written the way\n    // this field expects\". Any further format Rule on the column is still the store's to judge.\n    case \"url\": {\n      if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(text) || /^mailto:/i.test(text)) return { value: text };\n      if (!/\\s/.test(text) && /^[^./@\\s]+(\\.[^./\\s]+)+(\\/.*)?$/.test(text)) return { value: `https://${text}` };\n      return { refusal: `${label} holds a link, and “${raw}” is not one. A link looks like company.com or https://company.com/page.` };\n    }\n    case \"email\": {\n      if (/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(text)) return { value: text };\n      return { refusal: `${label} holds an email address, and “${raw}” is not one. An email looks like name@company.com.` };\n    }\n    default:\n      // text, long_text, phone — the string IS the value, and the format Rules on it are the\n      // store's to judge.\n      return { value: raw };\n  }\n}\n\n/** What a whole set of typed-in answers became. */\nexport interface CoercedAnswers {\n  /** Ready to send to the store. Only the keys that coerced cleanly. */\n  values: Record<string, unknown>;\n  /** Field key → the sentence saying why that answer was not written. */\n  refusals: Record<string, string>;\n  /** The field keys the caller sent that this table has no Field for. */\n  unknownKeys: string[];\n}\n\n/**\n * Every typed-in answer on one screen, coerced together — the shape the two\n * public doors and the import wizard actually need.\n *\n * Keys the table has no Field for are reported rather than dropped: the store\n * refuses an unknown key by name and a caller that quietly deleted it would\n * hide a real mismatch between a page and its table.\n */\nexport function coerceTypedAnswers(\n  fields: readonly CoercibleField[],\n  answers: Readonly<Record<string, unknown>>,\n  opts: {\n    kernel?: KernelTargets | undefined;\n    /** Choices per Field key, for the list columns. */\n    options?: ReadonlyMap<string, ChoiceOptions> | undefined;\n    /** Field key → the words that screen printed above the box. */\n    labels?: Readonly<Record<string, string>> | undefined;\n    /** Relation columns' targets, indexed by name, by field key (VISION-REACH G1). */\n    relationNames?: ReadonlyMap<string, RelationNameIndex> | undefined;\n  } = {},\n): CoercedAnswers {\n  const byKey = new Map(fields.map((f) => [f.key, f]));\n  const values: Record<string, unknown> = {};\n  const refusals: Record<string, string> = {};\n  const unknownKeys: string[] = [];\n\n  for (const [key, given] of Object.entries(answers)) {\n    const field = byKey.get(key);\n    if (!field) {\n      unknownKeys.push(key);\n      // Passed through untouched: it is the STORE's job to say it does not\n      // know this key, in its own words, naming it.\n      values[key] = given;\n      continue;\n    }\n    // ALREADY THE RIGHT SHAPE IS LEFT ALONE. A screen with real editors hands\n    // over a number, a boolean or an array already; only a STRING needs this.\n    if (typeof given !== \"string\") {\n      values[key] = given;\n      continue;\n    }\n    const opt: CoerceOptions = {};\n    const choices = opts.options?.get(key);\n    if (choices) opt.options = choices;\n    const named = opts.relationNames?.get(key);\n    if (named) opt.relationNames = named;\n    if (opts.kernel) opt.kernel = opts.kernel;\n    const label = opts.labels?.[key];\n    if (label) opt.label = label;\n\n    const answered = coerceTypedAnswer(field, given, opt);\n    if (\"refusal\" in answered) refusals[key] = answered.refusal;\n    else values[key] = answered.value;\n  }\n\n  return { values, refusals, unknownKeys };\n}\n","// src/autonumber.ts — @ai-matrx/records\n//\n// A RECORD NUMBER'S PREFIX (lane NOTION-PROPS-3; champion: Notion's ID property, \"TASK-42\"). The store keeps\n// the number (`config.system: autonumber`) and the prefix rides the column's display format\n// (`display_format: {id: \"autonumber\", options: {prefix}}`, judged by `custom._display_format_check`: up to\n// 16 characters on one line, never ending in a digit). The prefix is shown, copied and searched; the value\n// stays the number, so a sort and a filter stay numeric.\n\nimport type { CoercibleField } from \"./coerce\";\n\ntype WithFormat = CoercibleField & { display_format?: unknown; key?: string };\n\n/** Whether a Field is a record number. */\nexport function isAutonumberField(field: CoercibleField | null | undefined): boolean {\n  return String(((field?.config ?? {}) as Record<string, unknown>)[\"system\"] ?? \"\") === \"autonumber\";\n}\n\n/** A record number's prefix (\"TASK-\"), or \"\" when it has none or the Field is not a record number. */\nexport function autonumberPrefixOf(field: WithFormat | null | undefined): string {\n  if (!field || !isAutonumberField(field)) return \"\";\n  const shown = field.display_format;\n  const options = shown && typeof shown === \"object\" ? ((shown as { options?: unknown }).options as Record<string, unknown> | undefined) : undefined;\n  const prefix = options?.[\"prefix\"];\n  return typeof prefix === \"string\" ? prefix : \"\";\n}\n\n/** A record number as a person reads it: its prefix and the number (\"TASK-42\"); null when there is none. */\nexport function autonumberWords(field: WithFormat, value: unknown): string | null {\n  const n = typeof value === \"number\" ? value : typeof value === \"string\" && /^\\d+$/.test(value.trim()) ? Number(value) : NaN;\n  if (!Number.isFinite(n)) return null;\n  return `${autonumberJoin(autonumberPrefixOf(field))}${Math.trunc(n)}`;\n}\n\n/**\n * A prefix as it stands before its number (walk 2026-10-08 D4): \"TASK\" reads \"TASK-2\", as the\n * Prefix box's own placeholder promises; a prefix that already ends in a separator (\"TASK-\",\n * \"INV #\", \"PO/\") is kept as typed. The same rule as the grid's `autonumber` format\n * (@ai-matrx/design-system field-formats), so a card, a copy and a cell never disagree.\n */\nexport function autonumberJoin(prefix: string): string {\n  return prefix === \"\" || /[-_#.:/\\s]$/.test(prefix) ? prefix : `${prefix}-`;\n}\n\n/**\n * A SEARCH FOR A RECORD NUMBER BY ITS WORDS. \"TASK-42\", \"task-42\" or \"TASK 42\" names record 42 of the record\n * number whose prefix is \"TASK-\": the store keeps 42, so the words are turned into that column's number.\n * Null when the words name no record number of these Fields.\n */\nexport function autonumberSearchOf<F extends WithFormat>(fields: readonly F[], words: string): { field: F; number: number } | null {\n  const text = words.trim();\n  if (text === \"\") return null;\n  const squash = (s: string) => s.toLowerCase().replace(/[\\s\\-_#.:/]+/g, \"\");\n  for (const field of fields) {\n    const prefix = autonumberPrefixOf(field);\n    if (!prefix) continue;\n    const m = /^(.*?)(\\d+)$/.exec(text);\n    if (!m) continue;\n    if (squash(m[1]!) !== squash(prefix) || squash(prefix) === \"\") continue;\n    return { field, number: Number(m[2]) };\n  }\n  return null;\n}\n\n/**\n * A read's filter with \"this record number is N\" added (AND). The flat shape takes the column's key; a rule\n * expression is wrapped in an `and` with `{op: eq, args: [{field: id}, {const: N}]}`.\n */\nexport function filterWithAutonumber(\n  filter: Record<string, unknown> | null | undefined,\n  field: { id: string; key: string },\n  n: number,\n): Record<string, unknown> {\n  const eq = { op: \"eq\", args: [{ field: field.id }, { const: n }] };\n  if (!filter) return { [field.key]: n };\n  const isRule = typeof filter[\"op\"] === \"string\" && Array.isArray(filter[\"args\"]);\n  return isRule ? { op: \"and\", args: [filter, eq] } : { ...filter, [field.key]: n };\n}\n","// src/typedMatch.ts — @ai-matrx/records\n//\n// WHAT A PERSON TYPED INTO A PICKER'S SEARCH, AND WHICH ITEM THEY MEANT — ONE RANKING.\n//\n// 🚨 WHY THIS EXISTS (grids review 3, 2026-09-30). An equipment log's \"Service types\" offers\n// Electrical · Calibration · Filter change. The reviewer selected the cell and typed `Cal`; the list\n// kept the store's order and highlighted Electrical — \"Electri-CAL\" contains the letters — so Enter\n// wrote Electrical. Every picker filtered by \"contains\" and nothing ranked.\n//\n// THE RULE (Airtable, Linear, Notion, the macOS menu search): what a person types is the START of\n// what they mean. Items are ranked\n//   1. exact — the whole words, any case;\n//   2. starts with — `Cal` → Calibration;\n//   3. a word starts with — `change` → Filter change, `ray` → X-ray;\n//   4. contains — `cal` → Electrical, last;\n// and ties keep the list's own order (the order the column's owner wrote). Case and accents are\n// ignored (`jose` finds José). An item that does not match at all is not shown.\n//\n// ONE FUNCTION, EVERY PICKER: a single choice, several choices, a person and a linked record in\n// the record grids (@ai-matrx/records-ui), and the Sheet's choice list (matrx-frontend\n// `ChoiceInput`, whose list sorts by `typedMatchScore`). A second ranking anywhere is a fork.\n\n/** How well one text matches what was typed: 4 exact, 3 starts with, 2 a word starts with, 1 contains, 0 not at all. */\nexport type TypedMatchScore = 0 | 1 | 2 | 3 | 4;\n\nfunction fold(text: string): string {\n  return text\n    .normalize(\"NFD\")\n    .replace(/[̀-ͯ]/g, \"\")\n    .toLowerCase()\n    .replace(/\\s+/g, \" \")\n    .trim();\n}\n\n/** A word starts at the start, or after anything that is not a letter or a digit (space, `-`, `/`, `(`…). */\nfunction startsAWord(text: string, query: string): boolean {\n  let from = text.indexOf(query);\n  while (from > 0) {\n    if (!/[\\p{L}\\p{N}]/u.test(text.charAt(from - 1))) return true;\n    from = text.indexOf(query, from + 1);\n  }\n  return from === 0;\n}\n\n/**\n * How well `text` matches what was typed. An empty search matches everything at the lowest rank\n * that still shows (1), so an empty box lists every item in its own order.\n */\nexport function typedMatchScore(text: string, typed: string): TypedMatchScore {\n  const query = fold(typed);\n  if (query === \"\") return 1;\n  const words = fold(text);\n  if (words === query) return 4;\n  if (words.startsWith(query)) return 3;\n  if (startsAWord(words, query)) return 2;\n  if (words.includes(query)) return 1;\n  return 0;\n}\n\n/**\n * The items that match what was typed, best first; ties keep the given order. `textsOf` answers the\n * words an item is found by — its NAME first, then anything that tells two apart (a second line).\n * The name ranks at its full strength; a second line only ever finds an item (it ranks as\n * \"contains\"), so `Sun` puts Sunny Okafor before the Patricia Marsh who lives on Sunset Blvd.\n */\nexport function rankTypedMatches<T>(items: readonly T[], typed: string, textsOf: (item: T) => string | readonly string[]): T[] {\n  const scored: Array<{ item: T; score: number; at: number }> = [];\n  items.forEach((item, at) => {\n    const texts = textsOf(item);\n    let score = 0;\n    const list = typeof texts === \"string\" ? [texts] : texts;\n    list.forEach((text, i) => {\n      const own = typedMatchScore(text, typed);\n      score = Math.max(score, i === 0 ? own : Math.min(own, 1));\n    });\n    if (score > 0) scored.push({ item, score, at });\n  });\n  scored.sort((a, b) => b.score - a.score || a.at - b.at);\n  return scored.map((s) => s.item);\n}\n","// src/pipeline.ts — @ai-matrx/records · PRODUCTS row 7\n//\n// A PIPELINE IS NOT A NEW KIND OF THING, and this module adds none. A pipeline is a\n// Choice Field that a Table names as its STAGE field, plus transition Rules of the ONE\n// Rule object (REC-15) about that Table. A move is an ORDINARY record write: the validate\n// use judges it, History records it because it is a write, and the entry effects are the\n// applicability use's own declared consequence.\n//\n// SO THIS PACKAGE ENFORCES NOTHING. Every type below is the shape of a door's answer, and\n// every judgment comes from the store. A board that decided in the browser which column a\n// card may enter would be a second opinion with nothing keeping it equal to the first —\n// and it would be the comfortable one, because it is the one nobody can be refused by.\n\nimport type { Uuid } from \"./record\";\n\n/** One stage of a board: the KEY the store keeps, and the LABEL a person reads. */\nexport interface PipelineStage {\n  /** The option's stable key — what a cell holds, and what a move is written with. */\n  key: string;\n  /** What the column heading says. Renaming a stage rewrites no record. */\n  label: string;\n  /** A retired choice can still be READ on a record that holds it; it cannot be picked anew. */\n  retired: boolean;\n}\n\n/** What each Rule of a pipeline is about. Closed, and the store is the authority. */\nexport const PIPELINE_RULE_KINDS = [\"moves\", \"requires\", \"who\", \"limit\", \"entry\"] as const;\n/**\n * A GATE is the general form under `requires`, `who` and `limit`, and the store spells it\n * `gate:1`, `gate:2` … so several gates can sit on one stage without one overwriting the\n * next. It is matched as a prefix rather than listed, because the number is open.\n */\nexport type PipelineRuleKind = (typeof PIPELINE_RULE_KINDS)[number] | `gate:${number}`;\n\n/**\n * WHAT A GATE DOES WHEN IT SAYS NO. The closed list `custom.stage_rule_on_fail_kinds()`\n * answers — a screen offering a third answer would be offering something no Rule can carry.\n */\nexport const STAGE_RULE_ON_FAIL = [\"refuse\", \"require_approval\"] as const;\nexport type StageRuleOnFail = (typeof STAGE_RULE_ON_FAIL)[number];\n\n/**\n * THE ORGANIZATION'S ONE KNOB (`custom/stage_rule_enforcement`). `refuse` is the default and\n * what a gate is for; `warn` lets the move through and hands the same sentence back. It never\n * softens `require_approval` — \"ask somebody\" and \"carry on with a note\" are different answers.\n */\nexport const STAGE_RULE_ENFORCEMENT = [\"refuse\", \"warn\"] as const;\nexport type StageRuleEnforcement = (typeof STAGE_RULE_ENFORCEMENT)[number];\n\n/**\n * One transition Rule, as `custom.pipeline_read` hands it back — WITH the sentence it says\n * when it refuses, because a screen that knows a rule exists but not what it refuses in\n * cannot warn anybody before they drag.\n */\nexport interface PipelineRule {\n  id: Uuid;\n  name: string;\n  /** The exact words a person is shown when this Rule stops a move. */\n  message: string;\n  kind: PipelineRuleKind | null;\n  /** The stage this Rule is about; `null` on the one Rule about the moves themselves. */\n  stage: string | null;\n  uses: string[];\n  /** What happens when a card ARRIVES in this stage — assign, notify, start a checklist. */\n  on_entry: Record<string, unknown> | null;\n  /**\n   * What this Rule does when it STOPS a move. `refuse` is the default and what every\n   * pipeline Rule did before gates existed; `require_approval` files the change in the\n   * approvals queue with this Rule's sentence as the reason and leaves the record alone.\n   */\n  on_fail?: StageRuleOnFail;\n  /**\n   * THE GATE AS IT WAS WRITTEN, which is the only thing that makes it EDITABLE.\n   *\n   * A gate is saved as one Rule whose expression is an `or` of four arms — not this\n   * stage, OR not a move, OR the gate is not about this card, OR the demand holds. That\n   * compiled form used to be the only copy, so a settings screen could read a gate's name\n   * and its sentence and nothing else: it would open every existing rule with a blank\n   * condition and overwrite it the first time somebody pressed Save.\n   *\n   * Absent on the four sugar rules (`moves`, `requires`, `who`, `limit`), which nobody\n   * writes in a condition builder, and on any gate declared before the store started\n   * keeping them. Absent means \"this one was not written here\" — never \"it has no\n   * condition\", which is a different and dangerous thing to draw.\n   */\n  when?: Record<string, unknown> | null;\n  /** @see {@link PipelineRule.when} — the condition that has to hold, as it was written. */\n  demands?: Record<string, unknown> | null;\n  version: number;\n}\n\n/**\n * WHAT A GATE WOULD DO TO THIS BOARD TODAY, from `custom.pipeline_gate_preview`.\n *\n * The one question somebody writing a rule that will refuse their colleagues' work\n * actually has, answered while they are still typing it — the gate is judged as an\n * argument, nothing is saved, and nothing is written. The store compiles it with the\n * SAME compiler `pipeline_declare` uses, so this count and the refusal at the door are\n * the same rule.\n */\nexport interface PipelineGatePreview {\n  is_pipeline: boolean;\n  /** Present, and it says what would make a board exist, when `is_pipeline` is false. */\n  why?: string;\n  /** The stage key the gate was tried against. */\n  stage?: string;\n  /** Live cards of this board this person may see that are not already in that stage. */\n  considered: number;\n  /** How many of them this gate would turn away. */\n  refused: number;\n  /**\n   * Up to three of them, BY NAME. A count with no names is a number nobody can check, and\n   * checking it is the whole reason to show it before saving.\n   */\n  examples: { record_id: Uuid; title: string }[];\n  /** True when the board is larger than the preview will walk, so the count is a floor. */\n  truncated?: boolean;\n  on_fail?: StageRuleOnFail;\n  /** The word this board uses for one of its cards — \"quote\", \"deal\" — for the sentence. */\n  noun?: string;\n}\n\n/** The whole board's definition, from `custom.pipeline_read`. */\nexport interface Pipeline {\n  is_pipeline: boolean;\n  /** Present, and it says what would make a board exist, when `is_pipeline` is false. */\n  why?: string;\n  table_id?: Uuid;\n  /** The Field KEY that holds the stage — the twin of a Table's `type_field`. */\n  stage_field?: string;\n  field_id?: Uuid;\n  /** What that column is called, e.g. \"Stage\". */\n  stage_label?: string;\n  /** In the order they were declared, which is the order the board draws them. */\n  stages?: PipelineStage[];\n  rules?: PipelineRule[];\n}\n\n/** One column of the board, with the store's own numbers over what this person may see. */\nexport interface PipelineColumn {\n  stage_key: string;\n  stage_label: string;\n  /** 1-based, the declared order. */\n  stage_position: number;\n  cards: number;\n  /** The total of the chosen measure, or null when no measure was asked for. */\n  total: number | null;\n  /** How many cards this column takes at once, or null when it takes any number. */\n  wip_limit: number | null;\n  /** True when the column already holds MORE than its limit — a state a board must show. */\n  over_limit: boolean;\n}\n\n/** One column this stage demands before a card may land in it. */\nexport interface PipelineMissingField {\n  field_id: Uuid;\n  key: string;\n  /** What the column is called, so a screen can ASK for it rather than only refuse. */\n  label: string;\n}\n\n/**\n * Whether a card may go to a column, answered BEFORE the finger lets go — by the same\n * Rules, through the same evaluator, on the document the move WOULD produce.\n *\n * A board grays a column, and snaps a card back, from this. It never decides for itself.\n */\nexport interface PipelineVerdict {\n  allowed: boolean;\n  is_pipeline: boolean;\n  /**\n   * The THREE answers a board has to draw differently, and the reason `allowed` alone is\n   * not enough: a card that is going for approval has not been refused, and a card that\n   * moved under `warn` has not been waved through silently.\n   */\n  outcome?: \"allowed\" | \"refused\" | \"needs_approval\" | \"warned\";\n  /** What this organization's one knob says right now. */\n  enforcement?: StageRuleEnforcement;\n  /** Set on `needs_approval`: what pressing on will actually do, in plain words. */\n  what_happens?: string;\n  /** Set on `warned`: the gates this organization asked to be told about, not stopped by. */\n  warnings?: StageRuleWarning[];\n  /** Approvals already filed against this card's own stage column that nobody has decided. */\n  pending?: StagePending[];\n  /** The stage key the move was asked about. */\n  to?: string;\n  /** The store's own sentence — shown verbatim, never paraphrased by a screen. */\n  why: string;\n  rule?: string;\n  rule_id?: Uuid;\n  rule_version?: number;\n  kind?: PipelineRuleKind;\n  /** What this Rule does when it stops a move. */\n  on_fail?: StageRuleOnFail;\n  /**\n   * When a stage demands columns that are empty, exactly which ones — so the screen can\n   * prompt for them on entry instead of sending the person away to find them.\n   */\n  missing?: PipelineMissingField[];\n}\n\n/** What `custom.pipeline_declare` says it made or changed. */\nexport interface PipelineDeclared {\n  table_id: Uuid;\n  stage_field: string;\n  field_id: Uuid;\n  stages: string[];\n  rules: Record<string, Uuid>;\n  /** Plain sentences naming each thing this declaration wrote. */\n  said: string[];\n}\n\n/** The declaration a person (or an agent) writes. Everything is optional but the stages. */\nexport interface PipelineSpec {\n  stage_field: { key: string; label?: string; options?: string[]; sort?: number };\n  transitions?: { from: string; to: string }[];\n  /** Stage name → the column keys that must be filled in to land there. */\n  requires?: Record<string, string[]>;\n  /** Stage name → the rung somebody needs on the record to move a card INTO it. */\n  who?: Record<string, \"viewer\" | \"commenter\" | \"editor\" | \"admin\">;\n  /** Stage name → how many cards may sit there at once. The mover is not counted. */\n  limits?: Record<string, number>;\n  /** Stage name → what happens when a card arrives: assign, notify, start a checklist. */\n  on_entry?: Record<string, Record<string, unknown>>;\n  /**\n   * Stage name → the gates a card has to get past to land there. The general form under\n   * `requires`, `who` and `limits`, and the only one that can say `require_approval`.\n   */\n  gates?: Record<string, PipelineGate[]>;\n  moves_message?: string;\n  requires_messages?: Record<string, string>;\n}\n\n/**\n * A gate the organization's own knob overruled. NOTHING FAILS SILENTLY: the move happened\n * and the sentence comes back WITH it, together with what to do about it.\n */\nexport interface StageRuleWarning {\n  rule_id: Uuid;\n  rule: string;\n  /** The gate's own sentence, shown verbatim. */\n  why: string;\n  what_to_do: string;\n}\n\n/** An approval filed against this card's stage column that nobody has decided yet. */\nexport interface StagePending {\n  approval_id: Uuid;\n  /** The stage key the card is waiting to go to. */\n  to: string;\n  why: string | null;\n  requested_at: string;\n  state: string;\n}\n\n/**\n * The same wait, asked for a WHOLE BOARD in one question (`custom.pipeline_pending`), so a\n * board can badge every card that is waiting without a round trip per card — and therefore\n * actually does it, instead of drawing a filed card as if nobody had ever dragged it.\n */\nexport interface StagePendingOnBoard extends StagePending {\n  record_id: Uuid;\n}\n\n/** What `custom.pipeline_move` answers — an OBJECT on every path, never a bare number. */\nexport interface PipelineMoveResult {\n  applied: boolean;\n  moved: boolean;\n  outcome: \"moved\" | \"moved_with_warnings\" | \"needs_approval\";\n  to: string;\n  version: number;\n  /** Set on `moved_with_warnings`. */\n  warnings?: StageRuleWarning[];\n  /** Set on `needs_approval`: the gate's sentence, the wait that was filed, and who has it. */\n  why?: string;\n  rule?: string;\n  rule_id?: Uuid;\n  approval_id?: Uuid;\n  approvers?: { user_id: Uuid; name: string | null; why: string }[];\n  what_happens?: string;\n}\n\n/** One card of a batch move (`custom.pipeline_move_many`). The version is REQUIRED: it is the\n * version the board loaded, and a card that changed since answers `changed_since_loaded`. */\nexport interface PipelineMoveManyItem {\n  record_id: Uuid;\n  stage: string;\n  expected_version: number;\n  /** Columns the stage asks for, filled in on the way in. */\n  also?: Record<string, unknown>;\n}\n\n/** What one card of a batch move came to. The sentence is always the store's own. */\nexport type PipelineMoveVerdict =\n  | \"moved\"\n  | \"needs_approval\"\n  | \"needs_fields\"\n  | \"changed_since_loaded\"\n  | \"no_right\"\n  | \"refused\";\n\nexport interface PipelineMoveManyResult {\n  index: number;\n  record_id: Uuid;\n  stage: string;\n  verdict: PipelineMoveVerdict;\n  sentence: string;\n  /** Set on `needs_fields`: the empty columns the stage asks for. */\n  needs?: PipelineMissingField[];\n  /** Set on `moved` / `needs_approval`: the card's version now. */\n  version?: number;\n  /** Set on `changed_since_loaded`: the version that won. */\n  current_version?: number;\n  expected_version?: number;\n  approval_id?: Uuid;\n  approvers?: { user_id: Uuid; name: string | null; why: string }[];\n  warnings?: StageRuleWarning[];\n  rule?: string;\n  code?: string;\n}\n\n/** What `custom.pipeline_move_many` answers: the counts, then one verdict per card in order. */\nexport interface PipelineMoveMany {\n  asked: number;\n  moved: number;\n  needs_approval: number;\n  not_moved: number;\n  results: PipelineMoveManyResult[];\n}\n\n/**\n * ONE GATE ON A STAGE, as the condition builder on the stage settings screen writes it.\n * `requires`, `who` and `limits` are sugar over this shape; this is the general form, and\n * it speaks the SAME condition language as filters and formulas — never a second one.\n */\nexport interface PipelineGate {\n  /** What the gate is called in the settings list. */\n  name?: string;\n  /** The sentence a person reads when it stops them. Required: a refusal with no words is a dead end. */\n  message: string;\n  /** WHEN this gate is about this record at all. Absent means always. */\n  when?: Record<string, unknown>;\n  /** What has to hold. One condition node of the one Rule language. */\n  demands: Record<string, unknown>;\n  /** Default `refuse`. */\n  on_fail?: StageRuleOnFail;\n}\n\n/**\n * THE ONE PLACE A SCREEN DECIDES WHETHER A CARD LOOKS DRAGGABLE — and it decides on the\n * PERSON, not on the rules. Whether a particular move is allowed is\n * `pipelineTransitionRefusal`, which is the store's answer; whether this person may move\n * anything at all is their level on the record, which the read door already told us.\n *\n * Absent rather than dead: a viewer's card carries no drag handle at all, instead of one\n * that looks live and snaps back every time.\n */\nexport function mayDrag(level: string | null | undefined): boolean {\n  return level === \"editor\" || level === \"admin\" || level === \"owner\";\n}\n","// src/rule.ts — @ai-matrx/records\n//\n// THE RULE. REC-15 … REC-19. ONE object with FOUR uses — validate, compute,\n// define membership, decide applicability — and no fifth. A Rule references\n// Fields BY ID, never by name (REC-17), and it has versions, so History knows\n// which version produced a Value (REC-19).\n\nimport type { Timestamp, Uuid } from \"./record\";\nimport type { RuleNodeKind, RuleUse } from \"./vocabulary\";\n\n/**\n * A rule expression as `custom.rule_eval` ACTUALLY evaluates it — read off the\n * door's own body, not invented here. A leaf is the node's name carrying its\n * payload (`{\"const\": 3}`, `{\"field\": \"<uuid>\"}`); an operator is\n * `{\"op\": \"eq\", \"args\": [...]}`.\n *\n * `field` / `parent_field` name a Field BY ID (REC-17 — the door refuses\n * `field_name`, `field_key` and `field_label` by name), and `merge_field` is\n * the resolver's seam, storable today and refused `0A000` until W5-MERGE-B.\n *\n * `p_values` is keyed by the Field's KEY: the door resolves the id to a key\n * (`custom.rule_field_key`) and then reads `p_values -> key`.\n */\nexport type RuleExpression =\n  | { const: unknown }\n  | { field: Uuid }\n  | { parent_field: Uuid }\n  | { merge_field: string }\n  | { op: RuleNodeKind; args: RuleExpression[] };\n\n/** REC-15. One Rule, four uses; a Rule may serve more than one. */\nexport interface Rule {\n  id: Uuid;\n  organization_id: Uuid;\n  name: string;\n  kind: string | null;\n  /** The Table this Rule is scoped to. */\n  scope_table_id: Uuid | null;\n  uses: RuleUse[];\n  validates: boolean;\n  computes: boolean;\n  defines_membership: boolean;\n  /**\n   * REC-16. An applicability Rule reads the record's own Values and its\n   * parent's, ONE level up, and no further.\n   */\n  decides_applicability: boolean;\n  applies_to_types: string[];\n  use_types: string[];\n  expr: RuleExpression;\n  /** Which Field this Rule's answer is about (REC-17: by id). */\n  target_field_id: Uuid | null;\n  /** What a person reads when this Rule refuses. */\n  message: string | null;\n  sort: number | null;\n  created_by: Uuid | null;\n  updated_by: Uuid | null;\n  created_at: Timestamp;\n  updated_at: Timestamp;\n  /** REC-19. Rules have versions, and History knows which one produced a Value. */\n  version: number;\n  metadata: Record<string, unknown>;\n  visibility: string;\n}\n\n/** What the store answers when a Rule is run: the answer and the version that gave it. */\nexport interface RuleAnswer {\n  rule_id: Uuid;\n  rule_name: string;\n  rule_version: number;\n  applies: boolean;\n  answer: unknown;\n}\n\n// ── PRODUCTS row 1: a form is a VIEW ON A REAL TABLE ─────────────────────────\n//\n// A form lives beside the Rules because that is what it is MADE of: an accept\n// Rule decides what counts as a complete answer, and a subscription Rule (DOOR-18)\n// decides who hears about one. The questions are Fields of the subject Table and\n// the answers are ordinary records in it — there is no form silo anywhere.\n\n/** One form as `custom.forms` reports it to its owner. */\nexport interface FormSummary {\n  form_id: string;\n  table_id: string;\n  title: string | null;\n  slug: string;\n  published_at: string | null;\n  closed_at: string | null;\n  submission_cap: number | null;\n  /** Every answer that arrived, rejected ones excluded from `in_table` and `held`. */\n  responses: number;\n  /** Answers that became records — the only number that means \"it is in the table\". */\n  in_table: number;\n  /** Answers waiting for a person, because the form's accept Rule did not clear them. */\n  held: number;\n  /** Answers the accept Rule or the decoy turned away. */\n  rejected: number;\n  /** draft · open · closed · full — the store's own word, never derived on a screen. */\n  state: \"draft\" | \"open\" | \"closed\" | \"full\";\n  quarantine_rule_id: string | null;\n  notify_rule_id: string | null;\n  presentation: Record<string, unknown>;\n}\n\n/**\n * THE ROUTE THROUGH A FORM, AS THE STORE WALKED IT (lane TYPEFORM-DUP) — `custom._form_route`,\n * reached by the owner's preview (`custom.form_preview_route`) and the stranger's page\n * (`custom.form_public_route`). One row per question in order (`asked` false only when a condition\n * hid it or a logic jump carried the person past it); the ending reached (null = the thank-you\n * screen); the score (null when no question carries points).\n */\nexport interface FormRoute {\n  asks: Array<{ field_key: string; asked: boolean; decided: boolean; said: string | null }>;\n  ending: string | null;\n  score: number | null;\n}\n\n/** A form's results for its owner — `custom.form_results`. Every number is the store's. */\nexport interface FormResults {\n  form_id: string;\n  /** Visits to the public link (one per page open, counted through the app's own route). */\n  views: number;\n  /** Visits that answered at least one question. */\n  starts: number;\n  /** Submissions that arrived (the decoy's excluded). */\n  completions: number;\n  /** completions / starts, as a percentage with one decimal; null before anybody started. */\n  completion_rate: number | null;\n  questions: Array<{\n    field_key: string;\n    /** Visits that were shown this question. */\n    reached: number;\n    /** Visits whose last question was this one and that never sent: the drop-off. */\n    left: number;\n    /** Submissions that answered it. */\n    answered: number;\n    /** The twelve most common answers (a list answer counts each of its parts). */\n    answers: Array<{ value: string; count: number }>;\n  }>;\n  endings: Array<{ ending: string | null; count: number }>;\n  hidden: Array<{ key: string; value: string; count: number }>;\n  score: { count: number; average: number; min: number; max: number } | null;\n}\n\n/**\n * ONE BOOKING PAGE, AS ITS OWNER SEES IT — `custom.bookings` (PRODUCTS row 14).\n *\n * A booking page is an `anon_form` whose `presentation -> 'booking'` carries the\n * availability and the id of a slots Table, so it is the SAME object a form is and\n * this is the same list `forms()` is, asked for the booking half. The numbers are\n * the store's own: a screen that counted appointments in the browser would drift\n * from the index that actually protects a slot.\n */\nexport interface BookingSummary {\n  form_id: string;\n  /** The Table the appointments land in — a booking is an ordinary record in it. */\n  table_id: string;\n  title: string | null;\n  slug: string;\n  published_at: string | null;\n  closed_at: string | null;\n  /** How long one appointment is. The offer is the store's, never the browser's. */\n  slot_minutes: number;\n  /** The organization's own zone, which is what the visitor's times are drawn in. */\n  timezone: string;\n  /** The ONE slots Table `custom.booking_declare` finds-or-makes for this page. */\n  slot_table_id: string;\n  booked: number;\n  cancelled: number;\n  /** Booked and still ahead of now — the number that answers \"what is coming\". */\n  upcoming: number;\n  /** Slots a visitor is holding right now, before they have given their details. */\n  held: number;\n  /** The next appointment, or null when there is none. */\n  next_at: string | null;\n  /** draft · open · closed — the store's own word, never derived on a screen. */\n  state: string;\n}\n\n/**\n * ONE WINDOW OF AN ORGANIZATION'S WEEK, in the shape `custom._booking_availability`\n * normalizes to and `custom._booking_slots` generates from. `weekday` is 0 for Sunday\n * and 6 for Saturday — the database's own numbering, so a picker and the store cannot\n * disagree about which day Monday is. A window may name ONE member, which is the \"with\n * whom\" of an appointment; naming somebody who is not a member is refused BY NAME.\n */\nexport interface BookingWindow {\n  weekday: number;\n  /** \"09:00\" */\n  from: string;\n  /** \"17:00\" — later in the day than `from`, or the store refuses it by name. */\n  to: string;\n  member_user_id?: string | null;\n}\n\n/**\n * WHAT IS ON OFFER. Every field is the store's to default: a page declared with an\n * empty availability comes back with the organization's timezone, a 30-minute slot and\n * Monday-to-Friday nine-to-five, because a booking page that offered nothing would look\n * broken rather than unconfigured. A screen shows what came BACK, never what it sent.\n */\nexport interface BookingAvailability {\n  timezone: string;\n  slot_minutes: number;\n  /** Dead time kept after each appointment, so two never touch. */\n  buffer_minutes: number;\n  /** How far ahead of now the earliest bookable slot is. */\n  lead_minutes: number;\n  /** Most appointments in one day, across every window. */\n  max_per_day: number;\n  /** How many days ahead the page offers. */\n  days: number;\n  windows: BookingWindow[];\n  /** CD-PAGE-10: places at one time for each host (1 = one person per time; a class or group visit takes more). */\n  capacity?: number;\n  /** CD-PAGE-10: none, auto (a new meet.jit.si room per booking) or link (the owner's own room in `video_url`). */\n  video?: \"none\" | \"auto\" | \"link\";\n  video_url?: string;\n  /** CD-PAGE-10: the owner's private iCal address; its busy times are never offered. Owner-only — never in a public answer. */\n  busy_feed?: string;\n  /** CD-PAGE-10: when the connected calendar was last read, and why the last read failed (the last good list is kept). */\n  busy_read_at?: string | null;\n  busy_problem?: string | null;\n}\n\n/**\n * WHAT `custom.booking_declare` ANSWERS. `availability` is the NORMALIZED offer —\n * show that, not the draft — and `questions_filled_in` is how many questions the store\n * took over (`slot`, `status`, `booked_with`), which a visitor is never asked.\n *\n * It does NOT publish. `anonPublish` is still the one act that opens the link, exactly\n * as it is for a form, so there is one act and one word for opening a public surface.\n */\nexport interface BookingDeclared {\n  form_id: string;\n  slot_table_id: string;\n  availability: BookingAvailability;\n  questions_asked: number;\n  questions_filled_in: number;\n  ms: number;\n}\n\n/**\n * THE VISITOR'S OWN LINK to a booking page. The page id IS the capability, exactly\n * as it is for a form; `custom.anon_submission.booking_ref` is the separate secret\n * that lets ONE visitor manage the appointment they made.\n */\nexport function bookingPath(formId: string): string {\n  return `/b/${formId}`;\n}\n\n/**\n * THE PUBLIC LINK, and the one place its shape is written down.\n *\n * The form's own id IS the capability — 122 bits of UUIDv4, exactly as\n * Typeform's form id in `/to/<id>` is and as an unguessable meeting slug is\n * here. There is no second secret to keep, and revoking it is closing the form.\n */\nexport function publicFormPath(formId: string): string {\n  return `/f/${formId}`;\n}\n","// src/portal.ts — @ai-matrx/records\n//\n// THE CLIENT PORTAL, FROM THE OWNER'S SIDE.\n//\n// A portal is the one way somebody with no membership of an organization is\n// let in to see the records that name them — their jobs, their invoices —\n// and nothing else. The store holds it in three tables (`custom.portal`,\n// `custom.portal_table`, `custom.portal_principal`) and answers about it\n// through six doors. These are the shapes those doors answer with, written\n// from the doors' own bodies and never from a screen's convenience.\n//\n// TWO FACTS THIS FILE EXISTS TO KEEP STRAIGHT, because a screen that gets\n// either of them wrong tells somebody a comforting lie:\n//\n//   · AN INVITATION CONFERS NOTHING. `custom.portal_invite` writes a row and\n//     says so in its own `say` sentence: the person gets access the moment\n//     they follow the sign-in link and the platform gives them an identity,\n//     and until then the row holds nothing at all. That is why\n//     `PortalPrincipal` carries `signed_in` separately from `is_active` —\n//     \"invited\" and \"can see their records\" are two different states and one\n//     number for both is how an owner comes to believe a client is looking at\n//     something they cannot reach.\n//\n//   · \"VIEW AS THIS CLIENT\" IS NOT A PORTAL-SHAPED QUERY.\n//     `custom.portal_preview` asks `custom.visible_set` for HER user id — the\n//     exact call `custom.read_records` makes when she opens the page — so the\n//     preview cannot disagree with what she sees. When she has not signed in\n//     yet it REFUSES with `02000` and a sentence, rather than answering an\n//     empty list that would read as \"she sees nothing\".\n\nimport type { Timestamp, Uuid } from \"./record\";\n\n/** One portal as `custom.portals` reports it to its organization. */\nexport interface PortalSummary {\n  portal_id: Uuid;\n  title: string;\n  slug: string;\n  /** The Table whose records ARE the clients. A principal is one of its rows. */\n  client_table_id: Uuid;\n  /** That Table's name, so a list never has to read a second door to draw a row. */\n  client_table: string;\n  is_active: boolean;\n  /** How many Tables this portal exposes. */\n  tables: number;\n  /** Everybody invited and not revoked — NOT everybody who can see anything. */\n  invited: number;\n  /** Of those, how many have followed the link and hold an identity. */\n  signed_in: number;\n  /** `magic_link` today, and the door refuses every other word by name. */\n  sign_in_method: string;\n  opened_at: Timestamp | null;\n}\n\n/**\n * ONE (portal, Table) PAIR, as `custom.portal_tables` reports it.\n *\n * 🚨 WHY THIS EXISTS (TAILS-3, 2026-09-21). The Portals rail sits on a Table's\n * page beside Forms, Bookings and Dashboards — all table-scoped — while\n * `custom.portals` takes no table at all. On Rincon Plumbing Co's **Parts**\n * table the rail read \"Portals 10\" and listed ten cards titled \"Your jobs and\n * invoices\", which belong to **Jobs**; the empty state never rendered, so the\n * \"Build it / Ask an agent\" offer was unreachable on EVERY table of any\n * organization that already had one portal.\n *\n * This is the whole of what a table-scoped rail needs: is the table I am\n * standing on in any portal, and if not, which portals could take it.\n */\nexport interface PortalTableRef {\n  portal_id: Uuid;\n  table_id: Uuid;\n  /** That Table's name, so a rail never reads a second door to draw a row. */\n  name: string;\n}\n\n/** One Table a portal exposes, as `custom.portal_card` reports it. */\nexport interface PortalTableExposure {\n  table_id: Uuid;\n  /** The Table's own name. */\n  name: string;\n  /**\n   * The key of the relation Field that says WHOSE a record is. This is the\n   * whole of \"only theirs\": the association that Field writes is what carries\n   * the record to the client, so a portal cannot exist without one.\n   */\n  names_via: string;\n  /** The field keys a client sees. Empty is impossible — the door fills it. */\n  visible_fields: string[];\n  /** The subset a client may change. Always a subset of `visible_fields`. */\n  editable_fields: string[];\n  comments: boolean;\n  /**\n   * The most a client is ever conveyed on this Table — `viewer`, `commenter`\n   * or `editor` — worked out by the door from the two lists above, never by a\n   * screen.\n   */\n  conveys: string;\n}\n\n/** One person a portal was opened to, as `custom.portal_card` reports them. */\nexport interface PortalPrincipal {\n  principal_id: Uuid;\n  email: string;\n  /** The record of the client Table this person IS, for the portal's purposes. */\n  client_record_id: Uuid;\n  /** That record's title — what an owner calls this client. */\n  client: string;\n  /** They followed the link and hold an identity. Until then this is false. */\n  signed_in: boolean;\n  /** Not revoked. An invitation that was never followed is still active. */\n  is_active: boolean;\n  invited_at: Timestamp;\n  revoked_at: Timestamp | null;\n  /**\n   * THE LINK THE OFFICE COPIES FOR THIS PERSON — `/invitations/portal/accept/<token>`, the\n   * path `custom.portal_invite` handed back when they were asked, read off the same\n   * `iam.invitations` row and never re-templated.\n   *\n   * 🚨 `null` IS AN ANSWER, NOT AN ABSENCE, and a screen must say which. It is null when they\n   * have already followed the link, when the office took it back (a revoke withdraws the\n   * invitation in the same statement), when it has expired, or when they were let in through\n   * the server's own magic-link route, which binds without an invitation at all. In every one\n   * of those cases there is genuinely no link to copy — so draw a sentence, never a dead\n   * control. (TAILS-5, 2026-09-21; the gap PORTAL-BIND left named.)\n   */\n  accept_path: string | null;\n}\n\n/** Everything about ONE portal: what it shows, and who it was opened to. */\nexport interface PortalCard {\n  portal_id: Uuid;\n  title: string;\n  slug: string;\n  is_active: boolean;\n  sign_in_method: string;\n  client_table_id: Uuid;\n  tables: PortalTableExposure[];\n  principals: PortalPrincipal[];\n  /**\n   * Whether this organization's outside lane is open\n   * (`custom/external_principal_enabled`). Declaring a portal opens it; while\n   * it is false every door refuses an outsider BY NAME, and a screen that drew\n   * the people as reachable anyway would be lying about the one thing that\n   * decides whether they can sign in at all.\n   */\n  external_lane_open: boolean;\n  /** S6 — the look and forms exactly as the owner stored them (`{}` when none). */\n  config: PortalConfig;\n  /** S6 — the look as a client sees it: the portal's own values over the organization's brand. */\n  style: PortalStyle;\n  /** S6 — every form on the portal, in its order, with its title, Table and state. */\n  forms: PortalFormRef[];\n  /** S6 — the accent names a portal may carry (the design system's `STYLE_COLORS`). */\n  accents: PortalAccent[];\n  /**\n   * S6 — the pictures that could be this portal's logo: the organization's own PUBLIC pictures in\n   * Files, newest first. A private file is never offered, because the store would refuse it.\n   */\n  logo_candidates: PublicPicture[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// S6 — A PORTAL CARRIES ITS OWN LOOK AND ITS FORMS (UI-CHAMPIONS-PLAN rows 45, 46, 55)\n//\n// The look and the forms live on the portal's own record (`custom.portal.config`), written only\n// by `custom.portal_declare(… p_config)` and judged there: a logo must be a PUBLIC picture of this\n// organization's Files (a portal's logo is shown on its sign-in page, before anybody has signed\n// in), an accent is one of the design system's color names, and a form is refused unless its\n// answers land in a Table the portal shows. The organization's brand is the default, so a portal\n// with no look of its own is never blank — `from_organization` says which values came from there.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The design system's color names (`STYLE_COLORS`), which is all an accent may be. */\nexport const PORTAL_ACCENTS = [\"slate\", \"green\", \"amber\", \"red\", \"blue\", \"violet\", \"teal\"] as const;\nexport type PortalAccent = (typeof PORTAL_ACCENTS)[number];\n\nexport function isPortalAccent(word: unknown): word is PortalAccent {\n  return typeof word === \"string\" && (PORTAL_ACCENTS as readonly string[]).includes(word);\n}\n\n/** One link in a portal's footer. The store takes only `https://`, `mailto:` and `tel:`. */\nexport interface PortalFooterLink {\n  label: string;\n  url: string;\n}\n\n/** A portal's look as the owner sets it. Every key is optional; absent means \"the organization's\". */\nexport interface PortalStyleInput {\n  display_name?: string | null;\n  welcome?: string | null;\n  logo_file_id?: Uuid | null;\n  accent?: PortalAccent | null;\n  footer_links?: PortalFooterLink[] | null;\n}\n\n/** One form on a portal, as the owner sets it. `order` is the position; `label` overrides the title. */\nexport interface PortalFormInput {\n  form_id: Uuid;\n  label?: string | null;\n  order?: number | null;\n}\n\n/**\n * What `portalDeclare({ config })` sends. A key given REPLACES that key; a key not given is KEPT;\n * `style: null` puts the organization's brand back and `forms: []` takes every form off.\n */\nexport interface PortalConfigInput {\n  style?: PortalStyleInput | null;\n  forms?: PortalFormInput[] | null;\n}\n\n/** The look and forms as the store holds them (normalized by the store). */\nexport interface PortalConfig {\n  style?: PortalStyleInput;\n  forms?: Array<{ form_id: Uuid; label?: string; order: number }>;\n}\n\n/** The look a client is shown — resolved by the store, never computed by a screen. */\nexport interface PortalStyle {\n  display_name: string;\n  welcome: string | null;\n  logo_file_id: Uuid | null;\n  /** The logo's PUBLIC address, or null. Readable by anybody the portal is shown to. */\n  logo_url: string | null;\n  /** Null means the app's own color. */\n  accent: PortalAccent | null;\n  footer_links: PortalFooterLink[];\n  /** MAKE-HOME W5 — a cover picture's PUBLIC address (a form's look carries one), or null. */\n  cover_file_id?: Uuid | null;\n  cover_url?: string | null;\n  /** Which of the values above came from the organization rather than the portal. */\n  from_organization: Array<\"display_name\" | \"logo\">;\n}\n\n/**\n * One of the organization's PUBLIC pictures (`custom._public_pictures`): the only pictures a\n * portal's logo or a form's logo and cover may be, because a stranger sees them before signing in.\n */\nexport interface PublicPicture {\n  file_id: Uuid;\n  name: string;\n  url: string | null;\n}\n\n/**\n * What a form's look editor needs (`custom.form_look_options`, MAKE-HOME W5b): the pictures the\n * store accepts, the colors, and the look a stranger would see for the draft presentation.\n */\nexport interface FormLookOptions {\n  pictures: PublicPicture[];\n  accents: PortalAccent[];\n  look: PortalStyle;\n}\n\n/** One form on a portal, with what the owner needs to see about it. */\nexport interface PortalFormRef {\n  form_id: Uuid;\n  /** What the portal calls it (the owner's label, else the form's title). */\n  label: string;\n  order: number;\n  title: string;\n  table_id: Uuid | null;\n  table: string;\n  /** `gone` is a form that was removed; the outsider's list only ever carries `open`. */\n  state: \"open\" | \"closed\" | \"full\" | \"gone\";\n}\n\n/** A Table's stages as a portal client may be told them (`custom.portal_me` → tables[].stage). */\nexport interface PortalStage {\n  /** The stage Field's key on the record. */\n  field: string;\n  label: string;\n  /** In the order they were declared. A record stores the stage's `key`. */\n  stages: Array<{ key: string; label: string; retired: boolean }>;\n}\n\n/** What `custom.portal_form` answers: one form on the caller's own portal. */\nexport interface PortalFormSpec {\n  form_id: Uuid;\n  portal_id: Uuid;\n  table_id: Uuid;\n  title: string;\n  label: string;\n  presentation: Record<string, unknown>;\n  /** The form's exposed Fields as the store holds them — never the one naming the client. */\n  fields: Array<Record<string, unknown> & { id: Uuid; key: string }>;\n  required: string[];\n  state: \"open\" | \"closed\" | \"full\";\n  message: string | null;\n}\n\n/** What `custom.portal_form_submit` answers. `held` waits for the office; `message` says so. */\nexport interface PortalFormAnswer {\n  submission_id: Uuid | null;\n  record_id: Uuid | null;\n  state: \"accepted\" | \"held\" | \"rejected\" | \"closed\" | \"full\" | \"too_many\";\n  message: string | null;\n}\n\n/** What `custom.portal_invite` answers. `say` is the door's own sentence. */\nexport interface PortalInvitation {\n  invited: boolean;\n  principal_id: Uuid;\n  portal_id: Uuid;\n  slug: string;\n  email: string;\n  client_record_id: Uuid;\n  client: string;\n  /** They already hold an identity. From a screen this is false: the door is passed no user. */\n  bound: boolean;\n  /**\n   * The door's own words, and the ONLY correct summary of what just happened —\n   * it says outright that an invitation confers nothing until the link is\n   * followed. Show it; never paraphrase it.\n   */\n  say: string;\n}\n\n/** What `custom.portal_revoke` answers. `say` names the consequence, past tense. */\nexport interface PortalRevocation {\n  revoked: boolean;\n  principal_id: Uuid;\n  email: string;\n  /** The door's own sentence: they can no longer sign in, and their records stop reaching them. */\n  say: string;\n}\n\n/** One row of \"what this client sees\", from `custom.portal_preview`. */\nexport interface PortalPreviewRow {\n  record_id: Uuid;\n  title: string;\n}\n\n/**\n * THE PUBLIC ADDRESS OF A PORTAL, and the one place its shape is written down.\n *\n * Unlike a form's link, a portal's slug is NOT the capability: the page it\n * serves asks who you are and emails a one-time link, so the slug is a name and\n * nothing more. That is why it is readable and why copying it is safe.\n */\nexport function portalPath(slug: string): string {\n  return `/portal/c/${slug}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// A PORTAL IS ARCHIVED, NEVER DELETED (ORG-CLEANUP, 2026-09-22)\n//\n// The store grew `custom.portal_archive`, `custom.portal_restore` and the\n// archive-aware `custom.list_portals` because Rincon Plumbing Co carried TEN\n// portals all titled \"Your jobs and invoices\" — nine of them the residue of one\n// walk repeated nine times — and there was no door to put any of them away.\n// `is_active = false` is not it: CLOSED is a state an organization chooses about\n// a portal it still has, and its clients are told so by name. ARCHIVED means it\n// is out of the way, and nothing is deleted: every exposed Table and every\n// invited person is handed back exactly as it was.\n//\n// These are the words a screen says about that, written once here so the rail,\n// the guard and any other client say the same thing.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * The platform archive filter's own three values, and no fourth. `custom.list_portals`\n * refuses anything else with `22023` rather than quietly treating it as one of them.\n */\nexport const PORTAL_ARCHIVE_FILTERS = [\"active\", \"archived\", \"all\"] as const;\nexport type PortalArchiveFilter = (typeof PORTAL_ARCHIVE_FILTERS)[number];\n\n/** THE LAW'S DEFAULT IS TO HIDE. A list nobody narrowed is the live things. */\nexport const DEFAULT_PORTAL_ARCHIVE_FILTER: PortalArchiveFilter = \"active\";\n\nexport function isPortalArchiveFilter(word: unknown): word is PortalArchiveFilter {\n  return typeof word === \"string\" && (PORTAL_ARCHIVE_FILTERS as readonly string[]).includes(word);\n}\n\n/** What `custom.portal_archive` and `custom.portal_restore` answer with. */\nexport interface PortalArchiveAnswer {\n  /** Where the portal stands NOW — true after an archive, false after a restore. */\n  archived: boolean;\n  /** False when it was already in that state; the sentence says so rather than lying about an act. */\n  changed: boolean;\n  portal_id: Uuid;\n  archived_at?: Timestamp | null;\n  /** The store's own sentence, in plain English. Show it verbatim; never a constraint name. */\n  sentence: string;\n}\n\n/**\n * THE CONSEQUENCE, SAID BEFORE THE CLICK — never a generic \"are you sure?\".\n *\n * What actually changes is two things: nobody can sign in to it any more, and it\n * leaves the organization's portal list. What does NOT change is everything\n * else, and saying so is the difference between an archive somebody dares to\n * press and one they avoid.\n */\nexport function portalArchiveConsequence(title: string, signedIn: number, invited: number): string {\n  const people =\n    invited === 0\n      ? \"Nobody is invited to it\"\n      : signedIn === 0\n        ? `The ${invited} ${invited === 1 ? \"person\" : \"people\"} invited to it will not be able to sign in`\n        : `The ${signedIn} ${signedIn === 1 ? \"person\" : \"people\"} signed in to it, and the ${invited - signedIn} still invited, will not be able to sign in`;\n  return (\n    `“${title}” will leave your portal list. ${people}, and their invitation links will say this ` +\n    `portal was archived and can be restored. Nothing is deleted — every Table it shows and ` +\n    `everyone invited to it is kept exactly as it is, and you can restore it at any time.`\n  );\n}\n\n/**\n * WHY THE TITLE HAS TO BE TYPED BACK, in the store's own reasoning. Ten portals\n * can carry one title, so the title is not what PICKS this one — the portal you\n * opened is. Typing it back is how you say you meant this one.\n */\nexport function portalConfirmLine(title: string): string {\n  return `Type the portal’s title — ${title} — to confirm you mean this one.`;\n}\n\n/** True when what the person typed is what the door will accept. The door decides; this only spares them a round trip. */\nexport function portalTitleTypedBack(typed: string, title: string): boolean {\n  return typed.trim() === (title ?? \"\").trim();\n}\n\n/**\n * WHAT AN EMPTY ARCHIVE LANE SAYS. An empty list is an answer: it says nothing\n * has been archived, so \"none here\" can never be read as \"the archive is broken\"\n * or as \"this organization has no portals at all\".\n */\nexport function emptyPortalArchiveLine(): string {\n  return \"No portal of this organization has been archived. A portal you put away waits here until somebody restores it, and nothing is ever destroyed.\";\n}\n","// src/rowControls.ts — @ai-matrx/records · ROW CONTROLS AND THE ARCHIVE OF WHAT IS BUILT ON A TABLE\n//\n// Lane MAKE-HOME wave 6a (2026-10-03). Two client halves of doors the chair landed:\n//\n//   · ROW CONTROLS (access ladder § Words, row layer): `custom.table_row_defaults(_set)`,\n//     `custom.table_row_defaults_apply`, `custom.record_row_controls(_set)`. A table names what its\n//     NEW rows start with (Arman 2026-10-02: auto-applied to every row, always overridable per row);\n//     \"Apply to existing rows\" moves the rows nobody set by hand. The web half (Published to the\n//     web, Indexed) answers `available: false` until its columns land — screens show it as a state.\n//\n//   · THE ARCHIVE OF FORMS, BOOKING PAGES AND CHECKLIST TEMPLATES: `custom.form_archive` /\n//     `custom.form_restore` / `custom.forms_archived` (a booking page is a form with a booking) and\n//     `custom.checklist_templates_archived` (a template is a record: `record_delete` archives it,\n//     `record_restore` brings it back). Delete means archive; every archive has a way back.\n//\n// The words are the access ladder's own (Only me · My team · Everyone · Everyone on AI Matrx) —\n// never coined here.\n\nimport type { Timestamp, Uuid } from \"./record\";\n\n/** The four values of \"Shown to\", in the ladder's order. */\nexport const SHOWN_TO_VALUES = [\"only_me\", \"my_team\", \"everyone\", \"everyone_on_ai_matrx\"] as const;\nexport type ShownTo = (typeof SHOWN_TO_VALUES)[number];\n\n/** THE WORDS (access ladder § Words, row \"Shown to\"). One label per value, used by every screen. */\nexport const SHOWN_TO_LABEL: Record<ShownTo, string> = {\n  only_me: \"Only me\",\n  my_team: \"My team\",\n  everyone: \"Everyone\",\n  everyone_on_ai_matrx: \"Everyone on AI Matrx\",\n};\n\nexport function isShownTo(word: unknown): word is ShownTo {\n  return typeof word === \"string\" && (SHOWN_TO_VALUES as readonly string[]).includes(word);\n}\n\n/**\n * Does a Table's Level give its records a \"Shown to\"? (Access ladder § Words: \"Private and\n * Confidential records have no 'Shown to'\".) Absent or unknown level = yes, as before. The ONE test\n * every screen asks before it draws the control, so a locked table never shows a control that does\n * not exist for it.\n */\nexport function levelHasShownTo(level: unknown): boolean {\n  const word = typeof level === \"string\" ? level.trim().toLowerCase() : \"\";\n  return word !== \"confidential\" && word !== \"private\";\n}\n\n/** What `custom.table_row_defaults` answers: the table's own choices, what applies, and what may change. */\nexport interface TableRowDefaults {\n  /** The table's own choice; null = the organization's default. */\n  shown_to: ShownTo | null;\n  published_to_web: boolean | null;\n  indexed: boolean | null;\n  effective: { shown_to: ShownTo; published_to_web: boolean; indexed: boolean };\n  allowed_shown_to: ShownTo[];\n  available: { shown_to: boolean; published_to_web: boolean; indexed: boolean };\n  can_change: boolean;\n}\n\n/** What `custom.table_row_defaults_set` takes. A key left out is left alone; null = back to the default. */\nexport interface TableRowDefaultsPatch {\n  shown_to?: ShownTo | null;\n  published_to_web?: boolean | null;\n  indexed?: boolean | null;\n}\n\n/** One pass of `custom.table_row_defaults_apply`. `done: false` → call again with `next_after`. */\nexport interface RowDefaultsApplied {\n  table_id: Uuid;\n  seen: number;\n  changed: number;\n  kept_by_hand: number;\n  done: boolean;\n  next_after: Uuid | null;\n  /** The store's own sentence. Show it verbatim. */\n  sentence: string;\n}\n\n/** What `custom.record_row_controls` answers for one row. */\nexport interface RecordRowControls {\n  shown_to: {\n    value: ShownTo | null;\n    effective: ShownTo;\n    type_default: ShownTo | null;\n    table_default: ShownTo | null;\n    allowed: ShownTo[];\n    is_child: boolean;\n    can_change: boolean;\n    legacy_only_me?: boolean;\n  };\n  published_to_web: { available: boolean; value: boolean; table_default: boolean | null; can_change: boolean };\n  indexed: {\n    available: boolean;\n    value: boolean | null;\n    table_default: boolean | null;\n    effective: boolean;\n    can_change: boolean;\n  };\n}\n\n/**\n * WHO MAY CHANGE A ROW'S \"Shown to\" (NOT its cells: a cell needs Editor on the table), in one sentence — the store's rung (`platform.shown_to_state`:\n * the person who made it, or someone with full access to it). Said where the control would be.\n */\nexport const SHOWN_TO_WHO_MAY_CHANGE = \"Only who added this row, or an admin, can change who sees it.\";\n\n/** The sentence beside the two web switches while the store does not carry them yet. */\nexport const ROW_WEB_NOT_READY = \"Not available for table rows yet.\";\n\n// ── The archive of what is built on a table ──────────────────────────────────\n\n/** What `custom.form_archive` and `custom.form_restore` answer with. */\nexport interface FormArchiveAnswer {\n  archived: boolean;\n  changed: boolean;\n  form_id: Uuid;\n  kind: \"form\" | \"booking\";\n  title: string | null;\n  archived_at?: Timestamp | null;\n  /** The store's own sentence. Show it verbatim. */\n  sentence: string;\n}\n\n/** One row of `custom.forms_archived` — a form or a booking page that was put away. */\nexport interface ArchivedForm {\n  form_id: Uuid;\n  table_id: Uuid;\n  table_name: string | null;\n  kind: \"form\" | \"booking\";\n  title: string | null;\n  slug: string;\n  archived_at: Timestamp;\n  archived_by: Uuid | null;\n  table_archived: boolean;\n  can_restore: boolean;\n}\n\n/** One row of `custom.checklist_templates_archived`. */\nexport interface ArchivedChecklistTemplate {\n  template_id: Uuid;\n  name: string | null;\n  about_table_id: Uuid | null;\n  about_table: string | null;\n  steps: number;\n  archived_at: Timestamp;\n  archived_by: Uuid | null;\n  table_archived: boolean;\n}\n\n/** What an archived form, booking page or checklist is called in a list. */\nexport const BUILT_KIND_WORD: Record<\"form\" | \"booking\" | \"checklist\", string> = {\n  form: \"Form\",\n  booking: \"Booking page\",\n  checklist: \"Checklist\",\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/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","// 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/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/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/automation.ts — @ai-matrx/records\n//\n// AUTOMATIONS ON A TABLE (lane AUTOMATION-DOOR, 2026-10-07): \"when this happens to a row of this table, do\n// these things\". Declared with one door (`custom.automation_declare`), stored in the Table record's\n// `automations` list, run from the store's own change feed. Fields are named by ID. The words for each part\n// are in FEATURE.md § Automations on a table.\n\nimport type { Uuid } from \"./record\";\n\n/** A value an action writes: a literal, or a reference the store resolves at run time. */\nexport type AutomationValue =\n  | string\n  | number\n  | boolean\n  | null\n  | { from: Uuid } // copy this property from the triggering row\n  | { now: true }\n  | { in_days: number } // that many days from the moment the automation runs (a date column keeps the person's day)\n  | { me: true }\n  | { clear: true }\n  | unknown[]\n  | Record<string, unknown>;\n\n/** `{ [field id]: value }` — every key is a live Field of the table the step writes to. */\nexport type AutomationValues = Record<Uuid, AutomationValue>;\n\n/** A filter in the store's one rule shape; inside an `edit_rows.where`, `{ trigger: <field id> }` means that value on the triggering row. */\nexport type AutomationFilter = Record<string, unknown>;\n\n/** Days of the week as the store counts them: 1 Monday … 7 Sunday. */\nexport type AutomationWeekday = 1 | 2 | 3 | 4 | 5 | 6 | 7;\n\nexport type AutomationTrigger =\n  | { on: \"row_added\" }\n  | { on: \"property_edited\"; field: Uuid; to?: unknown }\n  | { on: \"form_answered\" }\n  /**\n   * AUTOMATIONS-AIRTABLE: Airtable's \"When record updated\" — any of `fields` edited (an empty list or none = any\n   * property).\n   */\n  | { on: \"record_updated\"; fields?: Uuid[] }\n  /**\n   * AUTOMATIONS-AIRTABLE: Airtable's \"When record matches conditions\" (the spec's `condition`, any depth) or, with\n   * `view_id`, \"When record enters view\" (that saved view's own filter, read at run time). Fires when a row COMES TO\n   * match — added matching, or edited from not matching to matching — never again while it stays matching.\n   */\n  | { on: \"record_matches\"; view_id?: Uuid }\n  /** AUTOMATIONS-AIRTABLE: a press of this button column (`custom.button_press`) on a row runs it on that row. */\n  | { on: \"button_pressed\"; field: Uuid }\n  /**\n   * AUTOMATION-TIME: a date or date-time property reaching now, `offset_days` before (negative) or after\n   * (positive), at `at` (HH:MM, default 09:00) in the person's own zone, else the organization's. Fires once per row\n   * per date value; the date changing re-arms it.\n   */\n  | { on: \"date_arrives\"; field: Uuid; offset_days?: number; at?: string }\n  /**\n   * AUTOMATION-TIME: the table acts with no row, every day / week (`weekday`) / month (`day`, 1-31, a short month\n   * runs on its last day) at `at`. `set`, a person property, `{from}` and `{trigger}` have no row to read and are\n   * refused; `add_row` is the repeating row and `edit_rows` the scheduled bulk edit.\n   */\n  | { on: \"schedule\"; every: \"day\" | \"week\" | \"month\"; at?: string; weekday?: AutomationWeekday; day?: number }\n  /**\n   * AT-AUTO2: every N minutes (5, 10, 15, 30) or every N hours (1, 2, 3, 4, 6, 8, 12) at `minute` past. Saved switched\n   * OFF; the person switches it on (no blind paid automations).\n   */\n  | { on: \"schedule\"; every: \"minutes\"; minutes: 5 | 10 | 15 | 30 }\n  | { on: \"schedule\"; every: \"hour\"; hours?: number; minute?: number }\n  /**\n   * AT-AUTO2: an inbound webhook. The store makes the automation's `webhook_secret`; the URL is\n   * `automationWebhookUrl(serverBase, automation)`. The JSON body is `{{trigger.body.…}}` to every step.\n   */\n  | { on: \"webhook\" }\n  /**\n   * W2-E: a new email in the OWNER's own connected Gmail matching `query` (Gmail search syntax; none = every new\n   * email). Like every connected-app trigger it has no row, is saved switched OFF, and once switched on the server\n   * checks the account on the automation's own personal schedule (`automationAppTriggerTerms`); each new item starts one\n   * run with the item as `{{trigger.body.…}}` (`subject`, `from`, `to`, `snippet`, `date`, `link`, `id`).\n   */\n  | { on: \"gmail_received\"; query?: string }\n  /**\n   * W2-E: an event on the owner's primary Google Calendar starts (`minutes_before` its start, 0-1440) or is created.\n   * `{{trigger.body.title}}`, `starts_at`, `ends_at`, `location`, `attendees`, `link`, `id`.\n   */\n  | { on: \"calendar_event\"; when?: \"starts\" | \"created\"; minutes_before?: number }\n  /**\n   * W2-E: a message posted in a Slack `channel` (optionally containing `contains`). The platform has no Slack sign-in\n   * yet, so the automation says so (`app_says`) until one exists.\n   */\n  | { on: \"slack_message\"; channel: string; contains?: string }\n  /**\n   * AT-MSFT: a new email in the owner's Outlook inbox, read through their own Microsoft connection (`Mail.ReadBasic`:\n   * envelopes only, never the body). `query` keeps it to `from:` / `subject:` terms and plain words (every term must\n   * match; none = every new email). `{{trigger.body.subject}}`, `from`, `from_name`, `to`, `received_at`, `link`, `id`.\n   */\n  | { on: \"outlook_received\"; query?: string };\n\n/** W2-E: the triggers that read the owner's connected account on a schedule (saved off; metered per check). */\nexport const AUTOMATION_APP_TRIGGERS = [\"gmail_received\", \"calendar_event\", \"slack_message\", \"outlook_received\"] as const;\nexport type AutomationAppTrigger = (typeof AUTOMATION_APP_TRIGGERS)[number];\nexport function isAutomationAppTrigger(on: string): on is AutomationAppTrigger {\n  return (AUTOMATION_APP_TRIGGERS as readonly string[]).includes(on);\n}\n\n/** W2-E: what one connected-app automation costs, read before switching it on (`GET /automations/app-triggers/terms`). */\nexport interface AutomationAppTriggerTerms {\n  every_minutes: number;\n  points_per_check: number;\n  checks_per_month: number;\n  points_per_month: number;\n  points_per_action: number;\n}\n\n/**\n * AT-AUTO2: a token a step's text or value may carry, resolved when the run reaches that step:\n * `{{trigger.<field key or id>}}`, `{{trigger.record_id}}`, `{{trigger.body.<path>}}`, `{{stepN.<path>}}`\n * (a find's `records` / `first` / `count` / `ids`, a script's `output.<key>`, an added row's `record_id`),\n * `{{item.<path>}}` / `{{index}}` inside a repeating group. A value that IS one token keeps its type (a list stays a list).\n */\nexport type AutomationToken = `{{${string}}}`;\n\n/** AT-AUTO2: one comparison of a conditional group's path. `value` / `to` take tokens. */\nexport interface AutomationComparison {\n  value: unknown;\n  is: \"equals\" | \"not_equals\" | \"contains\" | \"not_contains\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"empty\" | \"not_empty\" | \"is_true\";\n  to?: unknown;\n}\n\nexport type AutomationWhen = { all: AutomationComparison[] } | { any: AutomationComparison[] };\n\nexport type AutomationAction =\n  | { do: \"set\"; values: AutomationValues }\n  | { do: \"add_row\"; table_id: Uuid; values: AutomationValues }\n  | { do: \"edit_rows\"; table_id: Uuid; where: AutomationFilter; values: AutomationValues; limit?: number }\n  | { do: \"notify\"; to: { person: Uuid } | { field: Uuid } | { author: true }; text: string; subject?: string; link?: string }\n  | { do: \"webhook\"; url: string }\n  /**\n   * AUTOMATIONS-AIRTABLE: an email through the platform's notification sender (event `custom.automation.email`) to an\n   * address, a member, the address (or person) in a property of the row, or the automation's author. `subject` and\n   * `body` take field tokens: `{Field name}` or `{{<field id>}}`. Nothing queued = the step fails and says why.\n   */\n  | { do: \"email\"; to: { address: string } | { person: Uuid } | { field: Uuid } | { author: true }; subject: string; body: string }\n  /** AUTOMATIONS-AIRTABLE: a Slack incoming webhook (`https://hooks.slack.com/...`), message with field tokens. */\n  | { do: \"slack\"; url: string; text: string }\n  | { do: \"agent\"; prompt: string }\n  /** AT-AUTO2: records of a table matching a filter (tokens allowed in `const`s); later steps read `{{stepN.records}}`. */\n  | { do: \"find\"; table_id: Uuid; where?: AutomationFilter; limit?: number }\n  /** AT-AUTO2: change the named records (one id, a list, `{{stepN.records}}`, `{{item.id}}`). */\n  | { do: \"update\"; table_id: Uuid; record: string | string[]; values: AutomationValues }\n  /** AT-AUTO2: Airtable's \"delete record\" — we archive (restorable), never hard delete. */\n  | { do: \"archive\"; record: string | string[]; table_id?: Uuid }\n  /**\n   * AT-AUTO2: JavaScript run by the server in the owner's own sandbox (never in the API process): `input` is\n   * `inputs` resolved, `output.set(key, value)` answers `{{stepN.output.key}}`, console lines land in the run.\n   * Metered to points. On a time trigger it is saved switched off.\n   */\n  | { do: \"script\"; code: string; inputs?: Record<string, unknown>; timeout_ms?: number; memory_mb?: number }\n  /** AT-AUTO2: if / else if / else — the first path whose `when` holds runs its steps; else `else`. */\n  | { do: \"if\"; branches: { label?: string; when: AutomationWhen; actions: AutomationAction[] }[]; else?: AutomationAction[] }\n  /**\n   * W2-E: open an issue in `repo` (owner/name) through the owner's own GitHub connection; `labels` comma-separated.\n   * Answers `{{stepN.output.number}}` / `.url`. A retry answers the same issue. Metered per issue.\n   */\n  | { do: \"github_issue\"; repo: string; title: string; body?: string; labels?: string }\n  /**\n   * MS-WRITE: send one Outlook email as the owner (`Mail.Send`, approved once under Settings -> Integrations -> Microsoft).\n   * `outlook_calendar_event` creates / changes / cancels an event on the owner's calendar (`Calendars.ReadWrite`; a retried\n   * create is the same event); `teams_message` posts in the channel named by a Teams \"Get link to channel\" link\n   * (`ChannelMessage.Send`) or in the chat named by a chat message's \"Copy link\" (`ChatMessage.Send`, AT-MSFT); work or\n   * school accounts. Each is metered per action at `automation.app_action_points`.\n   */\n  | { do: \"outlook_mail\"; to: string; subject: string; body: string }\n  | {\n      do: \"outlook_calendar_event\";\n      action?: \"create\" | \"update\" | \"cancel\";\n      event_id?: string;\n      title?: string;\n      starts_at?: string;\n      ends_at?: string;\n      duration_minutes?: number;\n      timezone?: string;\n      attendees?: string;\n      description?: string;\n      notify?: boolean;\n    }\n  | { do: \"teams_message\"; channel_link: string; message: string }\n  /**\n   * AT-SLACK: post one message in a Slack channel (name like `general` or an ID like `C0123ABC`) AS the owner, through\n   * their own Slack sign-in (Settings -> Integrations -> Slack, user scope `chat:write`). Sent once; answers\n   * `{{stepN.output.ts}}` / `.channel`. Metered per message at `automation.app_action_points`. The `slack` step\n   * (an incoming-webhook URL) is separate and unchanged.\n   */\n  | { do: \"slack_post\"; channel: string; message: string }\n  /** AT-AUTO2: repeat `actions` for each item of a list token (at most 200 items). */\n  | { do: \"for_each\"; list: string; actions: AutomationAction[] };\n\nexport interface AutomationSpec {\n  name: string;\n  trigger: AutomationTrigger;\n  /** An optional filter on the triggering row. */\n  condition?: AutomationFilter | null;\n  actions: AutomationAction[];\n}\n\n/** `custom.automation_declare`: stored, or refused with one sentence per path (`trigger`, `actions.0.values.<field>` …). */\nexport type AutomationDeclared =\n  | {\n      ok: true;\n      automation_id: Uuid;\n      table_id: Uuid;\n      enabled: boolean;\n      spec: AutomationSpec;\n      /**\n       * AUTOMATIONS-AIRTABLE: true when the trigger is a time and a step is an agent — AI on a schedule is saved\n       * switched OFF and turned on only by `automationSetEnabled`; `says` is the store's sentence.\n       */\n      ai_on_schedule?: boolean;\n      says?: string;\n      reused?: boolean;\n    }\n  | { ok: false; _errors: Record<string, string> };\n\nexport type AutomationRunStatus = \"ran\" | \"failed\" | \"stopped\" | \"waiting\";\n\nexport interface AutomationLastRun {\n  run_id: Uuid;\n  status: AutomationRunStatus;\n  at: string;\n  says: string | null;\n}\n\nexport interface AutomationItem {\n  id: Uuid;\n  /** AT-AUTO2: a webhook automation's secret, part of its URL. */\n  webhook_secret?: string | null;\n  /** AT-AUTO2: the last payload its webhook received (its test run uses it). */\n  webhook_sample?: { body: unknown; at: string } | null;\n  /** W2-E: a connected-app trigger's last check, and why it could not read the account (null = it could). */\n  app_checked_at?: string | null;\n  app_says?: string | null;\n  /** W2-E: the last item a connected-app trigger handed to a run. */\n  app_sample?: { body: unknown; at: string } | null;\n  name: string;\n  spec: AutomationSpec;\n  enabled: boolean;\n  archived_at?: string | null;\n  /** AUTOMATIONS-AIRTABLE: why the store switched it off (a watched view was removed); cleared when switched on. */\n  disabled_reason?: string | null;\n  created_by?: Uuid | null;\n  created_at?: string;\n  updated_at?: string;\n  last_run: AutomationLastRun | null;\n}\n\nexport interface AutomationList {\n  table_id: Uuid;\n  automations: AutomationItem[];\n}\n\n/** archive / restore / set_enabled. */\nexport interface AutomationFlipped {\n  ok: true;\n  automation_id: Uuid;\n  table_id: Uuid;\n  enabled: boolean;\n  archived_at: string | null;\n}\n\nexport interface AutomationStep {\n  n: number;\n  do: AutomationAction[\"do\"];\n  /** AT-AUTO2: the repeat round (0-based) a step inside a repeating group ran in. */\n  index?: number;\n  /** AT-AUTO2: a script's console lines. */\n  logs?: string[];\n  /** AT-AUTO2: a server step's answer, as text. */\n  output_text?: string;\n  found?: number;\n  status: \"done\" | \"failed\" | \"waiting\";\n  /** The store's own words. */\n  says: string;\n  hint?: string | null;\n  record_id?: Uuid;\n  edited?: number;\n  prompt?: string;\n}\n\nexport interface AutomationRun {\n  run_id: Uuid;\n  status: AutomationRunStatus;\n  says: string | null;\n  record_id: Uuid | null;\n  trigger: {\n    /** `test` for a test run (`of` is the automation's own trigger), `button_pressed` for a press. */\n    on: AutomationTrigger[\"on\"] | \"test\";\n    /** AT-AUTO2: a webhook's payload. */\n    body?: unknown;\n    of?: AutomationTrigger[\"on\"];\n    /** A test run: whether the row met the condition (null = it could not be worked out). */\n    condition_met?: boolean | null;\n    operation: string;\n    via: string | null;\n    changed_field_ids: Uuid[];\n    /** A time trigger's own facts: the moment it was due, and (date arrives) the date it read. */\n    fires_at?: string;\n    date_value?: string;\n    every?: \"day\" | \"week\" | \"month\";\n  } | null;\n  steps: AutomationStep[];\n  started_at: string | null;\n  finished_at: string | null;\n  ran_by: Uuid | null;\n  at: string;\n}\n\nexport interface AutomationRuns {\n  automation_id: Uuid;\n  runs: AutomationRun[];\n  /** Pass back as `cursor` for the next, older page; null at the end. */\n  next_cursor: string | null;\n}\n\n/** AUTOMATIONS-AIRTABLE: `custom.automation_test` — one run now on a picked row (none for a schedule), on or off. */\nexport interface AutomationTested {\n  ok: true;\n  run_id: Uuid;\n  automation_id: Uuid;\n  record_id: Uuid | null;\n  status: AutomationRunStatus;\n  says: string | null;\n  steps: AutomationStep[];\n  condition_met: boolean | null;\n}\n\n/** AT-AUTO2: `custom.automation_revisions` — every save of one automation, newest first. */\nexport interface AutomationRevision {\n  revision_id: Uuid;\n  at: string;\n  by: Uuid | null;\n  note: \"created\" | \"edited\";\n  enabled: boolean;\n  spec: AutomationSpec;\n}\n\nexport interface AutomationRevisions {\n  automation_id: Uuid;\n  table_id: Uuid;\n  revisions: AutomationRevision[];\n}\n\n/** AT-AUTO2: the public URL of a webhook automation (null until the store made its secret). */\nexport function automationWebhookUrl(serverBase: string, item: Pick<AutomationItem, \"id\" | \"webhook_secret\">): string | null {\n  if (!item.webhook_secret) return null;\n  return `${serverBase.replace(/\\/+$/, \"\")}/api/automations/hooks/${item.id}/${item.webhook_secret}`;\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/base.ts — @ai-matrx/records · lane AT-BASE\n//\n// A BASE is a Home's group of tables (custom.table.home_id) with an identity (custom.base: name, icon, color, description).\n// This file is the whole-base verbs, built ONLY from doors that already exist — never a second copy engine:\n//\n//   duplicateBase   every table of the Home, one at a time through the per-table door (`tableDuplicate`, which loops its own\n//                   passes until \"done\"), then ONE finishing call (`custom.base_copy_finish`) that points the copies' link\n//                   columns and link cells at each other, then ONE call (`custom.copy_table_extras`) that carries each table's\n//                   automations (OFF) and pages onto its copy. With or without records.\n//   snapshotBase    a snapshot is that same copy, with records, put away (archived: out of every list, restorable).\n//   restoreSnapshot a restore is a copy OF the put-away copies into a NEW base: nothing is ever overwritten.\n//\n// The verbs take a port, so a host binds them to the live client and a test binds them to a recording one.\n// Import-inert: types and functions, no side effects.\n\nimport type { RecordsResult } from \"./results\";\nimport type { TableDuplicated, TableDuplicateProgress } from \"./placement\";\nimport type { Uuid } from \"./record\";\n\nexport interface BaseTable {\n  id: Uuid;\n  name: string;\n}\n\nexport interface BasePort {\n  /** `RecordsClient.tableDuplicate`: one table, with its own passes looped until done. */\n  tableDuplicate(args: {\n    tableId: Uuid;\n    withRecords?: boolean;\n    name?: string | null;\n    organizationId?: Uuid | null;\n    onProgress?: (progress: TableDuplicateProgress) => void;\n  }): Promise<RecordsResult<TableDuplicated>>;\n  /** `custom.base_copy_finish`: {old table id: its copy's id} → how many link columns and cells now point inside the copy. */\n  finish(args: { organizationId: Uuid; pairs: Record<Uuid, Uuid> }): Promise<RecordsResult<{ relinked_columns: number; relinked_cells: number }>>;\n  /**\n   * `custom.copy_table_extras`: {source table id: its copy's id} → the automations (switched OFF) and pages every copy now carries,\n   * with the copy's own column and view ids. THE ONE home of that step — 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  /** `RecordsClient.tableArchive` / its restore: put a copy away, or bring it back to be copied from. */\n  archive?(tableId: Uuid): Promise<RecordsResult<unknown>>;\n  unarchive?(tableId: Uuid): Promise<RecordsResult<unknown>>;\n  /** The door that makes a table's Home today (`declareTable`): a new record \"<name>\" in the person kernel. A NEW base is a new Home. */\n  createHome?(name: string): Promise<RecordsResult<Uuid>>;\n  /** The one door that moves a table between Homes: `custom.record_reparent` (`RecordsClient.recordReparent`). Pages and automations ride on their table. */\n  moveInto?(tableId: Uuid, homeId: Uuid): Promise<RecordsResult<unknown>>;\n}\n\nexport interface BaseCopyProgress {\n  /** 1-based position of the table being copied, and how many there are. */\n  at: number;\n  of: number;\n  tableName: string;\n  pass: TableDuplicateProgress | null;\n}\n\nexport interface BaseCopied {\n  /** The NEW Home every copied table now lives in (a copy is its own base); null when the port cannot make Homes. */\n  homeId: Uuid | null;\n  /** Source table id → its copy. */\n  pairs: Record<Uuid, Uuid>;\n  tables: Array<{ from: BaseTable; copy: BaseTable; records: number }>;\n  relinkedColumns: number;\n  relinkedCells: number;\n  /** Automations copied (every one OFF) and pages copied, with every table id inside them pointing at the copies. */\n  automations: number;\n  pages: number;\n  /** One sentence per automation or page that could not be copied. */\n  extrasRefused: string[];\n  /** What a copy never carries, from the per-table door's own words, once per table. */\n  notCopied: string[];\n}\n\nexport type BaseCopyResult =\n  | { ok: true; data: BaseCopied }\n  /**\n   * The table it stopped at; the copies made before it are named so they can be opened or archived.\n   * `strayCopyId`: the store made a copy of `stoppedAt` before the refusal (a pass failed, or its\n   * answer could not be read), so a table exists that `made` does not name — null when none did.\n   */\n  | { ok: false; error: unknown; stoppedAt: BaseTable; made: BaseCopied[\"tables\"]; strayCopyId: Uuid | null };\n\n/** The copy a `tableDuplicate` refusal says the store had already made (`detail.copyId`), or null. */\nexport function copyIdOfRefusal(error: unknown): Uuid | null {\n  const detail = (error as { detail?: unknown } | null)?.detail;\n  const id = detail && typeof detail === \"object\" ? (detail as { copyId?: unknown }).copyId : undefined;\n  return typeof id === \"string\" && id ? id : null;\n}\n\n/** \"Harbor Studio (copy)\", the same word the table dialog offers. */\nexport function baseCopyName(name: string): string {\n  return `${name.trim() || \"Base\"} (copy)`;\n}\n\n/** \"Harbor Studio (restored 10/15/2026)\". */\nexport function restoredBaseName(name: string, on: string): string {\n  return `${name.trim() || \"Base\"} (restored ${on})`;\n}\n\n/** Duplicate every table of a base. `names` (by source table id) overrides the \"<name>\" a copy is given. */\nexport async function duplicateBase(\n  port: BasePort,\n  args: {\n    organizationId: Uuid;\n    tables: readonly BaseTable[];\n    withRecords: boolean;\n    /** The copy's name for each table; default the source's own name (the copies live together in the new base). */\n    nameFor?: (table: BaseTable) => string;\n    onProgress?: (p: BaseCopyProgress) => void;\n    /** Put the copies in a NEW Home with this name (a base is a Home); absent keeps each copy where the per-table door put it. */\n    homeName?: string;\n  },\n): Promise<BaseCopyResult> {\n  const made: BaseCopied[\"tables\"] = [];\n  const pairs: Record<Uuid, Uuid> = {};\n  const notCopied = new Set<string>();\n  for (const [i, table] of args.tables.entries()) {\n    const res = await port.tableDuplicate({\n      tableId: table.id,\n      withRecords: args.withRecords,\n      organizationId: args.organizationId,\n      name: args.nameFor ? args.nameFor(table) : table.name,\n      onProgress: (pass) => args.onProgress?.({ at: i + 1, of: args.tables.length, tableName: table.name, pass }),\n    });\n    if (!res.ok) return { ok: false, error: res.error, stoppedAt: table, made, strayCopyId: copyIdOfRefusal(res.error) };\n    pairs[table.id] = res.data.table.id;\n    made.push({ from: table, copy: res.data.table, records: res.data.copied.records });\n    for (const n of res.data.notCopied) notCopied.add(n);\n  }\n  // Links BETWEEN the copied tables now point at each other; links to a table outside the base stay as they were.\n  const fin = args.tables.length > 1 ? await port.finish({ organizationId: args.organizationId, pairs }) : null;\n  if (fin && !fin.ok) return { ok: false, error: fin.error, stoppedAt: args.tables[args.tables.length - 1] as BaseTable, made, strayCopyId: null };\n  let homeId: Uuid | null = null;\n  if (args.homeName && port.createHome && port.moveInto) {\n    const home = await port.createHome(args.homeName);\n    if (!home.ok) return { ok: false, error: home.error, stoppedAt: args.tables[args.tables.length - 1] as BaseTable, made, strayCopyId: null };\n    homeId = home.data;\n    for (const m of made) {\n      const moved = await port.moveInto(m.copy.id, homeId);\n      if (!moved.ok) return { ok: false, error: moved.error, stoppedAt: m.from, made, strayCopyId: null };\n    }\n  }\n  const copied = await port.copyTableExtras({ organizationId: args.organizationId, pairs });\n  // A refusal of the step itself is said in the result, never dropped: the tables are copied, their extras are not.\n  const extras = copied.ok\n    ? { automations: copied.data.automations, pages: copied.data.pages, extrasRefused: copied.data.extras_refused }\n    : { automations: 0, pages: 0, extrasRefused: [`The automations and pages could not be copied: ${sentence(copied.error)}`] };\n  return {\n    ok: true,\n    data: {\n      homeId,\n      pairs,\n      tables: made,\n      relinkedColumns: fin?.ok ? fin.data.relinked_columns : 0,\n      relinkedCells: fin?.ok ? fin.data.relinked_cells : 0,\n      ...extras,\n      notCopied: [...notCopied],\n    },\n  };\n}\n\nfunction sentence(error: unknown): string {\n  const m = (error as { message?: unknown } | null)?.message;\n  return typeof m === \"string\" && m ? m : \"the store gave no reason.\";\n}\n\nexport interface BaseSnapshotRecord {\n  label: string;\n  origin: \"manual\" | \"schedule\";\n  /** Source table → the put-away copy that holds its columns, views and records as they were. */\n  tables: Array<{ table_id: Uuid; snapshot_table_id: Uuid; name: string; records: number }>;\n}\n\n/** Take a snapshot: copy every table WITH records, then put each copy away so no list shows it. */\nexport async function snapshotBase(\n  port: BasePort,\n  args: { organizationId: Uuid; tables: readonly BaseTable[]; label: string; origin?: \"manual\" | \"schedule\"; onProgress?: (p: BaseCopyProgress) => void },\n): Promise<\n  | { ok: true; snapshot: BaseSnapshotRecord }\n  /** `leftInLists`: copies that could NOT be put away (each still in the lists) — empty when the failure left nothing behind. */\n  | { ok: false; error: unknown; stoppedAt: BaseTable; leftInLists: Uuid[] }\n> {\n  const copied = await duplicateBase(port, {\n    organizationId: args.organizationId,\n    tables: args.tables,\n    withRecords: true,\n    nameFor: (t) => `Snapshot ${args.label} · ${t.name}`,\n    ...(args.onProgress ? { onProgress: args.onProgress } : {}),\n  });\n  if (!copied.ok) {\n    // A half snapshot is never left in the lists — including the copy the store finished (or half\n    // made) for the table it stopped at, which `made` does not name (W4 walk, 2026-10-18: every\n    // press left a 1,200-row \"Snapshot …\" table in the person's list).\n    const ids = [...copied.made.map((m) => m.copy.id), ...(copied.strayCopyId ? [copied.strayCopyId] : [])];\n    return { ok: false, error: copied.error, stoppedAt: copied.stoppedAt, leftInLists: await putAway(port, ids) };\n  }\n  const left = await putAway(port, copied.data.tables.map((t) => t.copy.id));\n  if (left.length > 0) {\n    const firstLeft = copied.data.tables.find((t) => t.copy.id === left[0]);\n    return {\n      ok: false,\n      error: new Error(`${left.length === 1 ? \"A snapshot copy\" : `${left.length} snapshot copies`} could not be put away and still show in your lists.`),\n      stoppedAt: firstLeft?.from ?? copied.data.tables[0]!.from,\n      leftInLists: left,\n    };\n  }\n  return {\n    ok: true,\n    snapshot: {\n      label: args.label,\n      origin: args.origin ?? \"manual\",\n      tables: copied.data.tables.map((t) => ({ table_id: t.from.id, snapshot_table_id: t.copy.id, name: t.from.name, records: t.records })),\n    },\n  };\n}\n\n/** Archive every id; answers the ones still in the lists (no archive door, or the store refused). */\nasync function putAway(port: BasePort, ids: readonly Uuid[]): Promise<Uuid[]> {\n  const left: Uuid[] = [];\n  for (const id of ids) {\n    const away = port.archive ? await port.archive(id) : undefined;\n    if (!away || !away.ok) left.push(id);\n  }\n  return left;\n}\n\n/** Restore a snapshot as a NEW base: each put-away copy is brought back, copied under its own name, and put away again. */\nexport async function restoreSnapshot(\n  port: BasePort,\n  args: { organizationId: Uuid; snapshot: BaseSnapshotRecord; baseName?: string; restoredOn?: string; onProgress?: (p: BaseCopyProgress) => void },\n): Promise<BaseCopyResult> {\n  const sources = args.snapshot.tables.map((t) => ({ id: t.snapshot_table_id, name: t.name }));\n  const byCopy = new Map(args.snapshot.tables.map((t) => [t.snapshot_table_id, t.name]));\n  for (const s of sources) await port.unarchive?.(s.id);\n  const out = await duplicateBase(port, {\n    organizationId: args.organizationId,\n    tables: sources,\n    withRecords: true,\n    nameFor: (t) => `${byCopy.get(t.id) ?? t.name} (restored)`,\n    homeName: restoredBaseName(args.baseName ?? \"Base\", args.restoredOn ?? new Date().toLocaleDateString()),\n    ...(args.onProgress ? { onProgress: args.onProgress } : {}),\n  });\n  for (const s of sources) await port.archive?.(s.id); // the snapshot stays a snapshot, whatever happened\n  return out;\n}\n","// src/capture-queue.ts — @ai-matrx/records · PRODUCTS row 15, primitive P13\n//\n// THE QUEUE THAT MAKES A PHONE WITH NO BARS AS GOOD AS A PHONE WITH FIVE.\n//\n// Fulcrum's field client is the bar: a crew captures all day in a yard with no signal and\n// nothing is lost, nothing is doubled, and nobody has to think about it. Four decisions\n// carry that, and each one is a thing this file refuses to do rather than a feature:\n//\n// 1. THE CAPTURE IS WRITTEN TO DISK BEFORE THE NETWORK IS EVEN ASKED. `enqueue` returns\n//    after IndexedDB has the answers AND the photograph's bytes. A queue that holds\n//    captures in memory until it can send them loses the day when the screen locks.\n//\n// 2. THE IDEMPOTENCY KEY IS MINTED WHEN THE CAPTURE IS TAKEN, NOT WHEN IT IS SENT. It is\n//    the row's own primary key here and `p_client_key` at the door. A lost acknowledgement\n//    — the commonest failure on a bad signal, because the write SUCCEEDED and the answer\n//    never came back — is then a replay that returns the first record's id, not a second\n//    bin.\n//\n// 3. THEY GO UP IN THE ORDER THEY HAPPENED, ONE AT A TIME. A crew's day is a sequence and\n//    a foreman reads it as one. Parallel uploads would also mean six photographs sharing\n//    one thin signal and all six timing out.\n//\n// 4. A REFUSAL IS NOT A RETRY. A required answer missing, a field the sheet does not ask\n//    for, a level the person does not hold — the door has decided, and sending it again\n//    every thirty seconds forever is how a queue becomes a silent hole. The item stays,\n//    marked `refused`, carrying the door's own sentence for the screen to show. The person\n//    fixes it or throws it away; nothing decides that for them.\n//\n// The bytes never go through this file twice: `uploadFile` is called once per file and its\n// reference is written back into the queued row, so a retry after a failed SUBMIT re-sends\n// the reference rather than the photograph.\n\nimport type { CaptureFileRef, CaptureOutcome } from \"./capture\";\n\n/** One file waiting to go up, with its bytes until they have. */\nexport interface QueuedCaptureFile {\n  field: string;\n  name: string;\n  mime_type: string;\n  size_bytes: number;\n  duration_ms?: number | null | undefined;\n  /** The bytes. Dropped once `uploaded` is set, so the queue does not hold them twice. */\n  blob?: Blob | null | undefined;\n  /** Set once the platform's byte store has them. */\n  uploaded?: { file_id?: string | null | undefined; url?: string | null | undefined } | null | undefined;\n}\n\n/** `waiting` → `sending` → `landed`, or `refused` when the door has decided. */\nexport type QueuedCaptureState = \"waiting\" | \"sending\" | \"landed\" | \"refused\";\n\nexport interface QueuedCapture {\n  /** Minted on the phone when the capture was taken. The row's key AND the door's. */\n  client_key: string;\n  organization_id: string;\n  sheet_id: string;\n  sheet_title?: string | undefined;\n  answers: Record<string, unknown>;\n  files: QueuedCaptureFile[];\n  device: string | null;\n  /** The moment the PHONE took it — never the moment the signal came back. */\n  captured_at: string;\n  location: Record<string, unknown> | null;\n  state: QueuedCaptureState;\n  attempts: number;\n  /** The door's own words, or the network's. Always something a person can act on. */\n  last_error: string | null;\n  record_id: string | null;\n  replayed: boolean;\n  queued_at: string;\n  landed_at: string | null;\n}\n\nexport interface CaptureQueueCounts {\n  waiting: number;\n  sending: number;\n  refused: number;\n  landed: number;\n}\n\n/** What one pass of `sync` did, item by item. Never a single boolean. */\nexport interface CaptureSyncReport {\n  attempted: number;\n  landed: number;\n  replayed: number;\n  refused: number;\n  deferred: number;\n  outcomes: Array<{\n    client_key: string;\n    state: QueuedCaptureState;\n    record_id: string | null;\n    replay: boolean;\n    says: string | null;\n  }>;\n  /** Set when the pass stopped early because the network went away again. */\n  stopped_because?: string;\n}\n\n/** The two calls the queue makes on the outside world. Injected, so this file is headless. */\nexport interface CaptureQueuePorts {\n  /** Put the bytes in the platform's ONE byte store and answer with the reference. */\n  uploadFile(\n    file: QueuedCaptureFile,\n    item: QueuedCapture,\n  ): Promise<{ file_id?: string | null; url?: string | null }>;\n  /** `client.captureSubmit`. */\n  submit(args: {\n    sheet_id: string;\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<{ ok: boolean; data?: CaptureOutcome | null; error?: { message?: string; code?: string } | null }>;\n}\n\n/** The smallest store the queue needs. IndexedDB in a browser, a Map in a test. */\nexport interface CaptureQueueStore {\n  all(): Promise<QueuedCapture[]>;\n  put(item: QueuedCapture): Promise<void>;\n  remove(clientKey: string): Promise<void>;\n  meta(key: string): Promise<string | null>;\n  setMeta(key: string, value: string): Promise<void>;\n}\n\nconst DB_NAME = \"matrx-capture\";\nconst DB_VERSION = 1;\nconst ITEMS = \"captures\";\nconst META = \"meta\";\n\n/**\n * THE TWO REFUSALS WORTH REPEATING, and they are the package's own list, not a guess.\n * `results.ts` says it in as many words: `stale_read` (40001) and `timed_out` (57014) are\n * \"the only two refusals in this list worth repeating\"; `store_limit` (53400) is the third\n * — the store ran out of something and the same call works in a quieter moment.\n *\n * EVERYTHING ELSE THE DOOR NAMES IS A DECISION. This was the other way round until a real\n * browser ran it (2026-09-20): the check listed SQLSTATEs, and `RecordsClient` hands back\n * its own WORD — `invalid_argument`, `door` — with the sqlstate beside it. So a capture the\n * store had refused by name was filed as a hiccup and queued again forever, which is the\n * exact silent hole this file's decision 4 exists to prevent. The unit suite passed because\n * it fed the check SQLSTATEs: it was testing the assumption, not the client.\n */\nexport const REFUSALS_WORTH_REPEATING: ReadonlySet<string> = new Set([\n  \"stale_read\", \"timed_out\", \"store_limit\",\n]);\nconst SQLSTATES_WORTH_REPEATING: ReadonlySet<string> = new Set([\"40001\", \"57014\", \"53400\"]);\n\n/**\n * Did the door DECIDE, or did the attempt merely fail? A failure with no code at all is a\n * network failure and waits; a refusal the store named is a decision and stays.\n */\nexport function isDecided(\n  error: { code?: string | null; sqlstate?: string | null } | null | undefined,\n): boolean {\n  if (!error) return false;\n  const { code, sqlstate } = error;\n  if (code && REFUSALS_WORTH_REPEATING.has(code)) return false;\n  if (sqlstate && SQLSTATES_WORTH_REPEATING.has(sqlstate)) return false;\n  return !!(code || sqlstate);\n}\n\n/**\n * A key that is unique on a phone that has been offline for a day and has never spoken to\n * a server. `crypto.randomUUID` where it exists; otherwise random bytes, and only then the\n * clock — because two captures in the same millisecond on two phones is exactly the case\n * that must not collide.\n */\nexport function mintClientKey(): string {\n  const c: Crypto | undefined = typeof crypto !== \"undefined\" ? crypto : undefined;\n  if (c && typeof c.randomUUID === \"function\") return `cap-${c.randomUUID()}`;\n  if (c && typeof c.getRandomValues === \"function\") {\n    const b = c.getRandomValues(new Uint8Array(16));\n    return `cap-${Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\")}`;\n  }\n  return `cap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n}\n\n/** The IndexedDB store. Returns null where there is no IndexedDB at all. */\nexport function indexedDbStore(name = DB_NAME): CaptureQueueStore | null {\n  const idb: IDBFactory | undefined =\n    typeof globalThis !== \"undefined\" ? (globalThis as { indexedDB?: IDBFactory }).indexedDB : undefined;\n  if (!idb) return null;\n\n  const open = (): Promise<IDBDatabase> =>\n    new Promise((resolve, reject) => {\n      const req = idb.open(name, DB_VERSION);\n      req.onupgradeneeded = () => {\n        const db = req.result;\n        if (!db.objectStoreNames.contains(ITEMS)) db.createObjectStore(ITEMS, { keyPath: \"client_key\" });\n        if (!db.objectStoreNames.contains(META)) db.createObjectStore(META);\n      };\n      req.onsuccess = () => resolve(req.result);\n      req.onerror = () => reject(req.error);\n    });\n\n  const run = <T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T> =>\n    open().then(\n      (db) =>\n        new Promise<T>((resolve, reject) => {\n          const tx = db.transaction(store, mode);\n          const req = fn(tx.objectStore(store));\n          req.onsuccess = () => resolve(req.result);\n          req.onerror = () => reject(req.error);\n          tx.oncomplete = () => db.close();\n        }),\n    );\n\n  return {\n    all: () => run<QueuedCapture[]>(ITEMS, \"readonly\", (s) => s.getAll() as IDBRequest<QueuedCapture[]>),\n    put: (item) => run<IDBValidKey>(ITEMS, \"readwrite\", (s) => s.put(item)).then(() => undefined),\n    remove: (key) => run<undefined>(ITEMS, \"readwrite\", (s) => s.delete(key)).then(() => undefined),\n    meta: (key) => run<string | undefined>(META, \"readonly\", (s) => s.get(key) as IDBRequest<string | undefined>)\n      .then((v) => v ?? null),\n    setMeta: (key, value) =>\n      run<IDBValidKey>(META, \"readwrite\", (s) => s.put(value, key)).then(() => undefined),\n  };\n}\n\n/** The in-memory store — for a test, and for a browser with storage switched off. */\nexport function memoryStore(): CaptureQueueStore {\n  const rows = new Map<string, QueuedCapture>();\n  const meta = new Map<string, string>();\n  return {\n    all: async () => Array.from(rows.values()),\n    put: async (item) => void rows.set(item.client_key, item),\n    remove: async (key) => void rows.delete(key),\n    meta: async (key) => meta.get(key) ?? null,\n    setMeta: async (key, value) => void meta.set(key, value),\n  };\n}\n\nexport interface CaptureQueueOptions {\n  ports: CaptureQueuePorts;\n  store?: CaptureQueueStore | null;\n  /** Watch `online` and drain when the signal comes back. Default true in a browser. */\n  autoSync?: boolean;\n  /** Told when anything changes, so a badge can say how many are waiting. */\n  onChange?: (counts: CaptureQueueCounts, items: QueuedCapture[]) => void;\n  now?: () => Date;\n}\n\nexport interface CaptureQueue {\n  /** Write one capture to disk. Returns its client key; the network is not asked here. */\n  enqueue(input: {\n    organization_id: string;\n    sheet_id: string;\n    sheet_title?: string;\n    answers: Record<string, unknown>;\n    files?: Array<Omit<QueuedCaptureFile, \"uploaded\">>;\n    device?: string | null;\n    captured_at?: string | null;\n    location?: Record<string, unknown> | null;\n    client_key?: string;\n  }): Promise<string>;\n  list(): Promise<QueuedCapture[]>;\n  counts(): Promise<CaptureQueueCounts>;\n  /** Send everything waiting, oldest first, one at a time. Safe to call at any moment. */\n  sync(): Promise<CaptureSyncReport>;\n  /** Try one refused item again — after the person has fixed what the door named. */\n  retry(clientKey: string, patch?: { answers?: Record<string, unknown> }): Promise<void>;\n  /** Throw one away. The only thing that ever removes a capture nobody sent. */\n  discard(clientKey: string): Promise<void>;\n  /** Forget what has already landed. Never touches anything still waiting. */\n  clearLanded(): Promise<number>;\n  lastSyncedAt(): Promise<string | null>;\n  isOnline(): boolean;\n  dispose(): void;\n}\n\nfunction countOf(items: QueuedCapture[]): CaptureQueueCounts {\n  const c: CaptureQueueCounts = { waiting: 0, sending: 0, refused: 0, landed: 0 };\n  for (const i of items) c[i.state] += 1;\n  return c;\n}\n\nexport function openCaptureQueue(opts: CaptureQueueOptions): CaptureQueue {\n  const now = opts.now ?? (() => new Date());\n  const store = opts.store ?? indexedDbStore() ?? memoryStore();\n  let syncing: Promise<CaptureSyncReport> | null = null;\n  let disposed = false;\n\n  const online = (): boolean => {\n    const nav = typeof navigator !== \"undefined\" ? navigator : undefined;\n    return nav ? nav.onLine !== false : true;\n  };\n\n  const announce = async () => {\n    if (!opts.onChange) return;\n    const items = await store.all();\n    opts.onChange(countOf(items), items);\n  };\n\n  const oldestFirst = (items: QueuedCapture[]) =>\n    items.slice().sort((a, b) => a.captured_at.localeCompare(b.captured_at));\n\n  const queue: CaptureQueue = {\n    async enqueue(input) {\n      const key = input.client_key ?? mintClientKey();\n      const item: QueuedCapture = {\n        client_key: key,\n        organization_id: input.organization_id,\n        sheet_id: input.sheet_id,\n        sheet_title: input.sheet_title,\n        answers: input.answers ?? {},\n        files: (input.files ?? []).map((f) => ({ ...f, uploaded: null })),\n        device: input.device ?? null,\n        captured_at: input.captured_at ?? now().toISOString(),\n        location: input.location ?? null,\n        state: \"waiting\",\n        attempts: 0,\n        last_error: null,\n        record_id: null,\n        replayed: false,\n        queued_at: now().toISOString(),\n        landed_at: null,\n      };\n      await store.put(item);\n      await announce();\n      return key;\n    },\n\n    list: () => store.all().then(oldestFirst),\n    counts: () => store.all().then(countOf),\n\n    async sync() {\n      if (syncing) return syncing;\n      syncing = (async (): Promise<CaptureSyncReport> => {\n        const report: CaptureSyncReport = {\n          attempted: 0, landed: 0, replayed: 0, refused: 0, deferred: 0, outcomes: [],\n        };\n        const pending = oldestFirst(await store.all()).filter((i) => i.state === \"waiting\" || i.state === \"sending\");\n        if (!online()) {\n          report.deferred = pending.length;\n          report.stopped_because = \"There is no signal, so nothing was sent. Everything is still here.\";\n          return report;\n        }\n\n        for (const item of pending) {\n          report.attempted += 1;\n          item.state = \"sending\";\n          item.attempts += 1;\n          await store.put(item);\n          await announce();\n\n          try {\n            // THE BYTES FIRST, AND ONLY ONCE. A file whose reference is already written\n            // back is not uploaded again, so a failure at the SUBMIT step does not send\n            // the photograph twice.\n            for (const f of item.files) {\n              if (f.uploaded) continue;\n              f.uploaded = await opts.ports.uploadFile(f, item);\n              f.blob = null;\n              await store.put(item);\n            }\n\n            const refs: CaptureFileRef[] = item.files.map((f) => ({\n              field: f.field,\n              name: f.name,\n              mime_type: f.mime_type,\n              size_bytes: f.size_bytes,\n              duration_ms: f.duration_ms ?? null,\n              file_id: f.uploaded?.file_id ?? null,\n              url: f.uploaded?.url ?? null,\n            }));\n\n            const res = await opts.ports.submit({\n              sheet_id: item.sheet_id,\n              client_key: item.client_key,\n              answers: item.answers,\n              files: refs,\n              device: item.device,\n              captured_at: item.captured_at,\n              location: item.location,\n            });\n\n            if (res.ok && res.data && res.data.record_id) {\n              item.state = \"landed\";\n              item.record_id = res.data.record_id;\n              item.replayed = !!res.data.replay;\n              item.landed_at = now().toISOString();\n              item.last_error = null;\n              report.landed += 1;\n              if (item.replayed) report.replayed += 1;\n              report.outcomes.push({\n                client_key: item.client_key, state: item.state,\n                record_id: item.record_id, replay: item.replayed,\n                says: res.data.message ?? null,\n              });\n            } else if (res.ok && res.data && !res.data.record_id) {\n              // The door answered in words — closed, not open yet. It is not a failure of\n              // this phone and it is not something a retry loop can fix.\n              item.state = \"refused\";\n              item.last_error = res.data.message ?? `This sheet is ${res.data.state}.`;\n              report.refused += 1;\n              report.outcomes.push({\n                client_key: item.client_key, state: item.state, record_id: null,\n                replay: false, says: item.last_error,\n              });\n            } else if (isDecided(res.error)) {\n              item.state = \"refused\";\n              item.last_error = res.error?.message ?? \"The store refused this capture.\";\n              report.refused += 1;\n              report.outcomes.push({\n                client_key: item.client_key, state: item.state, record_id: null,\n                replay: false, says: item.last_error,\n              });\n            } else {\n              item.state = \"waiting\";\n              item.last_error = res.error?.message ?? \"It could not be sent just now.\";\n              report.deferred += 1;\n              report.outcomes.push({\n                client_key: item.client_key, state: item.state, record_id: null,\n                replay: false, says: item.last_error,\n              });\n            }\n          } catch (err) {\n            // A thrown error is the NETWORK, not a decision: it waits.\n            item.state = \"waiting\";\n            item.last_error =\n              err instanceof Error ? err.message : \"It could not be sent just now.\";\n            report.deferred += 1;\n            report.outcomes.push({\n              client_key: item.client_key, state: item.state, record_id: null,\n              replay: false, says: item.last_error,\n            });\n          }\n\n          await store.put(item);\n          await announce();\n\n          if (!online()) {\n            report.stopped_because =\n              \"The signal went away again. Everything still on the phone is still here.\";\n            break;\n          }\n        }\n\n        await store.setMeta(\"last_synced_at\", now().toISOString());\n        return report;\n      })();\n      try {\n        return await syncing;\n      } finally {\n        syncing = null;\n      }\n    },\n\n    async retry(clientKey, patch) {\n      const items = await store.all();\n      const item = items.find((i) => i.client_key === clientKey);\n      if (!item) return;\n      if (patch?.answers) item.answers = { ...item.answers, ...patch.answers };\n      item.state = \"waiting\";\n      item.last_error = null;\n      await store.put(item);\n      await announce();\n    },\n\n    async discard(clientKey) {\n      await store.remove(clientKey);\n      await announce();\n    },\n\n    async clearLanded() {\n      const items = await store.all();\n      const landed = items.filter((i) => i.state === \"landed\");\n      for (const i of landed) await store.remove(i.client_key);\n      await announce();\n      return landed.length;\n    },\n\n    lastSyncedAt: () => store.meta(\"last_synced_at\"),\n    isOnline: online,\n\n    dispose() {\n      disposed = true;\n      if (typeof window !== \"undefined\" && handler) window.removeEventListener(\"online\", handler);\n    },\n  };\n\n  let handler: (() => void) | null = null;\n  const auto = opts.autoSync ?? typeof window !== \"undefined\";\n  if (auto && typeof window !== \"undefined\") {\n    handler = () => {\n      if (!disposed) void queue.sync();\n    };\n    window.addEventListener(\"online\", handler);\n  }\n\n  return queue;\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/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/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/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","/**\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/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/record-scope.ts — @ai-matrx/records · AGT-N-9 · PRODUCTS row 11\n//\n// A CONVERSATION THAT IS ABOUT ONE RECORD.\n//\n// These are the shapes `custom.record_scope_context` and its three siblings answer. They\n// are types over ONE door, not a model of their own: the assembly happens inside the\n// database, through `custom.read_record`, under the operating person's own field-level\n// security, and this file only says what comes back.\n//\n// TWO ABSENCES, NEVER ONE. `withheld[].because` is `\"masked\"` when the STORE kept a Field\n// from this reader, and `\"policy\"` when the ORGANIZATION keeps it out of conversations.\n// A screen that collapsed them would tell somebody \"you may not see this\" about a field\n// they can read on the record two inches away.\n\nimport type { PermissionLevel } from \"./level\";\nimport type { Uuid } from \"./record\";\n\n/** One value the agent was given, with the triple that makes it citable. */\nexport interface RecordScopeField {\n  key: string;\n  label: string;\n  type: string;\n  value: unknown;\n  /** DYN: a merge field resolves to a TRIPLE, not a string. */\n  cite: {\n    record_id: Uuid;\n    field_id: Uuid;\n    value_version: number;\n    written_at: string | null;\n  };\n}\n\n/** A Field the agent was NOT given, and which of the two reasons it is. */\nexport interface RecordScopeWithheld {\n  key: string;\n  label: string;\n  because: \"masked\" | \"policy\";\n  reason: string;\n  needs?: string;\n  /** The whole sentence, already written — a screen prints it rather than composing one. */\n  says: string;\n}\n\nexport interface RecordScopeRelation {\n  via: string;\n  target_id: Uuid;\n  foreign: boolean;\n  masked: boolean;\n  your_level: PermissionLevel | null;\n  card: Record<string, unknown> | null;\n  why: string | null;\n}\n\nexport interface RecordScopeHistoryEntry {\n  version: number;\n  at: string;\n  what: string;\n  who: string | null;\n  changes: Array<Record<string, unknown>>;\n}\n\nexport interface RecordScopeComment {\n  id: Uuid;\n  body: string;\n  created_at: string;\n  created_by_name: string;\n  field_key: string | null;\n}\n\nexport interface RecordScopeContext {\n  record: {\n    id: Uuid;\n    title: string;\n    table_id: Uuid;\n    table_name: string | null;\n    scope_type: string;\n    plural: string;\n    version: number;\n    updated_at: string;\n    your_level: PermissionLevel;\n  };\n  fields: RecordScopeField[];\n  withheld: RecordScopeWithheld[];\n  relations: RecordScopeRelation[];\n  history: RecordScopeHistoryEntry[];\n  comments: RecordScopeComment[];\n  may_comment: boolean;\n  siblings: {\n    shown: Array<{ id: Uuid; title: string }>;\n    more_than_shown: boolean;\n    says: string;\n  };\n  /** Questions derived from THIS record's shape — never a fixed list. */\n  suggested: string[];\n  /** One sentence naming what is not in the conversation. Printed verbatim. */\n  says: string;\n  assembled_at: string;\n}\n\n/** What a conversation is about. `readable` false means the person lost access to it. */\nexport interface ConversationScope {\n  bound: boolean;\n  readable?: boolean;\n  record_id?: Uuid;\n  table_id?: Uuid;\n  scope_type?: string;\n  title?: string;\n  bound_at?: string;\n  bound_by?: Uuid;\n  because?: string;\n}\n\nexport interface ConversationScopeContext {\n  scope: ConversationScope;\n  context: RecordScopeContext | null;\n}\n\n/** `About: Acme Industrial` — the chip a bound chat wears. */\nexport function scopeChip(scope: ConversationScope): string {\n  return scope.title ? `About: ${scope.title}` : \"About: this record\";\n}\n","// src/table-kind.ts — A TABLE IS A KIND (KINDS-GLUE wave 3 §1–2).\n//\n// `table:<uuid>` names \"a record of that Table\". It is never a registry row: its schema is\n// derived, when asked for, from the Table's live Fields as the store's door\n// `custom.table_kind_facts` (N1) answers them — `TableKindFacts` is that door's JSON verbatim.\n//\n// ONE MAPPING, THREE OUTPUTS, TWO LANGUAGES. `table-kind-mapping.json` beside this file is the\n// one data file (aidream copies it verbatim into matrx-graph). From it:\n//   - stored   — the JSON Schema a value is validated against (mirrors custom.validate_values and\n//                custom._undeclared_key_guard: closed only on a `fields` Table, platform keys allowed;\n//                uses the door's column_source / platform_keys / per-Field field_kind when present,\n//                else derives them);\n//   - authored — a plain object every provider binds (no allOf / if / patternProperties);\n//   - render   — the content-ir KindSchema the web draws with, never stricter than the store.\n// Each is Fields-only here (`tableJsonSchema`, `tableRenderSchema`); the control keys are wave 2's\n// one function (`withControlKeys` / `withControlKeyFields` in @ai-matrx/content-ir), applied by\n// the caller. The Python twin is `matrx_graph.table_kinds`; both write byte-identical JSON for\n// the golden fixture (guard 3 (a), `__tests__/table-kind-round-trip.test.ts`).\n\nimport { isLowercaseUuidShape } from \"@ai-matrx/kit/uuid\";\nimport MAPPING from \"./table-kind-mapping.json\";\n\nexport const TABLE_KIND_PREFIX = \"table:\";\nconst KIND_KEY = \"__kind\";\n\ntype Json = Record<string, unknown>;\n\n/** `custom.table_kind_facts(p_table_id)` verbatim (N1). */\nexport interface TableKindFacts {\n  organization_id: string;\n  table_id: string;\n  name: string | null;\n  title_field: string | null;\n  agent_writable: boolean;\n  purpose: string | null;\n  version: number | null;\n  type_field: string | null;\n  stamp: string | null;\n  /** Every live Field document (typed ones included), plus `id` and `version`, in `sort` order. */\n  fields: Array<Record<string, unknown>>;\n  /** `{<list field key>: [{key, label, id, retired, position}]}`, retired included, live first. */\n  choices: Record<string, Array<{ key?: string | null; label?: string | null; id?: string | null; retired?: boolean; position?: number | null }>>;\n  /** `custom.table_column_source` (`fields` / `free_form` / `code`) once the door carries it; absent, the mapping's default. */\n  column_source?: string | null;\n  /** `custom.record_platform_keys()` once the door carries it; absent, the mapping's keys. */\n  platform_keys?: string[] | null;\n}\n\n/** The content-ir `KindSchema` shape, structurally (this package does not depend on content-ir). */\nexport interface TableRenderSchema {\n  kind: string;\n  fields: Record<string, Record<string, unknown>>;\n}\n\nexport type TableSchemaMode = \"stored\" | \"authored\";\n\ntype KindSpec = {\n  shape: \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"choice\" | \"relation\" | \"entity_reference\" | \"address\" | \"computed\";\n  value?: Json;\n  authored?: boolean;\n  unit?: boolean;\n  hint?: string;\n  rating?: boolean;\n};\n\ntype Mapping = {\n  kernels: { file: string; person: string };\n  system_kinds: string[];\n  by_behaviour: Record<string, string>;\n  choice_enum_limit: number;\n  rating_max: number;\n  address_parts: string[];\n  address_part_max: number;\n  column_source_default: string;\n  platform_keys: Record<string, Json>;\n  stored_patterns: { record_id: string; datetime: string };\n  kinds: Record<string, KindSpec>;\n  render: Record<string, { one: Json; many: Json }>;\n};\n\nconst M = MAPPING as unknown as Mapping;\n\n/** The one mapping (records' own file; the Python copy is generated from it). */\nexport function tableKindMapping(): Readonly<Mapping> {\n  return M;\n}\n\nexport function isTableKind(slug: unknown): slug is `table:${string}` {\n  return typeof slug === \"string\" && slug.startsWith(TABLE_KIND_PREFIX) && isLowercaseUuidShape(slug.slice(TABLE_KIND_PREFIX.length));\n}\n\nexport function tableKindSlug(tableId: string): `table:${string}` {\n  const slug = `${TABLE_KIND_PREFIX}${String(tableId).trim().toLowerCase()}`;\n  if (!isTableKind(slug)) throw new Error(`${JSON.stringify(tableId)} is not a table id`);\n  return slug;\n}\n\nexport function tableIdOf(slug: string): string {\n  if (!isTableKind(slug)) throw new Error(`${JSON.stringify(slug)} is not a table kind`);\n  return slug.slice(TABLE_KIND_PREFIX.length);\n}\n\n// ── field kinds ─────────────────────────────────────────────────────────────────────────\n\nfunction clone<T>(value: T): T {\n  return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction truthy(value: unknown): boolean {\n  return value === true || value === \"true\";\n}\n\nfunction configOf(d: Json): Json {\n  const cfg = d.config;\n  return cfg && typeof cfg === \"object\" && !Array.isArray(cfg) ? (cfg as Json) : {};\n}\n\n/** Twin of `custom.parity_type` — the first answer wins. */\nfunction parityType(d: Json): string | null {\n  const t = d.type;\n  const fmt = d.format;\n  const cfg = configOf(d);\n  if (t === \"boolean\") return \"checkbox\";\n  if (t === \"list\") return truthy(d.multi) ? \"multi_select\" : \"select\";\n  if (t === \"relation\" && d.relation_target === M.kernels.file) return \"attachment\";\n  if (t === \"relation\" && d.relation_target === M.kernels.person) return \"member\";\n  if (t === \"formula\" && \"pick\" in cfg) return \"lookup\";\n  if (t === \"formula\" && \"agg\" in cfg) return \"rollup\";\n  if (t === \"formula\" && \"expr\" in cfg) return \"formula\";\n  if (t === \"text\" && (fmt === \"url\" || fmt === \"email\" || fmt === \"phone\")) return fmt;\n  if (t === \"range\" && fmt === \"percent\") return \"percent\";\n  if (t === \"range\" && d.unit && fmt === \"currency\") return \"currency\";\n  if (t === \"range\" && (cfg.kind === \"date\" || cfg.kind === \"datetime\")) return \"datetime\";\n  return null;\n}\n\n/** Twin of `custom.field_kind_of`: the field kind a stored Field document declares. */\nexport function fieldKindOf(d: Record<string, unknown>): string | null {\n  const t = d.type;\n  const fmt = d.format;\n  const cfg = configOf(d);\n  if (t === \"range\" && (fmt === \"rating\" || fmt === \"duration\")) return fmt;\n  if (t === \"text\" && (fmt === \"address\" || fmt === \"barcode\" || fmt === \"rich_text\" || fmt === \"signature\")) return fmt;\n  if (t === \"list\" && fmt === \"status\") return \"status\";\n  if (t === \"formula\" && fmt === \"count\" && cfg.agg === \"count\") return \"count\";\n  if (t === \"formula\" && typeof cfg.system === \"string\" && M.system_kinds.includes(cfg.system)) return cfg.system;\n  if (t === \"relation\" && Array.isArray(cfg.allowed_types)) return \"entity_reference\";\n  const parity = parityType(d);\n  if (parity !== null) return parity;\n  if (t === \"text\") return fmt === \"long\" || truthy(cfg.multiline) ? \"long_text\" : \"text\";\n  if (t === \"range\") return \"number\";\n  if (t === \"relation\") return \"relation\";\n  return null;\n}\n\n/**\n * The store's own `field_kind` when the facts carry it (`custom.field_kind_of` per Field, asked\n * of the door); otherwise this twin's derivation of the same answer.\n */\nfunction fieldKind(d: Json): string | null {\n  if (\"field_kind\" in d) return typeof d.field_kind === \"string\" ? d.field_kind : null;\n  return fieldKindOf(d);\n}\n\nfunction kindSpec(d: Json): KindSpec {\n  const kind = fieldKind(d) ?? M.by_behaviour[String(d.type)] ?? \"formula\";\n  return M.kinds[kind] ?? M.kinds.formula!;\n}\n\n// ── per Field ───────────────────────────────────────────────────────────────────────────\n\nfunction unconditionalRules(d: Json): Json[] {\n  const rules = Array.isArray(d.rules) ? (d.rules as unknown[]) : [];\n  return rules.filter(\n    (r): r is Json =>\n      !!r &&\n      typeof r === \"object\" &&\n      !Array.isArray(r) &&\n      !(Array.isArray((r as Json).applies_to_types) && ((r as Json).applies_to_types as unknown[]).length > 0) &&\n      !(typeof (r as Json).applies_to_types === \"string\" && (r as Json).applies_to_types !== \"\"),\n  );\n}\n\n/** A rule's number, as Python's twin writes it (6.0 is 6). */\nfunction numberOf(value: unknown): number | null {\n  if (typeof value === \"boolean\") return null;\n  if (typeof value === \"number\" && Number.isFinite(value)) return value;\n  if (typeof value === \"string\" && /^-?[0-9]+(\\.[0-9]+)?$/.test(value)) return Number(value);\n  return null;\n}\n\nfunction choiceTokens(facts: TableKindFacts, key: string): string[] {\n  const tokens: string[] = [];\n  for (const choice of facts.choices?.[key] ?? []) {\n    for (const token of [choice.key, choice.label, choice.id]) {\n      if (typeof token === \"string\" && token && !tokens.includes(token)) tokens.push(token);\n    }\n  }\n  return tokens;\n}\n\nfunction liveChoiceKeys(facts: TableKindFacts, key: string): string[] {\n  const keys: string[] = [];\n  for (const choice of facts.choices?.[key] ?? []) {\n    const k = choice.key;\n    if (!choice.retired && typeof k === \"string\" && k && !keys.includes(k)) keys.push(k);\n  }\n  return keys;\n}\n\nfunction item(facts: TableKindFacts, d: Json, mode: TableSchemaMode): Json {\n  const spec = kindSpec(d);\n  const shape = spec.shape;\n  const cfg = configOf(d);\n  const key = String(d.key);\n  if (shape === \"string\" || shape === \"number\" || shape === \"boolean\") {\n    const out = clone(spec.value ?? {});\n    for (const rule of unconditionalRules(d)) {\n      const kind = rule.kind;\n      const value = numberOf(rule.value);\n      if (shape === \"number\" && kind === \"min\" && value !== null) out.minimum = value;\n      else if (shape === \"number\" && kind === \"max\" && value !== null) out.maximum = value;\n      else if (shape === \"string\" && kind === \"length\" && value !== null) out.maxLength = Math.trunc(value);\n    }\n    if (spec.rating && !(\"maximum\" in out)) out.maximum = M.rating_max;\n    if (spec.unit && d.unit && mode === \"stored\") out[\"x-matrx-unit\"] = d.unit;\n    return out;\n  }\n  if (shape === \"datetime\") {\n    // The store casts a string to timestamptz; the pattern refuses what no cast can read.\n    if (mode === \"stored\") return { type: [\"number\", \"string\"], pattern: M.stored_patterns.datetime };\n    return { type: \"string\", format: cfg.kind === \"date\" ? \"date\" : \"date-time\" };\n  }\n  if (shape === \"choice\") {\n    if (truthy(cfg.allow_other)) return { type: \"string\" };\n    if (mode === \"stored\") return { type: \"string\", enum: choiceTokens(facts, key) };\n    const live = liveChoiceKeys(facts, key);\n    if (live.length === 0 || live.length > M.choice_enum_limit) return { type: \"string\" };\n    return { type: \"string\", enum: live };\n  }\n  if (shape === \"relation\") {\n    // custom.validate_values refuses a value that is not an id by this very regex.\n    if (mode === \"stored\") return { type: \"string\", format: \"uuid\", pattern: M.stored_patterns.record_id };\n    return { type: \"string\", format: \"uuid\" };\n  }\n  if (shape === \"entity_reference\") {\n    const allowed = (Array.isArray(cfg.allowed_types) ? (cfg.allowed_types as unknown[]) : []).filter(\n      (t): t is string => typeof t === \"string\",\n    );\n    const id: Json = { type: \"string\", format: \"uuid\" };\n    if (mode === \"stored\") id.pattern = M.stored_patterns.record_id;\n    const out: Json = {\n      type: \"object\",\n      properties: { token: { type: \"string\", enum: allowed }, id },\n      required: [\"token\", \"id\"],\n    };\n    if (mode === \"authored\") out.additionalProperties = false;\n    return out;\n  }\n  if (shape === \"address\") {\n    const part: Json =\n      mode === \"authored\"\n        ? { type: \"string\", maxLength: M.address_part_max }\n        : { type: [\"string\", \"null\"], maxLength: M.address_part_max };\n    const out: Json = {\n      type: \"object\",\n      properties: Object.fromEntries(M.address_parts.map((p) => [p, { ...part }])),\n      additionalProperties: false,\n    };\n    if (mode === \"stored\") out.minProperties = 1;\n    return out;\n  }\n  return { readOnly: true };\n}\n\nfunction isTyped(d: Json): boolean {\n  return Array.isArray(d.applies_to_types) && (d.applies_to_types as unknown[]).length > 0;\n}\n\nfunction storedValue(facts: TableKindFacts, d: Json): Json {\n  const shape = kindSpec(d).shape;\n  if (shape === \"computed\") return { readOnly: true };\n  const one = item(facts, d, \"stored\");\n  const required = truthy(d.required) && !isTyped(d);\n  let value: Json;\n  if (shape === \"relation\" || shape === \"entity_reference\") {\n    const many: Json = { type: \"array\", items: one };\n    const ceiling = numberOf(d.relation_max);\n    if (ceiling !== null) many.maxItems = Math.trunc(ceiling);\n    if (required) many.minItems = 1;\n    value = { anyOf: [one, many] };\n  } else if (truthy(d.multi)) {\n    value = { type: \"array\", items: one };\n    if (required) value.minItems = 1;\n  } else {\n    value = one;\n  }\n  return required ? value : { anyOf: [value, { type: \"null\" }] };\n}\n\nfunction authoredValue(facts: TableKindFacts, d: Json, typeLabels: string[]): Json {\n  const spec = kindSpec(d);\n  const shape = spec.shape;\n  const one = item(facts, d, \"authored\");\n  let value: Json;\n  if (shape === \"relation\" || shape === \"entity_reference\") {\n    value = { type: \"array\", items: one };\n    const ceiling = numberOf(d.relation_max);\n    if (ceiling !== null) value.maxItems = Math.trunc(ceiling);\n  } else if (truthy(d.multi)) {\n    value = { type: \"array\", items: one };\n  } else {\n    value = one;\n  }\n  const extras: string[] = [];\n  if (spec.unit && d.unit) extras.push(`Amount in ${String(d.unit)}.`);\n  if (spec.hint) extras.push(spec.hint);\n  if (typeLabels.length > 0) extras.push(`Only for ${typeLabels.join(\", \")} records.`);\n  const label = String(d.label || d.key);\n  value.description = extras.length > 0 ? `${label}. ${extras.join(\" \")}` : label;\n  return value;\n}\n\nfunction isAuthored(d: Json): boolean {\n  const spec = kindSpec(d);\n  return spec.shape !== \"computed\" && spec.authored !== false;\n}\n\nfunction typeChoice(facts: TableKindFacts, word: string) {\n  for (const choice of facts.choices?.[facts.type_field ?? \"\"] ?? []) {\n    if (word === choice.key || word === choice.label || word === choice.id) return choice;\n  }\n  return null;\n}\n\nfunction typeSynonyms(facts: TableKindFacts, word: string): [string, string[]] {\n  const choice = typeChoice(facts, word);\n  if (!choice) return [word, [word]];\n  const out: string[] = [];\n  for (const token of [choice.key, choice.label, choice.id]) {\n    if (typeof token === \"string\" && token && !out.includes(token)) out.push(token);\n  }\n  return [String(choice.key || word), out];\n}\n\nfunction typeLabels(facts: TableKindFacts, d: Json): string[] {\n  const labels: string[] = [];\n  for (const word of (d.applies_to_types as unknown[]) ?? []) {\n    const choice = typeChoice(facts, String(word));\n    const label = choice ? String(choice.label || choice.key) : String(word);\n    if (!labels.includes(label)) labels.push(label);\n  }\n  return labels;\n}\n\nfunction liveFields(facts: TableKindFacts): Json[] {\n  return (facts.fields ?? []).filter((d): d is Json => !!d && typeof d === \"object\" && !!(d as Json).key);\n}\n\n// ── whole schemas ───────────────────────────────────────────────────────────────────────\n\n/** The Fields-only JSON Schema of a record of this Table (no control keys). */\nexport function tableJsonSchema(facts: TableKindFacts, mode: TableSchemaMode): Json {\n  const slug = tableKindSlug(String(facts.table_id));\n  const fields = liveFields(facts);\n  const properties: Json = { [KIND_KEY]: { const: slug } };\n  const required: string[] = [KIND_KEY];\n\n  if (mode === \"stored\") {\n    const branches = new Map<string, { if: Json; then: { required: string[]; properties: Json } }>();\n    for (const d of fields) {\n      const key = String(d.key);\n      properties[key] = storedValue(facts, d);\n      const computed = kindSpec(d).shape === \"computed\";\n      if (!truthy(d.required) || computed) continue;\n      if (!isTyped(d)) {\n        required.push(key);\n        continue;\n      }\n      if (!facts.type_field) continue;\n      for (const word of d.applies_to_types as unknown[]) {\n        const [typeKey, synonyms] = typeSynonyms(facts, String(word));\n        let branch = branches.get(typeKey);\n        if (!branch) {\n          branch = {\n            if: { properties: { [facts.type_field]: { enum: synonyms } }, required: [facts.type_field] },\n            then: { required: [], properties: {} },\n          };\n          branches.set(typeKey, branch);\n        }\n        if (!branch.then.required.includes(key)) {\n          branch.then.required.push(key);\n          branch.then.properties[key] = { not: { type: \"null\" } };\n        }\n      }\n    }\n    const platformKeys = Array.isArray(facts.platform_keys) ? facts.platform_keys : Object.keys(M.platform_keys);\n    for (const name of platformKeys) {\n      // A key the platform writes into every record (custom.record_platform_keys()); a Field of\n      // the same name is the column and keeps its own shape.\n      if (typeof name === \"string\" && !(name in properties)) properties[name] = clone(M.platform_keys[name] ?? {});\n    }\n    const schema: Json = {\n      type: \"object\",\n      properties,\n      patternProperties: { \"^_\": {} },\n      required,\n    };\n    // custom._undeclared_key_guard judges only a `fields` Table: a free_form (document) or code\n    // Table keeps any key, so its schema stays open (custom.table_column_source).\n    if ((facts.column_source || M.column_source_default) === \"fields\") schema.additionalProperties = false;\n    if (branches.size > 0) schema.allOf = [...branches.values()];\n    return schema;\n  }\n\n  for (const d of fields) {\n    if (!isAuthored(d)) continue;\n    const key = String(d.key);\n    const typed = isTyped(d);\n    properties[key] = authoredValue(facts, d, typed ? typeLabels(facts, d) : []);\n    if (truthy(d.required) && !typed) required.push(key);\n  }\n  return { type: \"object\", properties, required, additionalProperties: false };\n}\n\n/**\n * The Fields-only content-ir `KindSchema` the web draws a record of this Table with: every Field\n * nullable and optional, choices open to every word the store accepts (keys, labels, ids,\n * retired included). Wrap it with `withControlKeyFields` from @ai-matrx/content-ir — table kinds\n * never pass through `kindSchemaFromJsonSchema`.\n */\nexport function tableRenderSchema(facts: TableKindFacts): TableRenderSchema {\n  const slug = tableKindSlug(String(facts.table_id));\n  const out: Record<string, Record<string, unknown>> = {};\n  for (const d of liveFields(facts)) {\n    const key = String(d.key);\n    const shape = kindSpec(d).shape;\n    const multi = truthy(d.multi);\n    let field: Json;\n    if (shape === \"choice\") {\n      field = { type: multi ? \"string[]\" : \"enum\", values: choiceTokens(facts, key) };\n      if (truthy(configOf(d).allow_other)) field.open = true;\n    } else {\n      field = clone(M.render[shape]![multi ? \"many\" : \"one\"]);\n    }\n    field.nullable = true;\n    out[key] = field;\n  }\n  return { kind: slug, fields: out };\n}\n","{\n  \"about\": \"THE ONE MAPPING from a store Field to a kind's three schemas (KINDS-GLUE wave 3 §2). Hand-written here; aidream copies it verbatim to packages/matrx-graph/matrx_graph/table_kind_mapping.json (scripts/generate_table_kind_mapping.py --check). Both languages derive from this file only: @ai-matrx/records src/table-kind.ts and matrx_graph.table_kinds. Keys of `kinds` are the store's field kinds (custom.field_kinds() plus the formula `system` kinds custom.field_kind_of answers). Stored mode only: `column_source_default` is custom.table_column_source's answer when the facts carry none (silence means the doctrine: Field rows are the columns); `platform_keys` mirrors custom.record_platform_keys() with each key's shape (parent_id: custom.containment_parent's uuid cast; icon: the record's own @ai-matrx/icons name, a string or null); `stored_patterns` mirror custom.validate_values' relation id regex and, for dates, refuse a string the timestamptz cast can never read (no digits, not a special word) while never refusing one it can.\",\n  \"version\": 2,\n  \"kernels\": {\n    \"file\": \"11111111-0000-4000-8000-000000000006\",\n    \"person\": \"11111111-0000-4000-8000-000000000005\"\n  },\n  \"system_kinds\": [\"created_by\", \"modified_by\", \"autonumber\", \"created_time\", \"modified_time\"],\n  \"by_behaviour\": {\n    \"text\": \"text\",\n    \"range\": \"number\",\n    \"list\": \"select\",\n    \"relation\": \"relation\",\n    \"boolean\": \"checkbox\",\n    \"formula\": \"formula\"\n  },\n  \"choice_enum_limit\": 100,\n  \"rating_max\": 5,\n  \"address_parts\": [\"street\", \"city\", \"region\", \"postal_code\", \"country\"],\n  \"address_part_max\": 200,\n  \"column_source_default\": \"fields\",\n  \"platform_keys\": {\n    \"parent_id\": { \"type\": [\"string\", \"null\"], \"pattern\": \"^(?:\\\\{[0-9a-fA-F]{4}(?:-?[0-9a-fA-F]{4}){7}\\\\}|[0-9a-fA-F]{4}(?:-?[0-9a-fA-F]{4}){7})$\" },\n    \"icon\": { \"type\": [\"string\", \"null\"] }\n  },\n  \"stored_patterns\": {\n    \"record_id\": \"^[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    \"datetime\": \"[0-9][^0-9]+[0-9]|[0-9]{5}|^\\\\s*(?:[Nn][Oo][Ww]|[Tt][Oo][Dd][Aa][Yy]|[Tt][Oo][Mm][Oo][Rr][Rr][Oo][Ww]|[Yy][Ee][Ss][Tt][Ee][Rr][Dd][Aa][Yy]|[Ee][Pp][Oo][Cc][Hh])(?![A-Za-z])\"\n  },\n  \"kinds\": {\n    \"text\": { \"shape\": \"string\", \"value\": { \"type\": \"string\" } },\n    \"long_text\": { \"shape\": \"string\", \"value\": { \"type\": \"string\" } },\n    \"email\": { \"shape\": \"string\", \"value\": { \"type\": \"string\", \"format\": \"email\" } },\n    \"phone\": { \"shape\": \"string\", \"value\": { \"type\": \"string\" } },\n    \"url\": { \"shape\": \"string\", \"value\": { \"type\": \"string\" } },\n    \"barcode\": { \"shape\": \"string\", \"value\": { \"type\": \"string\", \"maxLength\": 256 } },\n    \"rich_text\": { \"shape\": \"string\", \"value\": { \"type\": \"string\" }, \"hint\": \"Markdown, no HTML.\" },\n    \"signature\": { \"shape\": \"string\", \"value\": { \"type\": \"string\", \"readOnly\": true }, \"authored\": false },\n    \"number\": { \"shape\": \"number\", \"value\": { \"type\": \"number\" } },\n    \"currency\": { \"shape\": \"number\", \"value\": { \"type\": \"number\" }, \"unit\": true },\n    \"percent\": { \"shape\": \"number\", \"value\": { \"type\": \"number\" }, \"hint\": \"A whole percent: 6 means 6%.\" },\n    \"rating\": { \"shape\": \"number\", \"value\": { \"type\": \"integer\", \"minimum\": 0 }, \"rating\": true },\n    \"duration\": { \"shape\": \"number\", \"value\": { \"type\": \"number\", \"minimum\": 0 }, \"hint\": \"A length of time in seconds.\" },\n    \"datetime\": { \"shape\": \"datetime\" },\n    \"checkbox\": { \"shape\": \"boolean\", \"value\": { \"type\": \"boolean\" } },\n    \"select\": { \"shape\": \"choice\" },\n    \"multi_select\": { \"shape\": \"choice\" },\n    \"status\": { \"shape\": \"choice\" },\n    \"relation\": { \"shape\": \"relation\" },\n    \"member\": { \"shape\": \"relation\" },\n    \"attachment\": { \"shape\": \"relation\", \"authored\": false },\n    \"entity_reference\": { \"shape\": \"entity_reference\" },\n    \"address\": { \"shape\": \"address\" },\n    \"formula\": { \"shape\": \"computed\" },\n    \"lookup\": { \"shape\": \"computed\" },\n    \"rollup\": { \"shape\": \"computed\" },\n    \"count\": { \"shape\": \"computed\" },\n    \"created_by\": { \"shape\": \"computed\" },\n    \"modified_by\": { \"shape\": \"computed\" },\n    \"autonumber\": { \"shape\": \"computed\" },\n    \"created_time\": { \"shape\": \"computed\" },\n    \"modified_time\": { \"shape\": \"computed\" }\n  },\n  \"render\": {\n    \"string\": { \"one\": { \"type\": \"string\" }, \"many\": { \"type\": \"string[]\" } },\n    \"number\": { \"one\": { \"type\": \"number\" }, \"many\": { \"type\": \"number[]\" } },\n    \"boolean\": { \"one\": { \"type\": \"boolean\" }, \"many\": { \"type\": \"boolean[]\" } },\n    \"datetime\": { \"one\": { \"type\": \"union\", \"scalars\": [\"string\", \"number\"] }, \"many\": { \"type\": \"json\" } },\n    \"relation\": { \"one\": { \"type\": \"json\" }, \"many\": { \"type\": \"json\" } },\n    \"entity_reference\": { \"one\": { \"type\": \"json\" }, \"many\": { \"type\": \"json\" } },\n    \"address\": { \"one\": { \"type\": \"json\" }, \"many\": { \"type\": \"json\" } },\n    \"computed\": { \"one\": { \"type\": \"json\" }, \"many\": { \"type\": \"json\" } }\n  }\n}\n","// src/alternates.ts — @ai-matrx/records\n//\n// \"USE THIS ONE\": PROMOTE A DISAGREEING VALUE, AND KEEP EVERY OTHER FIELD'S CANDIDATES.\n//\n// A value that two sources disagree about carries the other candidates in its envelope's\n// `alternates`, inside the record's `_values` block. Choosing one makes it the value and\n// demotes the value it replaces to an alternate, so nothing is lost and the choice can be\n// undone by choosing back.\n//\n// 🚨 THE TRAP THIS FILE EXISTS FOR. `custom.record_update` merges `data || patch` SHALLOWLY.\n// A patch carrying `_values: { phone: … }` REPLACES the whole `_values` block, erasing every\n// other field's envelope and alternates. So the patch carries the WHOLE `_values` block, copied\n// from the document just read, with only the chosen field's envelope changed. The chosen\n// envelope never carries `ver`, `actor` or `at`: the store stamps those.\n//\n// The write is against the version the document was read at (`expectedVersion`), so a colleague's\n// change in between is refused, never overwritten.\n\nimport type { RecordsClient } from \"./core/client\";\nimport type { RecordDocument, ValueAlternate, ValueEnvelope, Uuid } from \"./record\";\nimport type { RecordsError, RecordsResult } from \"./results\";\n\nexport interface ChooseAlternateArgs {\n  record_id: Uuid;\n  field_key: string;\n  /** Position in the field's `alternates` list as the record holds it. */\n  alternate_index: number;\n  /** When given, the alternate holding this rank is chosen instead — the list a screen drew may be ordered differently. */\n  rank?: number;\n}\n\nfunction refuse(code: RecordsError[\"code\"], message: string, hint: string): RecordsResult<number> {\n  return { ok: false, error: { code, message, hint, ours: true } as RecordsError };\n}\n\n/**\n * WHERE THE DISPLACED VALUE CAME FROM. A value somebody typed in has no `src` pointer — only the actor and\n * the time the store stamped — and the store re-stamps both the moment the chosen value takes the envelope,\n * so copying `envelope.src` alone left the demoted value as \"Unknown source\". When there is no pointer, the\n * source is written inline from the actor and time (the store interns an inline source into `_sources`).\n */\nfunction displacedSource(envelope: ValueEnvelope): { src?: string } {\n  if (envelope.src) return { src: envelope.src };\n  const by = envelope.actor === \"agent\" ? \"an agent\" : envelope.actor === \"system\" ? \"the system\" : envelope.actor ? \"a person\" : null;\n  if (by === null) return {};\n  const day = typeof envelope.at === \"string\" && envelope.at.length >= 10 ? ` on ${envelope.at.slice(0, 10)}` : \"\";\n  return { src: { name: `Entered by ${by}${day}` } as unknown as string };\n}\n\n/** The patch that makes alternate `alternate_index` of `field_key` the value. Pure; exported for tests. */\nexport function alternatePatch(\n  document: RecordDocument,\n  field_key: string,\n  alternate_index: number,\n  rank?: number,\n): { ok: true; patch: Record<string, unknown> } | { ok: false; message: string } {\n  const block = (document._values ?? {}) as Record<string, ValueEnvelope>;\n  const envelope = block[field_key];\n  const alternates: ValueAlternate[] = Array.isArray(envelope?.alternates) ? envelope.alternates : [];\n  const at = rank === undefined ? alternate_index : alternates.findIndex((a) => a.rank === rank);\n  alternate_index = at;\n  const chosen = alternates[at];\n  if (!envelope || !chosen) return { ok: false, message: \"That other value is no longer on this record.\" };\n\n  const kept = alternates.filter((_, i) => i !== alternate_index);\n  const current = document[field_key];\n  const next: ValueAlternate[] = [...kept];\n  if (current !== null && current !== undefined) {\n    const taken = new Set(kept.map((a) => a.rank));\n    let rank = 1;\n    while (taken.has(rank)) rank += 1;\n    next.push({ value: current, ...displacedSource(envelope), rank });\n  }\n\n  // The chosen field's envelope: everything it held, minus what the store stamps and what is no longer true.\n  const { ver: _ver, actor: _actor, at: _at, on_behalf_of: _on, absent: _absent, alternates: _alts, src: _src, ...rest } =\n    envelope as ValueEnvelope & Record<string, unknown>;\n  const changed: Record<string, unknown> = { ...rest, ...(chosen.src ? { src: chosen.src } : {}) };\n  if (next.length > 0) changed[\"alternates\"] = next;\n\n  return {\n    ok: true,\n    patch: {\n      [field_key]: chosen.value,\n      // THE WHOLE BLOCK — every other field's envelope and alternates travel with it.\n      _values: { ...block, [field_key]: changed },\n    },\n  };\n}\n\nexport async function chooseAlternate(\n  client: Pick<RecordsClient, \"recordRead\" | \"recordAsOf\" | \"recordUpdate\">,\n  { record_id, field_key, alternate_index, rank }: ChooseAlternateArgs,\n): Promise<RecordsResult<number>> {\n  const read = await client.recordRead({ record_id, withVersion: true });\n  if (!read.ok) return read;\n  // A MASKED FIELD'S ENVELOPE CANNOT BE COPIED WHOLE: writing the block back could replace what this\n  // person is not allowed to see. Refuse, write nothing.\n  if (Object.keys(read.data.hidden ?? {}).length > 0) {\n    return refuse(\"refused_by_rule\", \"Some fields here are hidden from you, so this choice can't be saved safely.\", \"Ask someone who can see every field.\");\n  }\n  const version = read.data.version;\n  if (version === null || version === undefined) {\n    return refuse(\"stale_read\", \"Nothing was saved: this record's latest changes could not be checked.\", \"Reload, then try again.\");\n  }\n  // `recordRead` hides the store's own `_values` and `_sources` blocks, so the document the patch is built\n  // from is the store's own account of the record as of now. It is read AFTER the version, so a write\n  // landing between the two makes the version stale and the store refuses, never clobbers.\n  const raw = await client.recordAsOf({ record_id, recorded_at: new Date().toISOString() });\n  if (!raw.ok) return raw;\n  if (raw.data === null) return refuse(\"not_found\", \"That record is no longer here.\", \"Reload, then look again.\");\n  const built = alternatePatch(raw.data as RecordDocument, field_key, alternate_index, rank);\n  if (!built.ok) return refuse(\"not_found\", built.message, \"Reload, then look again.\");\n  return client.recordUpdate({ record_id, patch: built.patch, expectedVersion: version });\n}\n","// src/datedValues.ts — @ai-matrx/records\n//\n// \"THE ADDRESS WAS X UNTIL JUNE 2024, THEN Y\" — THE WORLD CLOCK ON ONE VALUE (Rule 10, test 6).\n//\n// A Field that says its values are dated (`field.dated`) keeps, inside its envelope in the record's\n// `_values` block, the periods it was true between: `dated: [{ from, to, value }]`, `from`/`to` as\n// `YYYY-MM-DD` days, `null` meaning \"since forever\" / \"still true\", each period half-open\n// [from, to). `custom.query_record_as_of(world_on)` answers from them; `custom._dated_values_guard`\n// refuses periods on a Field that is not dated, and malformed or overlapping periods, in its own words.\n//\n// 🚨 THE SAME TRAP `alternates.ts` exists for: `custom.record_update` merges `data || patch`\n// SHALLOWLY, so a patch carrying `_values: { address: … }` would erase every other field's envelope.\n// The patch carries the WHOLE `_values` block, read from the store's own document, with only this\n// field's `dated` replaced, and is written against the version it was read at.\n//\n// The field's plain value becomes the period in force today (nothing when no period covers today):\n// the record says now what the world clock says now.\n\nimport type { RecordsClient } from \"./core/client\";\nimport type { RecordDocument, ValueEnvelope, Uuid } from \"./record\";\nimport type { RecordsError, RecordsResult } from \"./results\";\n\n/** One period a value was true between. `from`/`to` are `YYYY-MM-DD`; `null` is open-ended. */\nexport interface ValuePeriod {\n  from: string | null;\n  to: string | null;\n  value: unknown;\n}\n\nexport interface SetValuePeriodsArgs {\n  record_id: Uuid;\n  field_key: string;\n  /** The whole list, in any order. An empty list clears the field's dates. */\n  periods: ValuePeriod[];\n  /** `YYYY-MM-DD` — the day whose period becomes the plain value. Defaults to today (UTC). */\n  today?: string;\n}\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nfunction refuse(code: RecordsError[\"code\"], message: string, hint: string): RecordsResult<number> {\n  return { ok: false, error: { code, message, hint, ours: true } as RecordsError };\n}\n\n/** The periods a document holds for one field, oldest first. Pure. */\nexport function valuePeriodsOf(document: RecordDocument | null | undefined, field_key: string): ValuePeriod[] {\n  const envelope = (document?._values as Record<string, ValueEnvelope & { dated?: unknown }> | undefined)?.[field_key];\n  const raw = envelope?.dated;\n  if (!Array.isArray(raw)) return [];\n  return sortPeriods(\n    raw\n      .filter((p): p is Record<string, unknown> => typeof p === \"object\" && p !== null)\n      .map((p) => ({ from: typeof p[\"from\"] === \"string\" ? p[\"from\"] : null, to: typeof p[\"to\"] === \"string\" ? p[\"to\"] : null, value: p[\"value\"] ?? null })),\n  );\n}\n\nfunction sortPeriods(periods: ValuePeriod[]): ValuePeriod[] {\n  return [...periods].sort((a, b) => (a.from ?? \"\") < (b.from ?? \"\") ? -1 : (a.from ?? \"\") > (b.from ?? \"\") ? 1 : 0);\n}\n\n/** The period true on `day` (`YYYY-MM-DD`), or null. Half-open: true from `from`, no longer true on `to`. */\nexport function periodInForce(periods: ValuePeriod[], day: string): ValuePeriod | null {\n  return periods.find((p) => (p.from === null || p.from <= day) && (p.to === null || day < p.to)) ?? null;\n}\n\n/** Why a list of periods cannot be stored, in a person's words — or null when it can. Pure. */\nexport function valuePeriodsProblem(periods: ValuePeriod[]): string | null {\n  for (const p of periods) {\n    if ((p.from !== null && !DAY.test(p.from)) || (p.to !== null && !DAY.test(p.to))) return \"Each date has to be a day, like 2024-06-01.\";\n    if (p.from !== null && p.to !== null && p.to <= p.from) return `A period can't end (${p.to}) on or before it starts (${p.from}).`;\n  }\n  const sorted = sortPeriods(periods);\n  for (let i = 1; i < sorted.length; i += 1) {\n    const before = sorted[i - 1]!;\n    const next = sorted[i]!;\n    if (before.to === null || next.from === null || next.from < before.to) return \"Two periods overlap. Each day can have only one value.\";\n  }\n  return null;\n}\n\n/** The patch that stores `periods` on `field_key`, keeping every other field's envelope. Pure; exported for tests. */\nexport function valuePeriodsPatch(\n  document: RecordDocument,\n  field_key: string,\n  periods: ValuePeriod[],\n  today: string,\n): { ok: true; patch: Record<string, unknown> } | { ok: false; message: string } {\n  const problem = valuePeriodsProblem(periods);\n  if (problem) return { ok: false, message: problem };\n  const block = (document._values ?? {}) as Record<string, ValueEnvelope & Record<string, unknown>>;\n  const envelope = block[field_key] ?? {};\n  // What the store stamps (ver, actor, at) and what is no longer true never travel back.\n  const { ver: _ver, actor: _actor, at: _at, on_behalf_of: _on, absent: _absent, dated: _dated, ...rest } = envelope as Record<string, unknown>;\n  const sorted = sortPeriods(periods);\n  const changed: Record<string, unknown> = { ...rest, dated: sorted.length > 0 ? sorted : null };\n  const now = periodInForce(sorted, today);\n  return {\n    ok: true,\n    patch: {\n      ...(sorted.length > 0 ? { [field_key]: now ? now.value : null } : {}),\n      _values: { ...block, [field_key]: changed },\n    },\n  };\n}\n\n/**\n * STORE WHEN A VALUE WAS TRUE. Reads the record's own document (`recordAsOf`, recorded now) after its\n * version, writes the whole `_values` block back with this field's periods replaced, against that version.\n * Refused when any field is hidden from the reader (the block could not be copied whole).\n */\nexport async function setValuePeriods(\n  client: Pick<RecordsClient, \"recordRead\" | \"recordAsOf\" | \"recordUpdate\">,\n  { record_id, field_key, periods, today }: SetValuePeriodsArgs,\n): Promise<RecordsResult<number>> {\n  const problem = valuePeriodsProblem(periods);\n  if (problem) return refuse(\"invalid_argument\", problem, \"Fix the dates, then save again.\");\n  const read = await client.recordRead({ record_id, withVersion: true });\n  if (!read.ok) return read;\n  if (Object.keys(read.data.hidden ?? {}).length > 0) {\n    return refuse(\"refused_by_rule\", \"Some fields here are hidden from you, so these dates can't be saved safely.\", \"Ask someone who can see every field.\");\n  }\n  const version = read.data.version;\n  if (version === null || version === undefined) {\n    return refuse(\"stale_read\", \"Nothing was saved: this record's latest changes could not be checked.\", \"Reload, then try again.\");\n  }\n  const raw = await client.recordAsOf({ record_id, recorded_at: new Date().toISOString() });\n  if (!raw.ok) return raw;\n  if (raw.data === null) return refuse(\"not_found\", \"That record is no longer here.\", \"Reload, then look again.\");\n  const built = valuePeriodsPatch(raw.data as RecordDocument, field_key, periods, today ?? new Date().toISOString().slice(0, 10));\n  if (!built.ok) return refuse(\"invalid_argument\", built.message, \"Fix the dates, then save again.\");\n  return client.recordUpdate({ record_id, patch: built.patch, expectedVersion: version });\n}\n","// src/ai-field-presets.ts — @ai-matrx/records · lane W2-C (AIRTABLE-PARITY row 95)\n//\n// THE ONE LIST of \"what an AI column does\" presets, read by BOTH homes of AI columns:\n//   · the table page's \"Let AI fill\" panel (records-ui `EnrichPanel`) — a preset becomes the column's instruction, which the\n//     `table.column_fill` mandate runs per row (the server also hands that mandate the column's kind and, for a choice column, its choices);\n//   · Spaces' \"AI autofill\" property (matrx-frontend `features/spaces/data/ai-autofill.tsx`, mandate `spaces.autofill`) — `autofillKind`\n//     is the kind that mandate already knows (summary | keywords | translation); every other preset runs as its `custom` kind with the\n//     same instruction this file writes.\n// Airtable's own AI field offers: Summarize, Categorize, Translate, Extract info, Sentiment, Describe image. Nothing here asks a model:\n// this file only writes the sentence a person would otherwise have to type. Import-inert: data and pure functions.\n\nimport { KERNEL_TABLES } from \"./store.generated\";\nimport { fieldKindFor, type CoercibleField, type FieldKind, type KernelTargets } from \"./coerce\";\n\nexport type AiPresetKey = \"summarize\" | \"keywords\" | \"categorize\" | \"translate\" | \"extract\" | \"sentiment\" | \"describe_image\";\n\n/** What the person must still say after choosing a preset. */\nexport type AiPresetAsk = \"language\" | \"what\";\n\n/** Spaces' autofill kinds (`features/spaces/data/sources.ts`); `custom` carries the instruction. */\nexport type AiAutofillKind = \"summary\" | \"keywords\" | \"translation\" | \"custom\";\n\nexport interface AiFieldPreset {\n  key: AiPresetKey;\n  label: string;\n  autofillKind: AiAutofillKind;\n  /** The one thing still to ask: a language (Translate) or what to pull out (Extract). */\n  ask?: AiPresetAsk;\n  /** The column kind the preset needs: Categorize fills a choice column, Describe image reads an attachment column. */\n  needs?: \"choice\" | \"attachment\";\n  /**\n   * The platform job (mandate key) that fills a column made from this preset when it is not the plain text one. Describe image\n   * is filled by a model that can SEE: the server shows it the row's picture attachments (the attachment columns named in the\n   * column's `inputs`). Every preset without a `mandate` runs as `table.column_fill`.\n   */\n  mandate?: string;\n}\n\nexport const AI_FIELD_PRESETS: readonly AiFieldPreset[] = [\n  { key: \"summarize\", label: \"Summarize\", autofillKind: \"summary\" },\n  { key: \"keywords\", label: \"Keywords\", autofillKind: \"keywords\" },\n  { key: \"categorize\", label: \"Categorize\", autofillKind: \"custom\", needs: \"choice\" },\n  { key: \"translate\", label: \"Translate\", autofillKind: \"translation\", ask: \"language\" },\n  { key: \"extract\", label: \"Extract\", autofillKind: \"custom\", ask: \"what\" },\n  { key: \"sentiment\", label: \"Sentiment\", autofillKind: \"custom\" },\n  { key: \"describe_image\", label: \"Describe image\", autofillKind: \"custom\", needs: \"attachment\", mandate: \"table.column_fill_image\" },\n];\n\nexport function aiFieldPreset(key: string): AiFieldPreset | undefined {\n  return AI_FIELD_PRESETS.find((p) => p.key === key);\n}\n\nexport interface AiPresetContext {\n  /** The language for Translate (\"Spanish\"); what to pull out for Extract (\"the invoice number\"). */\n  answer?: string | undefined;\n  /** The names of the columns the preset reads, when the person narrowed it (e.g. the attachment column). */\n  reads?: readonly string[] | undefined;\n}\n\nconst clean = (s: string | undefined): string => (s ?? \"\").trim().replace(/\\s+/g, \" \");\n\n/**\n * The instruction a preset writes. It is a plain sentence a person can read and edit; it names no model and no table. A preset that\n * still needs an answer (language, what to extract) and was given none returns `null`, so a screen never saves half a sentence.\n */\nexport function presetInstruction(key: AiPresetKey, ctx: AiPresetContext = {}): string | null {\n  const from = ctx.reads && ctx.reads.length > 0 ? ` (${ctx.reads.join(\", \")})` : \"\";\n  const answer = clean(ctx.answer);\n  switch (key) {\n    case \"summarize\":\n      return `Summarize this record's text${from} in one or two plain sentences.`;\n    case \"keywords\":\n      return `List the five most useful keywords for this record${from}, separated by commas.`;\n    case \"categorize\":\n      return `Choose the one option of this column that best fits this record${from}. Answer with that option exactly as written.`;\n    case \"translate\":\n      return answer ? `Translate this record's text${from} into ${answer}. Keep names and numbers as they are.` : null;\n    case \"extract\":\n      return answer ? `Find ${answer} in this record's text${from} and write only that value. If it is not there, say nothing was found.` : null;\n    case \"sentiment\":\n      return `Read this record's text${from} and say whether its tone is positive, neutral or negative. Answer with that one word.`;\n    case \"describe_image\":\n      return `Describe the picture${from ? ` in the attachment${from}` : \" attached to this record\"} in one or two plain sentences: what is shown and anything written on it.`;\n  }\n}\n\n/**\n * The columns a preset's model must read, as the `inputs` of the column's enrichment. Describe image reads the table's attachment\n * columns (without them the model is shown nothing and answers \"nothing found\"); every other preset reads none by name, so the\n * answer is `undefined` and the declaration stays as it was.\n */\nexport function presetInputs(key: AiPresetKey | undefined, attachmentColumnKeys: readonly string[]): string[] | undefined {\n  if (!key || aiFieldPreset(key)?.needs !== \"attachment\") return undefined;\n  const keys = attachmentColumnKeys.filter((k) => k.trim().length > 0);\n  return keys.length > 0 ? [...new Set(keys)] : undefined;\n}\n\n/**\n * Which presets a column may offer: Categorize only for a choice column (the server passes the column's own choices to the\n * mandate), Describe image only when the table has an attachment column to read. Everything else fits any column.\n */\nexport function presetsFor(args: { targetIsChoice: boolean; hasAttachmentColumn: boolean }): readonly AiFieldPreset[] {\n  return AI_FIELD_PRESETS.filter((p) => (p.needs === \"choice\" ? args.targetIsChoice : p.needs === \"attachment\" ? args.hasAttachmentColumn : true));\n}\n\nconst kernelId = (name: string): string => KERNEL_TABLES.find((t) => t.name === name)?.id ?? \"\";\nconst DEFAULT_KERNEL: KernelTargets = { file: kernelId(\"File\"), person: kernelId(\"Person\") };\nconst UNREADABLE_KINDS: ReadonlySet<FieldKind> = new Set<FieldKind>([\"attachment\", \"relation\", \"entity_reference\", \"member\", \"json\", \"rollup\", \"lookup\"]);\n/** The store's sensitivity order (custom.enrich_sensitivity_rank): an AI fill reads up to the organization's ceiling. */\nconst SENSITIVITY_RANK: Readonly<Record<string, number>> = { public: 1, internal: 2, restricted: 3, confidential: 4 };\n/** Whether a column of this sensitivity is within the ceiling; an unknown word (either side) is never read by default. */\nexport function withinSensitivityCeiling(sensitivity: string | null | undefined, ceiling: string): boolean {\n  const have = SENSITIVITY_RANK[(sensitivity ?? \"internal\").trim().toLowerCase()];\n  const max = SENSITIVITY_RANK[ceiling.trim().toLowerCase()] ?? SENSITIVITY_RANK.public!;\n  return have !== undefined && have <= max;\n}\n\n/** The slice of a Field the default-inputs question reads. */\nexport type EnrichInputField = CoercibleField & {\n  key: string;\n  archived_at?: string | null;\n  source?: string | null;\n  sensitivity?: string | null;\n  context_policy?: string | null;\n};\n\n/**\n * THE DEFAULT `inputs` of a new AI column: the record's OTHER readable fields, by key. A column saved with no inputs hands the\n * model nothing to read (every row comes back \"nothing to find\"), so both homes of AI columns - the table page's \"Let AI fill\" and\n * Spaces' \"AI autofill\" - start from this list. Left out: the column itself, other AI columns (no loops), retired columns,\n * pictures/links/people/rolled-up values (a text model cannot read them), and anything the store would refuse an enrichment\n * to read (sensitivity above the organization's ceiling - `recordsLimits().enrichmentSensitivityCeiling`, the knob\n * custom/enrichment_sensitivity_ceiling - or a column that says no agent may see it). `on_request` columns are fetched only when\n * asked, so they are not read by default either.\n */\nexport function defaultEnrichInputs(\n  fields: readonly EnrichInputField[],\n  targetKey: string,\n  ceiling: string = \"internal\",\n  kernel: KernelTargets = DEFAULT_KERNEL,\n): string[] {\n  const keys = fields\n    .filter((f) => f.key && f.key !== targetKey && !f.archived_at && f.source !== \"agent\")\n    .filter((f) => f.context_policy !== \"exclude\" && f.context_policy !== \"on_request\")\n    .filter((f) => withinSensitivityCeiling(f.sensitivity, ceiling))\n    .filter((f) => !UNREADABLE_KINDS.has(fieldKindFor(f, kernel)))\n    .map((f) => f.key);\n  return [...new Set(keys)];\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/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/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/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/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/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","// src/core/clientInOrganization.ts — @ai-matrx/records/core\n//\n// A records client that speaks for ONE organization: the one a row LIVES in. Every by-id door of the\n// record store (history, restore preview, version read) takes the client's organization as\n// `p_organization_id`; a row read through a client bound to a different organization answers EMPTY,\n// not refused. So a by-id read or write of a stored row goes through\n// `clientInOrganization(client, row.organizationId)`, never the page's client as-is.\n//\n// Same organization (or none named) -> the same client; otherwise ONE sibling client per\n// organization, reused. The sibling map is held on globalThis under a registered symbol so a page\n// that loaded this package twice (ESM and CJS) still shares one sibling per organization.\n\nimport { createRecordsClient, type RecordsClient } from \"./client\";\n\ntype Siblings = WeakMap<RecordsClient, Map<string, RecordsClient>>;\n\nfunction siblingsOfPage(): Siblings {\n  const key = Symbol.for(\"@ai-matrx/records/core.clientInOrganization\");\n  const g = globalThis as unknown as Record<symbol, Siblings | undefined>;\n  return (g[key] ??= new WeakMap());\n}\n\nexport function clientInOrganization<C extends RecordsClient>(client: C, organizationId: string | null | undefined): C {\n  if (!organizationId || organizationId === client.config.organizationId) return client;\n  const siblings = siblingsOfPage();\n  let byOrg = siblings.get(client);\n  if (!byOrg) siblings.set(client, (byOrg = new Map()));\n  let sibling = byOrg.get(organizationId);\n  if (!sibling) {\n    sibling = createRecordsClient({ ...client.config, organizationId, organizationIds: [] });\n    byOrg.set(organizationId, sibling);\n  }\n  return sibling as C;\n}\n","// src/core/declareTable.ts — @ai-matrx/records/core\n//\n// HEADLESS (lane GRID-PRIMITIVES, asked by INTEG-CLIENTS 2026-09-24): this is the ONE birth of a\n// person-made Table, moved here from @ai-matrx/records-ui so the extension's service worker and\n// server-side births — no React, no host — walk the same doors. records-ui re-exports it.\n//\n// DECLARING A TABLE, THROUGH THE DOORS THAT DECLARE ONE.\n//\n// REC-1: a Table has to live somewhere. `custom._table_shape_guard` refuses a\n// Table with no Home in those words (\"a table has to live somewhere - give it a\n// home\"), so the sequence is fixed and this module is the one place that walks\n// it for a person-made table:\n//\n//   1. `record_write` into the person kernel — the Home record. (A Home is an\n//      ORDINARY record: it is not a Table, not a Field, not a View.)\n//   2. `table_declare` — the Table, under that Home.\n//   3. `field_declare_many` — every column, each through `field_declare`.\n//\n// Since TABLE-CREATE-SPEED-2 the store walks all three inside `custom.table_create`,\n// in ONE transaction: one round trip, and a refusal leaves nothing behind.\n//\n// STEP 4 USED TO BE `record_write` INTO THE FIELD KERNEL, AND THAT IS WHY\n// NOBODY COULD MAKE A TABLE. A Field is a record (REC-25), so this walked in\n// through the ordinary write door — and that door writes exactly one row with\n// `data_class = 'record'`. Since `custom._field_class_guard` landed it refuses\n// that row outright (23514 / FLD-13, \"a column of a table is stored as a field,\n// and this one says record\"), and before the guard it wrote a Field that no\n// reader asking for a Field by class could see. Either way the column was never\n// really made — and because `table_declare` runs FIRST and succeeds, every\n// \"Create table\" showed a red refusal AND left a table behind it. Measured on\n// the published screens (records-ui 0.16.0) on 2026-09-20: four tables in one\n// organization, each declaring a column name, none of them with a Field row.\n//\n// So the column goes through `custom.field_declare`, which is the door built\n// for exactly this: it takes what a PERSON knows — a name, a type, and for a\n// list the choices themselves — tells the Table first, stamps\n// `data_class = 'field'`, and fills in a name the Table declared and never\n// defined. And a table that could not take all of its columns is UNDONE, so a\n// person sees either a table or a refusal and never both.\n\nimport type { RecordsClient } from \"./client\";\nimport type { FieldTypeWord, NewFieldDeclaration } from \"../field\";\nimport type { RecordsError } from \"../results\";\nimport type { FieldDrift } from \"../table\";\nimport type { Uuid } from \"../record\";\n\n/** One Field a person asked for, in the words a person uses (FLD-1 / FLD-11). */\nexport interface NewFieldSpec {\n  key: string;\n  label: string;\n  /**\n   * The word for what this column holds — any word `custom._field_document_for`\n   * resolves for `type` (a parity type, a behavior, a plain synonym, or a kind\n   * such as `signature`, `relation`, `entity_reference`, `autonumber`). It is\n   * sent to the door as `type`, unmapped; a word that means nothing is refused\n   * by name, with the list.\n   */\n  type: FieldTypeWord;\n  sort?: number;\n  required?: boolean;\n  multi?: boolean;\n  config?: Record<string, unknown>;\n  /** A choice list's choices, as words. The store keeps them as a Table (FLD-5). */\n  options?: string[];\n  /** A column that points at another Table of this organization (FLD-11 / REL-8). */\n  relationTarget?: Uuid;\n  /** A currency column's symbol; a date column's day-or-day-and-time. */\n  unit?: string;\n  kind?: \"date\" | \"datetime\";\n  /**\n   * An `entity_reference` column's kinds: the platform entity tokens it may point\n   * at (`ai_model`, `note`, `web_site` …; `custom.entity_reference_kinds()` lists\n   * them). The store refuses an entity reference that names none.\n   */\n  allowedTypes?: string[];\n  /**\n   * No two live records may hold the same value here (a `unique` Rule, FLD-3 / B1). A column\n   * `recordUpsert` finds a record by must carry it.\n   */\n  unique?: boolean;\n  /**\n   * An EXISTING choice list's Table — the column uses those very option records instead of making a\n   * new list (a drafts table copying its source table's column keeps the same choices). Sent as\n   * `config.options_table_id`.\n   */\n  optionsTableId?: Uuid;\n  /**\n   * Anything else `custom.field_declare` accepts, passed through verbatim and applied LAST (a stored\n   * Field document copied key for key, `format`, `sensitivity`, `via` / `pick` / `agg` / `of`, …).\n   * The store judges every key; a word it does not take is refused by name.\n   */\n  declaration?: Partial<NewFieldDeclaration> & Record<string, unknown>;\n}\n\nexport interface NewTableSpec {\n  name: string;\n  /** The token the Table is addressed by. Derived from the name when absent. */\n  slug?: string;\n  labelSingular?: string;\n  labelPlural?: string;\n  /** The Field whose value is the record's title (REC-2). Defaults to the first Field. */\n  titleField?: string;\n  fields?: NewFieldSpec[];\n  /**\n   * `ensureTable` only: put a NEW table in this existing Home (one the caller may change, in this\n   * organization) instead of making a Home for it. A table that already exists stays where it is.\n   */\n  homeId?: Uuid;\n  /** SC-1 placement: the app (one of its features) keeps this table, not the organization. */\n  platformOwned?: boolean;\n  /**\n   * WHICH feature keeps it, one lower-case word (`agent_output`, `context`, …). `ensureTable` finds a\n   * table by slug AND this word: a person's table of the same slug is a different table.\n   */\n  keptFor?: string;\n  /** The content kind whose outputs this table holds. */\n  kind?: string;\n  /** A drafts table: the Table its records are drafts of. */\n  draftsFor?: Uuid;\n  /** A drafts table: that Table's stamp when the drafts table last matched it. */\n  draftsStamp?: string;\n  /**\n   * An TYPED TABLE's declaration facts (`defineTypedTable`, `@ai-matrx/records/typed-table`): scope, owner,\n   * gate reason, review date and spec hash, stored on the Table document as `app_table`. Written\n   * when the table is born; an existing table keeps the block it was born with.\n   */\n  typedTable?: Record<string, unknown>;\n  /**\n   * THE APP'S CODE DEPENDS ON THIS TABLE (`code_depends: true` on its document; lane 12 P5). The\n   * store then refuses archiving, renaming (slug or kept_for), moving or unmarking it through every\n   * door; the one way through is `archiveTypedTableDeliberately`. `ensureTable` writes it on birth and\n   * merges it onto an existing table that lacks it. Only an typed-table spec (`typedTable`) carries it.\n   */\n  codeDepends?: boolean;\n  /**\n   * `ensureTable` only, on BIRTH: what a new row starts with, set through\n   * `custom.table_row_defaults_set` (e.g. `{ shown_to: \"only_me\" }` — hidden from other people's\n   * lists, never locked). A table that already exists keeps its own.\n   */\n  rowDefaults?: { shown_to?: \"only_me\" | \"my_team\" | \"everyone\" | null };\n  /**\n   * `ensureTable` only, on BIRTH: every member of the organization reaches the new table at this\n   * level (`custom.share_lane_set(…, 'organization', level)`), so members can add rows to a table\n   * one of them made first. A table that already exists keeps its own sharing.\n   */\n  membersReach?: \"viewer\" | \"commenter\" | \"editor\";\n}\n\n/**\n * What `ensureTable` answers: `declareTable`'s answer, plus whether this call MADE the table and\n * how the columns it already had differ from the spec (`drift`, reported and never applied — see\n * `FieldDrift`). `drift` is `[]` on a birth and when nothing differs.\n */\nexport type EnsureResult =\n  | { ok: true; data: Uuid; homeId: Uuid; created: boolean; drift: FieldDrift[] | null }\n  | { ok: false; error: RecordsError };\n\nexport type DeclareResult =\n  /**\n   * The Table's id — and its HOME's, because REC-14 gives the Table exactly one\n   * and the caller that made it is the only one that can tidy it up again. A\n   * caller reading `data` alone is unaffected.\n   */\n  | { ok: true; data: Uuid; homeId: Uuid }\n  | { ok: false; error: RecordsError };\n\n/** `My Sales Pipeline` → `my_sales_pipeline`. A token, never a sentence. */\nexport function tokenFor(name: string): string {\n  return (\n    name\n      .trim()\n      .toLowerCase()\n      .replace(/[^a-z0-9]+/g, \"_\")\n      .replace(/^_+|_+$/g, \"\")\n      .slice(0, 48) || \"table\"\n  );\n}\n\n/** The one Field a Table cannot be declared without: something to call a record. */\n/**\n * WHY THE FIRST FIELD IS NOT REQUIRED.\n *\n * It was, and the cost showed up the moment the grid could add a row: \"New\n * record\" writes an empty record and puts you in the first cell, and the store\n * correctly refused every one of them — `REC-51: Title is required` — so the\n * one gesture that makes a grid feel like a grid never worked on a table a\n * person had just made. A title is what makes a record a CHIP (REC-2), which is\n * a fact about how it is shown, not a promise it can never be written without;\n * an organization that wants it demanded says so in the field editor, and the\n * store then enforces it for everyone.\n */\nexport const DEFAULT_FIELDS: NewFieldSpec[] = [\n  { key: \"title\", label: \"Title\", type: \"text\", sort: 10, required: false },\n];\n\n/**\n * One column, in the shape `custom.field_declare` takes — and EVERYTHING a\n * person said about it. The keys after the type are not decoration: without\n * `options` the door refuses a choice list outright (\"A list of choices needs\n * its choices\"), without `unit` a money column is dollars whatever the person\n * picked, and without `relation_target` a column that points at another of this\n * organization's own tables cannot be declared at all.\n */\nexport function fieldDeclarationFor(field: NewFieldSpec): NewFieldDeclaration {\n  return {\n    key: field.key,\n    label: field.label,\n    sort: field.sort ?? 100,\n    required: field.required ?? false,\n    multi: field.multi ?? false,\n    ...declaredType(field),\n    ...(field.config ? { config: field.config } : {}),\n    ...(field.options ? { options: field.options } : {}),\n    ...(field.relationTarget ? { relation_target: field.relationTarget } : {}),\n    ...(field.unit ? { unit: field.unit } : {}),\n    ...(field.kind ? { kind: field.kind } : {}),\n    ...(field.allowedTypes ? { allowed_types: field.allowedTypes } : {}),\n    ...(field.unique ? { rules: [{ kind: \"unique\" as const }] } : {}),\n    ...(field.optionsTableId\n      ? { config: { ...(field.config ?? {}), options_table_id: field.optionsTableId } }\n      : {}),\n    ...(field.declaration ?? {}),\n  } as NewFieldDeclaration;\n}\n\n/** The Table's own declaration, as `custom.table_declare` takes it — one place for both births. */\nfunction tableSpecFor(spec: NewTableSpec, fields: NewFieldSpec[], slug: string): Record<string, unknown> {\n  const titleField = spec.titleField ?? fields[0]!.key;\n  return {\n    name: spec.name,\n    slug,\n    type: \"entity\",\n    label_singular: spec.labelSingular ?? spec.name,\n    label_plural: spec.labelPlural ?? spec.name,\n    display: \"list\",\n    weight: \"light\",\n    ordered: false,\n    row_order: \"manual\",\n    title_field: titleField,\n    retention_days: 365,\n    // AGT-1: a table a person made is agent-writable by declaration; the\n    // organization turns it off, never this package.\n    agent_writable: true,\n    default_sort: [{ field: titleField, direction: \"asc\" }],\n    ...(spec.platformOwned !== undefined ? { kept_by_the_app: spec.platformOwned } : {}),\n    ...(spec.keptFor ? { kept_for: spec.keptFor } : {}),\n    ...(spec.kind ? { kind: spec.kind } : {}),\n    ...(spec.draftsFor ? { drafts_for: spec.draftsFor } : {}),\n    ...(spec.draftsStamp ? { drafts_stamp: spec.draftsStamp } : {}),\n    ...(spec.typedTable ? { app_table: spec.typedTable } : {}),\n    ...(spec.typedTable && spec.codeDepends ? { code_depends: true } : {}),\n  };\n}\n\n/**\n * FIND THIS TABLE BY ITS SLUG, OR MAKE IT — the birth a PAGE uses (lane PLATFORM-APP-DATA).\n *\n * `declareTable` is a person's \"Create table\": it always makes a new one. A page that keeps its\n * own data (\"the front desk's callback log\") needs the opposite — THE table of that address,\n * made the first time and found every time after — and the hand-written version of that\n * (list every table, search, then declare) made two tables when two tabs saved first at once.\n * `custom.table_ensure` does the find and the make in ONE transaction under a lock on\n * (organization, slug), so both callers get the same table; a second call adds any column the\n * spec names that the table does not have yet and never retypes or drops one.\n *\n * Same answer shape as `declareTable` (the Table's id and its Home's) plus `created` and `drift`:\n * every column the table already had whose stored type, format, label, multi, required or unique\n * differs from the spec — reported, never applied. On a store without the\n * door it is `door_absent`, never a fallback to the racing walk.\n */\nexport async function ensureTable(client: RecordsClient, spec: NewTableSpec): Promise<EnsureResult> {\n  // A table's confidentiality is a reader list plus a reason (`custom.set_table_confidential`), not a\n  // column `table_ensure` takes, so a `sensitivity` word on the spec used to be dropped without a sound.\n  // It is refused out loud instead; a field's own `sensitivity` still travels in `declaration`.\n  if ((spec as { sensitivity?: unknown }).sensitivity !== undefined) {\n    return {\n      ok: false,\n      error: {\n        code: \"invalid_argument\",\n        message:\n          \"A table cannot be made confidential when it is created. Create it, then choose who may read it from its sharing settings.\",\n      },\n    };\n  }\n  const fields = spec.fields && spec.fields.length > 0 ? spec.fields : DEFAULT_FIELDS;\n  const slug = spec.slug ?? tokenFor(spec.name);\n  const ensured = await client.tableEnsure({\n    spec: {\n      ...tableSpecFor(spec, fields, slug),\n      ...(spec.homeId ? { home_id: spec.homeId } : {}),\n      ...(spec.rowDefaults ? { row_defaults: spec.rowDefaults } : {}),\n      ...(spec.membersReach ? { members_reach: spec.membersReach } : {}),\n      fields: fields.map(fieldDeclarationFor),\n    },\n  });\n  if (!ensured.ok) return ensured;\n  return {\n    ok: true,\n    data: ensured.data.table_id,\n    homeId: ensured.data.home_id as Uuid,\n    created: ensured.data.created,\n    drift: ensured.data.drift,\n  };\n}\n\nexport async function declareTable(\n  client: RecordsClient,\n  spec: NewTableSpec,\n): Promise<DeclareResult> {\n  const fields = spec.fields && spec.fields.length > 0 ? spec.fields : DEFAULT_FIELDS;\n  const slug = spec.slug ?? tokenFor(spec.name);\n\n  // ONE CALL, ONE TRANSACTION (TABLE-CREATE-SPEED-2): `custom.table_create` writes the Home, the\n  // Table under it and every column through the same three doors, so a refusal anywhere leaves\n  // nothing behind — no take-back dance, and one round trip instead of four.\n  const made = await client.tableCreate({\n    spec: { ...tableSpecFor(spec, fields, slug), fields: fields.map((f) => ({ name: f.key })) },\n    fields: fields.map(fieldDeclarationFor),\n  });\n  if (!made.ok) return made;\n  return { ok: true, data: made.data.table_id, homeId: made.data.home_id };\n}\n\n/**\n * Columns for an existing Table, through the door that declares one. Used by\n * the create path and by import.\n *\n * A column the store refused STOPS the sequence and hands back the store's own\n * sentence: a Table that quietly lost a column is the silent failure this\n * package exists to prevent.\n */\nexport async function addFields(\n  client: RecordsClient,\n  tableId: Uuid,\n  fields: NewFieldSpec[],\n): Promise<{ ok: true; data: Uuid } | { ok: false; error: RecordsError }> {\n  /*\n   * A COLUMN GOES THROUGH THE COLUMN DOOR (FLD-13).\n   *\n   * This wrote each Field as a plain record into the Field kernel Table, and\n   * the store now refuses it out loud: `custom.record_write` stores a record\n   * whose class defaults to \"record\", \"which makes the column invisible to\n   * every reader that asks for a Field by class — including the duplicate check\n   * that stops one table having the same column twice\" (`23514`,\n   * `refused_by_rule`). Measured 2026-09-20: this is why `demo/live-smoke`\n   * could not declare a table at all.\n   *\n   * `custom.field_declare` is the door that exists for this. It is also the one\n   * that derives a parity type, creates a choice Table for a list column and\n   * stamps the auto Rules a url or a percent carries — none of which a hand-\n   * written record ever got, so every column made this way was thinner than one\n   * made through the field panel.\n   */\n  // ONE CALL (TABLE-CREATE-SPEED-2): every column through `custom.field_declare_many`, in order, in one\n  // transaction — a refused column leaves none of them, and the store's own sentence comes back.\n  if (fields.length === 0) return { ok: true, data: tableId };\n  const result = await client.fieldDeclareMany({ table_id: tableId, specs: fields.map(fieldDeclarationFor) });\n  if (!result.ok) return result;\n  return { ok: true, data: tableId };\n}\n\n/**\n * `NewFieldSpec.type` is the word a caller writes, and it goes to\n * `custom.field_declare` AS `type` — every word, unmapped.\n *\n * `custom._field_document_for` reads three keys, and only `type` resolves every\n * word it knows: the parity floor, the plain behaviors and their synonyms, and\n * every kind that is neither (`signature`, `relation`, `entity_reference`, the\n * store's own stamps `autonumber` / `created_time` / `modified_time`, `list`,\n * `boolean` …). `parity_type` accepts ONLY the parity floor. This used to map\n * the plain words to `plain` and send EVERY other word as `parity_type`, so an\n * `entity_reference` column was refused \"There is no field type called\n * \"entity_reference\"\" and a `relation` or `signature` column the same way\n * (lane DECLARE-ENTITY-REF, 2026-09-25). The store owns the vocabulary; a word\n * that means nothing is refused by the door, by name, with the list.\n *\n * The one thing said here: a caller that asked for multiline text gets long\n * text, which is what the store stores `config.multiline` for.\n */\nfunction declaredType(field: NewFieldSpec): { type: FieldTypeWord } {\n  const word = (field.type ?? \"text\").toLowerCase() as FieldTypeWord;\n  if ((word === \"text\" || word === \"string\") && field.config?.[\"multiline\"] === true) {\n    return { type: \"long_text\" };\n  }\n  return { type: word };\n}\n","// src/core/tableKindFacts.ts — @ai-matrx/records · KINDS-GLUE wave 3 slice 4\n//\n// THE READER OF A TABLE AS A KIND. `custom.table_kind_facts(p_table_id)` (N1) answers a Table's\n// live Fields, choices, type field and stamp as the asking person, and finds the Table's\n// organization itself — so a `table:<uuid>` sighted in a chat, a note or a canvas can be answered\n// before anybody knows which organization the Table lives in. That is why this is a standalone\n// reader over a data source rather than a method that needs an organization-bound client (the\n// client carries the same door as `tableKindFacts({ table_id })` for callers that have one).\n//\n// The answer is the door's JSON verbatim (`TableKindFacts`); nothing is reshaped. A refusal is\n// the store's own sentence (`42501` \"You do not have access to this table, …\"), mapped through\n// the one refusal funnel and never thrown.\n\nimport { err, ok, type RecordsResult } from \"../results\";\nimport { isTableKind, tableIdOf, type TableKindFacts } from \"../table-kind\";\nimport { DOORS } from \"./doors\";\nimport { mapPgError } from \"./pgError\";\nimport { asRecordsDataSource } from \"./supabase\";\n\n/**\n * Read one Table's kind facts. `table` is the Table's id or its `table:<uuid>` slug.\n * `dataSource` is a supabase-js client carrying the person's session (or a bound data source).\n */\nexport async function tableKindFacts(dataSource: unknown, table: string): Promise<RecordsResult<TableKindFacts>> {\n  const tableId = isTableKind(table) ? tableIdOf(table) : String(table).trim().toLowerCase();\n  const source = asRecordsDataSource(dataSource);\n  const response = await source.rpc(DOORS.tableKindFacts, { p_table_id: tableId }, { schema: \"custom\" });\n  if (response.error) return err(mapPgError(response.error, \"tableKindFacts\"));\n  const facts = response.data as TableKindFacts | null;\n  if (!facts || typeof facts !== \"object\") {\n    return err({\n      code: \"not_found\",\n      message: \"The store answered nothing for this table.\",\n      hint: \"custom.table_kind_facts returned no facts. Nothing was read.\",\n    });\n  }\n  return ok(facts);\n}\n","// src/core/landingOutcomes.ts — @ai-matrx/records (HEADLESS)\n//\n// WHERE DID THIS MESSAGE'S KIND OUTPUTS LAND? (KINDS-GLUE wave 2 §7.2, slice 3.)\n//\n// A chat answer that carries `__kind` blocks has its outputs stored by the server behind\n// `store_emitted_records`: a row of the kind's outputs table in `custom.record`, reached by a\n// `produced_by` edge whose target is `record`, the landing facts on the edge's metadata\n// (`fingerprint`, `ordinal`, `kind`, `table_id`, `chain`, …).\n//\n// 🚨 THIS PACKAGE READS THE RECORD STORE ONLY. The retired kind store\n// (`content_ir.kind_instance`) is never reached from here — the old-system-unreachable guard\n// holds that. During the transition a HOST that still draws old kind-store rows reads them\n// through its own legacy reader and hands them in as `store: \"kind_instance\"` landings; the\n// matcher below treats both alike, so the old rows keep their card until wave 5 drains them.\n//\n// `landingOutcomesFor` reads once per message. `outcomeForBlock` then answers ONE block.\n//\n// 🚨 A BLOCK IS MATCHED BY (message, kind, fingerprint) — NEVER BY `block_id`. A block id is a\n// render-time address that moves when the splitter re-cuts an answer (an edit, a re-stream, a\n// new parser version); the fingerprint is the block's bytes. Matching by id would pin an output\n// to whichever block happens to sit at that address today. Identical blocks in one message share\n// a fingerprint and are told apart by `ordinal` (their order among identical blocks).\n//\n// When the chat team reserves `chat.message.metadata.kind_outputs` (slice 6) this reads that key\n// first and keeps the edges as the fallback; refusals have no edge, so until then a refused\n// emission answers `none` — the card says it was not saved, never \"Saved\".\n\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport type { PgError } from \"../results\";\nimport { err, ok, type RecordsResult } from \"../results\";\nimport type { RecordsFilter } from \"../ports\";\nimport { DOORS } from \"./doors\";\nimport { mapPgError } from \"./pgError\";\nimport { asRecordsDataSource } from \"./supabase\";\n\n/** The edge label every store writes from a message to what it produced. */\nexport const PRODUCED_BY_LABEL = \"produced_by\";\n/** The edge's source entity — `chat.message`. */\nexport const LANDING_SOURCE_TYPE = \"message\";\n/** The edge target this package reads: a record of the store. */\nexport const LANDING_TARGET_TYPES = {\n  record: \"record\",\n} as const;\n\n/**\n * `record` is the only store this package answers. `kind_instance` exists so a host's own\n * legacy reader can hand its old rows to `outcomeForBlock` during the transition.\n */\nexport type LandingStore = \"record\" | \"kind_instance\";\n\n/**\n * The platform Field of an outputs table that the output's owner sets herself to keep it\n * (design §5.3). Keep confirms (§5.2): a kept output is never flagged for review. Writing it is\n * an ordinary `recordUpdate({ patch: { [OUTPUT_KEPT_KEY]: true } })` as the person — the store's\n * own envelope trigger admits exactly this one platform Field from a person.\n */\nexport const OUTPUT_KEPT_KEY = \"output_kept\";\n\n/**\n * - `saved`: the row is there and this reader can read it.\n * - `archived`: the row is in the archive (the store answered 02000 to an admitted reader).\n * - `unreadable`: the edge is there but the store refused the read — `refusal` says why.\n */\nexport type LandingState = \"saved\" | \"archived\" | \"unreadable\";\n\nexport interface Landing {\n  store: LandingStore;\n  recordId: string;\n  /** The organization the row lives in (the edge's own). */\n  organizationId: string | null;\n  /** The kind slug the output instantiates. `null` when the landing did not say. */\n  kind: string | null;\n  /** The emitted block's fingerprint. `null` when the landing did not record one. */\n  fingerprint: string | null;\n  /** The order among identical blocks of one message. */\n  ordinal: number | null;\n  /** The render address the landing recorded — informative only, never matched on. */\n  blockId: string | null;\n  /** The outputs table (record store only, from the edge). */\n  tableId: string | null;\n  state: LandingState;\n  title: string | null;\n  /**\n   * The review flag. Record store: true when any value was written by an agent and not yet by a\n   * person (the store keeps confirmation per value). Kind store: the row's `confirmation`.\n   * `null` when it could not be read.\n   */\n  unconfirmed: boolean | null;\n  archivedAt: string | null;\n  createdAt: string | null;\n  /** The store's own sentence when the read was refused. */\n  refusal: string | null;\n  /**\n   * A fork's copied output (B8): its chain belongs to another conversation. Read-only — no\n   * actions are offered on it.\n   */\n  fromSource: boolean;\n  /**\n   * THE ROWS THIS OUTPUT PUT IN OTHER TABLES (CD-AGENT-09, VISION \"Kinds and their storage\": \"we\n   * 'know' which of those entries came from an add or update from a __kind and clicking it shows\n   * only that data\"). A list output (a flashcard set's cards, a timeline's events) lands its items\n   * as rows of their own kind's outputs table, each stamped with the output's Series\n   * (`output_chain`) and Version (`output_generation`). One entry per table the items went to,\n   * with the store's flat filter that shows exactly those rows. Record store only; absent when the\n   * output holds no list, or the parent table's columns could not be read.\n   */\n  contents?: LandingContents[];\n}\n\n/** One table an output's list items landed in, and the filter that shows only them. */\nexport interface LandingContents {\n  /** The items' own outputs table. */\n  tableId: string;\n  /** The column on the output that holds them (\"Cards (flashcard)\"). */\n  label: string;\n  count: number;\n  /** `{ output_chain, output_generation }`: this output's rows in that table, and no others. */\n  filter: Record<string, string | number>;\n}\n\n/** The Fields an output's list items ride on: a relation the kind declared (`config.child_kind`). */\ninterface FieldRow {\n  id?: string;\n  data?: { key?: unknown; label?: unknown; type?: unknown; relation_target?: unknown; config?: { child_kind?: unknown } | null } | null;\n}\n\n/**\n * The tables an output's list items went to, from the output's own document and its table's\n * relation Fields. Pure: the reader hands in what it read.\n */\nexport function landingContentsOf(document: unknown, fields: readonly FieldRow[]): LandingContents[] {\n  const doc = (document ?? {}) as Record<string, unknown>;\n  const chain = text(doc.output_chain);\n  if (!chain) return [];\n  const generation = doc.output_generation;\n  const filter: Record<string, string | number> = { output_chain: chain };\n  if (typeof generation === \"number\" || (typeof generation === \"string\" && generation.trim() !== \"\")) {\n    filter.output_generation = typeof generation === \"string\" && /^\\d+$/.test(generation) ? Number(generation) : (generation as string | number);\n  }\n  const out = new Map<string, LandingContents>();\n  for (const row of fields) {\n    const data = row.data ?? {};\n    const key = text(data.key);\n    const target = text(data.relation_target);\n    if (!key || !target || data.type !== \"relation\" || !text(data.config?.child_kind)) continue;\n    const value = doc[key];\n    const count = Array.isArray(value) ? value.filter((v) => typeof v === \"string\" && v).length : typeof value === \"string\" && value ? 1 : 0;\n    if (count === 0) continue;\n    const seen = out.get(target);\n    if (seen) seen.count += count;\n    else out.set(target, { tableId: target, label: text(data.label) ?? key, count, filter: { ...filter } });\n  }\n  return [...out.values()];\n}\n\nexport interface LandingOutcomes {\n  messageId: string;\n  landings: Landing[];\n}\n\n/** What a host knows about the block it is drawing. */\nexport interface LandingBlock {\n  kind: string;\n  fingerprint: string | null | undefined;\n  /** The block's order among identical blocks of this message, when the host knows it. */\n  ordinal?: number | null;\n  /**\n   * The render address. Accepted so a host can hand in what it has; NEVER used to match\n   * (see the header). A guard plants a block-id matcher and must go red.\n   */\n  blockId?: string | null;\n}\n\nexport type BlockOutcome =\n  | { state: \"none\" }\n  | { state: \"landed\"; landing: Landing }\n  | { state: \"several\"; landings: Landing[] };\n\n\ninterface EdgeRow {\n  target_type: string;\n  target_id: string;\n  organization_id: string | null;\n  metadata: Record<string, unknown> | null;\n  created_at: string | null;\n}\n\nfunction text(value: unknown): string | null {\n  return typeof value === \"string\" && value.trim() ? value : null;\n}\n\nfunction whole(value: unknown): number | null {\n  return typeof value === \"number\" && Number.isInteger(value) ? value : null;\n}\n\nasync function rows<T>(query: RecordsFilter, where: string): Promise<RecordsResult<T[]>> {\n  const response = await query;\n  if (response.error) return err(mapPgError(response.error as PgError, where));\n  return ok((response.data ?? []) as T[]);\n}\n\n/**\n * The review flag of a record-store output, from its value envelopes as\n * `custom.record_values_versioned` answers them: any value whose last writer was an agent.\n * (`custom.read_record` answers the bare document — envelopes stripped — so it cannot say.)\n */\nexport function valuesAreUnconfirmed(values: ReadonlyArray<{ actor?: unknown }> | null | undefined): boolean {\n  return (values ?? []).some((value) => value?.actor === \"agent\" || value?.actor === \"ai\");\n}\n\n/** True when the owner kept this output (`output_kept`), which confirms it. */\nexport function outputIsKept(document: unknown): boolean {\n  return ((document ?? {}) as Record<string, unknown>)[OUTPUT_KEPT_KEY] === true;\n}\n\nfunction documentTitle(document: unknown, metadata: Record<string, unknown>): string | null {\n  const doc = (document ?? {}) as Record<string, unknown>;\n  return text(metadata.title) ?? text(doc.title) ?? text(doc.name) ?? null;\n}\n\n/**\n * Every output this message produced in the record store, as this reader may see them.\n *\n * `dataSource` is a supabase-js client carrying the person's session (or a bound data source).\n * `conversationId`, when given, marks outputs whose chain belongs to another conversation as\n * `fromSource` (a forked conversation's copy).\n */\nexport async function landingOutcomesFor(\n  dataSource: unknown,\n  messageId: string,\n  options: { conversationId?: string | null } = {},\n): Promise<RecordsResult<LandingOutcomes>> {\n  if (!isUuidShape(messageId)) return ok({ messageId, landings: [] });\n  const source = asRecordsDataSource(dataSource);\n\n  const edges = await rows<EdgeRow>(\n    source\n      .schema(\"platform\")\n      .from(\"associations\")\n      .select(\"target_type,target_id,organization_id,metadata,created_at\")\n      .eq(\"source_type\", LANDING_SOURCE_TYPE)\n      .eq(\"source_id\", messageId)\n      .eq(\"label\", PRODUCED_BY_LABEL)\n      .eq(\"target_type\", LANDING_TARGET_TYPES.record)\n      .is(\"deleted_at\", null),\n    \"landingOutcomesFor.edges\",\n  );\n  if (!edges.ok) return edges;\n\n  const landings: Landing[] = [];\n  /** Each outputs table's relation Fields, read once per call (a message's outputs share tables). */\n  const fieldsOf = new Map<string, Promise<FieldRow[] | null>>();\n  const readFields = (organizationId: string | null, tableId: string): Promise<FieldRow[] | null> => {\n    let pending = fieldsOf.get(tableId);\n    if (!pending) {\n      pending = Promise.resolve(\n        source.rpc(DOORS.applicableFields, { p_organization_id: organizationId, p_table_id: tableId }, { schema: \"custom\" }),\n      ).then((answer) => (answer.error ? null : ((answer.data ?? []) as FieldRow[])));\n      fieldsOf.set(tableId, pending);\n    }\n    return pending;\n  };\n\n  // ── the record store ──────────────────────────────────────────────────────\n  for (const edge of edges.data) {\n    const meta = edge.metadata ?? {};\n    const organizationId = edge.organization_id ?? text(meta.organization_id);\n    const chainConversation = text(meta.conversation_id);\n    const base = {\n      store: \"record\" as const,\n      recordId: edge.target_id,\n      organizationId,\n      kind: text(meta.kind),\n      fingerprint: text(meta.fingerprint),\n      ordinal: whole(meta.ordinal),\n      blockId: text(meta.block_id),\n      tableId: text(meta.table_id),\n      createdAt: edge.created_at,\n      archivedAt: null,\n      fromSource: Boolean(\n        options.conversationId && chainConversation && chainConversation !== options.conversationId,\n      ),\n    };\n    const read = await source.rpc(\n      DOORS.readRecord,\n      { p_organization_id: organizationId, p_record_id: edge.target_id },\n      { schema: \"custom\" },\n    );\n    if (read.error) {\n      const refusal = mapPgError(read.error, \"landingOutcomesFor.record\");\n      // 02000 reaches only a reader the ladder already admitted: the row is in the archive.\n      const archived = refusal.sqlstate === \"02000\";\n      landings.push({\n        ...base,\n        state: archived ? \"archived\" : \"unreadable\",\n        title: text(meta.title),\n        unconfirmed: null,\n        refusal: archived ? null : refusal.message,\n      });\n      continue;\n    }\n    const envelopes = await source.rpc(\n      DOORS.recordValuesVersioned,\n      { p_organization_id: organizationId, p_record_id: edge.target_id },\n      { schema: \"custom\" },\n    );\n    const fields = base.tableId ? await readFields(organizationId, base.tableId) : null;\n    const contents = fields ? landingContentsOf(read.data, fields) : [];\n    landings.push({\n      ...base,\n      ...(contents.length > 0 ? { contents } : {}),\n      state: \"saved\",\n      title: documentTitle(read.data, meta),\n      // Keep confirms (§5.2). Otherwise a refused envelope read is \"unknown\", never \"confirmed\".\n      unconfirmed: outputIsKept(read.data)\n        ? false\n        : envelopes.error\n          ? null\n          : valuesAreUnconfirmed(envelopes.data as Array<{ actor?: unknown }> | null),\n      refusal: null,\n    });\n  }\n\n  landings.sort((a, b) => (a.createdAt ?? \"\").localeCompare(b.createdAt ?? \"\"));\n  return ok({ messageId, landings });\n}\n\n/**\n * The outcome for ONE block: matched by (message, kind, fingerprint), never by block id.\n *\n * - A record-store landing matches only on an equal fingerprint — an output the store cannot\n *   tie to these bytes is never claimed for them.\n * - A host-supplied kind-store row saved before fingerprints were recorded (fingerprint `null`), or a block that\n *   carries none, matches by kind alone — the old card's truth, kept until wave 5.\n * - Several equal matches are told apart by `ordinal` when the host knows it; otherwise the answer\n *   is `several` and the host says so.\n */\nexport function outcomeForBlock(outcomes: LandingOutcomes, block: LandingBlock): BlockOutcome {\n  const sameKind = outcomes.landings.filter((l) => l.kind === block.kind);\n  const fingerprint = block.fingerprint ?? null;\n  let matches: Landing[];\n  if (fingerprint) {\n    matches = sameKind.filter((l) => l.fingerprint === fingerprint);\n    if (matches.length === 0) {\n      matches = sameKind.filter((l) => l.store === \"kind_instance\" && l.fingerprint === null);\n    }\n  } else {\n    matches = sameKind.filter((l) => l.store === \"kind_instance\");\n  }\n  if (matches.length > 1 && typeof block.ordinal === \"number\") {\n    const byOrdinal = matches.filter((l) => l.ordinal === block.ordinal);\n    if (byOrdinal.length === 1) matches = byOrdinal;\n  }\n  const [only] = matches;\n  if (!only) return { state: \"none\" };\n  if (matches.length === 1) return { state: \"landed\", landing: only };\n  return { state: \"several\", landings: matches };\n}\n\n/** True when any landing of `kind` for this block is in the record store. */\nexport function blockLandedInStore(outcomes: LandingOutcomes, block: LandingBlock): boolean {\n  const outcome = outcomeForBlock(outcomes, block);\n  if (outcome.state === \"landed\") return outcome.landing.store === \"record\";\n  if (outcome.state === \"several\") return outcome.landings.some((l) => l.store === \"record\");\n  return false;\n}\n","// src/core/storeDoors.ts — @ai-matrx/records (HEADLESS)\n//\n// THE ONE PLACE AN APP'S OWN CODE REACHES THE STORE'S DOORS WITHOUT A TYPED CLIENT METHOD\n// (lane ONE-DOOR, 2026-10-10). Only this package says `custom`; an app file never types the\n// schema, so `check:no-custom-store-code` (matrx-frontend) holds the line at zero.\n//\n// WHAT IT IS: `storeDoors(client)` binds ANY supabase-js client to the store's schema and hands\n// back `rpc(fn, args)`. It is a pure move of the hand-written `.schema(\"custom\")` layers the\n// website grew (public form, booking, e-sign and portal lanes; the template gallery; the page\n// seeds): the answer is exactly what PostgREST gave, `{ data, error }`, nothing wrapped,\n// nothing softened, nothing retried.\n//\n// PRIVILEGES ARE THE CLIENT'S, NEVER THIS FILE'S. This holds no key and opens no connection.\n// Hand it the person's browser client and every door runs as the person; hand it a server\n// session client and it runs as that session; hand it the service-role (admin) client — as the\n// public form / booking / e-sign / portal lanes must, for a visitor with no session — and it\n// runs as the service role. A call never gets wider or narrower by passing through here.\n// `/core` and the server both use the same function: it needs no DOM and no React.\n//\n// The named doors below are one-line members of the same `rpc` (door name + argument names live\n// here, once). Each returns the raw `{ data, error }` so a caller that already reads that shape\n// moves with no behavior change; a caller that wants `RecordsResult` uses `RecordsClient`.\n\nimport { isRetrySafe, retryTransient } from \"./transient\";\nimport { supabaseDataSource } from \"./supabase\";\nimport type { RecordsDataSource } from \"../ports\";\n\n/** The schema every door of the record store lives in. The only place an app-facing string says it. */\nexport const STORE_SCHEMA = \"custom\";\n\n/** What a door refused with, as PostgREST gave it. */\nexport interface StoreDoorError {\n  message: string;\n  code?: string | null;\n  hint?: string | null;\n  details?: string | null;\n}\n\nexport interface StoreDoorAnswer<T = unknown> {\n  data: T | null;\n  error: StoreDoorError | null;\n}\n\n/** The bare caller: the same `rpc(fn, args)` shape the hand-written layers declared. */\nexport interface StoreCaller {\n  rpc(fn: string, args?: Record<string, unknown>): PromiseLike<{ data: unknown; error: StoreDoorError | null }>;\n}\n\n/** The named doors an app calls most. Every member is a thin call over `rpc`; nothing is added to the answer. */\nexport interface StoreDoors extends StoreCaller {\n  /** `custom.where_id_opens(p_id)` — which organization an object lives in. `data` is null when it is not given to the caller; the error is plain JSON (it streams to a browser as is). */\n  whereIdOpens(id: string): PromiseLike<{ data: unknown; error: { code: string | null; message: string } | null }>;\n  /** `custom.table_kernel_id()` — the id of the store's Table kernel (a constant of the store). */\n  tableKernelId(): PromiseLike<StoreDoorAnswer<string>>;\n  /** `custom.read_records_by_ids` — the records of `ids` the caller may read in `tableId`, in `organizationId`. */\n  readRecordsByIds(organizationId: string, tableId: string, ids: readonly string[]): PromiseLike<StoreDoorAnswer>;\n  /** `custom.read_records_page` — one page; `args` are the door's own named arguments. */\n  readRecordsPage(args: Record<string, unknown>): PromiseLike<StoreDoorAnswer>;\n  /** `custom.record_table` — the table a record lives in. */\n  recordTable(organizationId: string, recordId: string): PromiseLike<StoreDoorAnswer<string>>;\n  /** `custom.applicable_fields` — the fields of a table. */\n  applicableFields(organizationId: string, tableId: string): PromiseLike<StoreDoorAnswer>;\n  /** `custom.field_declare` — declare one field on a table. */\n  fieldDeclare(organizationId: string, tableId: string, spec: Record<string, unknown>): PromiseLike<StoreDoorAnswer<string>>;\n  /** `custom.record_update` — patch a record's values. */\n  recordUpdate(organizationId: string, recordId: string, patch: Record<string, unknown>): PromiseLike<StoreDoorAnswer>;\n  /** `custom.entity_reference_words` — the labels of `{token,id}` refs, withheld when the caller may not open them. */\n  entityReferenceWords(organizationId: string, refs: ReadonlyArray<{ token: string; id: string }>): PromiseLike<StoreDoorAnswer>;\n  /** `custom.templates` — the catalog (one page of cards for `filter`). */\n  templates(filter: Record<string, unknown>): PromiseLike<StoreDoorAnswer>;\n  /** `custom.template_from_tables` — draft a template spec from existing tables. */\n  templateFromTables(args: { organizationId: string; tableIds: readonly string[]; includeRows: boolean; rowsPerTable: number }): PromiseLike<StoreDoorAnswer>;\n  /** `custom.template_declare` — declare a template (`scope` is `\"org\"` for an organization's own). */\n  templateDeclare(scope: string, spec: Record<string, unknown>): PromiseLike<StoreDoorAnswer>;\n  /** `custom.template_keep` — keep a one-off template in the organization's own. */\n  templateKeep(templateId: string): PromiseLike<StoreDoorAnswer>;\n  /** `custom.template_archive` — archive (or, with `restore`, bring back) an organization's own template. */\n  templateArchive(templateId: string, restore?: boolean): PromiseLike<StoreDoorAnswer>;\n  /** `custom.template_install_claim` — the host step's lease on one install step. */\n  templateInstallClaim(args: { organizationId: string; installId: string; kind: string; label: string; sourceId?: string | null; leaseSeconds: number }): PromiseLike<StoreDoorAnswer>;\n  /** `custom.template_install_note` — record the thing a host step made. */\n  templateInstallNote(args: { organizationId: string; installId: string; kind: string; id: string; label: string }): PromiseLike<StoreDoorAnswer>;\n}\n\n/**\n * Bind a supabase-js client (browser, server session, anon, or service-role) to the store's\n * doors. A client with no `schema()` is refused by name on every call (`data_source_unbound`), never\n * a thrown `undefined is not a function` in a render.\n */\nexport function storeDoors(client: unknown): StoreDoors {\n  const source: RecordsDataSource = supabaseDataSource((client ?? {}) as object);\n  // TEMPLATE-INSTALL-3: the same transient-error retry as the one door call (core/doorCall.ts): a read, an idempotent door, or a call carrying\n  // the caller's install id is asked again after PGRST002 / a 502-504 / a reset connection / a lock or timeout; any other write is asked once.\n  const call = (fn: string, args: Record<string, unknown> = {}) =>\n    retryTransient(() => source.rpc(fn, args, { schema: STORE_SCHEMA }), { safe: isRetrySafe(fn, args) }) as PromiseLike<{ data: unknown; error: StoreDoorError | null }>;\n  const typed = <T>(fn: string, args: Record<string, unknown>) => call(fn, args) as PromiseLike<StoreDoorAnswer<T>>;\n  return {\n    rpc: call,\n    async whereIdOpens(id) {\n      const raw = await call(\"where_id_opens\", { p_id: id });\n      const e = raw.error as { code?: unknown; message?: unknown } | null;\n      return {\n        data: raw.data ?? null,\n        error: e\n          ? { code: typeof e.code === \"string\" ? e.code : null, message: typeof e.message === \"string\" ? e.message : \"The record store refused.\" }\n          : null,\n      };\n    },\n    tableKernelId: () => typed<string>(\"table_kernel_id\", {}),\n    readRecordsByIds: (organizationId, tableId, ids) =>\n      typed(\"read_records_by_ids\", { p_organization_id: organizationId, p_table_id: tableId, p_record_ids: ids }),\n    readRecordsPage: (args) => typed(\"read_records_page\", args),\n    recordTable: (organizationId, recordId) => typed<string>(\"record_table\", { p_organization_id: organizationId, p_record_id: recordId }),\n    applicableFields: (organizationId, tableId) => typed(\"applicable_fields\", { p_organization_id: organizationId, p_table_id: tableId }),\n    fieldDeclare: (organizationId, tableId, spec) =>\n      typed<string>(\"field_declare\", { p_organization_id: organizationId, p_table_id: tableId, p_spec: spec }),\n    recordUpdate: (organizationId, recordId, patch) =>\n      typed(\"record_update\", { p_organization_id: organizationId, p_record_id: recordId, p_patch: patch }),\n    entityReferenceWords: (organizationId, refs) =>\n      typed(\"entity_reference_words\", { p_organization_id: organizationId, p_refs: refs.map((r) => ({ token: r.token, id: r.id })) }),\n    templates: (filter) => typed(\"templates\", { p_filter: filter }),\n    templateFromTables: ({ organizationId, tableIds, includeRows, rowsPerTable }) =>\n      typed(\"template_from_tables\", {\n        p_organization_id: organizationId,\n        p_table_ids: tableIds,\n        p_include_rows: includeRows,\n        p_rows_per_table: rowsPerTable,\n      }),\n    templateDeclare: (scope, spec) => typed(\"template_declare\", { p_scope: scope, p_spec: spec }),\n    templateKeep: (templateId) => typed(\"template_keep\", { p_template_id: templateId }),\n    templateArchive: (templateId, restore) =>\n      typed(\"template_archive\", restore === undefined ? { p_template_id: templateId } : { p_template_id: templateId, p_restore: restore }),\n    templateInstallClaim: ({ organizationId, installId, kind, label, sourceId, leaseSeconds }) =>\n      typed(\"template_install_claim\", {\n        p_organization_id: organizationId,\n        p_install_id: installId,\n        p_kind: kind,\n        p_label: label,\n        ...(sourceId ? { p_source_id: sourceId } : {}),\n        p_lease_seconds: leaseSeconds,\n      }),\n    templateInstallNote: ({ organizationId, installId, kind, id, label }) =>\n      typed(\"template_install_note\", {\n        p_organization_id: organizationId,\n        p_install_id: installId,\n        p_kind: kind,\n        p_id: id,\n        p_label: label,\n      }),\n  };\n}\n","// src/core/validation.ts — @ai-matrx/records\n//\n// THE MIRROR. It predicts ONLY what the store's own triggers will refuse, and it\n// says it in the store's own words.\n//\n// Read this next sentence before changing anything here: THIS IS NOT\n// VALIDATION. The store validates. `custom.validate_values`,\n// `custom.validate_value_envelope` and `custom.size_refusal` are the truth, they\n// run inside the write door, and they cannot be bypassed by a client. What this\n// module buys is the half-second between a person typing and a round trip — it\n// tells a form what the store is ABOUT to say, so the form can say it first.\n//\n// Two rules keep it honest:\n//   1. Every prediction names the store body that would raise it\n//      (`predicted_by`), so the next reader can go and check.\n//   2. A prediction the store would NOT make is a defect, and so is a message\n//      that differs from the store's by one word. The real-door suite plants\n//      each of these against the live store and compares the sentences.\n//\n// Where the mirror cannot see — option membership, relation targets, anything\n// that needs a query — it says nothing at all and lets the door answer. Silence\n// here means \"ask the store\", never \"it is fine\".\n\nimport { fieldAppliesToType } from \"../recordType\";\nimport type { Field, FieldRule } from \"../field\";\nimport type { RecordDocument, ValueEnvelope } from \"../record\";\nimport type { PredictedRefusal } from \"../results\";\nimport {\n  ABSENCE_REASONS,\n  PER_VALUE_ACCESS_WORDS,\n  VALUE_ALTERNATE_KEYS,\n  VALUE_ENVELOPE_KEYS,\n} from \"../store.generated\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n/** The published defaults, which are also what the store falls back to when it cannot read a knob. */\nexport const DEFAULT_VALUE_MAX_BYTES = 100_000;\nexport const DEFAULT_DOCUMENT_MAX_BYTES = 1_048_576;\n\nexport interface MirrorLimits {\n  value_max_bytes?: number;\n  document_max_bytes?: number;\n}\n\nconst jsonType = (value: unknown): string => {\n  if (value === null) return \"null\";\n  if (Array.isArray(value)) return \"array\";\n  switch (typeof value) {\n    case \"string\":\n      return \"string\";\n    case \"number\":\n      return \"number\";\n    case \"boolean\":\n      return \"boolean\";\n    case \"object\":\n      return \"object\";\n    default:\n      return \"null\";\n  }\n};\n\n/**\n * `octet_length(x::text)` — the store measures the JSONB TEXT, and jsonb does\n * not render the way `JSON.stringify` does: it puts a space after every `:` and\n * every `,`. On an 18-key document that is 35 bytes the mirror used to miss, and\n * the real-door suite caught it by holding the two sentences side by side\n * (\"this record is 1080242 bytes\" vs the mirror's 1080207). So the mirror\n * renders the way Postgres does.\n */\nfunction pgJsonbText(value: unknown): string {\n  if (value === null || value === undefined) return \"null\";\n  if (Array.isArray(value)) return `[${value.map(pgJsonbText).join(\", \")}]`;\n  if (typeof value === \"object\") {\n    // jsonb keeps the LAST of duplicate keys and drops nothing else; an object\n    // literal in TypeScript cannot carry duplicates, so entries are the set.\n    const parts = Object.entries(value as Record<string, unknown>).map(\n      ([k, v]) => `${JSON.stringify(k)}: ${pgJsonbText(v)}`,\n    );\n    return `{${parts.join(\", \")}}`;\n  }\n  return JSON.stringify(value);\n}\n\nconst jsonBytes = (value: unknown): number => new TextEncoder().encode(pgJsonbText(value)).length;\n\n/**\n * `custom.validate_values`. The label the store uses is the Field's label, or\n * its key when the label is empty — the same `coalesce(nullif(...))`.\n */\nfunction labelOf(field: Field): string {\n  return field.label && field.label.length > 0 ? field.label : field.key;\n}\n\nfunction ruleRefusal(\n  field: Field,\n  rule: FieldRule,\n  item: unknown,\n  values: Record<string, unknown>,\n): PredictedRefusal | null {\n  const label = labelOf(field);\n  const base = { sqlstate: \"23514\", predicted_by: \"custom.validate_values\", field_key: field.key };\n  const num = typeof item === \"number\" ? item : null;\n  switch (rule.kind) {\n    case \"min\":\n      if (num !== null && num < Number(rule.value)) {\n        return { ...base, message: `${label} has to be at least ${rule.value}`, hint: \"FLD-3: an attached validation Rule, not a behavior.\" };\n      }\n      return null;\n    case \"max\":\n      if (num !== null && num > Number(rule.value)) {\n        return { ...base, message: `${label} cannot be more than ${rule.value}`, hint: \"FLD-3: an attached validation Rule, not a behavior.\" };\n      }\n      return null;\n    case \"length\":\n      if (typeof item !== \"string\") return null;\n      if (rule.value !== undefined && rule.value !== null && rule.value !== \"\" && item.length > Number(rule.value)) {\n        return { ...base, message: `${label} is longer than ${rule.value} characters`, hint: \"FLD-3.\" };\n      }\n      // STORE-RULE-GAPS: the shortest. A blank is `required`'s question.\n      if (typeof rule.min === \"number\" && item !== \"\" && item.length < rule.min) {\n        return {\n          ...base,\n          message: `${label} has to be at least ${rule.min} characters long`,\n          hint: \"FLD-3.\",\n          detail: { field_key: field.key, rule: \"length\", min: rule.min },\n        };\n      }\n      return null;\n    case \"pattern\":\n      if (typeof item === \"string\" && !new RegExp(String(rule.value)).test(item)) {\n        const example = typeof rule.example === \"string\" ? rule.example.trim() : \"\";\n        if (example !== \"\") {\n          return {\n            ...base,\n            message: `${label} is not written the way this field expects`,\n            hint: `Enter it like ${example}.`,\n            detail: { field_key: field.key, rule: \"pattern\", example },\n          };\n        }\n        return { ...base, message: `${label} is not written the way this field expects`, hint: \"FLD-3.\" };\n      }\n      return null;\n    case \"equals_field\": {\n      const other = values[String(rule.value)];\n      if (other !== undefined && other !== null && JSON.stringify(other) !== JSON.stringify(item)) {\n        return {\n          ...base,\n          message: `${label} and ${rule.value} have to be the same`,\n          hint: \"FLD-3 / T8: a constraint across two fields is a Rule attached to one of them, never a behavior.\",\n        };\n      }\n      return null;\n    }\n    case \"differs_from_field\": {\n      const other = values[String(rule.value)];\n      if (other !== undefined && JSON.stringify(other) === JSON.stringify(item)) {\n        return { ...base, message: `${label} and ${rule.value} have to be different`, hint: \"FLD-3.\" };\n      }\n      return null;\n    }\n    default:\n      return null;\n  }\n}\n\n/**\n * Predict `custom.validate_values`. Everything it checks WITHOUT a query is\n * mirrored; option membership and relation targets are deliberately left to the\n * door, and the mirror says nothing about them.\n */\nexport function predictValueRefusals(\n  fields: Field[],\n  values: Record<string, unknown>,\n  recordType?: string,\n): PredictedRefusal[] {\n  const found: PredictedRefusal[] = [];\n  for (const field of fields) {\n    // A COLUMN THIS RECORD'S TYPE DOES NOT HAVE is not asked about (CLOSE-CORE CD-CORE-15): the store validates\n    // only the columns that apply to the record's type, so a grid holding every column of a Shape table never\n    // predicts \"Radius is required\" for a Rectangle.\n    if (!fieldAppliesToType(field, recordType)) continue;\n    const label = labelOf(field);\n    const base = { sqlstate: \"23514\", predicted_by: \"custom.validate_values\", field_key: field.key };\n    const raw = values[field.key];\n    const isEmpty =\n      raw === undefined ||\n      raw === null ||\n      (field.multi && Array.isArray(raw) && raw.length === 0);\n\n    if (isEmpty) {\n      if (field.required) {\n        found.push({\n          ...base,\n          message: `${label} is required`,\n          hint: `REC-51: the field ${field.key} of this table.`,\n        });\n      }\n      continue;\n    }\n\n    if (field.type === \"formula\") {\n      found.push({\n        ...base,\n        message: `${label} is worked out by the system, so it cannot be typed in`,\n        hint: `FLD-9: this formula computes on ${field.compute_on ?? \"write\"}.`,\n      });\n      continue;\n    }\n\n    let items: unknown[];\n    if (field.multi) {\n      if (!Array.isArray(raw)) {\n        found.push({ ...base, message: `${label} holds many values, so it takes a list`, hint: \"FLD-2: the multi modifier.\" });\n        continue;\n      }\n      items = raw;\n    } else {\n      if (Array.isArray(raw)) {\n        found.push({ ...base, message: `${label} holds one value, and it was given a list`, hint: \"FLD-2: multi is off for this field.\" });\n        continue;\n      }\n      items = [raw];\n    }\n\n    for (const item of items) {\n      if (field.type === \"text\" && typeof item !== \"string\") {\n        found.push({ ...base, message: `${label} takes words, and it was given a ${jsonType(item)}`, hint: \"FLD-1: text.\" });\n      } else if (field.type === \"range\") {\n        const kind = (field.config?.[\"kind\"] as string | undefined) ?? \"number\";\n        if (typeof item === \"number\") {\n          /* fine */\n        } else if (typeof item === \"string\" && (kind === \"date\" || kind === \"datetime\")) {\n          if (Number.isNaN(Date.parse(item))) {\n            found.push({ ...base, message: `${label} takes a date, and ${item} is not one`, hint: \"FLD-1: range, of kind date.\" });\n          }\n        } else {\n          found.push({ ...base, message: `${label} takes a number, and it was given a ${jsonType(item)}`, hint: \"FLD-1: range.\" });\n        }\n      } else if (field.type === \"list\") {\n        if (typeof item !== \"string\") {\n          found.push({\n            ...base,\n            message: `${label} takes one of its choices, and it was given a ${jsonType(item)}`,\n            hint: \"FLD-5 / FLD-6: a list field stores the id of the option RECORD, because every pick-list is already a Table.\",\n          });\n        }\n        // MEMBERSHIP needs the store: the mirror stops here on purpose. A list\n        // cell holds the option's KEY (CHOICE-VALUE) and the door also takes its\n        // label or id, so no shape of string is predictably wrong here — and a\n        // column that takes other values (STORE-RULE-GAPS `allow_other`) ADDS an\n        // unknown word. This used to refuse every value that was not a uuid,\n        // which the store has not required since option keys landed.\n      } else if (field.type === \"relation\") {\n        if (typeof item !== \"string\") {\n          found.push({ ...base, message: `${label} points at a record, and it was given a ${jsonType(item)}`, hint: \"FLD-1: relation.\" });\n        } else if (!isUuidShape(item)) {\n          found.push({\n            ...base,\n            message: `${label} points at something that is not there`,\n            hint: `REC-51: ${label} stores the id of a record, and what it was given is not an id at all.`,\n          });\n        }\n        // EXISTENCE needs the store: the mirror stops here on purpose.\n      }\n\n      for (const rule of field.rules ?? []) {\n        const applies =\n          !rule.applies_to_types ||\n          rule.applies_to_types.length === 0 ||\n          (recordType !== undefined && fieldAppliesToType(rule, recordType));\n        if (!applies) continue;\n        const refusal = ruleRefusal(field, rule, item, values);\n        if (refusal) found.push(refusal);\n      }\n    }\n\n    if (field.type === \"relation\" && field.multi && field.relation_max !== null) {\n      const n = items.length;\n      if (n > field.relation_max) {\n        found.push({\n          ...base,\n          message: `${label} points at ${n} things, and it can point at ${field.relation_max} at most`,\n          hint: \"REC-51: relation_max.\",\n        });\n      }\n    }\n  }\n  return found;\n}\n\n/** Predict `custom.size_refusal`, with the same two ceilings and the same sentences. */\nexport function predictSizeRefusal(\n  document: RecordDocument,\n  limits: MirrorLimits = {},\n): PredictedRefusal | null {\n  const valueMax = limits.value_max_bytes ?? DEFAULT_VALUE_MAX_BYTES;\n  const docMax = limits.document_max_bytes ?? DEFAULT_DOCUMENT_MAX_BYTES;\n  for (const [key, value] of Object.entries(document)) {\n    if (key.startsWith(\"_\")) continue;\n    const bytes = jsonBytes(value);\n    if (bytes > valueMax) {\n      return {\n        field_key: key,\n        sqlstate: \"23514\",\n        predicted_by: \"custom.size_refusal\",\n        message:\n          `${key} is ${bytes} bytes, and one value in a record holds at most ${valueMax}. ` +\n          `Put the big thing in a file record and point the value at it - this store has a File table for exactly that.`,\n      };\n    }\n  }\n  const total = jsonBytes(document);\n  if (total > docMax) {\n    return {\n      sqlstate: \"23514\",\n      predicted_by: \"custom.size_refusal\",\n      message:\n        `this record is ${total} bytes, and one record holds at most ${docMax}. ` +\n        `Put the big things in file records and point the values at them - this store has a File table for exactly that.`,\n    };\n  }\n  return null;\n}\n\n/**\n * Predict `custom.value_envelope_refusal`. The store returns the FIRST problem\n * it finds and stops; so does this, key order included, so the two agree on\n * which sentence a person sees.\n */\nexport function predictEnvelopeRefusal(document: RecordDocument): PredictedRefusal | null {\n  const say = (message: string): PredictedRefusal => ({\n    message,\n    sqlstate: \"23514\",\n    predicted_by: \"custom.value_envelope_refusal\",\n  });\n\n  let sources: Record<string, unknown> = {};\n  if (Object.prototype.hasOwnProperty.call(document, \"_sources\")) {\n    const block = document._sources as unknown;\n    if (jsonType(block) !== \"object\") {\n      return say(\n        `this record's provenance block (_sources) must be an object of pointer -> source, and it is a ${jsonType(block)}.`,\n      );\n    }\n    sources = block as Record<string, unknown>;\n    for (const pointer of Object.keys(sources)) {\n      if (!/^s[0-9]+$/.test(pointer)) {\n        return say(\n          `\"${pointer}\" is not a provenance pointer. A pointer is interned by this store and looks like s1, s2, s3 — it is never a name a writer chooses.`,\n        );\n      }\n      if (jsonType(sources[pointer]) !== \"object\") {\n        return say(\n          `the source at ${pointer} must be an object describing where the value came from, and it is a ${jsonType(sources[pointer])}.`,\n        );\n      }\n    }\n    const distinct = new Set(Object.values(sources).map((v) => JSON.stringify(v)));\n    if (distinct.size !== Object.keys(sources).length) {\n      return say(\n        `the same source is written twice in this record's provenance block. A source is interned once per save and every value that came from it points at the one entry.`,\n      );\n    }\n  }\n\n  if (!Object.prototype.hasOwnProperty.call(document, \"_values\")) return null;\n  const block = document._values as unknown;\n  if (jsonType(block) !== \"object\") {\n    return say(\n      `this record's value block (_values) must be an object of field key -> envelope, and it is a ${jsonType(block)}.`,\n    );\n  }\n\n  for (const [key, envUnknown] of Object.entries(block as Record<string, unknown>)) {\n    if (jsonType(envUnknown) !== \"object\") {\n      return say(`the envelope for ${key} must be an object, and it is a ${jsonType(envUnknown)}.`);\n    }\n    const env = envUnknown as Record<string, unknown> & Partial<ValueEnvelope>;\n\n    for (const k of Object.keys(env)) {\n      if (!(VALUE_ENVELOPE_KEYS as readonly string[]).includes(k)) {\n        if ((PER_VALUE_ACCESS_WORDS as readonly string[]).includes(k)) {\n          return say(\n            `${key} cannot carry \"${k}\": access belongs to a Field and to a Record, never to a single value. A value that must be secret goes in a contained record with its own access.`,\n          );\n        }\n        return say(\n          `${key} carries \"${k}\", which is not part of a value envelope. An envelope holds ${VALUE_ENVELOPE_KEYS.join(\", \")}.`,\n        );\n      }\n    }\n\n    // ver, actor, on_behalf_of and at ARE NOT PREDICTED, and that is not an\n    // omission. `custom._value_envelope` runs `custom.stamp_value_envelopes`\n    // (which overwrites actor, on_behalf_of and at with the caller's real\n    // identity) and `custom.value_versions` (which writes ver) BEFORE\n    // `custom.value_envelope_refusal` ever looks. A caller who sends\n    // `{\"actor\":\"wizard\"}` or no `ver` at all is not refused — the store simply\n    // writes the truth over it. The mirror used to predict a refusal here; the\n    // real-door suite planted those five envelopes at the live door, the store\n    // accepted every one, and the prediction came out. Silence here is the\n    // store's behavior, not a gap.\n\n    if (\"absent\" in env && env.absent !== null) {\n      const absent = String(env.absent);\n      if (!(ABSENCE_REASONS as readonly string[]).includes(absent)) {\n        return say(\n          `${key}: \"${absent}\" is not a reason a value can be missing. The reasons are ${ABSENCE_REASONS.join(\", \")}.`,\n        );\n      }\n      if (key in document && document[key] !== null) {\n        return say(`${key} both holds a value and says why it is missing (\"${absent}\"). It can be one or the other.`);\n      }\n    }\n\n    if (\"src\" in env && env.src !== null) {\n      if (typeof env.src !== \"string\") {\n        return say(\n          `${key}: its source must be a provenance pointer this store interned. Write the source itself and the store interns it; ${jsonType(env.src)} is not a pointer.`,\n        );\n      }\n      if (!(env.src in sources)) {\n        return say(`${key} points at the source ${env.src}, and this record's provenance block has no such entry.`);\n      }\n    }\n\n    if (\"alternates\" in env && env.alternates !== null) {\n      if (!Array.isArray(env.alternates)) {\n        return say(`${key}: its other candidate values must be a list, and it is a ${jsonType(env.alternates)}.`);\n      }\n      const ranks: number[] = [];\n      for (const altUnknown of env.alternates) {\n        if (jsonType(altUnknown) !== \"object\") {\n          return say(`${key}: every other candidate is a value, a source and a rank, and one of them is a ${jsonType(altUnknown)}.`);\n        }\n        const alt = altUnknown as unknown as Record<string, unknown>;\n        for (const k of Object.keys(alt)) {\n          if (!(VALUE_ALTERNATE_KEYS as readonly string[]).includes(k)) {\n            if ((PER_VALUE_ACCESS_WORDS as readonly string[]).includes(k)) {\n              return say(\n                `${key}: an alternate cannot carry \"${k}\" — read and write access belong to a Field and to a Record, never to a single value.`,\n              );\n            }\n            return say(\n              `${key}: an alternate carries \"${k}\", which is not part of one. An alternate holds ${VALUE_ALTERNATE_KEYS.join(\", \")} — a rank, which is the order an organization's sources are trusted in, and never a score or a confidence a machine invented.`,\n            );\n          }\n        }\n        if (!(\"value\" in alt)) {\n          return say(`${key}: an alternate with no value is not a candidate for anything.`);\n        }\n        const rank = alt[\"rank\"];\n        if (typeof rank !== \"number\" || !Number.isInteger(rank) || rank < 1) {\n          return say(`${key}: every alternate carries a whole rank of 1 or more — the order its source is trusted in.`);\n        }\n        if (ranks.includes(rank)) {\n          return say(`${key}: two alternates claim rank ${rank}. A rank is an order, so it is held by one candidate.`);\n        }\n        ranks.push(rank);\n        if (\"src\" in alt && alt[\"src\"] !== null) {\n          if (typeof alt[\"src\"] !== \"string\") {\n            return say(`${key}: an alternate's source must be a provenance pointer this store interned, and it is a ${jsonType(alt[\"src\"])}.`);\n          }\n          if (!(String(alt[\"src\"]) in sources)) {\n            return say(`${key}: an alternate points at the source ${String(alt[\"src\"])}, and this record's provenance block has no such entry.`);\n          }\n        }\n      }\n    }\n  }\n  return null;\n}\n\n/** Everything the mirror can see about one write, in the order the store sees it. */\nexport function predictWriteRefusals(args: {\n  fields: Field[];\n  document: RecordDocument;\n  recordType?: string;\n  limits?: MirrorLimits;\n}): PredictedRefusal[] {\n  const { fields, document, recordType, limits } = args;\n  const values: Record<string, unknown> = {};\n  for (const [k, v] of Object.entries(document)) {\n    if (!k.startsWith(\"_\")) values[k] = v;\n  }\n  const found: PredictedRefusal[] = [];\n  const envelope = predictEnvelopeRefusal(document);\n  if (envelope) found.push(envelope);\n  const size = predictSizeRefusal(document, limits);\n  if (size) found.push(size);\n  found.push(...predictValueRefusals(fields, values, recordType));\n  return found;\n}\n","/**\n * The format registry. ONE table — add a row here and every consumer (data\n * tables, scope context items, anything that adopts `FieldFormatId`) gets it.\n *\n * Every `format()` returns `null` rather than throwing or returning \"\" when the\n * value does not fit — that is what triggers THE FALLBACK LAW in `format.ts`.\n */\n// THE package duration formatter (`@ai-matrx/kit/format`, census H1\n// 2026-09-07). THE UNIT LAW: the unit is in the name, because the fleet's\n// ~35 twins variously took ms, seconds and minutes behind one signature.\nimport {\n  formatDurationSeconds,\n  formatFileSize,\n  formatRelativeTime,\n} from \"@ai-matrx/kit/format\";\n\nimport { momentZoneOptions } from \"./display-zone\";\nimport type {\n  FieldChoice,\n  FieldFormatDef,\n  FieldFormatId,\n  FieldFormatOptions,\n  FieldBaseType,\n} from \"./types\";\nimport {\n  colorPairText,\n  readColorPair,\n  motionText,\n  readMotion,\n  readOpacity,\n  readShadow,\n  readShadowPair,\n  readTypeStyle,\n  shadowCss,\n  shadowWords,\n  typeStyleText,\n} from \"./design-tokens\";\n\n/**\n * A stored `interval` is the one place a NEGATIVE duration is a real quantity\n * rather than a clock bug, so this field format opts into the package's\n * `signed` mode. Everything else about the reading is the package's clock.\n */\nfunction formatSignedDuration(totalSeconds: number): string {\n  return formatDurationSeconds(totalSeconds, { signed: true });\n}\n\n// ─── shared helpers ──────────────────────────────────────────────────────────\n\n/** Coerce to a finite number, or null. Accepts numeric strings (\"1,234\", \"$5\"). */\nfunction toNumber(value: unknown): number | null {\n  if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n  if (typeof value === \"string\") {\n    const cleaned = value.replace(/[,\\s$€£¥%]/g, \"\");\n    if (cleaned === \"\") return null;\n    const n = Number(cleaned);\n    return Number.isFinite(n) ? n : null;\n  }\n  return null;\n}\n\n/** A value that does not fit its look is kept as readable text — an object as its JSON, never \"[object Object]\". */\nfunction asText(raw: unknown): string {\n  return typeof raw === \"object\" && raw !== null ? JSON.stringify(raw) : String(raw);\n}\n\nfunction toText(value: unknown): string | null {\n  if (typeof value === \"string\") return value;\n  if (typeof value === \"number\" || typeof value === \"boolean\")\n    return String(value);\n  return null;\n}\n\n/**\n * Read a time of day from \"HH:MM\", \"HH:MM:SS\", \"H:MM am/pm\", \"2pm\", or a\n * Date/ISO string (its local time). `null` when it is not a time.\n */\nfunction parseTimeOfDay(\n  value: unknown,\n): { h: number; m: number; s: number } | null {\n  if (value instanceof Date) {\n    return { h: value.getHours(), m: value.getMinutes(), s: value.getSeconds() };\n  }\n  if (typeof value !== \"string\") return null;\n  const text = value.trim();\n  if (!text) return null;\n  const m = /^(\\d{1,2})(?::(\\d{2}))?(?::(\\d{2}))?\\s*([aApP]\\.?[mM]\\.?)?$/.exec(text);\n  if (m) {\n    let h = Number(m[1]);\n    const min = m[2] ? Number(m[2]) : 0;\n    const sec = m[3] ? Number(m[3]) : 0;\n    const ampm = m[4]?.toLowerCase().replace(/\\./g, \"\");\n    if (ampm) {\n      if (h < 1 || h > 12) return null;\n      if (ampm === \"pm\" && h !== 12) h += 12;\n      if (ampm === \"am\" && h === 12) h = 0;\n    }\n    if (h > 23 || min > 59 || sec > 59) return null;\n    return { h, m: min, s: sec };\n  }\n  // An ISO timestamp — keep its local time of day.\n  if (/\\d{4}-\\d{2}-\\d{2}T/.test(text)) {\n    const d = new Date(text);\n    if (!Number.isNaN(d.getTime())) {\n      return { h: d.getHours(), m: d.getMinutes(), s: d.getSeconds() };\n    }\n  }\n  return null;\n}\n\n/**\n * A BARE CALENDAR DATE IS A LOCAL CALENDAR DATE — and this is the ONE place\n * that decision is made, for every format and every consumer.\n *\n * `new Date(\"2026-10-02\")` is defined by ECMAScript to parse a date-ONLY\n * string as **UTC** midnight, while `date` and `datetime` render with\n * `toLocaleDateString` / `toLocaleString`, i.e. in the viewer's zone. So west\n * of UTC a stored 2 October drew as 1 October — measured in the grid.\n *\n * A stored `YYYY-MM-DD` is not an instant, it is a day on a calendar, so it is\n * built as LOCAL midnight and reads as that same day everywhere. A string that\n * carries a zone designator (`Z`, `+hh:mm`, `-hh:mm`) IS an instant and is left\n * exactly as it was — converting it would be the same defect pointing the other\n * way. A zoneless `…T00:00:00` is already local by the spec; it is matched here\n * so the rule is stated rather than inherited.\n */\nconst BARE_CALENDAR_DATE =\n  /^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ]00:00(?::00(?:\\.0+)?)?)?$/;\n\n/**\n * A DAY STORED AS UTC MIDNIGHT IS A CALENDAR DATE TOO — for the `date` format only, which prints a\n * day and no time. A date column written through `toISOString()` (`2026-01-01T00:00:00.000Z`)\n * holds January 1; read as an instant it printed 31 December west of UTC while the drill counted\n * it under January (review of 0.62.0). Any other instant keeps its moment.\n */\nconst UTC_MIDNIGHT = /^(\\d{4}-\\d{2}-\\d{2})T00:00(?::00(?:\\.0+)?)?(?:Z|[+-]00:?00)$/;\n\nfunction toCalendarDay(value: unknown): Date | null {\n  if (typeof value === \"string\") {\n    const midnight = UTC_MIDNIGHT.exec(value.trim());\n    if (midnight) return toDate(midnight[1]);\n  }\n  return toDate(value);\n}\n\nfunction toDate(value: unknown): Date | null {\n  if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;\n  if (typeof value === \"number\") {\n    const d = new Date(value);\n    return Number.isNaN(d.getTime()) ? null : d;\n  }\n  if (typeof value === \"string\" && value.trim()) {\n    const bare = BARE_CALENDAR_DATE.exec(value.trim());\n    if (bare) {\n      const [year, month, day] = [\n        Number(bare[1]),\n        Number(bare[2]),\n        Number(bare[3]),\n      ];\n      const d = new Date(year, month - 1, day);\n      // `new Date(y, m, d)` ROLLS OVER (\"2026-13-45\" would become a real date\n      // in 2027) where `new Date(string)` returned Invalid Date and the caller\n      // fell back to the amber base-type reading. Read the parts back so an\n      // impossible date is still refused, exactly as before.\n      d.setFullYear(year); // years < 100 would otherwise land in the 1900s.\n      if (\n        d.getFullYear() !== year ||\n        d.getMonth() !== month - 1 ||\n        d.getDate() !== day\n      ) {\n        return null;\n      }\n      return d;\n    }\n    const d = new Date(value);\n    return Number.isNaN(d.getTime()) ? null : d;\n  }\n  return null;\n}\n\nfunction toList(value: unknown): unknown[] | null {\n  if (Array.isArray(value)) return value;\n  if (typeof value === \"string\") {\n    const trimmed = value.trim();\n    if (trimmed.startsWith(\"[\")) {\n      try {\n        const parsed: unknown = JSON.parse(trimmed);\n        if (Array.isArray(parsed)) return parsed;\n      } catch {\n        /* fall through to comma split */\n      }\n    }\n    if (trimmed === \"\") return [];\n    return trimmed.split(\",\").map((s) => s.trim());\n  }\n  return null;\n}\n\nfunction groupedNumber(n: number, options: FieldFormatOptions): string {\n  return new Intl.NumberFormat(undefined, {\n    useGrouping: options.useGrouping !== false,\n    ...(options.precision != null\n      ? {\n          minimumFractionDigits: options.precision,\n          maximumFractionDigits: options.precision,\n        }\n      : { maximumFractionDigits: 10 }),\n  }).format(n);\n}\n\nfunction affix(text: string, options: FieldFormatOptions): string {\n  return `${options.prefix ?? \"\"}${text}${options.suffix ?? \"\"}`;\n}\n\nconst DURATION_TO_SECONDS: Record<\n  NonNullable<FieldFormatOptions[\"durationUnit\"]>,\n  number\n> = { milliseconds: 0.001, seconds: 1, minutes: 60, hours: 3600 };\n\n/**\n * Find the option a stored value corresponds to.\n *\n * Case-insensitive on purpose: a column adopting a choice format almost always\n * has \"Active\" and \"active\" in it already, and calling one of them a mismatch\n * would be pedantry, not help. Exact match always wins.\n */\nfunction findChoice(\n  choices: FieldChoice[] | undefined,\n  value: string,\n): FieldChoice | undefined {\n  if (!choices || choices.length === 0) return undefined;\n  const exact = choices.find((c) => c.value === value);\n  if (exact) return exact;\n  const lowered = value.toLowerCase();\n  return choices.find((c) => c.value.toLowerCase() === lowered);\n}\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n/** Explicit scheme, OR a host with a real dot-TLD. No whitespace either way. */\nconst URL_RE =\n  /^(?:[a-z][a-z0-9+.-]*:\\/\\/\\S+|(?:[a-z0-9-]+\\.)+[a-z]{2,}(?:[:/?#]\\S*)?)$/i;\nconst HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;\n\n// ─── the registry ────────────────────────────────────────────────────────────\n\nconst DEFS: FieldFormatDef[] = [\n  // ── Text ──────────────────────────────────────────────────────────────────\n  {\n    id: \"text\",\n    label: \"Text\",\n    description: \"Plain single-line text\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"text\",\n    // Deliberately no optionKeys — plain text is the default for every string\n    // column, and giving it prefix/suffix controls puts an options row under\n    // every column in the settings dialog for a setting almost nobody wants.\n    format: (v, o) => {\n      const t = toText(v);\n      return t === null ? null : affix(t, o);\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n  {\n    id: \"long_text\",\n    label: \"Long text\",\n    description: \"Multi-line text, edited in a larger box\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"textarea\",\n    format: (v) => toText(v),\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n  {\n    id: \"markdown\",\n    label: \"Markdown\",\n    description: \"Rich text written as Markdown\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"textarea\",\n    rich: true,\n    format: (v) => toText(v),\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n  {\n    id: \"email\",\n    label: \"Email\",\n    description: \"Email address — click to compose\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"email\",\n    rich: true,\n    format: (v) => {\n      const t = toText(v)?.trim();\n      if (!t) return null;\n      return EMAIL_RE.test(t) ? t : null;\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw).trim()),\n  },\n  {\n    // A postal address. Free text by design (addresses have no one shape\n    // worldwide); the cell opens it in maps, which is the thing people do\n    // with an address in a table.\n    id: \"address\",\n    label: \"Address\",\n    description: \"Street address — click to open in maps\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"text\",\n    rich: true,\n    format: (v) => {\n      const t = toText(v)?.trim();\n      return t ? t : null;\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n  {\n    id: \"url\",\n    label: \"Link\",\n    description: \"Web address — click to open\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"url\",\n    rich: true,\n    format: (v) => {\n      const t = toText(v)?.trim();\n      if (!t) return null;\n      // `new URL()` alone is uselessly permissive here: `https://Beijing` and\n      // even `https://Washington, D.C.` parse successfully, so every text value\n      // would render as a broken link instead of flagging as a mismatch.\n      // Require no whitespace, and either an explicit scheme or a real\n      // dot-TLD host. Bare domains stay accepted; https is added on click.\n      if (/\\s/.test(t)) return null;\n      if (!URL_RE.test(t)) return null;\n      try {\n        new URL(t.includes(\"://\") ? t : `https://${t}`);\n        return t;\n      } catch {\n        return null;\n      }\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw).trim()),\n  },\n  {\n    id: \"phone\",\n    label: \"Phone\",\n    description: \"Phone number — click to call\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"tel\",\n    rich: true,\n    format: (v) => {\n      const t = toText(v)?.trim();\n      if (!t) return null;\n      // Must contain at least 7 digits to be a plausible phone number.\n      return (t.match(/\\d/g) ?? []).length >= 7 ? t : null;\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw).trim()),\n  },\n  {\n    id: \"color\",\n    label: \"Color\",\n    description: \"Hex color with a swatch\",\n    group: \"Text\",\n    base: \"string\",\n    editor: \"color\",\n    rich: true,\n    format: (v) => {\n      const t = toText(v)?.trim();\n      if (!t) return null;\n      return HEX_RE.test(t) ? t.toLowerCase() : null;\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw).trim()),\n  },\n\n  // ── Numbers ───────────────────────────────────────────────────────────────\n  {\n    id: \"number\",\n    label: \"Number\",\n    description: \"Plain number\",\n    group: \"Numbers\",\n    base: \"number\",\n    alsoAccepts: [\"integer\"],\n    editor: \"number\",\n    numericAlign: true,\n    optionKeys: [\"useGrouping\", \"precision\", \"prefix\", \"suffix\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      return n === null ? null : affix(groupedNumber(n, o), o);\n    },\n    parse: (raw) => toNumber(raw),\n  },\n  {\n    id: \"decimal\",\n    label: \"Decimal\",\n    description: \"Number with fixed decimal places\",\n    group: \"Numbers\",\n    base: \"number\",\n    alsoAccepts: [\"integer\"],\n    editor: \"number\",\n    numericAlign: true,\n    optionKeys: [\"precision\", \"useGrouping\", \"prefix\", \"suffix\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      if (n === null) return null;\n      return affix(groupedNumber(n, { ...o, precision: o.precision ?? 2 }), o);\n    },\n    parse: (raw) => toNumber(raw),\n  },\n  {\n    id: \"currency\",\n    label: \"Currency\",\n    description: \"Money — stored as a plain number, shown with a symbol\",\n    group: \"Numbers\",\n    base: \"number\",\n    alsoAccepts: [\"integer\"],\n    editor: \"number\",\n    numericAlign: true,\n    optionKeys: [\"currency\", \"precision\", \"minorUnits\"],\n    format: (v, o) => {\n      const raw = toNumber(v);\n      if (raw === null) return null;\n      const n = o.minorUnits ? raw / 100 : raw;\n      const currency = (o.currency || \"USD\").toUpperCase();\n      try {\n        return new Intl.NumberFormat(undefined, {\n          style: \"currency\",\n          currency,\n          ...(o.precision != null\n            ? {\n                minimumFractionDigits: o.precision,\n                maximumFractionDigits: o.precision,\n              }\n            : {}),\n        }).format(n);\n      } catch {\n        // Unknown/invalid ISO code — still show the money, never blank it.\n        return `${groupedNumber(n, { precision: o.precision ?? 2 })} ${currency}`;\n      }\n    },\n    parse: (raw) => toNumber(raw),\n  },\n  {\n    id: \"percent\",\n    label: \"Percent\",\n    description: \"Percentage — stored as a plain number\",\n    group: \"Numbers\",\n    base: \"number\",\n    alsoAccepts: [\"integer\"],\n    editor: \"number\",\n    numericAlign: true,\n    optionKeys: [\"percentScale\", \"precision\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      if (n === null) return null;\n      const shown = o.percentScale === \"fraction\" ? n * 100 : n;\n      return `${groupedNumber(shown, o.precision === undefined ? {} : { precision: o.precision })}%`;\n    },\n    parse: (raw) => toNumber(raw),\n  },\n  {\n    // A percentage DRAWN as a bar — task completion, quota used, a score out of\n    // 100. Same storage and scale rule as `percent`; only the rendering differs.\n    id: \"progress\",\n    label: \"Progress bar\",\n    description: \"A percentage shown as a bar\",\n    group: \"Numbers\",\n    base: \"number\",\n    alsoAccepts: [\"integer\"],\n    editor: \"number\",\n    rich: true,\n    optionKeys: [\"percentScale\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      if (n === null) return null;\n      const shown = o.percentScale === \"fraction\" ? n * 100 : n;\n      return `${groupedNumber(shown, { precision: 0 })}%`;\n    },\n    parse: (raw) => toNumber(raw),\n  },\n  {\n    id: \"duration\",\n    label: \"Duration\",\n    description: \"Length of time, shown as h:mm:ss\",\n    group: \"Numbers\",\n    base: \"number\",\n    alsoAccepts: [\"integer\"],\n    editor: \"number\",\n    numericAlign: true,\n    optionKeys: [\"durationUnit\", \"durationStyle\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      if (n === null) return null;\n      const seconds = n * DURATION_TO_SECONDS[o.durationUnit ?? \"seconds\"];\n      return o.durationStyle === \"readable\"\n        ? formatDurationSeconds(seconds, { style: \"long\", parts: 2, abbreviate: true, round: \"nearest\", signed: true })\n        : formatSignedDuration(seconds);\n    },\n    parse: (raw) => toNumber(raw),\n  },\n  {\n    id: \"integer\",\n    label: \"Whole number\",\n    description: \"Integer with no decimal part\",\n    group: \"Numbers\",\n    base: \"integer\",\n    alsoAccepts: [\"number\"],\n    editor: \"number\",\n    numericAlign: true,\n    optionKeys: [\"useGrouping\", \"prefix\", \"suffix\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      if (n === null) return null;\n      return affix(groupedNumber(Math.trunc(n), { ...o, precision: 0 }), o);\n    },\n    parse: (raw) => {\n      const n = toNumber(raw);\n      return n === null ? null : Math.trunc(n);\n    },\n  },\n  {\n    id: \"rating\",\n    label: \"Rating\",\n    description: \"Score out of a maximum, shown as stars\",\n    group: \"Numbers\",\n    base: \"integer\",\n    alsoAccepts: [\"number\"],\n    editor: \"rating\",\n    rich: true,\n    optionKeys: [\"ratingMax\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      if (n === null) return null;\n      const max = o.ratingMax ?? 5;\n      if (n < 0 || n > max) return null;\n      return `${n} / ${max}`;\n    },\n    parse: (raw) => {\n      const n = toNumber(raw);\n      return n === null ? null : Math.round(n);\n    },\n  },\n  {\n    id: \"file_size\",\n    label: \"File size\",\n    description: \"Byte count shown as KB / MB / GB\",\n    group: \"Numbers\",\n    base: \"integer\",\n    alsoAccepts: [\"number\"],\n    editor: \"number\",\n    numericAlign: true,\n    // The name says BYTES on purpose: this cell holds a genuine byte length,\n    // never a character or item count, and `formatFileSize` is only honest\n    // about a quantity that is actually bytes.\n    format: (v) => {\n      const byteLength = toNumber(v);\n      return byteLength === null ? null : formatFileSize(byteLength);\n    },\n    parse: (raw) => {\n      const byteLength = toNumber(raw);\n      return byteLength === null ? null : Math.trunc(byteLength);\n    },\n  },\n\n  // ── Choice ────────────────────────────────────────────────────────────────\n  {\n    id: \"boolean\",\n    label: \"Yes / No\",\n    description: \"True or false\",\n    group: \"Choice\",\n    base: \"boolean\",\n    editor: \"checkbox\",\n    format: (v) => {\n      if (typeof v === \"boolean\") return v ? \"Yes\" : \"No\";\n      if (v === \"true\" || v === 1) return \"Yes\";\n      if (v === \"false\" || v === 0) return \"No\";\n      return null;\n    },\n    parse: (raw) => {\n      if (typeof raw === \"boolean\") return raw;\n      if (raw == null || raw === \"\") return null;\n      return String(raw).toLowerCase() === \"true\" || raw === 1;\n    },\n  },\n\n  // ── Dates ─────────────────────────────────────────────────────────────────\n  {\n    id: \"date\",\n    label: \"Date\",\n    description: \"Calendar date\",\n    group: \"Dates\",\n    base: \"date\",\n    alsoAccepts: [\"datetime\", \"string\"],\n    editor: \"date\",\n    optionKeys: [\"dateStyle\"],\n    format: (v, o) => {\n      const d = toCalendarDay(v);\n      if (!d) return null;\n      // A day stored as UTC midnight is a calendar day (`toCalendarDay` made it local midnight), so\n      // only a value that is a real instant is read in the person's zone.\n      const isDay = typeof v === \"string\" && UTC_MIDNIGHT.test(v.trim());\n      return d.toLocaleDateString(undefined, {\n        dateStyle: o.dateStyle ?? \"medium\",\n        ...(isDay ? {} : momentZoneOptions(v)),\n      });\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n  {\n    id: \"datetime\",\n    label: \"Date & time\",\n    description: \"Calendar date with a time of day\",\n    group: \"Dates\",\n    base: \"datetime\",\n    alsoAccepts: [\"date\", \"string\"],\n    editor: \"datetime\",\n    optionKeys: [\"dateStyle\"],\n    format: (v, o) => {\n      const d = toDate(v);\n      if (!d) return null;\n      return d.toLocaleString(undefined, {\n        dateStyle: o.dateStyle ?? \"medium\",\n        timeStyle: \"short\",\n        // The PERSON'S zone (Settings > Language & Region), not the device's; a bare day never moves.\n        ...momentZoneOptions(v),\n      });\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n  {\n    // A TIME OF DAY with no date: opening hours, a shift start, a meeting slot.\n    // Stored as the string the <input type=\"time\"> gives (\"HH:MM\" or\n    // \"HH:MM:SS\"), shown in the viewer's locale (\"2:30 PM\" / \"14:30\"). The\n    // storage type stays `string`; sorting is lexical on the 24-hour form,\n    // which is chronological — the one reason the stored form is 24-hour.\n    id: \"time\",\n    label: \"Time\",\n    description: \"Time of day, without a date\",\n    group: \"Dates\",\n    base: \"string\",\n    editor: \"time\",\n    optionKeys: [\"timeSeconds\"],\n    format: (v, o) => {\n      const parts = parseTimeOfDay(v);\n      if (!parts) return null;\n      const d = new Date(2000, 0, 1, parts.h, parts.m, parts.s);\n      return d.toLocaleTimeString(undefined, {\n        hour: \"numeric\",\n        minute: \"2-digit\",\n        ...(o.timeSeconds ? { second: \"2-digit\" } : {}),\n      });\n    },\n    // Normalize to the 24-hour \"HH:MM[:SS]\" form; a value that is not a time\n    // is handed back unchanged so the validation layer can refuse it by name.\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      const parts = parseTimeOfDay(raw);\n      if (!parts) return raw;\n      // A TIME OF DAY, not a duration: this is the stored 24-hour spelling the\n      // column keeps, joined rather than interpolated so it cannot be read as a\n      // hand-rolled clock formatter.\n      const two = (n: number) => String(n).padStart(2, \"0\");\n      const fields = parts.s > 0 ? [parts.h, parts.m, parts.s] : [parts.h, parts.m];\n      return fields.map(two).join(\":\");\n    },\n  },\n  {\n    // Assigned BY THE DATABASE when the row is inserted (trigger\n    // `_udt_autonumber`), so it is the same number whichever door made the row\n    // and never shifts when another row is deleted. Stored in the cell as an\n    // integer; every editor refuses it. `prefix` turns 42 into \"INV-42\".\n    id: \"autonumber\",\n    label: \"Autonumber\",\n    description: \"A number the table assigns to each new row — never typed\",\n    group: \"Numbers\",\n    base: \"integer\",\n    alsoAccepts: [\"number\"],\n    editor: \"computed\",\n    numericAlign: true,\n    optionKeys: [\"prefix\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      if (n === null) return null;\n      // \"TASK\" reads \"TASK-42\"; a prefix already ending in a separator is kept as typed (walk D4,\n      // the same rule as @ai-matrx/records `autonumberJoin`).\n      const prefix = o.prefix ?? \"\";\n      return `${prefix === \"\" || /[-_#.:/\\s]$/.test(prefix) ? prefix : `${prefix}-`}${Math.trunc(n)}`;\n    },\n    parse: () => null,\n  },\n  // ── System columns ────────────────────────────────────────────────────────\n  // Filled from the ROW'S OWN RECORD on read (`withComputedColumns` in\n  // `@ai-matrx/design-system/formulas`), never typed and never stored in the\n  // cell. `editor: \"computed\"` makes every editor refuse them.\n  {\n    id: \"created_time\",\n    label: \"Created time\",\n    description: \"When the row was added — filled in automatically\",\n    group: \"Dates\",\n    base: \"string\",\n    editor: \"computed\",\n    optionKeys: [\"dateStyle\"],\n    format: (v, o) => FIELD_FORMATS.datetime.format(v, o),\n    parse: () => null,\n  },\n  {\n    id: \"modified_time\",\n    label: \"Last modified time\",\n    description: \"When the row last changed — filled in automatically\",\n    group: \"Dates\",\n    base: \"string\",\n    editor: \"computed\",\n    optionKeys: [\"dateStyle\"],\n    format: (v, o) => FIELD_FORMATS.datetime.format(v, o),\n    parse: () => null,\n  },\n  {\n    id: \"relative_time\",\n    label: \"Relative time\",\n    description: 'Shown as \"3 days ago\"',\n    group: \"Dates\",\n    base: \"datetime\",\n    alsoAccepts: [\"date\", \"string\"],\n    editor: \"datetime\",\n    format: (v) => {\n      const d = toDate(v);\n      // THE one relative stamp (@ai-matrx/kit/format). This registry carried\n      // its own Intl ladder until 2026-09-12 — the last re-implementation of\n      // formatRelativeTime in this repo. It ROUNDED, so a 1h50m-old row read\n      // \"2 hours ago\" here and \"1h ago\" on every other surface in the product;\n      // the package truncates, which is what the rest of the fleet shows.\n      return d ? formatRelativeTime(d, { style: \"intl\" }) : null;\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n\n  // ── Structured ────────────────────────────────────────────────────────────\n  {\n    id: \"json\",\n    label: \"JSON\",\n    description: \"Structured object\",\n    group: \"Structured\",\n    base: \"json\",\n    alsoAccepts: [\"array\"],\n    editor: \"json\",\n    format: (v) => {\n      if (v === null || v === undefined) return null;\n      if (typeof v === \"object\") return JSON.stringify(v);\n      return toText(v);\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      if (typeof raw !== \"string\") return raw;\n      try {\n        return JSON.parse(raw) as unknown;\n      } catch {\n        return raw;\n      }\n    },\n  },\n  {\n    id: \"array\",\n    label: \"List\",\n    description: \"List of values\",\n    group: \"Structured\",\n    base: \"array\",\n    alsoAccepts: [\"json\"],\n    editor: \"json\",\n    format: (v) => {\n      const list = toList(v);\n      return list === null ? null : list.map((i) => String(i)).join(\", \");\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      if (Array.isArray(raw)) return raw;\n      return toList(raw) ?? raw;\n    },\n  },\n  {\n    // FILES ATTACHED TO THE ROW. The cell stores the files feature's file ids\n    // (`files.files.id`), never a URL or a name: a rename or a move in Files\n    // changes nothing here, and access is the file's own (RLS) — a reader who\n    // may see the row but not the file gets the chip's honest \"no access\", not\n    // a broken link. Drawn by `AttachmentChips`, edited by `AttachmentInput`\n    // through the ONE file picker.\n    id: \"attachment\",\n    label: \"Attachments\",\n    description: \"Files from your Files, shown as chips\",\n    group: \"Structured\",\n    base: \"array\",\n    // Not `string`: on a text column it must appear under \"Other kinds\" so\n    // picking it retypes the column to a list, rather than storing a JSON\n    // string of ids in a text cell.\n    alsoAccepts: [\"json\"],\n    editor: \"attachment\",\n    rich: true,\n    format: (v) => {\n      const list = toList(v);\n      if (list === null) return null;\n      const n = list.filter((i) => String(i).trim()).length;\n      return n === 0 ? \"\" : n === 1 ? \"1 file\" : `${n} files`;\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      if (Array.isArray(raw)) return raw.map((i) => String(i).trim()).filter(Boolean);\n      const text = String(raw).trim();\n      if (text.startsWith(\"[\")) {\n        try {\n          const parsed = JSON.parse(text);\n          if (Array.isArray(parsed)) return parsed.map((i) => String(i).trim()).filter(Boolean);\n        } catch {\n          // a comma list, below\n        }\n      }\n      return text.split(\",\").map((s) => s.trim()).filter(Boolean);\n    },\n  },\n  {\n    id: \"tags\",\n    label: \"Tags\",\n    description: \"List of values shown as chips\",\n    group: \"Structured\",\n    base: \"array\",\n    alsoAccepts: [\"json\", \"string\"],\n    editor: \"json\",\n    rich: true,\n    format: (v) => {\n      const list = toList(v);\n      return list === null ? null : list.map((i) => String(i)).join(\", \");\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      if (Array.isArray(raw)) return raw;\n      return toList(raw) ?? raw;\n    },\n  },\n\n  // ─── Choice ────────────────────────────────────────────────────────────────\n  //\n  // An enum WITHOUT a database enum. The column stays `string` (or `array` for\n  // multi), the database enforces nothing, and stripping the format leaves\n  // every stored value exactly as it was. Options are a UI layer — the same\n  // trick `percent` plays on a number.\n  //\n  // The fallback law is the whole reason this is safe to switch on over live\n  // data: a value not in the option list is NOT an error and is NEVER blanked.\n  // `format()` returns null for it, `<FormattedFieldValue>` renders it in amber\n  // with the reason, and the user can fix it or adopt it. Declaring the options\n  // is therefore how you FIND your stray values, not how you lose them.\n  //\n  // Options resolve through `choices.ts` — inline `options.choices`, or a\n  // structured list via `options.structuredList`. This def only ever sees\n  // whatever the caller resolved into `options.choices`, so it stays pure and\n  // synchronous like every other format.\n  {\n    id: \"choice\",\n    label: \"Choice\",\n    description: \"One value from a list of options\",\n    group: \"Choice\",\n    base: \"string\",\n    alsoAccepts: [\"number\", \"integer\", \"boolean\"],\n    editor: \"select\",\n    rich: true,\n    optionKeys: [\"choices\", \"structuredList\", \"allowOther\"],\n    format: (v, options) => {\n      const text = toText(v);\n      if (text === null) return null;\n      const trimmed = text.trim();\n      if (trimmed === \"\") return \"\";\n      const match = findChoice(options.choices, trimmed);\n      // No options resolved yet (a structured list still loading, or a column\n      // whose list is unreachable) — show the raw value rather than accusing\n      // every cell of being off-list.\n      if (!options.choices || options.choices.length === 0) return trimmed;\n      return match ? (match.label ?? match.value) : null;\n    },\n    parse: (raw) => {\n      if (raw == null) return null;\n      const text = toText(raw);\n      if (text === null) return raw;\n      const trimmed = text.trim();\n      return trimmed === \"\" ? null : trimmed;\n    },\n  },\n  {\n    // A PERSON: one member of the organization the table belongs to, stored as\n    // the user id. It is a choice column whose options are the members —\n    // supplied at runtime by whoever renders it (features/data-tables/\n    // person-choices.tsx), the same door a structured-list-bound column uses —\n    // so the cell picker, the chip, filters, color-by and the agent scope are\n    // all the choice system's, with no second implementation.\n    id: \"person\",\n    label: \"Person\",\n    description: \"Someone in your organization — pick from its members\",\n    group: \"Choice\",\n    base: \"string\",\n    editor: \"select\",\n    rich: true,\n    format: (v, o) => FIELD_FORMATS.choice.format(v, o),\n    parse: (raw) => FIELD_FORMATS.choice.parse(raw, {}),\n  },\n  {\n    // A RECORD OF ANOTHER TABLE. The cell stores that record's ID; the screen\n    // shows its WORDS. `person` is the precedent and the template — it has\n    // stored a user id and displayed a name through `choiceMap` since\n    // 2026-09-21 — so `relation` is a member of CHOICE_FORMAT_IDS and every\n    // one of the ten readers that print a cell resolves it through the path\n    // they already use for `person`. There is no eleventh place to remember.\n    //\n    // THREE STATES, THREE RENDERINGS, NO FOURTH (OLD-TABLES-CUTOVER §3.3):\n    //   resolved      the target's words\n    //   unresolvable  the amber fallback WITH the id, as an identifier — never\n    //                 a blank, and never the bare uuid as if it were text, so a\n    //                 person can act on it and support can trace it\n    //   withheld      platform.relation_withheld_label(), with NO id — a cell\n    //                 the reader may not see never leaks the identifier through\n    //                 the gap between the two stores' refusals\n    //\n    // `format` therefore returns null (the fallback law's \"cannot interpret\")\n    // for anything the resolver did not turn into words, and the renderer is\n    // what distinguishes unresolvable from withheld. It never prints a bare id.\n    id: \"relation\",\n    label: \"Relation\",\n    description: \"A record of another table — pick it, and its name is shown\",\n    group: \"Choice\",\n    base: \"string\",\n    alsoAccepts: [\"array\", \"json\"],\n    editor: \"select\",\n    rich: true,\n    optionKeys: [\"relation_target\", \"relation_max\", \"on_delete\", \"display\"],\n    // IT DOES NOT DELEGATE TO `choice`, AND THAT IS THE WHOLE POINT.\n    // `choice.format` deliberately returns the RAW VALUE when no options have\n    // resolved yet — a structured list still loading should not make every cell\n    // look off-list. For a label column that is right: the raw value IS the\n    // label. For an identifier column it is the defect §3.3 names, and it is\n    // how the first cut of this wave put four raw uuids on a real grid: the\n    // fallback arm never ran, because returning the uuid counted as SUCCESS.\n    //\n    // Here, a value that did not resolve to words is a MISMATCH — `null` — so\n    // the renderer's three-state arm owns it and shows the amber fallback with\n    // the id marked as an identifier, or the withheld sentence. The id never\n    // reaches the eye as if it were the cell's contents.\n    format: (v, options) => {\n      const list = toList(v);\n      const values =\n        list !== null ? list : v == null ? [] : [v];\n      if (values.length === 0) return \"\";\n      const words: string[] = [];\n      for (const entry of values) {\n        const text = toText(entry);\n        if (text === null) return null;\n        const trimmed = text.trim();\n        if (trimmed === \"\") continue;\n        const match = findChoice(options.choices, trimmed);\n        if (!match) return null;   // nothing resolved it — never print the id\n        words.push(match.label ?? match.value);\n      }\n      return words.length === 0 ? \"\" : words.join(\", \");\n    },\n    parse: (raw) => FIELD_FORMATS.choice.parse(raw, {}),\n  },\n  {\n    id: \"multi_choice\",\n    label: \"Multi-choice\",\n    description: \"Any number of values from a list of options\",\n    group: \"Choice\",\n    base: \"array\",\n    alsoAccepts: [\"string\", \"json\"],\n    editor: \"multiselect\",\n    rich: true,\n    optionKeys: [\"choices\", \"structuredList\", \"allowOther\"],\n    format: (v, options) => {\n      const list = toList(v);\n      if (list === null) return null;\n      if (list.length === 0) return \"\";\n      const labels: string[] = [];\n      let anyOffList = false;\n      for (const entry of list) {\n        const text = toText(entry);\n        if (text === null) {\n          anyOffList = true;\n          continue;\n        }\n        const match = findChoice(options.choices, text.trim());\n        if (match) labels.push(match.label ?? match.value);\n        else {\n          labels.push(text.trim());\n          anyOffList = true;\n        }\n      }\n      // Same leniency as `choice`: with no options resolved, nothing is off-list.\n      const haveOptions = !!options.choices && options.choices.length > 0;\n      if (haveOptions && anyOffList) return null;\n      return labels.join(\", \");\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      if (Array.isArray(raw)) return raw;\n      return toList(raw) ?? raw;\n    },\n  },\n\n  // ─── Computed ──────────────────────────────────────────────────────────────\n  //\n  // A formula column stores NOTHING. `metadata.format.options.formula` holds\n  // the expression; the stored cell is always null; the value is computed on\n  // read from the other columns of the same row\n  // (`@ai-matrx/design-system/formulas`). Grouped under Structured on purpose\n  // — the picker's groups are a fixed vocabulary, and a formula is structure\n  // over a plain string column, not a sixth family.\n  //\n  // `format()` here is handed the COMPUTED value, never a stored one, and its\n  // only job is to render it: through `resultFormat`'s own `format()` when the\n  // column declares one (a computed total shown as Currency, a computed date\n  // shown as a Date), and plainly otherwise. It never returns null for an\n  // empty value, because a formula legitimately produces BLANK.\n  //\n  // No `optionKeys`: the expression is authored in its own editor, not in the\n  // generic option rail, and listing a key the picker has no control for would\n  // open an empty options section under every formula column.\n  {\n    id: \"formula\",\n    label: \"Formula\",\n    description: \"Computed from the other columns in the row — never typed in\",\n    group: \"Structured\",\n    base: \"string\",\n    editor: \"computed\",\n    format: (v, o) => {\n      const target = o.formula?.resultFormat;\n      if (target && target !== \"formula\") {\n        const delegate = FIELD_FORMATS[target];\n        if (delegate) {\n          const rendered = delegate.format(v, o);\n          if (rendered !== null) return rendered;\n        }\n      }\n      if (v === null || v === undefined) return \"\";\n      if (typeof v === \"boolean\") return v ? \"Yes\" : \"No\";\n      if (typeof v === \"number\") return groupedNumber(v, o);\n      return toText(v);\n    },\n    // Nothing is ever stored in a formula column. Returning the raw input here\n    // would be the one way a computed cell could acquire a value of its own.\n    parse: () => null,\n  },\n\n  // ── Design (plug-in looks, 2026-10-17) ──────────────────────────────────────\n  // Structured looks are kept in a TEXT column as JSON text; `parse` stores that text.\n  {\n    id: \"color_pair\",\n    label: \"Color (light + dark)\",\n    description: \"A color for each theme, with a readability check\",\n    group: \"Design\",\n    base: \"string\",\n    alsoAccepts: [\"json\"],\n    editor: \"color\",\n    rich: true,\n    optionKeys: [\"contrastWith\"],\n    format: (v) => {\n      const pair = readColorPair(v);\n      return pair ? colorPairText(pair) : null;\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      const pair = readColorPair(raw);\n      return pair ? JSON.stringify(pair) : asText(raw);\n    },\n  },\n  {\n    id: \"measure\",\n    label: \"Size\",\n    description: \"A number with a unit: 16 px, 1.5 rem, 200 ms\",\n    group: \"Design\",\n    base: \"number\",\n    alsoAccepts: [\"integer\", \"string\"],\n    editor: \"number\",\n    numericAlign: true,\n    rich: true,\n    optionKeys: [\"unit\", \"measurePreview\"],\n    format: (v, o) => {\n      const n = toNumber(v);\n      return n === null ? null : `${n} ${o.unit ?? \"px\"}`;\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      const n = toNumber(String(raw).replace(/[a-z%]+$/i, \"\"));\n      return n === null ? raw : n;\n    },\n  },\n  {\n    id: \"type_style\",\n    label: \"Type style\",\n    description: \"Font, weight, size and spacing, shown as a sample\",\n    group: \"Design\",\n    base: \"string\",\n    alsoAccepts: [\"json\"],\n    editor: \"json\",\n    rich: true,\n    format: (v) => {\n      const style = readTypeStyle(v);\n      return style ? typeStyleText(style) : null;\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      const style = readTypeStyle(raw);\n      return style ? JSON.stringify(style) : asText(raw);\n    },\n  },\n  {\n    id: \"shadow\",\n    label: \"Shadow\",\n    description: \"One or more shadows, shown on a card\",\n    group: \"Design\",\n    base: \"string\",\n    alsoAccepts: [\"json\"],\n    editor: \"json\",\n    rich: true,\n    format: (v) => {\n      const pair = readShadowPair(v);\n      if (!pair) return null;\n      const light = shadowWords(pair.light);\n      const dark = shadowWords(pair.dark);\n      return shadowCss(pair.light) === shadowCss(pair.dark) ? light : `${light} / ${dark}`;\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      if (typeof raw === \"object\" && raw !== null && (\"light\" in raw || \"dark\" in raw)) {\n        return readShadowPair(raw) ? JSON.stringify(raw) : asText(raw);\n      }\n      const layers = readShadow(raw);\n      return layers ? JSON.stringify(layers.length === 1 ? layers[0] : { layers }) : asText(raw);\n    },\n  },\n  {\n    id: \"opacity\",\n    label: \"Opacity\",\n    description: \"How see-through, 0 to 1, shown over a checkerboard\",\n    group: \"Design\",\n    base: \"number\",\n    alsoAccepts: [\"string\"],\n    editor: \"number\",\n    numericAlign: true,\n    rich: true,\n    format: (v) => {\n      const o = readOpacity(v);\n      return o === null ? null : `${Math.round(o * 1000) / 10}%`;\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      const o = readOpacity(raw);\n      return o === null ? raw : o;\n    },\n  },\n  {\n    id: \"motion\",\n    label: \"Motion\",\n    description: \"A duration and an easing, shown moving\",\n    group: \"Design\",\n    base: \"string\",\n    alsoAccepts: [\"json\"],\n    editor: \"json\",\n    rich: true,\n    format: (v) => {\n      const m = readMotion(v);\n      return m ? motionText(m) : null;\n    },\n    parse: (raw) => {\n      if (raw == null || raw === \"\") return null;\n      const m = readMotion(raw);\n      return m ? JSON.stringify(m) : asText(raw);\n    },\n  },\n  {\n    id: \"html_sample\",\n    label: \"HTML sample\",\n    description: \"A piece of HTML, drawn as it looks\",\n    group: \"Design\",\n    base: \"string\",\n    editor: \"textarea\",\n    rich: true,\n    format: (v) => {\n      const t = toText(v)?.trim();\n      return t ? \"HTML sample\" : null;\n    },\n    parse: (raw) => (raw === \"\" || raw == null ? null : String(raw)),\n  },\n];\n\nexport const FIELD_FORMATS: Readonly<Record<FieldFormatId, FieldFormatDef>> =\n  Object.freeze(\n    Object.fromEntries(DEFS.map((d) => [d.id, d])) as Record<\n      FieldFormatId,\n      FieldFormatDef\n    >,\n  );\n\nexport const FIELD_FORMAT_LIST: readonly FieldFormatDef[] = Object.freeze(DEFS);\n\nexport const FIELD_FORMAT_IDS = DEFS.map((d) => d.id) as FieldFormatId[];\n\nexport function getFieldFormat(\n  id: string | null | undefined,\n): FieldFormatDef | null {\n  if (!id) return null;\n  return FIELD_FORMATS[id as FieldFormatId] ?? null;\n}\n\n/**\n * The format a column gets when it declares none — the identity format for its\n * storage type. Every existing column therefore behaves exactly as before.\n */\nexport function defaultFormatForBase(base: string): FieldFormatId {\n  switch (base as FieldBaseType) {\n    case \"number\":\n      return \"number\";\n    case \"integer\":\n      return \"integer\";\n    case \"boolean\":\n      return \"boolean\";\n    case \"date\":\n      return \"date\";\n    case \"datetime\":\n      return \"datetime\";\n    case \"json\":\n      return \"json\";\n    case \"array\":\n      return \"array\";\n    default:\n      return \"text\";\n  }\n}\n\n/** Formats that can legally sit on a given storage type. */\nexport function formatsForBase(base: string): FieldFormatDef[] {\n  return DEFS.filter(\n    (d) => d.base === base || (d.alsoAccepts ?? []).includes(base as FieldBaseType),\n  );\n}\n\n/** Group the pickable formats for a base type, preserving registry order. */\nexport function groupedFormatsForBase(\n  base: string,\n): { group: FieldFormatDef[\"group\"]; formats: FieldFormatDef[] }[] {\n  const out: { group: FieldFormatDef[\"group\"]; formats: FieldFormatDef[] }[] =\n    [];\n  for (const def of formatsForBase(base)) {\n    const bucket = out.find((g) => g.group === def.group);\n    if (bucket) bucket.formats.push(def);\n    else out.push({ group: def.group, formats: [def] });\n  }\n  return out;\n}\n","// The ZONE every moment is shown in: the person's saved time zone (IANA), set once by the host.\n//\n// A stored instant (`2026-11-03T00:30:00Z`) has no zone of its own; the screen picks one. Until\n// 2026-10-20 it was always the device's, so a person who saved Asia/Tokyo in Settings still read\n// \"Nov 2, 4:30 PM\" on a Los Angeles laptop. This is the ONE slot the date-and-time formats, the\n// table's display text and every consumer of them read. A bare calendar date (\"2026-11-02\") is a\n// day on a calendar, not an instant, and is never moved by any zone (see `momentZoneOptions`).\n//\n// A GLOBAL SLOT, never a module `let`: this file is bundled into more than one entry, and a module\n// `let` would give each copy its own zone (kit global-slot doctrine; see `setColorRuleTimeZone`).\n\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\nconst slot = globalSlot<{ zone: string | null }>(\"ai-matrx.design-system.display-time-zone\", () => ({ zone: null }));\n\n/** The person's zone (IANA) for every moment shown. Unset or junk, the device's own zone applies. */\nexport function setDisplayTimeZone(zone: string | null | undefined): void {\n  if (!zone || !zone.trim()) {\n    slot.zone = null;\n    return;\n  }\n  try {\n    new Intl.DateTimeFormat(\"en-US\", { timeZone: zone });\n    slot.zone = zone;\n  } catch {\n    slot.zone = null;\n  }\n}\n\nexport function getDisplayTimeZone(): string | null {\n  return slot.zone;\n}\n\n/**\n * A bare calendar day, or a time written with no zone at all (\"2026-11-02T16:30\"): a wall clock the\n * writer meant as it reads, never an instant, so no zone moves it. An instant carries `Z` or an offset.\n */\nconst WALL_CLOCK = /^\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?$/;\n\n/**\n * The `timeZone` option to print `value` with: the person's zone for an instant (a Date, an epoch\n * number, a string that names a time of day), nothing for a calendar day or a zoneless wall clock so it reads\n * the same everywhere.\n */\nexport function momentZoneOptions(value: unknown): { timeZone?: string } {\n  const zone = slot.zone;\n  if (!zone) return {};\n  if (typeof value === \"string\" && WALL_CLOCK.test(value.trim())) return {};\n  return { timeZone: zone };\n}\n","/**\n * DESIGN-TOKEN VALUES — the pure half of the four plug-in looks a column can wear\n * (`color_pair`, `measure`, `type_style`, `shadow`).\n *\n * Each structured look is kept in a TEXT column as JSON text, so stripping the look leaves a\n * readable string and nothing to migrate (the fallback law). These readers accept the object\n * itself or its JSON text, and answer `null` when the value is not that shape — never a throw.\n *\n * No React, no DOM: the record grid, the section card, a server render and an agent's summary\n * all read the same answer.\n */\n\nimport { isHexColor } from \"@ai-matrx/kit/color-util\";\n\nfunction objectOf(value: unknown): Record<string, unknown> | null {\n  if (value && typeof value === \"object\" && !Array.isArray(value)) return value as Record<string, unknown>;\n  if (typeof value !== \"string\") return null;\n  const text = value.trim();\n  if (!text.startsWith(\"{\")) return null;\n  try {\n    const parsed = JSON.parse(text) as unknown;\n    return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null;\n  } catch {\n    return null;\n  }\n}\n\nfunction num(value: unknown): number | null {\n  if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n  if (typeof value === \"string\" && value.trim() !== \"\") {\n    const n = Number(value.trim());\n    return Number.isFinite(n) ? n : null;\n  }\n  return null;\n}\n\n/** \"#abc\" → \"#aabbcc\"; an 8-digit hex keeps its alpha. Lower case. Null when not a hex. */\nexport function normalizeHex(value: unknown): string | null {\n  if (!isHexColor(value)) return null;\n  const t = value.trim().toLowerCase();\n  if (t.length === 4) return `#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`;\n  return t;\n}\n\n// ── Color pair ───────────────────────────────────────────────────────────────\n\n/** A color for each theme. `dark` absent = the dark theme uses the light color. */\nexport interface ColorPair {\n  light: string;\n  dark?: string;\n  /**\n   * The contrast this color must reach on what it is read on, when it is not text: 3 for a line, a field\n   * outline or a focus ring (WCAG 1.4.11). Absent = text, 4.5. Data on the row, so every checker agrees.\n   */\n  min?: number;\n}\n\n/** The contrast a text color needs (WCAG 1.4.3 AA). */\nexport const TEXT_CONTRAST = 4.5;\n\n/** A color pair, or a plain hex read as a light color that dark inherits. */\nexport function readColorPair(value: unknown): ColorPair | null {\n  if (isHexColor(value)) return { light: normalizeHex(value)! };\n  const obj = objectOf(value);\n  if (!obj) return null;\n  const light = normalizeHex(obj[\"light\"]);\n  if (!light) return null;\n  const dark = normalizeHex(obj[\"dark\"]);\n  const min = typeof obj[\"min\"] === \"number\" && obj[\"min\"] >= 1 && obj[\"min\"] <= 21 ? obj[\"min\"] : undefined;\n  return { light, ...(dark ? { dark } : {}), ...(min !== undefined ? { min } : {}) };\n}\n\nexport function colorPairText(pair: ColorPair): string {\n  return pair.dark ? `${pair.light} / ${pair.dark}` : pair.light;\n}\n\nfunction channel(c: number): number {\n  const s = c / 255;\n  return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n}\n\n/** WCAG relative luminance of a hex color (alpha ignored). */\nexport function relativeLuminance(hex: string): number | null {\n  const h = normalizeHex(hex);\n  if (!h) return null;\n  const r = parseInt(h.slice(1, 3), 16);\n  const g = parseInt(h.slice(3, 5), 16);\n  const b = parseInt(h.slice(5, 7), 16);\n  return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);\n}\n\n/**\n * WCAG contrast ratio of two hex colors, 1–21, ROUNDED DOWN to one decimal — so a pair that\n * misses 4.5:1 (4.46) never reads as 4.5 and passes. Null when either is not a color.\n */\nexport function contrastRatio(a: string, b: string): number | null {\n  const la = relativeLuminance(a);\n  const lb = relativeLuminance(b);\n  if (la === null || lb === null) return null;\n  const [hi, lo] = la > lb ? [la, lb] : [lb, la];\n  return Math.floor(((hi + 0.05) / (lo + 0.05)) * 10 + 1e-9) / 10;\n}\n\n/** The WCAG levels a ratio clears: 4.5 for body text, 3 for large text and controls. */\n/** How a ratio reads against the minimum it must reach (a pair's `min`, else text's 4.5). */\nexport function contrastLevel(ratio: number, min: number = TEXT_CONTRAST): \"pass\" | \"large-only\" | \"fail\" {\n  if (ratio >= min) return \"pass\";\n  if (min > 3 && ratio >= 3) return \"large-only\";\n  return \"fail\";\n}\n\n// ── Measure ───────────────────────────────────────────────────────────────────\n\nexport const MEASURE_UNITS = [\"px\", \"rem\", \"em\", \"%\", \"pt\", \"ms\", \"s\", \"deg\"] as const;\nexport type MeasureUnit = (typeof MEASURE_UNITS)[number];\n\n/** What a measure's picture draws: two boxes this far apart, a corner this round, a bar this long. */\nexport const MEASURE_PREVIEWS = [\"spacing\", \"radius\", \"size\", \"border\", \"none\"] as const;\nexport type MeasurePreview = (typeof MEASURE_PREVIEWS)[number];\n\n// ── Type style ────────────────────────────────────────────────────────────────\n\nexport interface TypeStyle {\n  font: string;\n  /** 100–900. */\n  weight: number;\n  /** px. */\n  size: number;\n  /** px. */\n  lineHeight?: number;\n  /** em. */\n  letterSpacing?: number;\n  italic?: boolean;\n}\n\nexport const TYPE_WEIGHTS: readonly { value: number; label: string }[] = [\n  { value: 100, label: \"Thin\" },\n  { value: 200, label: \"Extra light\" },\n  { value: 300, label: \"Light\" },\n  { value: 400, label: \"Regular\" },\n  { value: 500, label: \"Medium\" },\n  { value: 600, label: \"Semibold\" },\n  { value: 700, label: \"Bold\" },\n  { value: 800, label: \"Extra bold\" },\n  { value: 900, label: \"Black\" },\n];\n\nexport function weightLabel(weight: number): string {\n  return TYPE_WEIGHTS.find((w) => w.value === weight)?.label ?? String(weight);\n}\n\nexport function readTypeStyle(value: unknown): TypeStyle | null {\n  const obj = objectOf(value);\n  if (!obj) return null;\n  const font = typeof obj[\"font\"] === \"string\" && obj[\"font\"].trim() !== \"\" ? obj[\"font\"].trim() : null;\n  const size = num(obj[\"size\"]);\n  if (!font || size === null || size <= 0) return null;\n  const weight = num(obj[\"weight\"]) ?? 400;\n  const lineHeight = num(obj[\"lineHeight\"]);\n  const letterSpacing = num(obj[\"letterSpacing\"]);\n  return {\n    font,\n    weight,\n    size,\n    ...(lineHeight !== null && lineHeight > 0 ? { lineHeight } : {}),\n    ...(letterSpacing !== null ? { letterSpacing } : {}),\n    ...(obj[\"italic\"] === true ? { italic: true } : {}),\n  };\n}\n\n/** \"Geist · 40\" — the chip under a type sample. */\nexport function typeStyleText(style: TypeStyle): string {\n  const parts = [style.font, style.weight === 400 ? null : weightLabel(style.weight), String(style.size)];\n  return parts.filter(Boolean).join(\" · \");\n}\n\n/** The CSS a sample is drawn in (React style keys). */\nexport function typeStyleCss(style: TypeStyle): Record<string, string | number> {\n  return {\n    // The named font first, then a generic of its kind, so an uninstalled font reads as a sans or a\n    // mono — never the browser's default serif.\n    // A stored stack (\"Inter, sans-serif\") is used as written.\n    fontFamily: style.font.includes(\",\")\n      ? style.font\n      : `\"${style.font.replace(/\"/g, \"\")}\", ${/mono|code|consol|courier/i.test(style.font) ? \"ui-monospace, monospace\" : \"ui-sans-serif, system-ui, sans-serif\"}`,\n    fontWeight: style.weight,\n    fontSize: `${style.size}px`,\n    ...(style.lineHeight ? { lineHeight: `${style.lineHeight}px` } : {}),\n    ...(style.letterSpacing !== undefined ? { letterSpacing: `${style.letterSpacing}em` } : {}),\n    ...(style.italic ? { fontStyle: \"italic\" } : {}),\n  };\n}\n\n// ── Shadow ────────────────────────────────────────────────────────────────────\n\nexport interface ShadowLayer {\n  x: number;\n  y: number;\n  blur: number;\n  spread: number;\n  /** Hex with optional alpha (\"#0000001a\"). */\n  color: string;\n  inset?: boolean;\n}\n\nexport function readShadow(value: unknown): ShadowLayer[] | null {\n  const parse = (o: Record<string, unknown>): ShadowLayer | null => {\n    const color = normalizeHex(o[\"color\"]);\n    const x = num(o[\"x\"]) ?? 0;\n    const y = num(o[\"y\"]) ?? 0;\n    const blur = num(o[\"blur\"]) ?? 0;\n    const spread = num(o[\"spread\"]) ?? 0;\n    if (!color) return null;\n    return { x, y, blur, spread, color, ...(o[\"inset\"] === true ? { inset: true } : {}) };\n  };\n  const obj = objectOf(value);\n  if (obj && Array.isArray(obj[\"layers\"])) {\n    const layers = (obj[\"layers\"] as unknown[]).map((l) => (l && typeof l === \"object\" ? parse(l as Record<string, unknown>) : null));\n    return layers.length > 0 && layers.every(Boolean) ? (layers as ShadowLayer[]) : null;\n  }\n  if (obj) {\n    const one = parse(obj);\n    return one ? [one] : null;\n  }\n  return null;\n}\n\nexport function shadowCss(layers: readonly ShadowLayer[]): string {\n  return layers\n    .map((l) => `${l.inset ? \"inset \" : \"\"}${l.x}px ${l.y}px ${l.blur}px ${l.spread}px ${l.color}`)\n    .join(\", \");\n}\n\n/** A shadow per theme: `{light, dark}` (each one layer or `{layers}`), or one shadow for both. */\nexport function readShadowPair(value: unknown): { light: ShadowLayer[]; dark: ShadowLayer[] } | null {\n  const obj = objectOf(value);\n  if (obj && (\"light\" in obj || \"dark\" in obj)) {\n    const light = readShadow(obj[\"light\"]);\n    if (!light) return null;\n    const dark = obj[\"dark\"] === undefined || obj[\"dark\"] === null ? light : readShadow(obj[\"dark\"]);\n    return dark ? { light, dark } : null;\n  }\n  const one = readShadow(value);\n  return one ? { light: one, dark: one } : null;\n}\n\n// ── Opacity ───────────────────────────────────────────────────────────────────\n\n/** An opacity 0–1 (\"0.035\", 0.5; \"50%\" reads as 0.5). Null when it is not one. */\nexport function readOpacity(value: unknown): number | null {\n  if (typeof value === \"string\" && value.trim().endsWith(\"%\")) {\n    const n = num(value.trim().slice(0, -1));\n    return n === null || n < 0 || n > 100 ? null : n / 100;\n  }\n  const n = num(value);\n  return n === null || n < 0 || n > 1 ? null : n;\n}\n\n// ── Motion ────────────────────────────────────────────────────────────────────\n\nexport interface Motion {\n  /** ms. */\n  duration: number;\n  /** A CSS easing: a keyword or cubic-bezier(…). */\n  easing: string;\n}\n\nexport const MOTION_EASINGS: readonly { value: string; label: string }[] = [\n  { value: \"linear\", label: \"Linear\" },\n  { value: \"ease\", label: \"Ease\" },\n  { value: \"ease-in\", label: \"Ease in\" },\n  { value: \"ease-out\", label: \"Ease out\" },\n  { value: \"ease-in-out\", label: \"Ease in-out\" },\n  { value: \"cubic-bezier(0.2, 0, 0, 1)\", label: \"Emphasized\" },\n];\n\nconst EASING = /^(?:linear|ease|ease-in|ease-out|ease-in-out|step-start|step-end|cubic-bezier\\(\\s*-?[\\d.]+\\s*,\\s*-?[\\d.]+\\s*,\\s*-?[\\d.]+\\s*,\\s*-?[\\d.]+\\s*\\))$/;\n\nexport function readMotion(value: unknown): Motion | null {\n  const obj = objectOf(value);\n  if (!obj) return null;\n  const duration = num(obj[\"duration\"]);\n  const easing = typeof obj[\"easing\"] === \"string\" ? obj[\"easing\"].trim() : \"ease\";\n  if (duration === null || duration < 0 || !EASING.test(easing)) return null;\n  return { duration, easing };\n}\n\nexport function motionText(m: Motion): string {\n  const named = MOTION_EASINGS.find((e) => e.value === m.easing)?.label ?? m.easing;\n  return `${m.duration} ms · ${named}`;\n}\n\n/** A shadow in words: \"4px · 12px blur\" for one layer, \"2 layers\" for more. */\nexport function shadowWords(layers: readonly ShadowLayer[]): string {\n  return layers.length === 1 ? `${layers[0]!.y}px · ${layers[0]!.blur}px blur` : `${layers.length} layers`;\n}\n","/**\n * THE FALLBACK LAW, implemented.\n *\n * `formatFieldValue` never blanks a cell and never throws. When the declared\n * format cannot interpret the stored value it returns `ok: false` with the\n * **base-type** rendering of that same value plus a human `reason`. The UI\n * renders that text in amber (see `<FormattedFieldValue>`), so a mismatch is\n * visible instead of invisible.\n */\nimport {\n  defaultFormatForBase,\n  getFieldFormat,\n  FIELD_FORMATS,\n} from \"./registry\";\nimport type {\n  FieldFormatConfig,\n  FieldFormatOptions,\n  FormatResult,\n} from \"./types\";\n\nfunction isEmpty(value: unknown): boolean {\n  return value === null || value === undefined || value === \"\";\n}\n\n/** Last-resort rendering — the raw value, readable, never empty-by-accident. */\nfunction baseText(value: unknown): string {\n  if (isEmpty(value)) return \"\";\n  if (typeof value === \"object\") {\n    try {\n      return JSON.stringify(value);\n    } catch {\n      return String(value);\n    }\n  }\n  return String(value);\n}\n\n/**\n * Read a field's declared format off its `metadata` JSONB. Returns null when\n * the field declares none (or declares one we don't know) — the caller then\n * falls back to the storage type's identity format, so an unknown or removed\n * format id degrades to plain, never to broken.\n */\nexport function readFieldFormatConfig(\n  metadata: unknown,\n): FieldFormatConfig | null {\n  if (!metadata || typeof metadata !== \"object\") return null;\n  const raw = (metadata as Record<string, unknown>).format;\n  if (!raw || typeof raw !== \"object\") return null;\n  const id = (raw as Record<string, unknown>).id;\n  if (typeof id !== \"string\" || !getFieldFormat(id)) return null;\n  const options = (raw as Record<string, unknown>).options;\n  // `exactOptionalPropertyTypes`: an absent `options` is the key being ABSENT,\n  // never the key holding `undefined` — the two are different documents once\n  // this config is written back out as JSON.\n  return {\n    id: id as FieldFormatConfig[\"id\"],\n    ...(options && typeof options === \"object\"\n      ? { options: options as FieldFormatOptions }\n      : {}),\n  };\n}\n\n/**\n * Resolve the format a field actually renders with: its declared one, or the\n * identity format for its storage type.\n */\nexport function resolveFieldFormat(\n  dataType: string,\n  metadata: unknown,\n): FieldFormatConfig {\n  const declared = readFieldFormatConfig(metadata);\n  if (declared) return declared;\n  return { id: defaultFormatForBase(dataType) };\n}\n\nexport function formatFieldValue(\n  value: unknown,\n  config: FieldFormatConfig | null | undefined,\n  /** The column's storage type — used for the fallback rendering. */\n  dataType?: string,\n): FormatResult {\n  if (isEmpty(value)) return { ok: true, text: \"\", empty: true };\n\n  const def = config ? getFieldFormat(config.id) : null;\n  const effective =\n    def ?? FIELD_FORMATS[defaultFormatForBase(dataType ?? \"string\")];\n\n  let formatted: string | null;\n  try {\n    formatted = effective.format(value, config?.options ?? {});\n  } catch {\n    formatted = null;\n  }\n\n  if (formatted !== null) return { ok: true, text: formatted, empty: false };\n\n  // Mismatch. Show what IS stored, flagged.\n  return {\n    ok: false,\n    text: baseText(value),\n    empty: false,\n    reason: `This value is not a valid ${effective.label.toLowerCase()} — showing the stored value instead.`,\n  };\n}\n\n/** Turn raw editor input into the value to store under a format. */\nexport function parseFieldInput(\n  raw: unknown,\n  config: FieldFormatConfig | null | undefined,\n  dataType?: string,\n): unknown {\n  const def = config ? getFieldFormat(config.id) : null;\n  const effective =\n    def ?? FIELD_FORMATS[defaultFormatForBase(dataType ?? \"string\")];\n  try {\n    return effective.parse(raw, config?.options ?? {});\n  } catch {\n    return raw;\n  }\n}\n\n/**\n * Would this stored value survive its declared format? Used to count mismatches\n * so a column can warn (\"4 values don't fit Currency\") instead of silently\n * showing amber cells.\n */\nexport function valueFitsFormat(\n  value: unknown,\n  config: FieldFormatConfig | null | undefined,\n  dataType?: string,\n): boolean {\n  return formatFieldValue(value, config, dataType).ok;\n}\n","// src/core/io.ts — @ai-matrx/records\n//\n// DOOR-11. CSV and XLSX, import and export — headless: bytes in, bytes out, no\n// `document`, no `Blob`, no download. The browser half (the anchor click, the\n// object URL) already exists and is not duplicated here: the design system's\n// `@ai-matrx/design-system/data-table/xlsx` owns it, and `records-ui` hands\n// these bytes to it.\n//\n// The column selection and the cell stringification are the SAME ones the\n// canonical table's CSV export uses (`rowsToCsvFromColumns` in that package):\n// same quoting rule (THE one writer, `@ai-matrx/kit/delimited`, formula-guarded), same header\n// row, same order. Two independent row builders\n// is how a user's CSV and their Excel file start disagreeing.\n//\n// DOOR-4 is why export takes READ VALUES rather than raw rows: exports store\n// only what the reading principal may see, and a ReadValue is what came back\n// THROUGH the read door. Handing this function a row it read around the door\n// would be the leak DOOR-4 forbids, and there is no overload that accepts one.\n\nimport { formatFieldValue, getFieldFormat, type FieldFormatOptions } from \"@ai-matrx/design-system/field-formats\";\nimport { parseDelimited, toDelimited } from \"@ai-matrx/kit/delimited\";\nimport { newerKindExportWords } from \"../newerKinds\";\nimport type { Field } from \"../field\";\nimport type { ReadValue } from \"../record\";\nimport { wholeValueNotRead, wholeValueOfRead } from \"./wholeValue\";\n\n/** One exportable row: the values of one record, keyed by field key. */\nexport type ExportRow = Record<string, ReadValue | undefined>;\n\n/**\n * The same stringification: a string stays itself, everything else becomes its\n * JSON, and an absent value becomes the store's own absence WORD rather than an\n * empty cell. A blank cell would be the silent failure VAL-2 exists to prevent —\n * \"we never asked\" and \"they refused\" are different facts and the export says\n * which.\n */\nexport function cellText(value: ReadValue | undefined): string {\n  if (!value) return \"\";\n  if (value.absent_reason) return `(${value.absent_reason})`;\n  const raw = value.value;\n  if (raw === null || raw === undefined) return \"\";\n  // A value kept as a file that nobody read for this export: its words and where the rest is.\n  const pointer = wholeValueOfRead(value);\n  if (pointer && typeof raw === \"string\") return wholeValueNotRead(raw, pointer);\n  if (typeof raw === \"string\") return raw;\n  return JSON.stringify(raw);\n}\n\n/**\n * ONE CELL OF ONE COLUMN (lane 10 P4): the column's own words for a value whose stored shape is not\n * what a person reads — an address on one line, a length of time as h:mm, who made a record by\n * name. Every other value is `cellText`'s.\n */\nexport function exportCellText(field: Field, value: ReadValue | undefined): string {\n  if (value && !value.absent_reason && value.value !== null && value.value !== undefined) {\n    const words = newerKindExportWords(field, value.value);\n    if (words !== null) return words;\n    const looked = designLookWords(field, value.value);\n    if (looked !== null) return looked;\n  }\n  return cellText(value);\n}\n\n/**\n * A DESIGN-TOKEN LOOK (color pair, size, type style, shadow — design-system `group: \"Design\"`) is\n * kept as JSON text or a bare number; a sheet gets its words (\"#ffffff / #0b0c0e\", \"16 px\"). A value\n * that does not fit its look is exported as stored. Null: not a design look.\n */\nexport function designLookWords(field: Field, value: unknown): string | null {\n  const raw = (field as unknown as { display_format?: { id?: unknown; options?: unknown } }).display_format;\n  const def = typeof raw?.id === \"string\" ? getFieldFormat(raw.id) : null;\n  if (!def || def.group !== \"Design\") return null;\n  const read = formatFieldValue(value, { id: def.id, ...(raw?.options && typeof raw.options === \"object\" ? { options: raw.options as FieldFormatOptions } : {}) });\n  return read.ok && !read.empty ? read.text : null;\n}\n\nfunction headerFor(field: Field): string {\n  return field.label && field.label.length > 0 ? field.label : field.key;\n}\n\n/** CSV through THE one writer (kit `toDelimited`; spreadsheet-safe by default). */\nexport function exportCsv(fields: Field[], rows: ExportRow[]): string {\n  return toDelimited(toAoa(fields, rows));\n}\n\n/**\n * MARKDOWN: the same header row and the same cells as CSV and XLSX (`toAoa`), written as a pipe table — pasteable into a\n * note, an issue or a chat. A `|` in a cell is escaped, a line break becomes `<br>`, and an empty cell stays empty.\n * No column, no table: a table with no columns is the empty string.\n */\nexport function exportMarkdown(fields: Field[], rows: ExportRow[]): string {\n  if (fields.length === 0) return \"\";\n  const cell = (text: string) => text.replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \"<br>\").trim();\n  const [head, ...body] = toAoa(fields, rows);\n  const line = (cells: string[]) => `| ${cells.map(cell).join(\" | \")} |`;\n  return [line(head ?? []), `| ${fields.map(() => \"---\").join(\" | \")} |`, ...body.map(line)].join(\"\\n\") + \"\\n\";\n}\n\n/** The header row plus every cell, as the sheet writer takes it. */\nexport function toAoa(fields: Field[], rows: ExportRow[]): string[][] {\n  return [fields.map(headerFor), ...rows.map((row) => fields.map((f) => exportCellText(f, row[f.key])))];\n}\n\n/**\n * The XLSX bytes, through Alchemy's one workbook engine. The import is dynamic so\n * a consumer that only ever exports CSV never pays for the library — the design-system module is loaded\n * the same way, and for the same reason.\n */\nexport async function exportXlsx(\n  fields: Field[],\n  rows: ExportRow[],\n  sheetLabel = \"Records\",\n): Promise<Uint8Array> {\n  const { writeWorkbookBytes } = await import(\"@ai-matrx/print/xlsx\");\n  const name = sheetLabel.replace(/[\\\\/?*[\\]:]/g, \" \").trim().slice(0, 31) || \"Data\";\n  // A number is a number cell (the rail's workbook says the same through records-ui `fileXlsx`); every other cell is the words the CSV carries.\n  const words = toAoa(fields, rows);\n  const sheet = words.map((line, at) =>\n    at === 0\n      ? line\n      : line.map((text, col) => {\n          const stored = rows[at - 1]?.[fields[col]!.key]?.value;\n          return typeof stored === \"number\" && Number.isFinite(stored) && !rows[at - 1]?.[fields[col]!.key]?.absent_reason ? stored : text;\n        }),\n  );\n  return writeWorkbookBytes({ sheets: [{ name, rows: sheet }] });\n}\n\n/**\n * A PARSED FILE, AND NOTHING ELSE: its headings, and every row keyed by them.\n *\n * 🚨 THERE IS NO `field`, NO `unmapped` AND NO WAY TO ASK FOR ONE, and that is\n * the point. Until 2026-09-20 this parse ALSO decided which Field each heading\n * meant — it took `fields`, matched each header by key or label, keyed the rows\n * by whatever it matched, and **dropped every column it did not**. That cannot\n * be the input to `custom.io_import_plan` / `custom.io_import_rows`, whose whole\n * job is to decide the mapping and to OFFER what they could not match as a new\n * column: the store can only offer a column whose values reached it.\n *\n * Measured by looking at the screen: every unmapped column's samples came back\n * empty and its proposal read \"every row in this column is empty, so there is\n * nothing to go on\" — for columns plainly full of values.\n *\n * The fix is the SHAPE, not a second field beside the first. These functions no\n * longer take `fields`, so a parse cannot decide a mapping even by accident, and\n * there is no safe path left beside the unsafe one.\n */\nexport interface ParsedImport {\n  /** The file's own headings, in the file's own order and spelling. */\n  headers: string[];\n  /** Every row, keyed by heading. Every column is here; nothing is dropped. */\n  rows: Array<Record<string, string>>;\n}\n\n/** Comma-separated text as rows — THE one reader (kit `parseDelimited`), quotes and embedded newlines included. */\nexport function parseCsv(text: string): string[][] {\n  return parseDelimited(text, { delimiter: \",\", skipEmptyLines: true }).data;\n}\n\nexport function importCsv(text: string): ParsedImport {\n  return fromMatrix(parseCsv(text));\n}\n\nexport async function importXlsx(bytes: ArrayBuffer | Uint8Array): Promise<ParsedImport> {\n  const { readWorkbookBytes: readWorkbook } = await import(\"@ai-matrx/print/xlsx\");\n  const sheet = (await readWorkbook(bytes)).sheets[0];\n  if (!sheet) return { headers: [], rows: [] };\n  return fromMatrix(sheet.grid({ raw: false, defval: \"\" }) as string[][]);\n}\n\nfunction fromMatrix(matrix: string[][]): ParsedImport {\n  const [header, ...body] = matrix;\n  if (!header) return { headers: [], rows: [] };\n  // A heading that repeats (\"Phone, Phone\") is kept under \"Phone\" and \"Phone (2)\": rows are keyed by\n  // heading, so the second column would otherwise overwrite the first and its values vanish unseen.\n  const seen = new Map<string, number>();\n  const headers = header.map((text) => {\n    const heading = String(text ?? \"\").replace(/^\\uFEFF/, \"\");\n    if (heading.trim().length === 0) return heading;\n    const n = (seen.get(heading) ?? 0) + 1;\n    seen.set(heading, n);\n    return n === 1 ? heading : `${heading} (${n})`;\n  });\n  const rows = body\n    .filter((line) => line.some((cell) => String(cell ?? \"\").trim().length > 0))\n    .map((line) => {\n      const record: Record<string, string> = {};\n      headers.forEach((heading, index) => {\n        if (heading.trim().length > 0) record[heading] = String(line[index] ?? \"\");\n      });\n      return record;\n    });\n  return { headers, rows };\n}\n","// src/core/wholeValue.ts — @ai-matrx/records\n//\n// A VALUE TOO BIG FOR ONE CELL LIVES IN A FILE, AND THE CELL POINTS AT IT.\n//\n// The store refuses one value over `custom/value_max_bytes` in its own words: \"Put the big thing\n// in a file record and point the value at it.\" The mover does exactly that (Python:\n// `matrx_records.big_values`): the whole text becomes a file of the same organization, the cell\n// keeps the FIRST CHARACTERS as its display words, and the cell's envelope `src` names a\n// provenance entry of kind `whole_value_in_file` that says which file, which File record, how\n// big, and the SHA-256 of the whole text.\n//\n// This is the reading half, ONE place: a screen asks `wholeValueOf` and shows the words with a\n// way to open the file; an export asks `withWholeValues` and writes the file's content, never the\n// words. A cell whose whole text could not be read says so in the file — never the words passed\n// off as the value.\n\nimport { formatFileSize } from \"@ai-matrx/kit/format\";\n\nimport type { RecordDocument, ReadValue, Uuid } from \"../record\";\nimport type { ExportRow } from \"./io\";\n\n/** The provenance kind a pointer cell's source carries. The Python side's `SOURCE_KIND`. */\nexport const WHOLE_VALUE_SOURCE_KIND = \"whole_value_in_file\";\n\n/** What a pointer cell's provenance entry says about the file holding its whole text. */\nexport interface WholeValuePointer {\n  kind: typeof WHOLE_VALUE_SOURCE_KIND;\n  /** The `files.files` id — what a host opens. */\n  file_id: Uuid;\n  /** The kernel File record carrying that file. */\n  file_record: Uuid;\n  /** The whole text's size, in UTF-8 bytes. */\n  bytes: number;\n  /** The whole text's length, in characters. */\n  chars: number;\n  sha256: string;\n  /** How many characters the cell itself holds (the display words). */\n  shown_chars: number;\n  mime?: string;\n  moved_from?: Record<string, unknown>;\n}\n\nfunction asPointer(source: unknown): WholeValuePointer | null {\n  if (!source || typeof source !== \"object\") return null;\n  const s = source as Record<string, unknown>;\n  if (s.kind !== WHOLE_VALUE_SOURCE_KIND || typeof s.file_id !== \"string\" || !s.file_id) return null;\n  return s as unknown as WholeValuePointer;\n}\n\n/** The pointer behind `document[key]`, or null when the cell holds its whole value. */\nexport function wholeValueOf(document: RecordDocument | null | undefined, key: string): WholeValuePointer | null {\n  if (!document) return null;\n  const envelope = (document._values ?? {})[key] as { src?: string | null } | undefined;\n  const pointer = envelope?.src;\n  if (typeof pointer !== \"string\") return null;\n  return asPointer((document._sources ?? {})[pointer as keyof typeof document._sources]);\n}\n\n/** The same question of a value read through the door (its `source` is the resolved entry). */\nexport function wholeValueOfRead(value: ReadValue | null | undefined): WholeValuePointer | null {\n  return asPointer(value?.source ?? null);\n}\n\n/** A size a person reads: \"728 KB\". */\nexport function wholeValueSize(pointer: WholeValuePointer): string {\n  return formatFileSize(pointer.bytes);\n}\n\n/**\n * The words an export writes for a pointer cell whose file could NOT be read: the display words,\n * then one sentence saying the whole text is elsewhere and where. Never the words alone — a\n * reader of the file would take the first thousand characters for the whole value.\n */\nexport function wholeValueNotRead(words: string, pointer: WholeValuePointer, why?: string): string {\n  return (\n    `${words}… [This is the start of a ${wholeValueSize(pointer)} text kept as file ${pointer.file_id}` +\n    (why ? `; it could not be read for this export: ${why}` : \"\") +\n    \"]\"\n  );\n}\n\n/** How a host reads a file's whole text. The records package holds no bytes. */\nexport type ReadFileText = (fileId: Uuid) => Promise<string>;\n\n/**\n * THE EXPORT WRITES THE FILE'S CONTENT. Every pointer cell in `rows` (a ReadValue whose `source`\n * is a whole-value pointer) is replaced with the file's whole text, read once per file. A read that\n * fails, or no reader at all, writes the honest sentence of `wholeValueNotRead` instead.\n */\nexport async function withWholeValues(rows: ExportRow[], read?: ReadFileText | null): Promise<ExportRow[]> {\n  const texts = new Map<string, Promise<string>>();\n  const out: ExportRow[] = [];\n  for (const row of rows) {\n    const next: ExportRow = { ...row };\n    for (const [key, value] of Object.entries(row)) {\n      const pointer = wholeValueOfRead(value);\n      if (!pointer || !value) continue;\n      const words = typeof value.value === \"string\" ? value.value : \"\";\n      if (!read) {\n        next[key] = { ...value, value: wholeValueNotRead(words, pointer, \"this screen has no way to read files\"), source: null };\n        continue;\n      }\n      if (!texts.has(pointer.file_id)) texts.set(pointer.file_id, read(pointer.file_id));\n      try {\n        // The value IS the whole text now, so it no longer points anywhere.\n        next[key] = { ...value, value: await texts.get(pointer.file_id)!, source: null };\n      } catch (thrown) {\n        const why = thrown instanceof Error ? thrown.message : String(thrown);\n        next[key] = { ...value, value: wholeValueNotRead(words, pointer, why), source: null };\n      }\n    }\n    out.push(next);\n  }\n  return out;\n}\n","// src/core/seed.ts — A PAGE'S FIRST ANSWERS, ASKED ON THE SERVER, DRAWN IN THE SERVER'S HTML (lane SSR-ROWS).\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 the table's bundle and the grid's first page AS HER, and the\n// page is drawn — rows and all — in the HTML it sends. The browser hydrates onto those rows: it asks\n// nothing it was already told, and nothing moves.\n//\n// THE SHAPE: a seed is a list of door answers, each under the door's name and its exact arguments —\n// the same key `custom.table_page_bundle` parts already use (PAGE-BUNDLE). The server builds it by\n// asking through a RECORDING data source (`recordingDataSource`): every answer a door gave goes in, and\n// a bundle's parts are spread into answers of their own doors. The page hands the seed to\n// `<RecordsSeedProvider>` (`/react`); a hook rendering on the server, or hydrating in the browser, runs\n// its own door call against the seed (`seededDataSource`) and draws the answer in that first pass.\n//\n// IT NEVER TURNS A REFUSAL OR A MISS INTO \"EMPTY\": only answers a door GAVE are seeded (a refusing\n// bundle part, an error, a door the server did not ask: none of them), and a hook whose call asks a\n// single door the seed does not hold is NOT seeded at all — it draws \"loading\" in both passes and asks\n// for itself after hydration, exactly as before. No React here (server-safe).\n\nimport type { RecordsDataSource, RecordsTableQuery } from \"../ports\";\nimport type { PgError } from \"../results\";\nimport { canonicalArgs } from \"./doorCall\";\n\n/** One door's answer, under its exact arguments. Plain JSON: it crosses from server to browser. */\nexport interface RecordsSeedAnswer {\n  door: string;\n  args: Record<string, unknown>;\n  data: unknown;\n}\n\n/** What a server asked for a page, as the person, and when. */\nexport interface RecordsSeed {\n  /** Epoch ms when the server asked. */\n  at: number;\n  answers: RecordsSeedAnswer[];\n}\n\n/** The doors whose answer is a list of other doors' answers (PAGE-BUNDLE, PAGE-BUNDLE-2). */\nconst BUNDLE_DOORS = new Set([\"table_page_bundle\", \"record_page_bundle\"]);\n\n/** The match key: a door and every argument, keys sorted at every depth. */\nexport function seedKey(door: string, args: Record<string, unknown>): string {\n  return `${door}|${canonicalArgs(args)}`;\n}\n\n/** A door answer, and — for a bundle — each of its usable parts as the answer of its own door. */\nfunction answersOf(door: string, args: Record<string, unknown>, data: unknown): RecordsSeedAnswer[] {\n  const out: RecordsSeedAnswer[] = [{ door, args, data }];\n  if (!BUNDLE_DOORS.has(door) || !data || typeof data !== \"object\") return out;\n  const parts = (data as { parts?: unknown }).parts;\n  if (!Array.isArray(parts)) return out;\n  for (const part of parts as Array<{ door?: unknown; args?: unknown; data?: unknown; error?: unknown }>) {\n    // A refusing part is asked by its own door — never seeded as an answer.\n    if (part.error !== undefined || part.data === undefined) continue;\n    if (typeof part.door !== \"string\" || !part.args || typeof part.args !== \"object\") continue;\n    out.push({ door: part.door, args: part.args as Record<string, unknown>, data: part.data });\n  }\n  return out;\n}\n\n/**\n * A data source that asks `source` and keeps every answer a door GAVE (errors are not kept). For a\n * server render: create a records client over it, ask what the page will ask, then `seed()`.\n */\nexport function recordingDataSource(source: RecordsDataSource): { source: RecordsDataSource; seed: () => RecordsSeed } {\n  const kept = new Map<string, RecordsSeedAnswer>();\n  const recording: RecordsDataSource = {\n    ...(source.opensInOneCall ? { opensInOneCall: true } : {}),\n    rpc(fn, args, options) {\n      return Promise.resolve(source.rpc(fn, args, options)).then((answer) => {\n        // `custom` (the record store) and `platform` (the entity and drill doors) are both served by name.\n        const schema = options?.schema ?? \"custom\";\n        if (!answer.error && (schema === \"custom\" || schema === \"platform\")) {\n          for (const a of answersOf(fn, args, answer.data)) kept.set(seedKey(a.door, a.args), a);\n        }\n        return answer;\n      });\n    },\n    schema: (name) => source.schema(name),\n  };\n  return { source: recording, seed: () => ({ at: Date.now(), answers: [...kept.values()] }) };\n}\n\n/** The seed as a lookup, built once per seed. */\nexport function seedIndex(seed: RecordsSeed): Map<string, unknown> {\n  const index = new Map<string, unknown>();\n  for (const a of seed.answers) {\n    for (const spread of answersOf(a.door, a.args, a.data)) index.set(seedKey(spread.door, spread.args), spread.data);\n  }\n  return index;\n}\n\nconst MISS: PgError = { code: \"SEED_MISS\", message: \"Not in the page's seed.\", details: null, hint: null } as unknown as PgError;\n\n/** A table read the seed cannot answer: every builder call returns itself, and awaiting it is a miss. */\nfunction missingQuery(onMiss: () => void): RecordsTableQuery {\n  const answer = () => {\n    onMiss();\n    return Promise.resolve({ data: null, error: MISS, count: null });\n  };\n  const chain: unknown = new Proxy(function () {}, {\n    get(_target, prop) {\n      if (prop === \"then\") return (ok: (v: unknown) => unknown, bad?: (e: unknown) => unknown) => answer().then(ok, bad);\n      return () => chain;\n    },\n    apply: () => chain,\n  });\n  return { select: () => chain } as unknown as RecordsTableQuery;\n}\n\n/**\n * ONE RUN AGAINST THE SEED: a data source answering from `index` only, and whether the run asked a\n * door the seed does not hold. It never opens a bundle itself (`opensInOneCall` off): the bundle's\n * parts are already answers in the index.\n */\nexport function seededDataSource(index: Map<string, unknown>): { source: RecordsDataSource; missed: () => boolean } {\n  let missed = false;\n  const source: RecordsDataSource = {\n    rpc(fn, args) {\n      const key = seedKey(fn, args);\n      if (index.has(key)) return Promise.resolve({ data: index.get(key), error: null });\n      missed = true;\n      return Promise.resolve({ data: null, error: MISS });\n    },\n    schema: () => ({ from: () => missingQuery(() => (missed = true)) }),\n  };\n  return { source, missed: () => missed };\n}\n","// src/core/table-logic.ts — the table owner's pure logic (HEADLESS: no React, no DOM, no network).\n//\n// Moved from matrx-frontend `features/data-tables` (W1-G2b, owner ruling 2026-10-16): the column and\n// row shapes the grid draws, the bulk-write op shapes and their guards, the service-result envelope,\n// and the two pure rules every importer shares (a value's data type; a display name's field key).\n// matrx-frontend `features/data-tables/types` re-exports these names; there is one definition.\n// `getTableMetadata` stays an app seam (it needs the app's table-home lookup) and is NOT here.\n\nimport type { RecordsError } from \"../results\";\n\n/** A database JSON column. Nothing is assumed about it; a reader narrows what it reads. */\nexport type Json = unknown;\n\n/** `public.field_data_type`. */\nexport type FieldDataType = \"string\" | \"number\" | \"integer\" | \"boolean\" | \"date\" | \"datetime\" | \"json\" | \"array\";\n\n/** A column as the grid draws it. */\nexport type DatasetField = {\n  id: string;\n  table_id: string;\n  field_name: string;\n  display_name: string;\n  data_type: FieldDataType;\n  field_order: number;\n  is_required: boolean;\n  is_public: boolean;\n  default_value: Json | null;\n  validation_rules: Json | null;\n  metadata: Json;\n  custom_fields: Json;\n  organization_id: string;\n  user_id: string;\n  created_at: string;\n  created_by: string | null;\n  updated_at: string;\n  updated_by: string | null;\n  deleted_at: string | null;\n  version: number;\n};\n\n/** A row as the grid holds it. */\nexport type DatasetRow = {\n  id: string;\n  table_id: string;\n  data: Json;\n  metadata: Json;\n  custom_fields: Json;\n  is_public: boolean;\n  organization_id: string;\n  user_id: string;\n  source_row_ref: string | null;\n  created_at: string;\n  created_by: string | null;\n  updated_at: string;\n  updated_by: string | null;\n  deleted_at: string | null;\n  version: number;\n};\n\n\n// ─── Bulk-write op shapes ───────────────────────────────────────────────────\n\nexport type BulkInsertOp = {\n  op: \"insert\";\n  data: Record<string, unknown>;\n};\n\nexport type BulkUpdateOp = {\n  op: \"update\";\n  row_id: string;\n  /** REPLACES the row's data wholesale. Keys not in `data` are dropped. */\n  data: Record<string, unknown>;\n  /**\n   * The version the person saw this row at, when the caller holds it (an undo carries the version its\n   * own write produced). Absent = the seam's ledger of the rows it drew (`lib/records/record-versions.ts`).\n   */\n  expected_version?: number | null;\n};\n\nexport type BulkMergeOp = {\n  op: \"merge\";\n  row_id: string;\n  /**\n   * Partial update — `data = existing_data || patch`. Keys in `data` overwrite\n   * the row's matching keys; keys absent from `data` are preserved. Use this\n   * when sending only changed fields.\n   */\n  data: Record<string, unknown>;\n  /**\n   * The version the person saw this row at, when the caller holds it (an undo carries the version its\n   * own write produced). Absent = the seam's ledger of the rows it drew (`lib/records/record-versions.ts`).\n   */\n  expected_version?: number | null;\n};\n\nexport type BulkCellOp = {\n  op: \"cell\";\n  row_id: string;\n  field_name: string;\n  value: unknown;\n  /**\n   * The version the person saw this row at, when the caller holds it (an undo carries the version its\n   * own write produced). Absent = the seam's ledger of the rows it drew (`lib/records/record-versions.ts`).\n   */\n  expected_version?: number | null;\n};\n\nexport type BulkDeleteOp = {\n  op: \"delete\";\n  row_id: string;\n};\n\nexport type BulkOp =\n  | BulkInsertOp\n  | BulkUpdateOp\n  | BulkMergeOp\n  | BulkCellOp\n  | BulkDeleteOp;\n\n/**\n * Per-op result envelope returned inside `bulkWrite`'s `results[]`.\n *\n * Note: insert / update / cell / delete that succeed return the full row.\n * Update / cell / delete against a row that is gone return `row_not_found`;\n * update / cell / merge against a row that is in Trash return `row_in_trash`\n * (with the server's own sentence in `message`). Both are soft failures — the\n * rest of the batch continues. Inserts that fail RAISE and abort the batch.\n */\nexport type BulkOpError = {\n  error: \"row_not_found\" | \"row_in_trash\";\n  row_id: string;\n  message?: string;\n};\nexport type BulkOpResult = DatasetRow | BulkOpError;\n\n/**\n * Narrow a bulk-write result slot to the error variant.\n * Successful results carry the full DatasetRow shape (no discriminator key\n * on the success side, so consumers narrow via this guard).\n */\nexport function isBulkOpError(r: BulkOpResult): r is BulkOpError {\n  return typeof r === \"object\" && r !== null && \"error\" in r;\n}\n\n/**\n * One plain sentence for the rows a batch could not change — the ONE wording\n * every bulk surface uses. A row in Trash is named as such (it can be restored),\n * never reported as \"could not be found\".\n */\nexport function describeBulkFailures(failed: BulkOpError[]): string {\n  const inTrash = failed.filter((f) => f.error === \"row_in_trash\").length;\n  const missing = failed.length - inTrash;\n  const parts: string[] = [];\n  if (inTrash > 0) {\n    parts.push(\n      `${inTrash} row${inTrash === 1 ? \" is\" : \"s are\"} in Trash — restore ${inTrash === 1 ? \"it\" : \"them\"} from Trash to edit`,\n    );\n  }\n  if (missing > 0) {\n    parts.push(\n      `${missing} row${missing === 1 ? \"\" : \"s\"} could not be found — ${missing === 1 ? \"it\" : \"they\"} may have been removed by someone else`,\n    );\n  }\n  return `${parts.join(\"; \")}.`;\n}\n\n\nexport type BulkWriteResponse = {\n  table_id: string;\n  count: number;\n  results: BulkOpResult[];\n};\n\n// ─── Service result envelope ────────────────────────────────────────────────\n\nexport type ServiceOk<T> = { success: true; data: T };\n/**\n * THE STORE'S OWN REFUSAL, kept whole (lane FIX-15, 2026-09-23).\n *\n * `error` is `PostgrestError.message` and nothing else, so a refusal written as\n * three parts — what happened, what the column is, what to do instead — reached\n * the screen as one third of itself, and the other two thirds (DETAIL and HINT)\n * were thrown away in this envelope. On production a name typed into a relation\n * column was refused by the store with a perfectly good sentence\n * and the person saw nothing usable.\n *\n * `refusal` carries the whole thing in the shape every Matrx screen already\n * knows how to draw (`RefusalNotice` / `RefusalLine` from `@ai-matrx/records-ui`,\n * which run it through `plainWords` so no machine identity is ever printed at a\n * person). `error` stays exactly what it was for the callers that print a line.\n */\nexport type ServiceErr = { success: false; error: string; refusal?: RecordsError };\nexport type ServiceResult<T> = ServiceOk<T> | ServiceErr;\n\n/**\n * Narrow a ServiceResult to the failure variant. Use instead of `!result.success`\n * inside generic functions where TS's narrow through `Promise<ServiceResult<T>>`\n * sometimes fails to discriminate the union members reliably.\n */\nexport function isServiceFailure<T>(r: ServiceResult<T>): r is ServiceErr {\n  return r.success === false;\n}\n\n\n// ─── A value's data type ────────────────────────────────────────────────────\n\nconst DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst DATETIME_PATTERN = /^\\d{4}-\\d{2}-\\d{2}[T\\s]\\d{2}:\\d{2}/;\n\n/**\n * Infer a table column's data type for a single value. Used by both the\n * CSV/Excel import path and the JSON-to-table path. The returned strings\n * align with `VALID_DATA_TYPES` in `table-utils.ts`.\n */\nexport function inferDataType(value: unknown): string {\n  if (value === null || value === undefined || value === \"\") return \"string\";\n\n  if (typeof value === \"boolean\") return \"boolean\";\n\n  if (typeof value === \"number\") {\n    return Number.isInteger(value) ? \"integer\" : \"number\";\n  }\n\n  if (typeof value === \"object\") {\n    return Array.isArray(value) ? \"array\" : \"json\";\n  }\n\n  // Strings — try numeric parse, then date patterns, then boolean keywords,\n  // else fall back to string.\n  const str = String(value);\n  const num = Number(str);\n  if (!isNaN(num) && str.trim() !== \"\") {\n    return Number.isInteger(num) ? \"integer\" : \"number\";\n  }\n\n  const lower = str.toLowerCase().trim();\n  if (lower === \"true\" || lower === \"false\") return \"boolean\";\n\n  if (DATE_PATTERN.test(str)) return \"date\";\n  if (DATETIME_PATTERN.test(str)) return \"datetime\";\n\n  return \"string\";\n}\n\n// ─── A display name's field key ─────────────────────────────────────────────\n\n/**\n * Sanitize a display name into a valid field name\n * Converts to lowercase, replaces special chars with underscores, follows snake_case\n * \n * @param displayName - The user-entered display name\n * @returns Sanitized field name in snake_case format\n * \n * @example\n * sanitizeFieldName(\"Total Revenue\") // returns \"total_revenue\"\n * sanitizeFieldName(\"Price ($)\") // returns \"price\"\n * sanitizeFieldName(\"2024 Sales\") // returns \"_2024_sales\"\n */\nexport function sanitizeFieldName(displayName: string): string {\n  if (!displayName || typeof displayName !== 'string') {\n    return '';\n  }\n\n  return displayName\n    .toLowerCase()\n    .trim()\n    .replace(/[^a-z0-9\\s_]/g, '') // Remove special chars (keep letters, numbers, spaces, underscores)\n    .replace(/\\s+/g, '_')          // Spaces to underscores\n    .replace(/^_+|_+$/g, '')       // Trim leading/trailing underscores\n    .replace(/_+/g, '_')           // Collapse multiple underscores\n    .replace(/^(\\d)/, '_$1');      // Prefix if starts with number\n}\n\n/**\n * Validate that a field name follows the required format\n * Must start with lowercase letter, contain only lowercase letters, numbers, and underscores\n * \n * @param fieldName - The field name to validate\n * @returns true if valid, false otherwise\n * \n * @example\n * validateFieldName(\"total_revenue\") // returns true\n * validateFieldName(\"Total Revenue\") // returns false\n * validateFieldName(\"123_sales\") // returns false\n */\nexport function validateFieldName(fieldName: string): boolean {\n  if (!fieldName || typeof fieldName !== 'string') {\n    return false;\n  }\n  \n  return /^[a-z][a-z0-9_]*$/.test(fieldName);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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ACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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AAI,iBAAiB,KAAKA,IAAG,EAAG,QAAO;AAEvC,SAAO;AACT;AAgBO,SAAS,kBAAkB,aAA6B;AAC7D,MAAI,CAAC,eAAe,OAAO,gBAAgB,UAAU;AACnD,WAAO;AAAA,EACT;AAEA,SAAO,YACJ,YAAY,EACZ,KAAK,EACL,QAAQ,iBAAiB,EAAE,EAC3B,QAAQ,QAAQ,GAAG,EACnB,QAAQ,YAAY,EAAE,EACtB,QAAQ,OAAO,GAAG,EAClB,QAAQ,SAAS,KAAK;AAC3B;AAcO,SAAS,kBAAkB,WAA4B;AAC5D,MAAI,CAAC,aAAa,OAAO,cAAc,UAAU;AAC/C,WAAO;AAAA,EACT;AAEA,SAAO,oBAAoB,KAAK,SAAS;AAC3C;","names":["exportCellText","rows","text","import_uuid","text","text","text","text","bad","day","text","import_uuid","text","TRUE_WORDS","FALSE_WORDS","text","text","item","window","rows","window","rows","rows","item","item","rows","countOf","err","text","import_uuid","item","text","import_global_slot","import_uuid","typeLabels","rank","refuse","registry","doorReady","import_global_slot","import_uuid","text","item","rows","text","refuse","import_format","whole","flight","copyId","schema","text","rows","window","siblings","import_uuid","import_uuid","item","num","isEmpty","block","import_format","import_global_slot","text","num","num","num","n","text","d","import_format","rows","exportCellText","rows","text","ok","str","num"]}