@ai-matrx/records 0.93.1 → 0.93.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/{client-D4mLGnph.d.ts → client-BKhJ6Ezn.d.ts} +8 -8
- package/dist/{client-BPcc-V2O.d.cts → client-DJFcYJ8I.d.cts} +8 -8
- package/dist/core/index.d.cts +17 -50
- package/dist/core/index.d.ts +17 -50
- package/dist/data/index.d.cts +11 -11
- package/dist/data/index.d.ts +11 -11
- package/dist/{declareTable-Br_4v6L7.d.ts → declareTable-BVvld0W6.d.ts} +4 -4
- package/dist/{declareTable-BSHX1Abl.d.cts → declareTable-y5e-Qasq.d.cts} +4 -4
- package/dist/entity/index.d.cts +7 -7
- package/dist/entity/index.d.ts +7 -7
- package/dist/{field-DjS7iId2.d.cts → field-F9BK-aUO.d.cts} +1 -1
- package/dist/{field-D-1OKy5r.d.ts → field-GR--cya9.d.ts} +1 -1
- package/dist/first-page/index.cjs +7276 -0
- package/dist/first-page/index.cjs.map +1 -0
- package/dist/first-page/index.d.cts +213 -0
- package/dist/first-page/index.d.ts +213 -0
- package/dist/first-page/index.js +7246 -0
- package/dist/first-page/index.js.map +1 -0
- package/dist/forms/index.d.cts +3 -3
- package/dist/forms/index.d.ts +3 -3
- package/dist/index.d.cts +12 -12
- package/dist/index.d.ts +12 -12
- package/dist/memory/index.d.cts +7 -7
- package/dist/memory/index.d.ts +7 -7
- package/dist/{objectOrganization-IBxZqFZQ.d.ts → objectOrganization-C2RtRmci.d.ts} +1 -1
- package/dist/{objectOrganization-CDAoE7Ft.d.cts → objectOrganization-Cec0G7mm.d.cts} +1 -1
- package/dist/{port-DyZ0GfxE.d.ts → port-Bhl_rn5k.d.ts} +3 -3
- package/dist/{port-B3UeC536.d.cts → port-CiDvXxG7.d.cts} +3 -3
- package/dist/{portal-CUwIsXsx.d.cts → portal-CL2Qtc-G.d.cts} +1 -1
- package/dist/{portal-DDOmQR1f.d.ts → portal-o9FhryoU.d.ts} +1 -1
- package/dist/{ports-DEkN-WfA.d.cts → ports-BTDZ9ydi.d.cts} +3 -3
- package/dist/{ports-YOhD5T7h.d.ts → ports-CCPhsr-V.d.ts} +3 -3
- package/dist/questions/index.cjs +7 -2
- package/dist/questions/index.cjs.map +1 -1
- package/dist/questions/index.d.cts +9 -9
- package/dist/questions/index.d.ts +9 -9
- package/dist/questions/index.js +7 -2
- package/dist/questions/index.js.map +1 -1
- package/dist/realtime/index.d.cts +3 -3
- package/dist/realtime/index.d.ts +3 -3
- package/dist/{record-zwSBU5PQ.d.cts → record-Bo1ahH3_.d.cts} +1 -1
- package/dist/{record-zwSBU5PQ.d.ts → record-Bo1ahH3_.d.ts} +1 -1
- package/dist/{relation-BbPDcXp5.d.cts → relation-BTww_Cby.d.cts} +2 -2
- package/dist/{relation-Dk9-VzY0.d.ts → relation-D8UmOxPh.d.ts} +2 -2
- package/dist/{rule-BVX1C83I.d.ts → rule-BojwTDvi.d.ts} +1 -1
- package/dist/{rule-CbBXN-FW.d.cts → rule-G4UQndi-.d.cts} +1 -1
- package/dist/search/index.d.cts +1 -1
- package/dist/search/index.d.ts +1 -1
- package/dist/seed-CQkIf8UR.d.cts +37 -0
- package/dist/seed-Dz8Hi2LZ.d.ts +37 -0
- package/dist/setup/index.d.cts +12 -12
- package/dist/setup/index.d.ts +12 -12
- package/dist/{subscription-BGgwsJ8c.d.ts → subscription-1ik9orQK.d.ts} +3 -3
- package/dist/{subscription-DVM2vL4e.d.cts → subscription-x61fFv_7.d.cts} +3 -3
- package/dist/{table-kind-BGokuDJj.d.ts → table-kind-C2bMlOaV.d.ts} +4 -4
- package/dist/{table-kind-C5ZLyOxE.d.cts → table-kind-C3PlCE9_.d.cts} +4 -4
- package/dist/templates/index.d.cts +10 -10
- package/dist/templates/index.d.ts +10 -10
- package/dist/typed-table/index.d.cts +10 -10
- package/dist/typed-table/index.d.ts +10 -10
- package/dist/{types-DB4J-zIt.d.ts → types-BBwIxf_z.d.ts} +2 -2
- package/dist/{types-reNR-zMe.d.cts → types-BTydwrlW.d.cts} +2 -2
- package/dist/{types-Bg1q6qwq.d.cts → types-C433sVT-.d.cts} +2 -2
- package/dist/{types-D31PewA2.d.ts → types-DYXymeSx.d.ts} +2 -2
- package/dist/{types-C3ywxkho.d.ts → types-Gur64NY0.d.ts} +2 -2
- package/dist/{types-DtEP7XLv.d.cts → types-_D768Jzt.d.cts} +2 -2
- package/dist/use-cases/index.d.cts +5 -5
- package/dist/use-cases/index.d.ts +5 -5
- package/dist/{validate-BWqeG2sK.d.ts → validate-BRfOuXKD.d.ts} +1 -1
- package/dist/{validate-QdnFP97_.d.cts → validate-CmZ93paU.d.cts} +1 -1
- package/dist/views/index.cjs +102 -0
- package/dist/views/index.cjs.map +1 -1
- package/dist/views/index.d.cts +51 -396
- package/dist/views/index.d.ts +51 -396
- package/dist/views/index.js +102 -0
- package/dist/views/index.js.map +1 -1
- package/dist/views-B156FsIH.d.cts +396 -0
- package/dist/views-Bny6SBX0.d.ts +396 -0
- package/package.json +12 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/first-page/index.ts","../../src/aggregate.ts","../../src/coerce.ts","../../src/store.generated.ts","../../src/fieldKind.ts","../../src/first-page/reads.ts","../../src/core/primedBundle.ts","../../src/core/recordChanges.ts","../../src/archive.ts","../../src/record.ts","../../src/subscription.ts","../../src/results.ts","../../src/core/pgError.ts","../../src/relation.ts","../../src/ops.ts","../../src/choice.ts","../../src/placement.ts","../../src/level.ts","../../src/core/keysetCursor.ts","../../src/table.ts","../../src/grid.ts","../../src/core/doors.ts","../../src/core/supabase.ts","../../src/drill.ts","../../src/core/query.ts","../../src/core/client.ts","../../src/first-page/seed.ts","../../src/core/seed.ts","../../src/entity/port/port.ts","../../src/entity/core/errors.ts","../../src/entity/core/client.ts","../../src/entity/core/realtime.ts","../../src/entity/core/wire.ts","../../src/entity/port/rows.ts","../../src/versions/rowVersion.ts","../../src/views/keys.ts","../../src/views/views.ts","../../src/views/look.ts"],"sourcesContent":["// @ai-matrx/records/first-page — THE GRID'S FIRST PAGE AND THE SERVER'S SEED, HEADLESS: the read arguments a grid\n// sends (sort, grouping, summaries, the view's question) and the seed a server asks as the person before the screen\n// exists. Zero React, zero design-system; records-ui binds its view codec. (Moved from records-ui, step 10, 2026-10-08.)\n\nexport * from \"./reads\";\nexport * from \"./seed\";\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","// 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 behaviours; 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 * behaviour, 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 behaviours 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, colour 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/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 catalogue — 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, 30 declarable field kinds,\n// 76 rule node kinds,\n// 9 kernel Tables, 937 doors, 70 knobs,\n// 1122 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 behaviour 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 behaviours 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); 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: \"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: \"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: \"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.arrayjoin\", 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.concatenate\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.contains\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.created_time\", 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.datetime_format\", 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.eq\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.find\", 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.if\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.isblank\", 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.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.max\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.min\", 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.or\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.regex_match\", 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.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.today\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.trim\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.upper\", evaluated_by: \"GRID-PRIMITIVES G3 (custom.formula_eval)\" },\n { node: \"fx.workday\", 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: \"length\", evaluated_by: \"W1-RULE\" },\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: \"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/** 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 * catalogue 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_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\", 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: \"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_archive\", args: \"p_organization_id uuid, p_automation_id uuid\", 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_restore\", 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: \"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: \"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_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: \"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: \"client_write_grants\", args: \"\", returns: \"TABLE(role_name text, object_name text, privilege text)\", security: \"invoker\" },\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: \"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: \"context_writer\", args: \"p_organization_id uuid\", returns: \"text\", 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: \"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_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_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: \"invoker\" },\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_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_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_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_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\", 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_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_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_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_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_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: \"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_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_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_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: \"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_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: \"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: \"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: \"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: \"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: \"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: \"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_index\", args: \"p_organization_id uuid\", returns: \"jsonb\", security: \"definer\" },\n { name: \"pick_list_index_everywhere\", args: \"\", 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_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: \"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_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\", 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_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_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: \"void\", 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_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: \"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: \"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_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_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: \"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_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: \"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_cancel\", args: \"p_organization_id uuid, p_request_id uuid, p_reason text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n { name: \"sign_request_create\", args: \"p_organization_id uuid, p_render_id uuid, p_field_key text, p_signer_email text, p_signer_name text, p_expires_in interval DEFAULT '14 days'::interval\", returns: \"jsonb\", security: \"definer\" },\n { name: \"sign_request_decline\", args: \"p_token text, p_reason text DEFAULT NULL::text, p_ip text DEFAULT NULL::text, p_user_agent text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n { name: \"sign_request_public\", args: \"p_token text, p_origin text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n { name: \"sign_request_remind\", args: \"p_organization_id uuid, p_request_id uuid\", returns: \"jsonb\", security: \"definer\" },\n { name: \"sign_request_sentence\", args: \"p_data jsonb\", returns: \"text\", security: \"invoker\" },\n { name: \"sign_request_sign\", args: \"p_token text, p_signed_name text, p_mark text, p_image text DEFAULT NULL::text, p_ip text DEFAULT NULL::text, p_user_agent text DEFAULT NULL::text, p_origin text DEFAULT NULL::text\", returns: \"jsonb\", security: \"definer\" },\n { name: \"sign_request_state\", args: \"p_data jsonb\", returns: \"text\", security: \"invoker\" },\n { name: \"sign_request_unchanged\", args: \"p_organization_id uuid, p_request_id uuid\", returns: \"boolean\", security: \"definer\" },\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: \"sign_token_decode\", args: \"p_token text\", returns: \"bytea\", security: \"invoker\" },\n { name: \"sign_token_encode\", args: \"p_bytes bytea\", returns: \"text\", security: \"invoker\" },\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: \"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_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: \"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: \"table_add_rung\", args: \"p_organization_id uuid, p_table_id uuid\", returns: \"permission_level\", security: \"invoker\" },\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_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_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_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_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_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_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_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_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: \"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: \"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: \"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_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_reads_the_copy\", value: \"true\", type: \"boolean\" },\n { key: \"agent_context_value_cap_bytes\", value: \"0\", type: \"integer\" },\n { key: \"agent_schema_changes\", value: \"\\\"ask\\\"\", type: \"string\" },\n { key: \"archive_confirm_over\", value: \"1000\", type: \"integer\" },\n { key: \"back_links\", value: \"true\", type: \"boolean\" },\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: \"context_copy_following\", value: \"true\", type: \"boolean\" },\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_model\", value: \"\\\"claude-fable-5-latest\\\"\", type: \"string\" },\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\\\": \\\"editor\\\"}}\", 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: \"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: \"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: \"scopes_written_in_the_store\", 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: \"false\", 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,_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_document,doc_render_read,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_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_update_rehoming_choices,form_archive,form_restore,io_restore,migrate_delete,migrate_extract_parent,migrate_merge,migrate_reclass,migrate_rename,migrate_reparent,migrate_retype,migrate_split,migrate_undo,organization_clear,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,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,sign_request_cancel,sign_request_create,sign_request_remind,sign_request_unchanged,table_archive,table_archive_deliberately,table_restore,table_row_defaults,table_row_defaults_apply,table_row_defaults_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_read,work_approval_request,work_assign,work_record_states,work_set_state\" },\n { code: \"0A000\", raised_by: \"checklist_step_complete,entity_row_write,external_rows,external_source_declare,external_write_through,promote_field,promoted_index_expr,promoted_query_sql,promoted_read,read_records_keyset,read_records_page,rule_eval,rule_filter_node_sql,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,_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,booking_declare,capture_submit,checklist_declare,context_resolve,context_template_define,context_type_write,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_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,sign_request_create,sign_request_sign,subscription_declare,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_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_run,_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_num,_fx_regex,_fx_unit,_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,_table_dimensions_check,_take_op_id,_template_bind,_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,booking_declare,button_press,containment_parent,context_scope_write,context_scopes,context_template_define,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_declare,enrich_land,enrich_normalize,enrich_pin,entity_back_links,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_duplicate,field_history,field_update,form_declare,form_draft_save,form_visit,formula_eval,formula_parse,formula_preview,formula_translate_notion,grid_layout_check,hub_changed_by,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,organization_clear,page_size,pick_list_create,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_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,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,sign_request_create,sign_request_sign,subscription_declare,table_archive_deliberately,table_ensure,table_find,table_from_example,table_move,table_row_defaults_set,table_rules,table_share_outside_grant,table_sync,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_keys_check,view_look_set,view_record_order_set,visibility_as_of,where_lists_live,where_tables_live,work_approval_request,work_decide_many,work_inbox,work_list,work_slot_hold\" },\n { code: \"23503\", raised_by: \"_action_check,_automation_flip,_automation_run,_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_runs,automations,autonumber_backfill,booking_cancel,booking_confirm,booking_declare,booking_hold,booking_reschedule,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,form_declare,form_draft_save,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,sign_request_create,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: \"_ctx_store_item,_ctx_store_scope,_ctx_store_type,_portal_config_judge,_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,sign_request_cancel,sign_request_create,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_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_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_restore,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,sign_request_create,sign_request_sign,status_groups_keyed,status_groups_of,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: \"40001\", raised_by: \"has_visibility_at,table_move,whole_value_complete\" },\n { code: \"42501\", raised_by: \"_agent_change_gate,_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,_store_door,_table_dimensions_infer,_table_duplicate_step,_table_shape_guard,_template_call,_value_envelope,_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,booking_confirm,booking_declare,booking_hold,capture_submit,checklist_run,comment_write,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,count_records_archived,dashboard_target_field_assert,doc_sign,enrich_declare,enrich_due,enrich_land,enrich_normalize,entity_field_declare,entity_field_retire,entity_field_update,entity_row_propose,entity_row_write,entity_value_write,external_write_through,field_restore,form_declare,form_draft_save,form_public_asks,form_submit,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,organization_clear,organization_contents,portal_declare,portal_form,portal_form_submit,portal_invitation,portal_invite,portal_invite_accept,portal_principal_bind,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_row_controls,record_table,record_write_graph,relation_halves_disagreements,relation_halves_repair,resolve_context,reverse_links_many,scope_table_provision,share_grant,subscription_mute,subscription_preview,table_archive_deliberately,table_copies_in_progress,table_duplicate,table_duplicate_continue,table_kind_facts,table_level_facts,table_move,table_row_defaults_apply,table_row_defaults_set,table_share_outside_accept,table_share_outside_grant,table_share_outside_invite,table_share_outside_resend,table_sync,table_templates,table_transfer_owner,table_webhook_declare,template_declare,template_install,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_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,data_home_changed_by,form_draft_save,hub_changed_by,pipeline_move_many,record_change_many,record_headers,relation_names_match,reverse_links_many,table_decorate,table_from_example,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,entity_field_protect_arman_explicitly_approved,inbox_clear,inbox_snooze,io_outbox_release,io_outbox_subscribe,table_duplicate,table_ensure,table_move,template_install,template_restore,template_upgrade,work_approval_decide,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: \"P0001\", raised_by: \"action_run,context_scope_write\" },\n { code: \"P0002\", raised_by: \"inbox_clear,inbox_snooze,publish_bind,template_archive,template_install,template_install_claim,template_install_note,template_keep,template_restore,template_uninstall,template_upgrade,whole_value_complete\" },\n { code: \"PT409\", raised_by: \"entity_row_write,record_change_many,record_update,record_upsert,record_write_graph_superseding\" },\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 \"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 \"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_remediation\",\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_usage\",\n \"agent_user_kv\",\n \"ai_api\",\n \"ai_calls\",\n \"ai_endpoint\",\n \"ai_model\",\n \"ai_model_alias\",\n \"ai_offering\",\n \"ai_provider\",\n \"ai_request_latency\",\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_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_muted_pattern\",\n \"app_log_norm_exception\",\n \"app_rate_limit\",\n \"app_setting\",\n \"app_sync_status\",\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 \"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 \"base_entity_template\",\n \"batch_cost_event\",\n \"batch_provider_batch\",\n \"batch_work_item\",\n \"billing_capability\",\n \"billing_capability_limit\",\n \"billing_connect_account\",\n \"billing_coupon\",\n \"billing_coupon_redemption\",\n \"billing_customer\",\n \"billing_free_period_grant\",\n \"billing_plan\",\n \"billing_plan_limit\",\n \"billing_price\",\n \"billing_product\",\n \"billing_spend_approval\",\n \"billing_spend_guardrail\",\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_type_default\",\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 \"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 \"contact_medium\",\n \"contact_submission\",\n \"content_certification\",\n \"content_ir_kind\",\n \"content_ir_kind_component\",\n \"content_ir_kind_component_incident\",\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_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_trust\",\n \"custom_agg_digest_checked\",\n \"custom_entity_definition\",\n \"custom_field_definition\",\n \"custom_field_target\",\n \"custom_io_outbox_consumer\",\n \"custom_io_outbox_consumption\",\n \"custom_record\",\n \"custom_share_tails_mine_repair\",\n \"custom_template\",\n \"custom_template_install\",\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_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_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 \"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_link\",\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_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_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_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_api_key\",\n \"iam_emergency_door_request\",\n \"iam_org_availability_key\",\n \"iam_read_lane_v2_rollout\",\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_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 \"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 \"org_admin_audit\",\n \"org_change_policy\",\n \"org_context_ledger\",\n \"org_industries\",\n \"org_member_control\",\n \"org_module_config\",\n \"org_plan\",\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 \"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_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 \"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_spec\",\n \"provision_spec_grandfather\",\n \"provision_vocabulary\",\n \"provlock_recall_visits_all8u5\",\n \"public_compat_wrapper\",\n \"public_placement_baseline\",\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 \"recompute_queue\",\n \"record\",\n \"record_alias\",\n \"redaction_mapping\",\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 \"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 \"search_item\",\n \"seo_ai_capability\",\n \"seo_ai_visibility_citation\",\n \"seo_ai_visibility_claim\",\n \"seo_ai_visibility_panel\",\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 \"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 \"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 \"surface\",\n \"system_announcement\",\n \"system_context_item\",\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_binding\",\n \"tool_bundle\",\n \"tool_call\",\n \"tool_call_facts\",\n \"tool_definition_version\",\n \"tool_executor\",\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_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 \"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_offering\",\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_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_voice_fingerprint\",\n \"web_youtube_video\",\n \"webhook_deliveries\",\n \"webhook_dispatch_state\",\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_comparison\",\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_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/fieldKind.ts — @ai-matrx/records · THE ONE \"WHAT DOES THIS COLUMN HOLD\" READER, with the store's own kernel\n// tables (File, Person) bound. records-ui's `editorKindFor` and every headless section (questions, first-page) read\n// a Field's kind through this, so a column is a number, a date or a choice in exactly one place.\n\nimport type { Field } from \"./field\";\nimport { fieldKindFor, type FieldKind, type KernelTargets } from \"./coerce\";\nimport { KERNEL_TABLES } from \"./store.generated\";\n\nconst kernelId = (name: string): string => KERNEL_TABLES.find((t) => t.name === name)?.id ?? \"\";\nconst KERNEL: KernelTargets = { file: kernelId(\"File\"), person: kernelId(\"Person\") };\n\n/** The Field's kind, as the store classifies it (the classifier records-ui's `editorKindFor` stands on). */\nexport function storeFieldKind(field: Field): FieldKind {\n return fieldKindFor(field, KERNEL);\n}\n","// src/first-page/reads.ts — @ai-matrx/records/first-page · WHAT A GRID ASKS THE STORE, AS PURE FUNCTIONS\n//\n// (Moved from records-ui `gridPage.ts`, `groupReads.ts`, `gridLook.ts`, step 10, 2026-10-08.) The grid (which asks\n// them) and the server's first-page seed (which asks them first, with the same arguments, so the browser's call\n// finds its answer) build every read argument here. Zero React, zero design-system.\n\nimport type { AggregateMeasure, AggregateOperation, StoreFilter } from \"../aggregate\";\nimport type { Field } from \"../field\";\nimport type { RecordPageSort } from \"../record\";\nimport type { Table } from \"../table\";\nimport { isRuleFilter } from \"../aggregate\";\nimport { storeFieldKind } from \"../fieldKind\";\n\n// ── sort ──────────────────────────────────────────────────────────────────────────────────\n\n/**\n * Does this column hold NUMBERS the store keeps — a number, money or percent column, or the record number\n * (`config.system: autonumber`, worked out once on save and kept)?\n */\nexport function holdsNumbers(field: Field): boolean {\n const kind = String(storeFieldKind(field));\n if (kind === \"number\" || kind === \"currency\" || kind === \"percent\") return true;\n return String(((field.config ?? {}) as Record<string, unknown>)[\"system\"] ?? \"\") === \"autonumber\";\n}\n\n/** How the store should compare a column's values when it sorts by it. The record number sorts 1, 2 … 10. */\nexport function sortAsFor(field: Field): NonNullable<RecordPageSort[\"as\"]> {\n if (holdsNumbers(field)) return \"number\";\n if (String(storeFieldKind(field)) === \"datetime\") return \"date\";\n return \"text\";\n}\n\n/** One column sort, by Field key — the grid's header sort and the table's default sort share it. */\nexport interface ColumnSort {\n /** The Field KEY. */\n id: string;\n direction: \"asc\" | \"desc\";\n}\n\n/** A header sort in the store's page-order shape. A sort on a column that is gone is no sort. */\nexport function pageSortFor(fields: readonly Field[], sort: ColumnSort | null | undefined): RecordPageSort[] {\n if (!sort) return [];\n const field = fields.find((f) => f.key === sort.id);\n if (!field) return [];\n return [{ field: field.key, direction: sort.direction === \"desc\" ? \"desc\" : \"asc\", as: sortAsFor(field) }];\n}\n\n/**\n * THE TABLE'S OWN SORT — or `null`. The store writes `default_sort` as `[{field, direction}]` with `field` a Field\n * KEY; older rows hold a bare key or `\"key desc\"`, so all three shapes are read. A sort naming a column the table\n * no longer has is DROPPED, never guessed at. Only the first sort key is used.\n */\nexport function defaultSortOf(table: Pick<Table, \"default_sort\"> | null | undefined, fields: readonly Field[]): ColumnSort | null {\n const raw = (table?.default_sort ?? null) as unknown;\n const first = Array.isArray(raw) ? raw[0] : raw;\n let name: string | null = null;\n let direction: \"asc\" | \"desc\" = \"asc\";\n if (typeof first === \"string\") {\n const trimmed = first.trim();\n if (trimmed === \"\") return null;\n if (trimmed.startsWith(\"-\")) {\n name = trimmed.slice(1).trim();\n direction = \"desc\";\n } else {\n const [head, tail] = trimmed.split(/\\s+/);\n name = head ?? null;\n if (tail && tail.toLowerCase() === \"desc\") direction = \"desc\";\n }\n } else if (first && typeof first === \"object\") {\n const entry = first as Record<string, unknown>;\n const named = entry[\"field\"] ?? entry[\"key\"] ?? entry[\"id\"];\n name = typeof named === \"string\" ? named : null;\n if (String(entry[\"direction\"] ?? \"\").toLowerCase() === \"desc\") direction = \"desc\";\n }\n if (!name) return null;\n // A Field named by its KEY (what the store writes) or, in an older row, by its id.\n const field = fields.find((f) => f.key === name) ?? fields.find((f) => f.id === name);\n return field ? { id: field.key, direction } : null;\n}\n\n// ── grouping and summaries ────────────────────────────────────────────────────────────────\n\n/** The parts of a grid grouping the reads depend on (records-ui's `GridGrouping` is one). */\nexport interface GroupingShape {\n field: string;\n then?: readonly unknown[] | undefined;\n across?: unknown;\n trail?: readonly unknown[] | undefined;\n}\n\n/**\n * A grouping the merged grid keeps as ROWS under group headers: one level, no pivot, no drill trail. Anything else\n * opens the drill, which reads other doors.\n */\nexport function isPlainGrouping<G extends GroupingShape>(grouping: G | undefined): grouping is G {\n return Boolean(grouping) && !(grouping!.then && grouping!.then.length > 0) && !grouping!.across && !(grouping!.trail && grouping!.trail.length > 0);\n}\n\n/** The page is asked in group order first, then in the sort the person chose. */\nexport function groupedPageSort(fields: readonly Field[], groupKey: string | null, sort: RecordPageSort[]): RecordPageSort[] {\n if (!groupKey) return sort;\n const field = fields.find((f) => f.key === groupKey);\n if (!field) return sort;\n return [{ field: groupKey, direction: \"asc\", as: sortAsFor(field) }, ...sort.filter((s) => s.field !== groupKey)];\n}\n\n/** Every summary the store answers (`custom.record_aggregate`); a chosen summary outside it is never sent. */\nexport const SUMMARY_OPERATIONS: readonly AggregateOperation[] = [\n \"count\",\n \"sum\",\n \"avg\",\n \"min\",\n \"max\",\n \"median\",\n \"filled\",\n \"empty\",\n \"unique\",\n \"percent_empty\",\n \"percent_filled\",\n \"range\",\n];\n\n/** The chosen summaries as the store's measures, in the order the grid sends them (sorted, unknown ops left out). */\nfunction chosenEntries(chosen: Record<string, string>): Array<[string, string]> {\n return (JSON.parse(JSON.stringify(Object.entries(chosen).sort())) as Array<[string, string]>).filter(([, op]) =>\n (SUMMARY_OPERATIONS as readonly string[]).includes(op),\n );\n}\n\n/** Every group's count and each chosen summary: `record_aggregate`'s measures when grouped by the grouping column. */\nexport function groupFactMeasures(chosen: Record<string, string>): AggregateMeasure[] {\n return [{ op: \"count\" }, ...chosenEntries(chosen).filter(([, op]) => op !== \"count\").map(([key, op]) => ({ op: op as AggregateOperation, key }))];\n}\n\n/** The summary bar's measures over the whole table: none when nothing is chosen. */\nexport function summaryBarMeasures(chosen: Record<string, string>): AggregateMeasure[] {\n return chosenEntries(chosen).map(([key, op]) => (op === \"count\" ? { op: \"count\" as const } : { op: op as AggregateOperation, key }));\n}\n\n/** The keys of the choice columns, in the table's field order: each has a header filter list with counts. */\nexport function choiceFieldKeys(fields: readonly Field[]): string[] {\n return fields\n .filter((f) => {\n const kind = String(storeFieldKind(f));\n return kind === \"select\" || kind === \"multi_select\";\n })\n .map((f) => f.key);\n}\n\n/** How many links a grid cell draws of a reverse column (the chips; the rest is \"+N\"). */\nexport const REVERSE_CELL_CHIPS = 3;\n\n// ── the view's own question ───────────────────────────────────────────────────────────────\n\n/**\n * THE VIEW'S OWN QUESTION, as the grid asks it: its Rule, else its flat filter (an empty flat filter is none).\n * The grid's column filters are laid over this by records-ui's `storeQuestion`; with none, this is the question.\n */\nexport function viewFilterOf(\n shown: { where?: StoreFilter | null | undefined; filters?: StoreFilter | null | undefined } | null,\n _fields?: readonly Field[],\n): StoreFilter | undefined {\n if (!shown) return undefined;\n const base: StoreFilter | undefined = shown.where ?? (shown.filters && Object.keys(shown.filters).length > 0 ? shown.filters : undefined);\n if (!base) return undefined;\n if (isRuleFilter(base)) return base;\n return Object.keys(base).length > 0 ? base : undefined;\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/** 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/recordChanges.ts — @ai-matrx/records · lane RECORDS-UI-FIX (2026-09-23)\n//\n// EVERY SCREEN SHOWING A RECORD HEARS EVERY WRITE TO IT MADE THROUGH THIS PACKAGE.\n//\n// 🚨 WHAT A PERSON MET (VERIFIER-16 LOW, guide re-walk 2026-09-23): the record panel read\n// \"History 3 versions\" after its fourth write, while the store held four. The history\n// panel read the chain once, when it opened, and nothing told it the grid cell or the\n// form beside it had just written a new version. It is not the no-op-version class (the\n// store's history had the row; the screen never asked again) — it is a screen that\n// cannot hear the writes made on the same page.\n//\n// So every successful write door of the client announces the record it wrote, and any\n// screen showing that record re-reads on the announcement. Page-local and synchronous;\n// a write from another tab or person is realtime's job, not this one's.\n\n//\n// ONE BUS PER REALM, IN GLOBAL SLOTS: every section of the built package carries its own copy of\n// this module (and ESM/CJS are two graphs), so a module-level Set split the bus — the core client\n// announced into one copy while records/react listened on another (2026-10-08). Guarded on the\n// packed tarball by scripts/check-shared-state.mjs.\n\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\ntype Listener = (recordId: string) => void;\n\nconst listeners = globalSlot(\"ai-matrx.records.record-change-listeners\", () => new Set<Listener>());\n\n/** Called by the client after a write door answered yes. */\nexport function announceRecordChanged(recordId: string): void {\n for (const listener of [...listeners]) {\n try {\n listener(recordId);\n } catch (thrown) {\n // A listener that throws must not take the write's answer with it.\n console.error(\"[@ai-matrx/records] a record-change listener threw\", thrown);\n }\n }\n}\n\n// ── A RECORD THE PAGE ARCHIVED IS NOT READ AGAIN (Spaces r39) ───────────────────────────────\n//\n// `custom.read_record` refuses an archived record (400), and a screen that showed the record keeps\n// its entry live after it closes (a peek opened on a new row, then closed) — so the archive's own\n// change announcement, and the realtime echo of it, re-read a record nobody can open: two failing\n// requests per archive. `recordDelete` marks the record removed here; the live entry skips its\n// re-read while the mark stands; `recordRestore` lifts it.\n\nconst removed = globalSlot(\"ai-matrx.records.removed-records\", () => new Set<string>());\n\n/** Called by the client after `record_delete` answered yes (before it announces the change). */\nexport function markRecordRemoved(recordId: string): void {\n removed.add(recordId);\n}\n\n/** Called by the client after `record_restore` answered yes (before it announces the change). */\nexport function markRecordRestored(recordId: string): void {\n removed.delete(recordId);\n}\n\n/** Whether this page archived the record and has not brought it back. */\nexport function isRecordRemoved(recordId: string): boolean {\n return removed.has(recordId);\n}\n\n/** Hear every record this page writes. Returns the unsubscribe. */\nexport function onRecordChanged(listener: Listener): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n}\n\n// ── A TABLE'S SHAPE MOVED (KINDS-GLUE wave 3 §1.4) ──────────────────────────────────────\n//\n// A record drawn as `table:<uuid>` in a chat, a note or a canvas draws through the Table's\n// Fields. When a Field is renamed, added, retired, brought back or retyped on this page, every\n// such card must re-read the Table's kind facts — so every structure door of the client\n// announces the Table here, the same page-local way record writes announce their record.\n// `null` means \"a Table changed and the door did not name which\" (a Field door is addressed by\n// the Field id alone): a listener then refreshes every Table it holds. Another tab's or\n// person's change is realtime's job (the `custom:table:<id>` notice with `kind: \"field\"`).\n\ntype TableListener = (tableId: string | null) => void;\n\nconst tableListeners = globalSlot(\"ai-matrx.records.table-structure-listeners\", () => new Set<TableListener>());\n\n/** Called by the client after a structure door (a Field or choice change) answered yes. */\nexport function announceTableStructureChanged(tableId: string | null): void {\n for (const listener of [...tableListeners]) {\n try {\n listener(tableId);\n } catch (thrown) {\n console.error(\"[@ai-matrx/records] a table-structure listener threw\", thrown);\n }\n }\n}\n\n/** Hear every Table whose shape this page changes. Returns the unsubscribe. */\nexport function onTableStructureChanged(listener: TableListener): () => void {\n tableListeners.add(listener);\n return () => tableListeners.delete(listener);\n}\n","// src/archive.ts — @ai-matrx/records · THE ARCHIVE, HEADLESS\n//\n// 🚨 THE DEFECT THIS EXISTS FOR (VERIFIER-10 F4, measured 2026-09-22 on Rincon\n// Plumbing Co's \"Truck 1 dispatch backlog\" as admin@admin.com):\n//\n// \"The grid's row action is Delete… Pressing it soft-deletes correctly:\n// deleted_at set, version 1 → 2, nothing removed, and the row leaves the\n// grid. Then it is gone for good as far as any screen is concerned. The\n// store's own custom.record_restore exists and does exactly the right thing.\n// The door is there; nothing reaches it.\"\n//\n// It could not have been reached. Every read door this store had answered LIVE\n// ROWS ONLY — `custom.read_records`, `read_records_by_ids` and\n// `read_records_matching` each hard-code `and r.deleted_at is null` — so no\n// screen could list an archived record however it was written. The store grew\n// `custom.read_records_archived` (migration\n// `fix10a_the_archive_has_a_read_door.sql`) and this module is its client half:\n// the vocabulary, the row shape, and the sentences a screen says about it.\n//\n// WHY THE SENTENCES LIVE HERE AND NOT IN THE UI. \"Archived by Maria Delgado on\n// 22 September\" is an answer about STORED FACTS, not a layout, and the desktop\n// app, the extension, an agent's reply and the web grid must all say it the\n// same way. A screen that composed its own would be a second answer to one\n// question, reached by knowing which client you are using.\n\nimport type { RecordDocument, ReadRow, Timestamp, Uuid } from \"./record\";\n\n/**\n * THE TWO LANES THE ARCHIVED-ITEMS LAW NAMES (Arman, 2026-09-09) — the same\n * split every other list in the platform makes between what is mine and what\n * is the organization's.\n *\n * · `mine` — what I archived.\n * · `org` — what anybody in this organization archived.\n *\n * `mine` is by construction a SUBSET of `org`: the store applies it as a\n * narrowing conjunct beside the read-access ladder, so a lane can never show a\n * record the ladder would have refused.\n */\nexport const ARCHIVE_LANES = [\"mine\", \"org\"] as const;\nexport type ArchiveLane = (typeof ARCHIVE_LANES)[number];\n\n/** THE DEFAULT LANE. The organization's archive, because \"where did that job go?\" is almost never a question about yourself. */\nexport const DEFAULT_ARCHIVE_LANE: ArchiveLane = \"org\";\n\n/** What each lane is called on a screen, and what it actually answers. */\nexport const ARCHIVE_LANE_LABEL: Record<ArchiveLane, string> = {\n mine: \"Archived by me\",\n org: \"Archived by anyone\",\n};\n\nexport const ARCHIVE_LANE_MEANS: Record<ArchiveLane, string> = {\n mine: \"The records you archived yourself.\",\n org: \"Everything anybody in this organization archived, including you.\",\n};\n\n/** A word that is not a lane is not silently answered as one. */\nexport function isArchiveLane(word: unknown): word is ArchiveLane {\n return typeof word === \"string\" && (ARCHIVE_LANES as readonly string[]).includes(word);\n}\n\n/**\n * One archived record, as `custom.read_records_archived` answers it: an\n * ordinary `ReadRow` — same id, same masked document, same level, same hidden\n * notices as it had while it was live — plus the two facts that only an archive\n * needs.\n *\n * `archivedBy` is null when the archiver is not a member of this organization\n * any more (their name is not this screen's to learn) or when the history\n * partition that held the SOFT_DELETE has rolled away. Null is an ANSWER and\n * gets its own sentence; it is never printed as an empty space.\n */\nexport interface ArchivedRow extends ReadRow {\n archivedAt: Timestamp;\n archivedBy: Uuid | null;\n archivedByName: string | null;\n}\n\n/** The row shape the door returns over the wire, before it is folded. */\nexport interface ArchivedDoorRow {\n id: Uuid;\n document: unknown;\n level: string;\n archived_at: Timestamp;\n archived_by: Uuid | null;\n archived_by_name: string | null;\n}\n\n/**\n * WHEN IT WAS ARCHIVED, THE WAY A PERSON SAYS IT — \"22 September 2026 at 01:53\".\n * Not an ISO string, and never a bare relative word like \"yesterday\" on its\n * own: somebody deciding whether to bring a record back is deciding about a\n * particular day's work.\n */\nexport function archivedWhen(at: Timestamp, locale = \"en-GB\"): string {\n const when = new Date(at);\n if (Number.isNaN(when.getTime())) return \"a moment nobody recorded\";\n return new Intl.DateTimeFormat(locale, {\n day: \"numeric\",\n month: \"long\",\n year: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n }).format(when);\n}\n\n/**\n * THE WHOLE SENTENCE A ROW IN THE ARCHIVE CARRIES. Both halves of the question\n * the archived-items law asks — who, and when — and an honest sentence when the\n * store could not answer the first half, rather than a blank where a name goes.\n */\nexport function archivedByLine(row: Pick<ArchivedRow, \"archivedAt\" | \"archivedByName\">, locale = \"en-GB\"): string {\n const when = archivedWhen(row.archivedAt, locale);\n const who = (row.archivedByName ?? \"\").trim();\n if (who === \"\") {\n return `Archived on ${when}. The store does not know who archived it — whoever did is no longer in this organization, or it happened before this table kept that.`;\n }\n return `Archived by ${who} on ${when}.`;\n}\n\n/**\n * WHAT AN EMPTY ARCHIVE SAYS, PER LANE. An empty list is an answer and it names\n * the lane it is empty for, so \"nothing here\" can never be read as \"nothing was\n * ever archived\" while the other lane holds twenty records.\n */\nexport function emptyArchiveLine(lane: ArchiveLane): string {\n return lane === \"mine\"\n ? \"You have not archived anything in this table. Switch to “Archived by anyone” to see what the rest of the organization has.\"\n : \"Nothing in this table has been archived. Records you remove from the grid arrive here, and nothing is ever destroyed.\";\n}\n\n/** A document that survived the round trip is the same document — used by the guard. */\nexport function sameDocument(a: RecordDocument, b: RecordDocument): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n","// src/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\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\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}\n\n/** DOOR-SPEED. One change in a `recordChangeMany` batch. */\nexport type RecordChange =\n | { op: \"insert\"; data: RecordDocument }\n | { op: \"update\"; record_id: Uuid; patch: RecordDocument; expected_version?: number | null }\n | { op: \"archive\"; record_id: Uuid };\n\n/** What one change did, in the order the changes were handed in. */\nexport type RecordChangeResult =\n | { op: \"insert\"; id: Uuid }\n | { op: \"update\"; id: Uuid; version: number }\n | { op: \"archive\"; id: Uuid; archived_at: string };\n\n/**\n * One revision of one record, as `custom.io_revisions` answers it, newest\n * first. `version` is the record's own version at that point — the number a\n * screen hands back as `expectedVersion` so the store, not the screen, decides\n * whether someone else got there first.\n */\nexport interface RecordRevision {\n version: number;\n changed_at: string;\n changed_by: Uuid | null;\n summary: string | null;\n}\n\n/** A whole record as `recordRead` answers it, through `custom.read_record`. */\nexport interface RecordRead {\n record_id: Uuid;\n /** The masked document. A hidden field is present and null. */\n document: RecordDocument;\n /** Why each masked field is masked, in the store's words. */\n hidden: Record<string, HiddenFieldNotice>;\n /**\n * FLD-9 / REC-19. Which Rule version produced each computed value. Present\n * only where the store has computed provenance for this record.\n */\n computed: Array<{\n field_key: string;\n field_id: Uuid;\n value: unknown;\n rule_id: Uuid;\n rule_version: number;\n computed_at: Timestamp;\n }>;\n /**\n * WHY `computed` IS EMPTY, when it is empty because nobody could read it.\n *\n * `custom.computed_provenance` is a footnote beside the record and its door is not\n * open to a person's seat (no EXECUTE for `authenticated`, measured 2026-09-21). It\n * used to fail the WHOLE read, so an organization's own owner was told \"You do not\n * have access to this\" about a record he could read — see `core/client.ts`. The\n * record comes back now, and this carries what the footnote's door said, so a screen\n * that draws rule provenance can say it could not read it rather than draw nothing\n * and mean two different things by it. `null` means the footnote was read fine (or\n * was never asked for).\n */\n computedUnavailable?: RecordsError | null;\n /**\n * Asked with `withVersion: true`: the version this read saw, so a safe edit (`recordUpdate` with `expected_version`) needs no\n * second call. Read beside the document in the same round of requests; `null` when the store\n * could not answer it (a write then refuses as \"version unread\", never as last-write-wins).\n */\n version?: number | null;\n}\n","// src/subscription.ts — @ai-matrx/records\n//\n// DOOR-18. A SUBSCRIPTION IS A RULE RECORD, NOT A TABLE.\n//\n// \"Tell me when something in this view changes\" is a Rule carrying a\n// `subscription` block that names a saved view, a cadence, a channel and a\n// recipient. There is no subscriptions table and no second notifier: the store\n// answers `custom.agg_subscriptions`, fires through `custom.agg_subscription_fire`\n// and delivers through `communication.notification`.\n//\n// AND THE ADMISSION TEST RUNS AS THE SUBSCRIBER, not as the writer\n// (`custom.agg_view_admits`): a change to a record the subscriber may not see\n// is not a notification they are entitled to, because the notification's mere\n// existence would leak the record.\n\nimport type { RecordFilter } from \"./aggregate\";\nimport type { Uuid } from \"./record\";\n\n/**\n * HOW OFTEN. `instant` fires the moment a record ENTERS the view; the other three\n * are summaries, assembled by the store at that cadence and sent as ONE message\n * naming what entered, left and changed since the last one.\n *\n * `immediate` and `digest` — the two words this store wrote before 2026-09-20 —\n * are still accepted everywhere and normalised 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 colours 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 catalogue. 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 recognise 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 recognise 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\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 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 \"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 cancelled 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 cancelled 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/** Map a PostgREST/supabase-js failure into the package's refusal shape. */\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 if (isNotASqlstate(sqlstate)) {\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 recognise 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.\n delete mapped.hint;\n }\n return mapped;\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 behaviours 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","/**\n * THE CLIENT OPERATION LEDGER — how a browser recognises 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 recognisable 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/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 normalises 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 recognise every one of them: what the read\n * door hands it is the LABEL, what the store holds is the KEY, and what a screen written before\n * this contract sends is the ID.\n */\nexport function isTheChosen(option: StoredRecord, value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n const asked = value.trim().toLowerCase();\n if (asked === \"\") return false;\n return (\n asked === optionKey(option).toLowerCase() ||\n asked === optionLabel(option).toLowerCase() ||\n asked === option.id.toLowerCase()\n );\n}\n\n/** Every value of one cell, as strings, whether the Field is multi or not. */\nexport function choiceValuesOf(value: unknown): string[] {\n if (Array.isArray(value)) return value.filter((v): v is string => typeof v === \"string\");\n if (typeof value === \"string\" && value !== \"\") return [value];\n return [];\n}\n\n/**\n * What the read door said about one column's choices: the key behind the label, and whether the\n * option was retired and why. Returns an empty array when the document carries no `_choices`\n * entry for that column, which is also what a document written before this contract looks like.\n */\nexport function choicesOf(document: RecordDocument | undefined, fieldKeyOrId: string): ChoiceOption[] {\n const block = document?.[\"_choices\"];\n if (!block || typeof block !== \"object\") return [];\n const entry = (block as Record<string, unknown>)[fieldKeyOrId];\n if (!entry) return [];\n const list = Array.isArray(entry) ? entry : [entry];\n return list.filter((x): x is ChoiceOption => !!x && typeof x === \"object\" && typeof (x as ChoiceOption).key === \"string\");\n}\n\n/** True when this cell's value points at a choice that has since been retired. */\nexport function holdsARetiredChoice(document: RecordDocument | undefined, fieldKeyOrId: string): boolean {\n return choicesOf(document, fieldKeyOrId).some((c) => c.retired === true);\n}\n\n/** True when a token looks like a uuid — which a choice value is no longer allowed to be. */\nexport function looksLikeAnId(value: unknown): boolean {\n return typeof value === \"string\" && isUuidShape(value);\n}\n\n/* ═══ WORDS TYPED INTO A CHOICE CELL THAT ARE NOT A CHOICE (lane CHOICE-COLUMN-EDIT) ═══════════\n *\n * A software team's \"Account Type\" column offers Cursor · Claude · Codex, and somebody types\n * \"Gemini\". Three answers are possible and the store has a door for each: add it to the choices\n * and the cell takes it (`recordUpdateAddingChoices`), keep it as typed on a column that takes\n * other values (`config.allow_other` — an ordinary `recordUpdate`), or refuse it. Which one is\n * the Feature Knob `custom/choice_nudge` (`choiceNudge()`), and this is the ONE place that\n * reads it, so the grid, the record form and every other surface answer the same way.\n */\n\n/** The Feature Knob `custom/choice_nudge`: ask (the default), always add, or never add. */\nexport type ChoiceNudge = \"ask\" | \"always_add\" | \"never_add\";\n\nexport const CHOICE_NUDGES: readonly ChoiceNudge[] = [\"ask\", \"always_add\", \"never_add\"];\n\n/** Any answer the knob door gives, as one of the three; anything unknown is the default, `ask`. */\nexport function asChoiceNudge(value: unknown): ChoiceNudge {\n return typeof value === \"string\" && (CHOICE_NUDGES as readonly string[]).includes(value) ? (value as ChoiceNudge) : \"ask\";\n}\n\n/** What `decideTypedChoice` answers. */\nexport type TypedChoiceDecision =\n /** Nothing was typed. */\n | { decision: \"empty\" }\n /** The words name a live choice (by its words or its key, any case): write `key`. */\n | { decision: \"chosen\"; key: string; label: string }\n /** Ask the person. `keepOffered` is true only when the column takes other values. */\n | { decision: \"ask\"; words: string; keepOffered: boolean }\n /** Add the words to the choices and the cell takes them — without asking (`always_add`). */\n | { decision: \"add\"; words: string }\n /** Keep the words as typed, an \"other\" value (`never_add` on a column that takes other values). */\n | { decision: \"keep_as_typed\"; words: string }\n /** The words are not one of the choices and nothing may add them (`never_add`, closed column). */\n | { decision: \"not_a_choice\"; words: string };\n\n/** A choice as either door hands it: an option record (`fieldOptions`) or a `_choices` entry. */\nexport type ChoiceLike = StoredRecord | ChoiceOption;\n\nfunction choiceKeyAndLabel(option: ChoiceLike): { key: string; label: string; retired: boolean } {\n if (typeof (option as ChoiceOption).key === \"string\" && typeof (option as ChoiceOption).label === \"string\") {\n const o = option as ChoiceOption;\n return { key: o.key, label: o.label, retired: o.retired === true };\n }\n // `custom.field_options` answers LIVE options only, so an option record is never retired.\n const record = option as StoredRecord;\n return { key: optionKey(record), label: optionLabel(record), retired: false };\n}\n\n/**\n * THE ONE DECISION for words typed into a choice cell.\n *\n * `options` are the column's choices; a retired one is not pickable, so words naming only a\n * retired choice are treated as new (adding them brings the retired choice back, which is what\n * the store does). `nudge` absent or unknown is `ask`.\n */\nexport function decideTypedChoice(args: {\n words: string;\n options: readonly ChoiceLike[];\n allowOther: boolean;\n nudge?: ChoiceNudge | string | null | undefined;\n}): TypedChoiceDecision {\n const words = args.words.trim();\n if (words === \"\") return { decision: \"empty\" };\n const asked = words.toLowerCase();\n for (const option of args.options) {\n const { key, label, retired } = choiceKeyAndLabel(option);\n if (retired) continue;\n if (label.toLowerCase() === asked || key.toLowerCase() === asked) return { decision: \"chosen\", key, label };\n }\n const nudge = asChoiceNudge(args.nudge);\n if (nudge === \"always_add\") return { decision: \"add\", words };\n if (nudge === \"never_add\") return args.allowOther ? { decision: \"keep_as_typed\", words } : { decision: \"not_a_choice\", words };\n return { decision: \"ask\", words, keepOffered: args.allowOther };\n}\n\n/* ═══ REMOVING A CHOICE THAT RECORDS STILL HOLD (lane CHOICE-TAILS, 2026-09-27) ════════════════\n *\n * A dental front desk's \"Visit Type\" offers Cleaning · Exam · X-ray · Whitening, and the office\n * stops booking X-rays as their own visit. Removing X-ray used to leave every record that held it\n * holding a retired choice, with nobody asked. Now the column editor asks, Notion-style:\n * \"3 records use “X-ray”.\" — move them to another choice, keep the words as other values (only\n * where the column takes other values), or clear them. The answer goes in the SAME save as the\n * list (`fieldUpdateRehomingChoices`), and that save answers its own undo.\n */\n\n/** How many records hold one choice (`custom.field_choice_usage`), keyed by the option's id. */\nexport interface ChoiceUsage {\n key: string;\n words: string;\n retired: boolean;\n /** Live records the caller may see whose cell holds the choice. */\n records: number;\n}\n\n/** Where the records of a removed choice go. */\nexport type ChoiceRehome =\n | { then: \"move\"; to: string }\n | { then: \"keep\" }\n | { then: \"clear\" };\n\n/** One cell as it was before a rehoming save — what its undo writes back. */\nexport interface ChoiceCellBack {\n record_id: string;\n value: unknown;\n}\n\n/** What `fieldUpdateRehomingChoices` answers. */\nexport interface ChoicesRehomed {\n field_id: string;\n rehomed: Array<{ choice_id: string; words: string; then: ChoiceRehome[\"then\"]; to: string | null; records: number }>;\n cells_back: number;\n /** Send `{ patch: { options: undo.options }, cells_back: undo.cells_back }` to put it all back. */\n undo: { options: Array<{ id: string; words: string }>; cells_back: ChoiceCellBack[] };\n}\n\n/**\n * THE CHOICES A LIST NO LONGER NAMES THAT RECORDS STILL HOLD — the ones the editor must ask about.\n * `beforeIds` is the list as the store answered it, `afterIds` the list as the person has it now.\n */\nexport function removedChoicesInUse(\n beforeIds: readonly string[],\n afterIds: readonly string[],\n usage: Readonly<Record<string, ChoiceUsage>> | null | undefined,\n): Array<{ id: string; words: string; records: number }> {\n if (!usage) return [];\n const kept = new Set(afterIds);\n return beforeIds\n .filter((id) => !kept.has(id))\n .map((id) => ({ id, words: usage[id]?.words ?? \"\", records: usage[id]?.records ?? 0 }))\n .filter((c) => c.records > 0);\n}\n\n/** “1 record uses “X-ray”.” · “3 records use “X-ray”.” — the question's first line. */\nexport function recordsUseSentence(records: number, words: string): string {\n return `${records} ${records === 1 ? \"record uses\" : \"records use\"} “${words}”.`;\n}\n\n/** What the answer will do, said before Save: “3 records move to “Exam”.” */\nexport function rehomeSentence(records: number, words: string, rehome: ChoiceRehome, toWords?: string): string {\n const n = `${records} ${records === 1 ? \"record\" : \"records\"}`;\n if (rehome.then === \"move\") return `${n} that ${records === 1 ? \"holds\" : \"hold\"} “${words}” ${records === 1 ? \"moves\" : \"move\"} to “${toWords ?? \"another choice\"}”.`;\n if (rehome.then === \"keep\") return `${n} ${records === 1 ? \"keeps\" : \"keep\"} “${words}” as another value.`;\n return `${n} that ${records === 1 ? \"holds\" : \"hold\"} “${words}” ${records === 1 ? \"is\" : \"are\"} cleared.`;\n}\n","// src/placement.ts — @ai-matrx/records\n//\n// WHO KEEPS A TABLE, AND WHETHER THE CONTEXT PICKER OFFERS IT (lane SC-1 PLACEMENT,\n// SCOPES-CONTEXT-TRANSITION.md §2.3 P1/P2 as amended by the plan attack, H5).\n//\n// The store answers these facts; this file only carries their shape and the two questions\n// every screen asks of them. It re-derives nothing — which tables a feature keeps is decided\n// ONCE, by `custom.table_placement` in the database, from the Table document's own keys and\n// the facts the door that made it already wrote (a column's choices, a scope's own table, a\n// checklist's steps, a booking page's holds, a workflow's states, the app's own tables).\n//\n// platform_owned the store's one flag. true = the app or one of its features keeps it,\n// and a person's list of tables shows it only behind \"Show everything\".\n// kept_for WHICH feature: context · choices · checklists · bookings · workflow ·\n// app · store, or whatever word the next feature brings. Null when the\n// organization keeps the table.\n// offered_as_context whether the context picker offers the Table. Only a Table somebody\n// marked (a scope type the scopes mover lands) is offered.\n// foundation lane 10 FD: part of the business's day-one data (Patients, Therapists,\n// Services). Independent of who keeps the table. Absent is false.\n//\n// Import-inert: types and pure functions, nothing else.\n\nimport type { Uuid } from \"./record\";\n\n/** The placement facts, as the Table document or `custom.table` carries them. */\nexport interface TablePlacement {\n platform_owned?: boolean | null;\n kept_for?: string | null;\n offered_as_context?: boolean | null;\n foundation?: boolean | null;\n}\n\n/**\n * One row of `custom.table_facts` since SC-1 — the two lane facts it always answered\n * (`visibility`, `mine`) and the placement, with the sentence a person reads and where the\n * table is used. A store without the SC-1 door answers the first three columns only; every\n * placement column is then `undefined`, and the readers below treat the table as the\n * organization's own — exactly what that store's older screens did.\n */\nexport interface TablePlacementFact extends TablePlacement {\n table_id: Uuid;\n visibility: string;\n mine: boolean;\n /** The heading a kept table is listed under: \"The context system\", \"The choices behind your columns\", … */\n keeper_group?: string | null;\n /** One plain sentence: who keeps it and where it opens from. Null for the organization's own. */\n keeper_says?: string | null;\n /** Where the table is used: `table` (another Table, or itself) or `scope` (a context scope). */\n used_in_kind?: \"table\" | \"scope\" | null;\n used_in_id?: Uuid | null;\n /** The Table that page belongs to, when `used_in_kind` is `table`. */\n used_in_table_id?: Uuid | null;\n}\n\n/** Whether a person's list of tables keeps this one out of sight until \"Show everything\". */\nexport function keptOutOfSight(placement: TablePlacement | null | undefined): boolean {\n return placement?.platform_owned === true;\n}\n\n/** Whether the Table is part of the business's day-one data (lane 10 FD). Absent is no. */\nexport function isFoundation(placement: TablePlacement | null | undefined): boolean {\n return placement?.foundation === true;\n}\n\n/** Whether the context picker may offer this Table. Absent is no. */\nexport function offeredAsContext(placement: TablePlacement | null | undefined): boolean {\n return placement?.offered_as_context === true;\n}\n\n/**\n * The placement facts folded onto a table list, by id. Pure — returns new objects and leaves\n * the list it was given alone. A table the facts do not name is returned unchanged.\n */\nexport function withTablePlacement<T extends { id: Uuid }>(\n tables: readonly T[],\n facts: readonly TablePlacementFact[] | null | undefined,\n): Array<T & Partial<TablePlacementFact>> {\n if (!facts) return [...tables];\n const byId = new Map(facts.map((f) => [f.table_id, f]));\n return tables.map((table) => {\n const fact = byId.get(table.id);\n if (!fact || fact.platform_owned === undefined) return table;\n return {\n ...table,\n platform_owned: fact.platform_owned,\n kept_for: fact.kept_for ?? null,\n offered_as_context: fact.offered_as_context ?? false,\n foundation: fact.foundation ?? false,\n keeper_group: fact.keeper_group ?? null,\n keeper_says: fact.keeper_says ?? null,\n used_in_kind: fact.used_in_kind ?? null,\n used_in_id: fact.used_in_id ?? null,\n used_in_table_id: fact.used_in_table_id ?? null,\n };\n });\n}\n\n/**\n * THE KEPT TABLES, GROUPED UNDER THEIR KEEPER, in the order each group first appears. A kept\n * table the store gave no heading goes under \"Platform tables\" — never dropped.\n */\nexport function keptGroups<T extends TablePlacement & Partial<TablePlacementFact>>(\n tables: readonly T[],\n): Array<{ group: string; tables: T[] }> {\n const out: Array<{ group: string; tables: T[] }> = [];\n const at = new Map<string, number>();\n for (const table of tables) {\n if (!keptOutOfSight(table)) continue;\n const group = table.keeper_group?.trim() || \"Platform tables\";\n let i = at.get(group);\n if (i === undefined) {\n i = out.length;\n at.set(group, i);\n out.push({ group, tables: [] });\n }\n out[i]!.tables.push(table);\n }\n return out;\n}\n\n/**\n * WHERE A KEPT TABLE OPENS FROM (THE DOOR LAW): the host's own addresses for a table and for a\n * context scope, chosen by what the store said the table is used in. With nothing said, the\n * table's own page — a kept table is never a row with nowhere to go.\n */\nexport function keptTableHref(\n fact: { table_id: Uuid } & Partial<TablePlacementFact>,\n hrefs: { table: (tableId: Uuid) => string; scope: (scopeId: Uuid) => string },\n): string {\n if (fact.used_in_kind === \"scope\" && fact.used_in_id) return hrefs.scope(fact.used_in_id);\n if (fact.used_in_kind === \"table\" && (fact.used_in_table_id || fact.used_in_id)) {\n return hrefs.table((fact.used_in_table_id || fact.used_in_id)!);\n }\n return hrefs.table(fact.table_id);\n}\n\n// ── WHERE A TABLE LIVES, AND MOVING IT (lane SC-1-TAILS; the owner, 2026-09-23: \"I am not seeing\n// how I can see what org this data is in … make it easy to see and set the org for something\") ──\n//\n// `custom.table_home` says which organization a Table lives in — read FROM THE TABLE, never from\n// the organization the person is working in — whether this person may move it and where to, and\n// what holds it in place; `custom.table_move` moves it (with every Table inside it or its rows)\n// or refuses with one sentence. These are the shapes and the two pure readers every screen uses:\n// `parseTableHome` reads the store's answer strictly (an answer it cannot read is \"could not\n// ask\", never a guess) and `moveConsequence` says what a move does before it happens (the\n// destructive-and-expensive-actions law). The client's `tableHome` / `tableMove` are the calls.\n\n/** One of the person's other organizations, and whether the Table can go there. */\nexport interface TableHomeDestination {\n id: Uuid;\n name: string;\n /**\n * The organization's web address (UI-FIX-19). A screen draws it beside a name another\n * destination also carries, so two organizations with one name can be told apart. `null` when\n * the store's answer predates it.\n */\n slug: string | null;\n /** The person's role there: owner · admin · member. */\n role: string;\n /** False when the store says the Table cannot go there; `why` says why, in its words. */\n ok: boolean;\n why: string | null;\n}\n\n/** `custom.table_home`'s answer, read. */\nexport interface TableHome {\n table: { id: Uuid; name: string; version: number };\n /** Where it lives, from the Table itself. */\n organization: { id: Uuid; name: string };\n /** The Table's maker, or an owner/admin of its organization. */\n mayMove: boolean;\n /** When `mayMove` is false: the sentence that says who can. */\n whyNot: string | null;\n /** Sentences for what holds it where it is. Empty when nothing does. */\n heldBy: string[];\n /** Every other organization this person belongs to. */\n destinations: TableHomeDestination[];\n carries: {\n fields: number;\n records: number;\n inTrash: number;\n choiceLists: number;\n withIt: number;\n /** Tables that ride along because they live inside it or inside its rows. */\n tablesInside: number;\n /** Links between its rows and rows that stay, which will reach back across the wall. */\n linksAcross: number;\n };\n}\n\n/** What `custom.table_move` answered when the move landed. */\nexport interface TableMoved {\n to: { id: Uuid; name: string };\n from: { id: Uuid; name: string };\n tableName: string;\n}\n\nfunction countOf(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction wordsOf(value: unknown): string | null {\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n/** Read the store's answer strictly: an answer this cannot read is `null`, never a guess. */\nexport function parseTableHome(raw: unknown): TableHome | null {\n if (!raw || typeof raw !== \"object\") return null;\n const row = raw as Record<string, unknown>;\n const table = row.table as Record<string, unknown> | undefined;\n const org = row.organization as Record<string, unknown> | undefined;\n if (!table || !org || !wordsOf(table.id) || !wordsOf(org.id) || !wordsOf(org.name)) return null;\n const carries = (row.carries ?? {}) as Record<string, unknown>;\n const destinations = Array.isArray(row.destinations) ? row.destinations : [];\n return {\n table: { id: String(table.id), name: wordsOf(table.name) ?? \"This table\", version: countOf(table.version) },\n organization: { id: String(org.id), name: String(org.name) },\n mayMove: row.may_move === true,\n whyNot: wordsOf(row.why_not),\n heldBy: Array.isArray(row.held_by) ? row.held_by.filter((s): s is string => typeof s === \"string\") : [],\n destinations: destinations\n .filter((d): d is Record<string, unknown> => !!d && typeof d === \"object\" && !!wordsOf((d as Record<string, unknown>).id))\n .map((d) => ({\n id: String(d.id),\n name: wordsOf(d.name) ?? \"An organization\",\n slug: wordsOf(d.slug),\n role: wordsOf(d.role) ?? \"member\",\n ok: d.ok === true,\n why: wordsOf(d.why),\n })),\n carries: {\n fields: countOf(carries.fields),\n records: countOf(carries.records),\n inTrash: countOf(carries.in_trash),\n choiceLists: countOf(carries.choice_lists),\n withIt: countOf(carries.with_it),\n tablesInside: countOf(carries.tables_inside),\n linksAcross: countOf(carries.links_across),\n },\n };\n}\n\n/** Read `custom.table_move`'s answer; `null` when it is not a landed move. */\nexport function parseTableMoved(raw: unknown): TableMoved | null {\n const row = (raw ?? {}) as Record<string, unknown>;\n const to = (row.to ?? {}) as Record<string, unknown>;\n const from = (row.from ?? {}) as Record<string, unknown>;\n const table = (row.table ?? {}) as Record<string, unknown>;\n if (row.moved !== true || !wordsOf(to.id)) return null;\n return {\n to: { id: String(to.id), name: wordsOf(to.name) ?? \"the new organization\" },\n from: { id: wordsOf(from.id) ?? \"\", name: wordsOf(from.name) ?? \"its old organization\" },\n tableName: wordsOf(table.name) ?? \"The table\",\n };\n}\n\n/**\n * What `custom.table_duplicate` answered when the copy landed (lane TABLE-ACTIONS). The copy is a\n * NEW Table in `organization`; `copied` counts what came with it and `notCopied` names, in the\n * store's own words, what a copy never carries (history, forms, portals, dashboards, rules, …).\n */\nexport interface TableDuplicated {\n table: { id: Uuid; name: string };\n from: { id: Uuid; name: string; organizationId: Uuid };\n organization: { id: Uuid; name: string };\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 if (row.duplicated !== true || row.status !== \"done\" || !wordsOf(table.id) || !wordsOf(organization.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: { id: String(organization.id), name: wordsOf(organization.name) ?? \"its organization\" },\n copied: {\n fields: countOf(copied.fields),\n choiceLists: countOf(copied.choice_lists),\n choices: countOf(copied.choices),\n views: countOf(copied.views),\n records: countOf(copied.records),\n withRecords: copied.with_records === true,\n },\n archivedFieldsLeft: countOf(left.archived_fields),\n archivedRecordsLeft: typeof left.archived_records === \"number\" ? left.archived_records : null,\n recordsNotYoursLeft: typeof left.records_not_yours_to_open === \"number\" ? left.records_not_yours_to_open : null,\n hiddenColumns: Object.fromEntries(\n Object.entries((left.hidden_columns ?? {}) as Record<string, unknown>).map(([name, n]) => [name, countOf(n)]),\n ),\n privateViewsLeft: countOf(left.private_views),\n rowReferencesDropped: Array.isArray(left.row_references_dropped)\n ? left.row_references_dropped.filter((s): s is string => typeof s === \"string\")\n : [],\n viewsSharedAsNewViews: Array.isArray(left.views_shared_as_new_views)\n ? left.views_shared_as_new_views.filter((s): s is string => typeof s === \"string\")\n : [],\n changedDuringCopy: (() => {\n const ch = (row.changed_during_copy ?? {}) as Record<string, unknown>;\n return {\n columnsArchivedSince: Array.isArray(ch.columns_archived_since)\n ? ch.columns_archived_since.filter((s): s is string => typeof s === \"string\")\n : [],\n rowsChangedAfterCopied: countOf(ch.rows_changed_after_copied),\n rowsArchivedSince: typeof ch.rows_archived_since === \"number\" ? ch.rows_archived_since : null,\n rowsAddedSince: typeof ch.rows_added_since === \"number\" ? ch.rows_added_since : null,\n };\n })(),\n viewsNotCopied: Array.isArray(left.views_not_copied)\n ? left.views_not_copied.filter((s): s is string => typeof s === \"string\")\n : [],\n notCopied: Array.isArray(left.not_copied) ? left.not_copied.filter((s): s is string => typeof s === \"string\") : [],\n path: wordsOf(row.path) ?? `/data/${String(table.id)}`,\n };\n}\n\nfunction plural(n: number, one: string, many: string): string {\n return `${n} ${n === 1 ? one : many}`;\n}\n\n/** The consequence of a move, said before it happens (destructive-and-expensive-actions law). */\nexport function moveConsequence(home: TableHome, to: Pick<TableHomeDestination, \"name\">): string {\n const c = home.carries;\n const parts = [plural(c.fields, \"column\", \"columns\"), plural(c.records, \"row\", \"rows\")];\n if (c.inTrash > 0) parts.push(`${c.inTrash} in the trash`);\n const extra = c.choiceLists + c.withIt;\n return (\n `${home.table.name} moves to ${to.name} with its ${parts.join(\", \")}` +\n (c.tablesInside > 0\n ? `, the ${plural(c.tablesInside, \"table\", \"tables\")} that live${c.tablesInside === 1 ? \"s\" : \"\"} inside it or its rows (with their own rows)`\n : \"\") +\n (extra > 0\n ? `, and ${plural(extra, \"thing\", \"things\")} built only on it (choice lists, rules, dashboards, templates)`\n : \"\") +\n `, its comments, forms, saved views and history. ` +\n (c.linksAcross > 0\n ? `${plural(c.linksAcross, \"link\", \"links\")} to rows that stay in ${home.organization.name} keep${c.linksAcross === 1 ? \"s\" : \"\"} pointing there, across the two organizations. `\n : \"\") +\n `People who see it only because they are in ${home.organization.name} stop seeing it; people it ` +\n `was shared with by name keep it. You can move it back from the same place.`\n );\n}\n","// src/level.ts — @ai-matrx/records\n//\n// THE FOUR WORDS, AND THEIR ORDER. `public.permission_level` is a closed enum —\n// viewer < commenter < edit_content < editor < admin — and the store says so in its own\n// refusals (\"This needs the admin level (viewer < commenter < editor < admin)\").\n//\n// It lives here, in the headless package, for one reason: a screen that has to\n// decide whether to DRAW a control needs the same ordering the door uses to\n// decide whether to accept the call. Two orderings is two answers to one\n// question, and the second one is always the wrong one.\n//\n// Nothing here decides policy. `atLeast` compares two words the store defined;\n// which word a door requires is the door's business and is never restated here.\n\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 order the store writes them in, lowest first. */\nexport const PERMISSION_LEVELS: readonly PermissionLevel[] = [\n \"viewer\",\n \"commenter\",\n \"edit_content\",\n \"editor\",\n \"admin\",\n] as const;\n\nconst ORDINAL: Record<PermissionLevel, number> = {\n viewer: 1,\n commenter: 2,\n edit_content: 3,\n editor: 4,\n admin: 5,\n};\n\n/** Whether `held` is the same rung as `needed` or a higher one. Nothing held is never enough. */\nexport function atLeast(held: PermissionLevel | null | undefined, needed: PermissionLevel): boolean {\n if (!held) return false;\n const have = ORDINAL[held];\n return have !== undefined && have >= ORDINAL[needed];\n}\n\n/** A level word the store sent, or null when it sent something this package does not know. */\nexport function asPermissionLevel(word: unknown): PermissionLevel | null {\n return typeof word === \"string\" && word in ORDINAL ? (word as PermissionLevel) : null;\n}\n\n/** The higher of two levels — what a person holds when two ways in both let them through. */\nexport function highestLevel(\n left: PermissionLevel | null | undefined,\n right: PermissionLevel | null | undefined,\n): PermissionLevel | null {\n if (!left) return right ?? null;\n if (!right) return left;\n return ORDINAL[left] >= ORDINAL[right] ? left : right;\n}\n\n/**\n * What one subject's level is, as `custom.my_levels` answers it. `null` is an\n * ANSWER — \"you hold nothing on this\" — and never a missing row: a screen that\n * could not tell \"no access\" from \"not asked yet\" would draw one of them as the\n * other.\n */\nexport interface MyLevel {\n id: string;\n level: PermissionLevel | null;\n}\n","// src/core/keysetCursor.ts — @ai-matrx/records\n//\n// THE KEYSET CURSOR AT THE CLIENT EDGE (AP3-KEYSET-DOOR, 2026-10-06). `custom.read_records_keyset`\n// answers its cursor as a small JSON object (the last row's sort values, its id, and a fingerprint of\n// the question it was made under). Screens never read it: it travels as one opaque base64url string\n// and is handed back unchanged. It carries nothing secret — the store re-applies the row predicate on\n// every page and refuses, by name, a cursor made under a different sort, filter or search.\n\nfunction utf8ToBinary(text: string): string {\n let out = \"\";\n for (const byte of new TextEncoder().encode(text)) out += String.fromCharCode(byte);\n return out;\n}\n\nfunction binaryToUtf8(binary: string): string {\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n}\n\n/** The store's cursor object as one opaque base64url string. */\nexport function encodeKeysetCursor(cursor: unknown): string {\n return btoa(utf8ToBinary(JSON.stringify(cursor))).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * The string back into the object the store made, or `null` when it is not one of its cursors (not\n * base64url, not JSON, or not an object). A null is refused at the edge; it is never sent as \"page 1\".\n */\nexport function decodeKeysetCursor(cursor: string): Record<string, unknown> | null {\n if (!/^[A-Za-z0-9_-]+$/.test(cursor)) return null;\n try {\n const padded = cursor.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (cursor.length % 4)) % 4);\n const value: unknown = JSON.parse(binaryToUtf8(atob(padded)));\n return value !== null && typeof value === \"object\" && !Array.isArray(value) ? (value as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n","// src/table.ts — @ai-matrx/records\n//\n// THE TABLE AND THE HOME. REC-1, REC-3, REC-14, REC-26, REC-32, REC-33.\n// A Table is a Record (REC-25), which is why every shape here carries the\n// record contract as well as its own columns: `custom.table` is a VIEW over\n// `custom.record`, and this is that view's shape.\n\nimport type { Timestamp, Uuid } from \"./record\";\nimport type {\n StorageMode,\n TableDisplay,\n TableOrigin,\n TableType,\n} from \"./vocabulary\";\n\n/**\n * REC-1. A Table declares its fields, exactly one Home, and the properties\n * `display`, `ordered`, `heavy` | `light`, `retention` and `detail`.\n */\nexport interface Table {\n id: Uuid;\n organization_id: Uuid;\n /**\n * The access ladder's Table \"Level\": organization · public · confidential · private. Absent is\n * the organization's own. Confidential and Private records have no \"Shown to\".\n */\n level?: string | null;\n /** The token this Table is addressed by. */\n slug: string;\n name: string;\n label_singular: string | null;\n label_plural: string | null;\n icon: string | null;\n color: string | null;\n /** REC-32. One of the seven, closed. */\n type: TableType;\n /** REC-11. A detail Table inherits only: no direct shares, never a Home. */\n detail: boolean;\n parent_token: string | null;\n /** AGT-1 / AGT-2. On by default for a custom table; an organization turns it off. */\n agent_writable: boolean;\n display: TableDisplay | null;\n ordered: boolean;\n /** REC-4. `heavy` is indexed with Rules on write; `light` is the whole document with Rules on read. */\n weight: StorageMode;\n /** REC-23. How long a soft delete stays reversible. */\n retention_days: number | null;\n /** REC-2. Every Table has one; without it a record cannot be a chip. */\n title_field: string | null;\n /** 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 /** 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 behaviour (`text`, `range`, …)\n * - `format` how it is shown (`long`, `phone`, `currency`, …); `null` when it has none\n * - `label` the column's name\n * - `multi` / `required` booleans (absent = `false`)\n * - `unique` whether it holds a `unique` rule\n * - `spec` the spec for that column could not be read at all; `declared` is the store's sentence\n *\n * The declared side is the spec as the store WOULD store it, so `long_text` compares as the\n * `text` + `long` it is stored as — never a false difference.\n */\n/** `extra`: a column the table holds that the spec no longer declares (kept, never removed). */\nexport type FieldDriftAspect = \"type\" | \"format\" | \"label\" | \"multi\" | \"required\" | \"unique\" | \"spec\" | \"extra\";\n\nexport interface FieldDrift {\n /** The column's key. */\n field: string;\n aspect: FieldDriftAspect;\n /** What the column holds now. */\n stored: string | boolean | null;\n /** What the spec asked for (for `spec`, the store's sentence about why it could not be read). */\n declared: string | boolean | null;\n}\n\nconst DRIFT_ASPECTS: readonly FieldDriftAspect[] = [\"type\", \"format\", \"label\", \"multi\", \"required\", \"unique\", \"spec\", \"extra\"];\n\n/**\n * The store's `drift` answer, typed. `null` when the store did not send one — a `table_ensure`\n * body older than `lane12_c_an_ensured_table_says_what_differs_from_its_spec.sql` — which means\n * \"not compared\", never \"no difference\". An entry of an aspect this package does not know is kept\n * as `spec`, so a newer store is never silenced.\n */\nexport function parseFieldDrift(raw: unknown): FieldDrift[] | null {\n if (!Array.isArray(raw)) return null;\n const scalar = (v: unknown): string | boolean | null =>\n typeof v === \"string\" || typeof v === \"boolean\" ? v : v === null || v === undefined ? null : JSON.stringify(v);\n return raw\n .filter((d): d is Record<string, unknown> => Boolean(d) && typeof d === \"object\")\n .map((d) => ({\n field: String(d.field ?? \"\"),\n aspect: DRIFT_ASPECTS.includes(d.aspect as FieldDriftAspect) ? (d.aspect as FieldDriftAspect) : \"spec\",\n stored: scalar(d.stored),\n declared: scalar(d.declared),\n }));\n}\n","// src/grid.ts — @ai-matrx/records\n//\n// THE GRID'S STORE PRIMITIVES (lane GRID-PRIMITIVES, 2026-09-22).\n//\n// The /data grid is being rebuilt on the record store with its UI and behaviour 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\";\nexport type GridRowHeight = \"compact\" | \"normal\" | \"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 honour, 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// ── 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/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\";\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 catalogue 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 * catalogue 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 catalogue 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 const owed = OWED_BY[name];\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: owed\n ? `That door is ${owed}. 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/** 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 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 honoured), 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 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 parityValues: \"parity_values\",\n tableDeclare: \"table_declare\",\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 fieldUpdate: \"field_update\",\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 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 // 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 catalogue: `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 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 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 // 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 // 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 commentWrite: \"comment_write\",\n commentResolve: \"io_comment_resolve\",\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 // 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 CATALOGUE 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 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 // 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 tableWebhookDeclare: \"table_webhook_declare\",\n tableWebhooks: \"table_webhooks\",\n tableWebhookArchive: \"table_webhook_archive\",\n tableFromExample: \"table_from_example\",\n autonumberBackfill: \"autonumber_backfill\",\n ioExport: \"io_export\",\n tableListEverywhere: \"table_list_everywhere\",\n dataHomeTables: \"data_home_tables\",\n adminAllTables: \"admin_all_tables\",\n tableSync: \"table_sync\",\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 catalogue 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 tableCopiesInProgress: \"table_copies_in_progress\",\n tableFind: \"table_find\",\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 honour `schema`.\n */\nexport function asRecordsDataSource(source: unknown): RecordsDataSource {\n if (source === null || typeof source !== \"object\") return supabaseDataSource({});\n if (isBound(source)) return source;\n const candidate = source as Partial<SupabaseLike> & { rpc?: unknown; from?: unknown; auth?: unknown };\n const looksLikeSupabaseJs =\n typeof candidate.schema === \"function\" &&\n typeof candidate.from === \"function\" &&\n candidate.auth !== null &&\n typeof candidate.auth === \"object\";\n if (looksLikeSupabaseJs || typeof candidate.rpc !== \"function\") return supabaseDataSource(source);\n return source as RecordsDataSource;\n}\n","// src/drill.ts — @ai-matrx/records\n//\n// THE ONE READ CONTRACT FOR EVERY TABLE (lane DRILL-STANDARD-DOOR, DRILL-DOWN-DESIGN.md §d).\n//\n// A question — group by these Dimensions, show these Measures, cut time by day…year in the\n// organization's calendar, compare with a prior window, pivot one Dimension across — asked of\n// a SOURCE, and answered in one shape whichever kind of source it is:\n//\n// { kind: \"table\", id } a custom Table in the record store (custom.record_aggregate,\n// its Dimensions from custom.table_dimensions)\n// { kind: \"entity\", token } a standard Postgres table by its registry token (\"agent\",\n// \"ai_model\"), or a DECLARED definition by its key (a fact over\n// several tables joined by their foreign keys, e.g. \"agents_by_model\")\n//\n// Three doors, all in schema `platform`, all SECURITY INVOKER: a standard table is counted by a\n// statement running as the person, so the table's own row security decides every row counted —\n// an answer never holds a number she could not assemble from rows she can open. Groups past the\n// cap (\"Groups shown before Other\", knob drill/groups_per_level) fold into ONE Other row, and the\n// total row says so in words.\n//\n// Vocabulary (Arman, 2026-09-29): \"Dimension\" and \"Measure\" are platform words; a saved\n// exploration is a Saved view. \"Drill definition\" is still a working label (DRILL-DOWN-DESIGN D0).\n\nimport type { Uuid } from \"./record\";\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 colour 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 colour — the old usage page's origin colours.\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\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 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\n/** The address of a finding's setting: `drill.finding.<definition>.<finding>.<knob>`. */\nexport function drillFindingKnob(definition: string, finding: string, knob: string): string {\n return `drill.finding.${definition}.${finding}.${knob}`;\n}\n\nexport interface DrillDefinition {\n key: string;\n label: string;\n source: DrillSource;\n /** One sentence: \"one row per agent\". */\n grain: string;\n lanes: DrillLane[];\n dimensions: DrillDimension[];\n measures: DrillMeasure[];\n paths: DrillPath[];\n detail: { columns: string[]; open?: string };\n default: DrillQuestion;\n /** Keys that came from inference, so a screen can say so. */\n inferred?: string[];\n mode?: \"invoker\" | \"definer\";\n /** Honest notes about what inference could not offer, in words. */\n says?: string[];\n /** Built-in Saved views, listed first and read-only. */\n views?: DrillView[];\n /** Findings (\"dig here\"), answered by the same door. */\n findings?: DrillFinding[];\n /** The records relation (what \"See these records\" reads): a definer definition's declared relation, or an invoker definition's own rows. */\n records?: DrillRecords;\n /**\n * The drill setting (minutes) after which the definition's `as_of` is old enough for a screen to say\n * \"the schedule is behind\" — null when the definition is counted live.\n */\n stale_after_knob: string | null;\n}\n\n/** One row of an answer. */\nexport interface DrillAnswerRow {\n /** `group` a shown group · `other` every group past the cap · `total` the whole answer (or a pivot column's total). */\n kind: \"group\" | \"other\" | \"total\";\n /** Each asked Dimension -> its value (a period by its label). A pivot cell also carries the `across` key. */\n groups: Record<string, unknown> | null;\n measures: Record<string, number | string | null> | null;\n row_count: number;\n prior_groups: Record<string, unknown> | null;\n prior_measures: Record<string, number | string | null> | null;\n prior_row_count: number | null;\n delta: Record<string, { current: number | null; prior: number | null; change: number | null; change_pct: number | null }> | null;\n compare: Record<string, unknown> | null;\n /** How many groups there were before the cap (current window). */\n distinct_groups: number | null;\n /** Relation Dimensions' labels, read as the person through the target's own row security. */\n labels: Record<string, string>;\n /** The answer's honest sentences (the cut, a column past its cap, a name that could not be read). */\n says: string | null;\n /** The moment a summary fact counted through (ISO); null when counted live from the table. */\n as_of: string | null;\n}\n\nexport interface DrillAnswer {\n rows: DrillAnswerRow[];\n /** Every sentence the rows carry, once. */\n says: string[];\n /** The total row (kind total, no group). */\n total: DrillAnswerRow | null;\n /** The moment the answer counted through (the rows' `as_of`); null when counted live. */\n as_of: string | null;\n}\n\n/** The records behind a number (\"see these records\"): the same filter, read as the person. */\nexport interface DrillRowsPage {\n total: number;\n limit: number;\n offset: number;\n rows: Array<Record<string, unknown>>;\n next_offset?: number;\n columns?: string[];\n says?: string;\n /** The moment these records are cut at — the number's `as_of`; null when read live. */\n as_of: string | null;\n /**\n * A definer definition's records, first page only: every Measure that adds up (sum, count, ratio)\n * summed over the SAME filter — what these records add up to, which is the number they open.\n */\n measures?: Record<string, number | string | null>;\n}\n\n/**\n * A DECLARED drill definition (a `*.drill.ts` file): an override of one standard table (its key\n * IS that table's registry token) or a fact over several tables (a key of its own). The one sync\n * script (scripts/drill-sync.ts) compiles each into `platform.drill_def__<key>()`; the store's\n * validator, platform.drill_definition_problems, judges it at sync, at census and on every ask.\n */\nexport interface DrillDeclaration {\n key: string;\n label: string;\n grain: string;\n /** The fact's registry token. */\n fact: string;\n /** invoker (default): the fact's own row security decides. definer: the lane rules below do. */\n mode?: \"invoker\" | \"definer\";\n lanes: DrillLane[];\n /** invoker: which columns narrow the organization and mine lanes. */\n lane_columns?: { organization?: string; mine?: string };\n /** definer ONLY, and required for every lane: a closed vocabulary, never SQL. */\n lane_rules?: {\n mine?: { column: string };\n organization?: { column: string; rule: \"member\" | \"admin\" };\n platform?: { rule: \"super_admin\" };\n };\n /** Star joins along a real foreign key, many-to-one only. `from` is a fact column or `join.column`. */\n joins?: Array<{ as: string; token: string; from: string }>;\n dimensions: DrillDimension[];\n measures: DrillMeasure[];\n paths?: DrillPath[];\n detail?: { columns: string[]; open?: string };\n default?: DrillQuestion;\n /** An override may hide inferred keys. */\n hide?: string[];\n /** Built-in Saved views (every question judged against this definition by the validator). */\n views?: DrillView[];\n /** Findings: questions with thresholds whose lines are settings. */\n findings?: DrillFinding[];\n /**\n * definer: the relation its records are read from (the same filter and lane rule); invoker: its own\n * fact, read as the person (lane DRILL-GAPS).\n */\n records?: DrillRecords;\n /** definer ONLY, and only over a fact that keeps a `<table>_watermark`: the stale line's setting. */\n stale_after_knob?: string;\n}\n\n/** Identity with a type: the one way a `*.drill.ts` file declares a definition. */\nexport function declareDrillDefinition<const T extends DrillDeclaration>(declaration: T): T {\n return declaration;\n}\n\n/** Decode the door's rows into an answer: the total row found, every sentence once. */\nexport function drillAnswerOf(rows: DrillAnswerRow[]): DrillAnswer {\n const says: string[] = [];\n for (const row of rows) {\n if (row.says && !says.includes(row.says)) says.push(row.says);\n }\n const total =\n rows.find((r) => r.kind === \"total\" && (!r.groups || Object.keys(r.groups).length === 0)) ?? null;\n const as_of = rows.find((r) => r.as_of != null)?.as_of ?? null;\n return { rows, says, total, as_of };\n}\n\n/** The door's name for each call (schema `platform`). */\nexport const DRILL_SCHEMA = \"platform\";\nexport const DRILL_DOORS = {\n describe: \"drill_describe\",\n ask: \"drill_ask\",\n rows: \"drill_rows\",\n} as const;\n","// src/core/query.ts — @ai-matrx/records\n//\n// THE QUERY. DOOR-6 … DOOR-10.\n//\n// Query by any combination of relation coordinates and any subset of them; as-of\n// a date on EITHER clock; promoted-field predicates. DOOR-10 is the one that\n// shapes this module: every query is filtered by Visibility INSIDE the query,\n// never post-filtered — which is why nothing here ever reads rows and then drops\n// some. The filtering happens in the store's own policies and in the doors; this\n// builder only describes what to ask for.\n//\n// DOOR-N-3: every hot read runs as a PREPARED statement. A client cannot prepare\n// anything itself, so the builder never concatenates a value into SQL: relation\n// coordinates resolve through `custom.relation_targets`, promoted predicates\n// through `custom.promoted_read`, and both are functions with typed parameters —\n// which is what \"prepared\" means on this side of the wire.\n\nimport type { RelationCoordinate } from \"../relation\";\nimport type { Timestamp, Uuid } from \"../record\";\n\n/**\n * DOOR-8. As-of on EITHER clock, and they are different questions:\n * · `record` — the record clock: what this record looked like at version time.\n * · `world` — the world clock: which values were true of the world then\n * (the Field's `dated` modifier).\n */\nexport interface AsOf {\n clock: \"record\" | \"world\";\n at: Timestamp;\n}\n\n/** A predicate over a PROMOTED field (REC-5: promotion light -> heavy). */\nexport interface PromotedPredicate {\n field_key: string;\n /** The value as text, exactly as `custom.promoted_read` takes it. */\n equals: string;\n}\n\nexport interface RecordQuery {\n table_id: Uuid;\n /** DOOR-6. Any combination, any subset. An empty list means \"no relation constraint\". */\n relations?: RelationCoordinate[];\n /** Predicates the store can answer from an index. */\n promoted?: PromotedPredicate[];\n /** DOOR-8. */\n asOf?: AsOf;\n /** DOOR-9. Ask across EVERY Home of this Table in one answer. */\n acrossHomes?: boolean;\n /** REC-23. Soft-deleted rows are out unless you say otherwise. */\n includeDeleted?: boolean;\n /** FLD-10. */\n recordType?: string;\n orderBy?: { column: \"created_at\" | \"updated_at\"; ascending?: boolean };\n limit?: number;\n offset?: number;\n}\n\n/**\n * What a query decomposes into: a set of door calls whose answers INTERSECT,\n * then one filtered read. Kept as data rather than hidden inside the client so\n * the suite can assert the plan as well as the answer — a query that quietly\n * stopped applying one of its coordinates is otherwise invisible.\n */\nexport interface QueryPlan {\n /** One `relation_targets` call per coordinate; the id sets are intersected. */\n relationCalls: Array<{ door: \"relation_targets\"; record_id: Uuid; via_key: string | null }>;\n /** One `promoted_read` call per predicate; intersected with the above. */\n promotedCalls: Array<{ door: \"promoted_read\"; field_key: string; value: string }>;\n /** The filtered read over `custom.record`, which the store's policies gate. */\n read: {\n table_id: Uuid;\n includeDeleted: boolean;\n recordType: string | null;\n asOf: AsOf | null;\n acrossHomes: boolean;\n orderBy: { column: string; ascending: boolean };\n limit: number;\n offset: number;\n };\n /**\n * Stated so nobody has to guess: when this is true the answer is the\n * intersection of the id sets above, and when it is false the read stands\n * alone.\n */\n intersects: boolean;\n}\n\nexport const DEFAULT_PAGE_SIZE = 50;\n\nexport function planQuery(query: RecordQuery): QueryPlan {\n const relationCalls = (query.relations ?? []).map((coordinate) => ({\n door: \"relation_targets\" as const,\n record_id: coordinate.record_id,\n via_key: coordinate.role ?? null,\n }));\n const promotedCalls = (query.promoted ?? []).map((predicate) => ({\n door: \"promoted_read\" as const,\n field_key: predicate.field_key,\n value: predicate.equals,\n }));\n return {\n relationCalls,\n promotedCalls,\n read: {\n table_id: query.table_id,\n includeDeleted: query.includeDeleted ?? false,\n recordType: query.recordType ?? null,\n asOf: query.asOf ?? null,\n acrossHomes: query.acrossHomes ?? false,\n orderBy: {\n column: query.orderBy?.column ?? \"created_at\",\n ascending: query.orderBy?.ascending ?? false,\n },\n limit: query.limit ?? DEFAULT_PAGE_SIZE,\n offset: query.offset ?? 0,\n },\n intersects: relationCalls.length + promotedCalls.length > 0,\n };\n}\n\n/** The intersection of the id sets a plan's calls produced. Order is preserved from the first set. */\nexport function intersectIds(sets: Uuid[][]): Uuid[] {\n if (sets.length === 0) return [];\n const [first, ...rest] = sets as [Uuid[], ...Uuid[][]];\n const others = rest.map((s) => new Set(s));\n return first.filter((id) => others.every((set) => set.has(id)));\n}\n","// src/core/client.ts — @ai-matrx/records\n//\n// THE TYPED CLIENT OVER THE STORE'S DOORS, AND NOTHING ELSE.\n//\n// Every write in this file goes through `custom.record_write`,\n// `custom.record_update`, `custom.record_delete` or `custom.record_restore`.\n// There is no `insert`, no `update` and no `delete` against `custom.record`\n// anywhere in this package, and there is no code path that adds one: DOOR-N-1\n// says there is exactly one write door and `authenticated` holds no direct\n// INSERT, UPDATE or DELETE grant on the store — a client that tried would be\n// refused, and a client that TRIES is a defect even when it is refused.\n//\n// Reads go through the read door too (DOOR-1, DOOR-10): the filtered select over\n// `custom.record` is gated by the store's own policies, and this file never\n// takes rows and then drops some of them. Where it needs an id set it asks a\n// door for one.\n//\n// Nothing here throws. Every method answers `RecordsResult`, and every refusal\n// carries the store's own sentence.\n\nimport { LOOK_WRITES, dropPrimedDoorAnswers, isWritingDoor, takePrimedDoorAnswer, takePrimedTablePageBundle } from \"./primedBundle\";\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 DashboardRunResult,\n DashboardSummary,\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 FieldHistoryEntry,\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 {\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 { REVERSE_LINKS_RECORDS_PER_CALL } from \"../relation\";\nimport type { RelationNamesAnswer } from \"../coerce\";\nimport { defaultOpLedger } from \"../ops\";\nimport type { Field } from \"../field\";\nimport type { FieldRetyped, MigrationUndone, RecordsMerged } from \"../retype\";\nimport type { FieldDuplicated } from \"../field\";\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, RecordsErrorSink } from \"../ports\";\nimport type { RecordsError, RecordsErrorCode, 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 AutomationRuns,\n AutomationSpec,\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 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\";\n\nconst DEFAULT_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 recognise — 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\nfunction sink(config: RecordsConfig): RecordsErrorSink {\n return (\n config.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/** 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\nexport interface RecordsClient {\n /** The config this client was built with, so a screen can show who it is acting as. */\n readonly config: RecordsConfig;\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 recordRestore(args: { record_id: Uuid }): Promise<RecordsResult<void>>;\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, colours, 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 * 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 * 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 catalogue 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 * 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 behaviour,\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 /** 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 * CHANGE WHAT A COLUMN HOLDS, through `custom.migrate_retype` (FLD-4 / T12). `to` is the store's\n * behaviour 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 * 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 colours, 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 /** The fields THIS organization added to that standard table. */\n entityFields(args: { token: string }): 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, cancelled, 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 colours, 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 // ── 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 /** 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 colour 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 * 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 }): 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 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 honours. 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 honoured 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 — `public.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, `public.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 /** 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 * 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 * 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 * 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 /** 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 * 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 /** 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 /**\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 */\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/** The surface every record-store saved view is kept under (`custom.view_declare` writes it). */\nconst SAVED_VIEW_SURFACE = \"custom/records\";\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 = sink(config);\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 function primedFor(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 const readsInFlight = new Map<string, Promise<Awaited<ReturnType<typeof config.dataSource.rpc>>>>();\n\n async function callDoor<T>(\n door: string,\n args: Record<string, unknown>,\n where: string,\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 = primedFor(door, args);\n if (primed) return ok(primed.data as T);\n const bundled = await fromBundle(door, args);\n if (bundled) return ok(bundled.data as T);\n // The generated catalogue, 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(config, door)) {\n const refusal = doorAbsent(door);\n scream({ code: refusal.code, message: refusal.message, ...(refusal.hint ? { hint: refusal.hint } : {}), 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 call = Promise.resolve(config.dataSource.rpc(`${door}`, args, { schema }));\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 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 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 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 catalogue 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 const unreadable = (): 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 };\n scream({ code: refusal.code, message: refusal.message, where: \"tableDuplicate\" });\n return err(refusal);\n };\n let current = answer;\n for (let pass = 0; pass < 10_000; pass += 1) {\n const progress = parseTableDuplicateProgress(current);\n if (!progress) return unreadable();\n onProgress?.(progress);\n if (progress.status === \"done\") {\n const copied = parseTableDuplicated(current);\n return copied ? ok(copied) : unreadable();\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 };\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) return next;\n current = next.data;\n }\n return unreadable();\n }\n\n /**\n * A PLATFORM DOOR IN `public` — the saved-view archive and the one restore door. Not the store's\n * catalogue (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 ): Promise<RecordsResult<T>> {\n const response = await config.dataSource.rpc(door, args, { schema: \"public\" });\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 * catalogue 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 catalogue 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 catalogue 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 const client: RecordsClient = {\n config,\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 recognises 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 recognises 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 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 catalogue (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 catalogue:\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 };\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 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 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, limit = 50, offset = 0 }) {\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 };\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, search, sort, view_id, limit = 50, offset = 0 }) {\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 }>(\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 };\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 });\n },\n\n async listKeyset({ table_id, filter, search, sort, after, ids, limit = 50 }) {\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 }>(\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 });\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 return { ...(document as Record<string, unknown>), 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 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 ...(recordType === undefined ? {} : { p_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 // 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 return ok(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 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 // `allow_other` is a choice list's own setting and the store keeps it in\n // the column's config (STORE-RULE-GAPS); the declaration names it plainly.\n const { allow_other, ...rest } = spec;\n const p_spec =\n allow_other === undefined\n ? rest\n : { ...rest, config: { ...(rest.config ?? {}), allow_other } };\n return structureMoved(table_id, await callDoor<Uuid>(\n DOORS.fieldDeclare,\n { p_organization_id: org, p_table_id: table_id, p_spec },\n \"fieldDeclare\",\n ));\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 }) {\n const rows = await callDoor<Array<{ id: Uuid; data: unknown }>>(\n DOORS.entityFields,\n { p_organization_id: org, p_token: token },\n \"entityFields\",\n );\n if (!rows.ok) return err(rows.error);\n return ok((rows.data ?? []).map((row) => ({ id: row.id, ...(row.data as object) }) as Field));\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 // catalogue (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 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 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 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 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 return callDoor<Uuid>(DOORS.personKernelId, {}, \"personKernelId\");\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 } 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 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 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 );\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 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 }) {\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 });\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 },\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 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 );\n },\n\n async viewRestore({ view_id }) {\n return publicDoor<boolean>(\"entity_undelete\", { p_token: \"platform_saved_view\", p_id: view_id }, \"viewRestore\");\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 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 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 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 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 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 return callDoor<DataHomeTable[]>(\n DOORS.dataHomeTables,\n include_platform_tables\n ? { p_organization_id: organization_id, p_include_platform_tables: true }\n : { p_organization_id: organization_id },\n \"dataHomeTables\",\n );\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 scopeTableProvision({ home_id, item_id, scope_id }) {\n return callDoor<Uuid>(\n DOORS.scopeTableProvision,\n { p_organization_id: org, p_item_id: item_id, p_scope_id: scope_id, p_home_id: home_id ?? null },\n \"scopeTableProvision\",\n );\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 return result;\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 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/first-page/seed.ts — @ai-matrx/records/first-page · THE GRID'S FIRST PAGE, ASKED BEFORE THE GRID EXISTS\n//\n// (Moved from records-ui `firstPage.ts` / `firstPageEntity.ts` / `entityQuery.ts`, step 10, 2026-10-08.)\n//\n// A host that renders on a server can ask the table page's first rows while the browser is still loading the app —\n// but only if it asks with EXACTLY the arguments the grid will send, or the records client cannot serve the grid\n// from it (a part is used only on an exact door + args match). This builds that request from the same pieces the\n// screen uses: the view the bar opens (the default view, else the first), the person's own look laid over it, the\n// opening sort (the view's sort, else the table's `default_sort`) and the table page's page size (100).\n//\n// IT ONLY PREDICTS THE PLAIN OPENING. A view grouped into sections, drilled, filtered, hand-ordered, built on a Rule,\n// or not a grid answers null — the grid asks for itself. A wrong guess costs one wasted read and never a wrong row.\n// Zero React, zero design-system (server-safe). A host that draws its own look passes its view codec (`codec`) so\n// the view is read exactly as its screen reads it; left out, the plain document is read.\n\nimport type { StoreFilter } from \"../aggregate\";\nimport type { DrillQuestion, DrillSource } from \"../drill\";\nimport type { RecordsConfig } from \"../ports\";\nimport { createRecordsClient, type RecordsClient } from \"../core/client\";\nimport { asRecordsDataSource } from \"../core/supabase\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { recordingDataSource, type RecordsSeed } from \"../core/seed\";\nimport type { Query } from \"../data/types\";\nimport { createSeedPort } from \"../entity/port/port\";\nimport type { Field } from \"../field\";\nimport type { RecordPageSort, Uuid } from \"../record\";\nimport type { Table } from \"../table\";\nimport { ownVersion } from \"../versions/rowVersion\";\nimport { readLooks, applyLook } from \"../views/look\";\nimport { plainPresentation, type ViewPresentationCodec, type ViewPresentationDocument } from \"../views/keys\";\nimport { defaultViewOf, viewFromRow, type SavedView, type SavedViewSpec } from \"../views/views\";\nimport {\n REVERSE_CELL_CHIPS,\n choiceFieldKeys,\n defaultSortOf,\n groupFactMeasures,\n groupedPageSort,\n isPlainGrouping,\n pageSortFor,\n summaryBarMeasures,\n viewFilterOf,\n type GroupingShape,\n} from \"./reads\";\n\n/** The table page's own page size (100 unless embedded). */\nexport const TABLE_PAGE_SIZE = 100;\n\n/** How many rows an embedded table reads at a time: its first page, and each \"Show more\". */\nexport const EMBEDDED_PAGE_SIZE = 50;\n\nexport interface FirstGridPageArgs {\n p_table_id: Uuid;\n p_filter: StoreFilter | Record<string, never>;\n p_search: null;\n p_sort: RecordPageSort[];\n p_view_id: null;\n p_limit: number;\n p_offset: 0;\n}\n\n/** The two parts of a view's presentation the first page reads: its grouping and its chosen summaries. */\nfunction presentationFacts(presentation: unknown): { grouping: GroupingShape | undefined; summaries: Record<string, string> } {\n const p = (presentation && typeof presentation === \"object\" ? presentation : {}) as Record<string, unknown>;\n const g = p[\"grouping\"] as GroupingShape | undefined;\n const grouping = g && typeof g === \"object\" && typeof g.field === \"string\" ? g : undefined;\n const s = p[\"summaries\"];\n return { grouping, summaries: s && typeof s === \"object\" ? (s as Record<string, string>) : {} };\n}\n\n/** The request for the plain opening, from what the screen itself reads — or null. Pure. */\nexport function firstGridPageArgs<P = ViewPresentationDocument>(input: {\n tableId: Uuid;\n table: Pick<Table, \"default_sort\"> | null;\n fields: readonly Field[];\n /** The view as THIS person sees it (the saved view with her look over it), or null for none. */\n shown: SavedView<P> | null;\n pageSize?: number;\n /**\n * The host draws the MERGED grid, which keeps a plain grouping as rows under group headers: the page is then\n * read in group order. The classic grid opens the drill for a grouped view, so a grouped view stays unseeded.\n */\n merged?: boolean;\n}): FirstGridPageArgs | null {\n const { shown, fields } = input;\n if (!shown) return null;\n if ((shown.layout ?? \"grid\") !== \"grid\") return null;\n if (shown.ruleId) return null;\n if (shown.order === \"manual\") return null;\n const { grouping } = presentationFacts(shown.presentation);\n if (grouping && !(input.merged && isPlainGrouping(grouping))) return null;\n const first = (shown.sorts ?? [])[0];\n const viewSort = first && fields.some((f) => f.key === first.field) ? { id: first.field, direction: first.direction } : null;\n const opening = viewSort ?? defaultSortOf(input.table, fields);\n return {\n p_table_id: input.tableId,\n p_filter: viewFilterOf(shown) ?? {},\n p_search: null,\n p_sort: groupedPageSort(fields, grouping?.field ?? null, pageSortFor(fields, opening)),\n p_view_id: null,\n p_limit: input.pageSize ?? TABLE_PAGE_SIZE,\n p_offset: 0,\n };\n}\n\ntype OpeningOptions<P> = { pageSize?: number; merged?: boolean; view?: SavedViewSpec<P> | undefined; codec?: ViewPresentationCodec<P> };\n\n/**\n * Read what the screen reads (through `client`, e.g. one served from `custom.table_page_bundle`) and build the first\n * page's request. Null when anything it needs is not answered.\n */\nexport async function firstGridPageRequest<P = ViewPresentationDocument>(\n client: Pick<RecordsClient, \"tableRead\" | \"fields\" | \"views\" | \"viewLookRead\">,\n tableId: Uuid,\n options: Omit<OpeningOptions<P>, \"view\"> = {},\n): Promise<FirstGridPageArgs | null> {\n return (await firstGridOpening<P>(client, tableId, options))?.args ?? null;\n}\n\n/** A spec as the grid shows it before any look is laid over it. */\nfunction shownFromSpec<P>(spec: SavedViewSpec<P>, tableId: Uuid): SavedView<P> {\n return { ...spec, subject: spec.subject ?? tableId, id: \"\" as Uuid, movedFrom: null };\n}\n\n/** The plain opening's request with what it was built from (the view as shown, the table's fields). */\nasync function firstGridOpening<P>(\n client: Pick<RecordsClient, \"tableRead\" | \"fields\" | \"views\" | \"viewLookRead\">,\n tableId: Uuid,\n options: OpeningOptions<P>,\n): Promise<{ args: FirstGridPageArgs; shown: SavedView<P> | null; fields: readonly Field[] } | null> {\n const codec = options.codec ?? (plainPresentation as unknown as ViewPresentationCodec<P>);\n const explicit = options.view;\n const [table, fields, views, looks] = await Promise.all([\n client.tableRead({ table_id: tableId }),\n client.fields({ table_id: tableId }),\n explicit ? Promise.resolve(null) : client.views({ table_id: tableId }),\n explicit ? Promise.resolve(null) : readLooks<P>(client, tableId, codec),\n ]);\n if (!table.ok || !fields.ok) return null;\n let shown: SavedView<P>;\n if (explicit) {\n // THE HOST'S OWN SPEC (a Space's grid): the view the grid is handed, with no saved view behind it.\n shown = shownFromSpec(explicit, tableId);\n } else {\n if (!views?.ok || !looks?.ok) return null;\n const mine = views.data.map((row) => viewFromRow<P>(row, codec)).filter((v) => v.subject === tableId);\n const view = defaultViewOf(mine) ?? mine[0] ?? null;\n // A table with no saved view opens on the unsaved default (the bar saves it a moment later).\n shown = view\n ? applyLook(view, looks.data[view.id])\n : shownFromSpec<P>({ name: \"All\", subject: tableId, layout: \"grid\", isDefault: true }, tableId);\n }\n const args = firstGridPageArgs<P>({\n tableId,\n table: table.data,\n fields: fields.data,\n shown,\n ...(options.pageSize ? { pageSize: options.pageSize } : {}),\n ...(options.merged ? { merged: true } : {}),\n });\n return args ? { args, shown, fields: fields.data } : null;\n}\n\n/**\n * THE PERSON'S SERVER-ROWS KNOBS, FROM THE TABLE'S BUNDLE: `custom.table_page_bundle` carries a `server_rows` part\n * (whether the page may wait for the server's rows, and for how long) resolved for the person asking. Null when the\n * seed holds no such answer (an older store, a refused part): the host treats that as off.\n */\nexport function serverRowsOf(seed: RecordsSeed | null | undefined): { on: boolean; capMs: number | null } | null {\n const found = seed?.answers.find((a) => a.door === \"server_rows\");\n const data = found?.data as { on?: unknown; cap_ms?: unknown } | undefined;\n if (!data || typeof data !== \"object\") return null;\n return { on: data.on === true, capMs: typeof data.cap_ms === \"number\" && data.cap_ms > 0 ? data.cap_ms : null };\n}\n\n/**\n * A TABLE PAGE'S SEED, ASKED BY THE SERVER AS THE PERSON.\n *\n * Asks what the table page opens on — the table's bundle, the grid's first page when it can be predicted, and on a\n * record page the record's bundle — through a recording data source, and answers every door answer it got as a\n * `RecordsSeed`. The host hands that to `<RecordsSeedProvider>` (`@ai-matrx/records/react`) above the table page.\n * `dataSource` is the person's own (a server Supabase client carrying her session). Never throws.\n */\nexport async function askTablePageSeed<P = ViewPresentationDocument>(input: {\n dataSource: unknown;\n organizationId: Uuid;\n tableId: Uuid;\n actor: RecordsConfig[\"actor\"];\n /** A record page: its record's bundle (`custom.record_page_bundle`) is asked beside the table's. */\n recordId?: Uuid | null;\n /**\n * Ask the grid's first page (default true). A function decides once the table's bundle has been answered — it is\n * handed everything asked so far, so a host can read the person's `server_rows` knob (`serverRowsOf`) first.\n */\n rows?: boolean | ((asked: RecordsSeed) => boolean);\n /** The table is drawn EMBEDDED: its page size. */\n embedded?: boolean;\n pageSize?: number;\n /** The host draws the merged grid: a view grouped by one field is seeded too (group counts, summary bar, link words). */\n merged?: boolean;\n /** THE VIEW THE HOST HANDS THE GRID, for a table with no saved view behind it. */\n view?: SavedViewSpec<P> | undefined;\n /** The host's view codec (records-ui binds its grid look). Left out: the plain document. */\n codec?: ViewPresentationCodec<P>;\n}): Promise<RecordsSeed> {\n const recording = recordingDataSource(asRecordsDataSource(input.dataSource));\n const client = createRecordsClient({\n dataSource: recording.source,\n organizationId: input.organizationId,\n actor: input.actor,\n onError: () => {},\n });\n const record = input.recordId\n ? Promise.resolve(\n recording.source.rpc(\"record_page_bundle\", { p_organization_id: input.organizationId, p_record_id: input.recordId }, { schema: \"custom\" }),\n ).catch(() => null)\n : null;\n try {\n const pageSize = input.pageSize ?? (input.embedded ? EMBEDDED_PAGE_SIZE : TABLE_PAGE_SIZE);\n const opening = await firstGridOpening<P>(client, input.tableId, {\n pageSize,\n ...(input.merged ? { merged: true } : {}),\n ...(input.view ? { view: input.view } : {}),\n ...(input.codec ? { codec: input.codec } : {}),\n });\n const wantRows = typeof input.rows === \"function\" ? input.rows(recording.seed()) : input.rows !== false;\n if (opening && wantRows) {\n const { args, shown, fields } = opening;\n const page = await client.listPage({\n table_id: args.p_table_id,\n filter: args.p_filter,\n search: args.p_search,\n sort: args.p_sort,\n view_id: args.p_view_id,\n limit: args.p_limit,\n offset: args.p_offset,\n });\n if (page.ok) {\n const { grouping, summaries: chosen } = presentationFacts(shown?.presentation);\n const groupKey = grouping?.field ?? null;\n const reads: Array<Promise<unknown>> = [];\n // The question every one of the grid's table reads carries: the view's own.\n const filter = args.p_filter && Object.keys(args.p_filter).length > 0 ? (args.p_filter as StoreFilter) : undefined;\n // The grouped grid's header counts and the summary bar.\n if (groupKey) {\n reads.push(client.recordAggregate({ table_id: input.tableId, groupBy: [groupKey], measures: groupFactMeasures(chosen), limit: 1000, ...(filter ? { filter } : {}) }));\n }\n const bar = summaryBarMeasures(chosen);\n if (bar.length > 0) reads.push(client.recordAggregate({ table_id: input.tableId, measures: bar, ...(filter ? { filter } : {}) }));\n // The words of every link on the page: one call per field, its ids in row order.\n for (const field of fields) {\n if (field.type !== \"list\" && field.type !== \"relation\") continue;\n const ids = new Set<string>();\n for (const row of page.data.rows) {\n const value = row.document?.[field.key];\n for (const id of Array.isArray(value) ? value.map(String) : typeof value === \"string\" ? [value] : []) if (isUuidShape(id)) ids.add(id);\n }\n if (ids.size > 0) reads.push(client.relationWordsMany({ field_id: field.id as Uuid, record_ids: [...ids] as Uuid[] }));\n }\n if (input.merged) {\n // The header filters' counts per choice column (one `record_aggregate` each, limit 500).\n for (const key of choiceFieldKeys(fields)) {\n reads.push(client.recordAggregate({ table_id: input.tableId, groupBy: [key], measures: [{ op: \"count\" }], limit: 500, ...(filter ? { filter } : {}) }));\n }\n }\n // The versions of the rows the page drew, for the rows that carry none themselves.\n const unversioned = page.data.rows.filter((row) => ownVersion(row) === null).map((row) => row.id);\n if (unversioned.length > 0) reads.push(client.recordHeaders({ ids: unversioned }));\n // The table's reverse columns and, for each, the page's links (`REVERSE_CELL_CHIPS` a record).\n reads.push(\n client.reverseColumns({ table_id: input.tableId }).then(async (columns) => {\n if (!columns.ok || columns.data.length === 0) return null;\n const record_ids = page.data.rows.map((row) => row.id);\n // ONE call for every reverse column; a store without that door is asked per column.\n const all = await client.reverseLinksFields({ table_id: input.tableId, source_field_ids: columns.data.map((c) => c.source_field_id), record_ids, limit: REVERSE_CELL_CHIPS });\n if (all.ok || all.error.code !== \"door_absent\") return null;\n return Promise.all(columns.data.map((c) => client.reverseLinksMany({ table_id: input.tableId, source_field_id: c.source_field_id, record_ids, limit: REVERSE_CELL_CHIPS })));\n }),\n );\n await Promise.all(reads.map((read) => read.catch(() => null)));\n }\n }\n } catch {\n // a seed is a head start, never a requirement: whatever was answered is kept\n }\n if (record) await record;\n return recording.seed();\n}\n\n// ── entity blocks, charts and tiles ───────────────────────────────────────────────────────\n\ntype Base = { dataSource: unknown; organizationId: Uuid; actor: RecordsConfig[\"actor\"] };\n\nfunction recordedClient(input: Base) {\n const recording = recordingDataSource(asRecordsDataSource(input.dataSource));\n const client = createRecordsClient({ dataSource: recording.source, organizationId: input.organizationId, actor: input.actor, onError: () => {} });\n return { recording, client };\n}\n\n/** A standard source's first read: its page size and the viewer's search (an empty search is none). */\nexport function entityTableQuery(options: { pageSize?: number | undefined; search?: string | null | undefined } = {}): Query {\n const search = (options.search ?? \"\").trim();\n return { ...(options.pageSize ? { pageSize: options.pageSize } : {}), ...(search ? { search } : {}) };\n}\n\n/** The block's own props that decide a chart's question. */\nexport interface EntityChartQuestionInput {\n /** The Dimension to group by. Absent: one total. */\n by?: string | undefined;\n /** What to count: the rows (default) or a number column summed. */\n measure?: { op: \"count\" } | { op: \"sum\" | \"avg\" | \"min\" | \"max\"; of: string } | undefined;\n where?: Record<string, unknown> | undefined;\n organization?: string | undefined;\n}\n\n/** The chart's `platform.drill_ask` question. */\nexport function entityChartQuestion(input: EntityChartQuestionInput): DrillQuestion & { organization?: string } {\n const m = input.measure ?? { op: \"count\" as const };\n return {\n ...(input.by ? { by: [input.by] } : {}),\n show: [m.op === \"count\" ? \"count\" : { op: m.op, of: m.of }],\n ...(input.where ? { where: input.where } : {}),\n ...(input.organization ? { organization: input.organization } : {}),\n };\n}\n\n/** Several seeds as one: the later answer wins on the same door and arguments; `at` is the oldest. */\nexport function mergeSeeds(...seeds: Array<RecordsSeed | null | undefined>): RecordsSeed {\n const held = seeds.filter((s): s is RecordsSeed => Boolean(s));\n const answers = new Map<string, RecordsSeed[\"answers\"][number]>();\n for (const seed of held) for (const a of seed.answers) answers.set(`${a.door}|${JSON.stringify(a.args)}`, a);\n return { at: held.length ? Math.min(...held.map((s) => s.at)) : Date.now(), answers: [...answers.values()] };\n}\n\n/**\n * AN ENTITY SOURCE'S BLOCK (a table, board or card of \"task\", \"project\", \"crm_deal\"): its columns and first page,\n * asked through the entity engine's own port with the question the block's `useEntityTable` sends. Never throws.\n */\nexport async function askEntityBlockSeed(\n input: Base & { token: string; question?: { pageSize?: number | undefined; search?: string | null | undefined } },\n): Promise<RecordsSeed> {\n const recording = recordingDataSource(asRecordsDataSource(input.dataSource));\n const port = createSeedPort(recording.source);\n try {\n await Promise.all([port.describe(input.token), port.list(input.token, entityTableQuery(input.question ?? {}))]);\n } catch {\n // a seed is a head start, never a requirement\n }\n return recording.seed();\n}\n\n/** AN ENTITY SOURCE'S CHART: `platform.drill_ask` with the question the block sends. */\nexport async function askChartSeed(\n input: Base & {\n source: { kind: \"entity\"; token: string };\n question?: EntityChartQuestionInput;\n },\n): Promise<RecordsSeed> {\n const { recording, client } = recordedClient(input);\n try {\n await client.drillAsk({ source: input.source as DrillSource, question: entityChartQuestion(input.question ?? {}) });\n } catch {\n // a seed is a head start, never a requirement\n }\n return recording.seed();\n}\n\n/** One aggregate question of a tile: `client.recordAggregate`'s arguments but the table. */\nexport type TileSpec = Omit<Parameters<RecordsClient[\"recordAggregate\"]>[0], \"table_id\">;\n\n/** A TABLE'S TILE: `custom.record_aggregate` over `tableId` for each `spec`. Read back with `useSeededAggregate`. */\nexport async function askTileSeed(input: Base & { tableId: Uuid; spec: TileSpec | TileSpec[] }): Promise<RecordsSeed> {\n const { recording, client } = recordedClient(input);\n const specs = Array.isArray(input.spec) ? input.spec : [input.spec];\n await Promise.all(specs.map((spec) => client.recordAggregate({ table_id: input.tableId, ...spec }).catch(() => null)));\n return recording.seed();\n}\n\n/**\n * THE FIRST PAGE WITH A HOST'S VIEW CODEC BOUND ONCE (records-ui binds its grid look): the host re-exports these\n * under the same names — bindings of the one definition here, never a second body.\n */\nexport function bindFirstPageCodec<P>(codec: ViewPresentationCodec<P>) {\n return {\n firstGridPageRequest: (\n client: Pick<RecordsClient, \"tableRead\" | \"fields\" | \"views\" | \"viewLookRead\">,\n tableId: Uuid,\n options: { pageSize?: number; merged?: boolean } = {},\n ) => firstGridPageRequest<P>(client, tableId, { ...options, codec }),\n askTablePageSeed: (input: Omit<Parameters<typeof askTablePageSeed<P>>[0], \"codec\">) => askTablePageSeed<P>({ ...input, codec }),\n };\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 \"./client\";\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/port/port.ts — @ai-matrx/records/entity\n//\n// THE HOST'S DATAPORT FOR ENTITY ALIASES (Applets CONTRACTS §4; PHASE-B-APPLETS U5, read-only).\n//\n// One port per mounted Applet, scoped to the aliases its record declares: `{kind:\"entity\", token}`.\n// Every call goes through the store's entity doors under the signed-in person's seat — the store\n// decides what she may see; nothing here widens or narrows it.\n//\n// · sources — canCreate / canUpdate are `entity_columns`' own answer for the person.\n// · columns — live: platform columns plus the organizations' custom fields (`origin`), the identity\n// columns left to `_id` / `_version` / `_organization_id`.\n// · list — KEYSET: the cursor is the door's `next_after`; the lane defaults to the type's own\n// landing lane (decided by the door, never here); `org` is a filter, never a lock.\n// · get — by id, through the same door every list row opens through. Every id asked in the same\n// tick (the engine re-reading the rows a notice named) is ONE `entity_get(ids)`.\n// · create — `entity_insert` into the organization the HOST names (`activeOrganizationId()`), never\n// guessed; with none, refused `organization_required` before anything is sent.\n// · update — `entity_update` with the `baseVersion` the person saw; a link (`EntityRef[]`) goes back\n// as its id, `_custom` as `{key: value}`. Stale → `stale_write` with the store's sentence.\n// · archive / restore — `entity_archive` / `entity_unarchive` (on these types, the trash).\n// Every write mints an op id (`mintOpId`) and sends it as header `x-matrx-op-id`, so the\n// notice of the writer's own change comes back marked and is dropped.\n// · subscribe — LIVE (U6): `rows:<alias>` hears the organization topics `mx:entity-org:<org>:<token>`\n// through the host's `realtime` (core/realtime.ts). An alias with an organization hears\n// that one; otherwise the active organization, then the organizations of the rows this\n// port has handed out (most rows first), then the person's other memberships — capped by\n// knob entity_data.realtime_max_org_topics. `{ids}` names rows to re-read; `{ids: null}`\n// re-reads all. With no `realtime` bound it says so out loud and stays a no-op.\n\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport type {\n Column,\n DataPortEventName,\n DataSource,\n HostDataPort,\n Page,\n Query,\n Row,\n RowsEvent,\n Uuid,\n Values,\n} from \"../../data\";\nimport { defaultOpLedger, type OpLedger } from \"../../ops\";\nimport type { RecordsResult } from \"../../results\";\nimport { createEntityClient, type EntityClient } from \"../core/client\";\nimport { refusal } from \"../core/errors\";\nimport { DEFAULT_MAX_ORG_TOPICS, orderOrganizationTopics, type EntityRealtime } from \"../core/realtime\";\nimport type { EntityColumnsAnswer, EntityGetAnswer, EntityWriteAnswer, EntityWireRow } from \"../core/types\";\nimport { toWire } from \"../core/wire\";\nimport { toColumns, toRow } from \"./rows\";\n\n/** An alias as the Applet record declares it for an entity: one token (a `platform.entity_types` word). */\nexport interface EntityAlias {\n kind: \"entity\";\n token: string;\n /** Whose custom fields `columns()` reads. Left out: every organization the person belongs to. */\n organizationId?: Uuid;\n /** Shown in `sources()`; the type's own name when left out. */\n label?: string;\n}\n\nexport interface CreateEntityDataPortOptions {\n /** A client from `createEntityClient` … */\n client?: EntityClient;\n /** … or the supabase-js client (or `rpc` source) to build one from. Give one of the two. */\n dataSource?: unknown;\n aliases: Readonly<Record<string, EntityAlias>>;\n /**\n * TOKEN-FIRST (the `/react` layer): an alias nobody declared is read as a type token —\n * `list(\"party\")` is `{kind:\"entity\", token:\"party\"}`. `sources()` still lists only the declared\n * aliases. Off by default: an Applet's port answers only what its record declares.\n */\n tokensAreAliases?: boolean;\n /**\n * The active organization (CONTRACTS §4: `viewer().activeOrganizationId`), read at the moment it is\n * needed: where `create` saves, and the first live topic joined. The host's own answer, never guessed;\n * null/undefined means none is chosen and `create` is refused `organization_required`.\n */\n activeOrganizationId?: () => Uuid | null | undefined;\n /** A fixed active organization, for a host whose port lives no longer than its choice. `activeOrganizationId` wins. */\n organization?: Uuid | null;\n /** The host's live-notice layer (`createEntityRealtime`). Left out, lists are as fresh as their last read. */\n realtime?: EntityRealtime;\n /** This port's own-write memory (`createOpLedger()`); absent ⇒ the realm's default ledger. */\n opLedger?: OpLedger;\n}\n\n/** A value as rows carry it → as the write doors take it: a link (`EntityRef[]` or one ref) becomes its id. */\nexport function toWireValue(value: unknown): unknown {\n if (isRef(value)) return value.id;\n if (Array.isArray(value) && value.length > 0 && value.every(isRef)) {\n // One link is one id; none is null; several are sent as ids and the door refuses a one-record column by name.\n return value.length === 1 ? (value[0] as { id: string }).id : value.map((ref) => (ref as { id: string }).id);\n }\n return value;\n}\n\nfunction isRef(value: unknown): value is { token: string; id: string } {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n && typeof (value as { token?: unknown }).token === \"string\" && typeof (value as { id?: unknown }).id === \"string\";\n}\n\n/** `Values` → the doors' `{column: value, _custom: {key: value}}`: links back to ids at both levels. */\nexport function toWireValues(values: Values): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue;\n if (key === \"_custom\" && value && typeof value === \"object\" && !Array.isArray(value)) {\n out._custom = Object.fromEntries(Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined).map(([k, v]) => [k, toWireValue(v)]));\n continue;\n }\n // A link column emptied in a grid arrives as [] and means \"no link\".\n out[key] = Array.isArray(value) && value.length === 0 && key !== \"_custom\" ? null : toWireValue(value);\n }\n return out;\n}\n\n/** A type as the person may use it: its name and whether she may add or change rows (`entity_columns`' own answer). */\nexport interface EntityTypeFacts {\n token: string;\n label: string;\n canCreate: boolean;\n canUpdate: boolean;\n}\n\n/** The host's entity port: the DataPort, plus `describe` for a token-first screen that has no `sources()` entry. */\nexport interface EntityDataPort extends HostDataPort {\n /** The type behind an alias, from the same one `entity_columns` read `columns()` uses. */\n describe(alias: string): Promise<RecordsResult<EntityTypeFacts>>;\n}\n\nexport function createEntityDataPort(options: CreateEntityDataPortOptions): EntityDataPort {\n const client: EntityClient = options.client ?? createEntityClient({ dataSource: options.dataSource });\n const ledger = options.opLedger ?? defaultOpLedger;\n const activeOrganization = (): Uuid | null => (options.activeOrganizationId ? options.activeOrganizationId() : options.organization) ?? null;\n /** Ids asked by `get` in this tick, per alias: answered by one `entity_get`. */\n const gets = new Map<string, Map<Uuid, ((answer: RecordsResult<Row | null>) => void)[]>>();\n const aliases = options.aliases;\n const shapes = new Map<string, Promise<RecordsResult<EntityColumnsAnswer>>>();\n let warnedNotLive = false;\n /** Which organization each row this port handed out belongs to, per alias: the \"held rows\" topic order. */\n const held = new Map<string, Map<Uuid, Uuid>>();\n const replans = new Map<string, Set<() => void>>();\n let memberships: Promise<Uuid[] | null> | null = null;\n let maxOrgTopics: Promise<number> | null = null;\n\n function hold(alias: string, rows: readonly { id?: unknown; organization_id?: unknown }[]) {\n const byId = held.get(alias) ?? new Map<Uuid, Uuid>();\n held.set(alias, byId);\n const before = new Set(byId.values());\n for (const r of rows) {\n if (typeof r.id === \"string\" && typeof r.organization_id === \"string\") byId.set(r.id, r.organization_id);\n }\n // A row from an organization this alias did not hold yet may move it into the joined topics.\n if ([...byId.values()].some((org) => !before.has(org))) for (const replan of replans.get(alias) ?? []) replan();\n }\n\n function heldCounts(alias: string): Map<Uuid, number> {\n const counts = new Map<Uuid, number>();\n for (const org of held.get(alias)?.values() ?? []) counts.set(org, (counts.get(org) ?? 0) + 1);\n return counts;\n }\n\n function membershipsOnce(): Promise<Uuid[] | null> {\n memberships ??= client.memberOrganizations().then((answer) => {\n if (answer.ok) return answer.data;\n memberships = null; // a refusal is never kept for the next asker\n console.warn(`[@ai-matrx/records/entity] Could not read your organizations for live updates: ${answer.error.message}`);\n return null;\n });\n return memberships;\n }\n\n function maxOrgTopicsOnce(): Promise<number> {\n maxOrgTopics ??= client.knob({ key: \"realtime_max_org_topics\", organizationId: activeOrganization() }).then((answer) => {\n const value = answer.ok ? Number(answer.data) : Number.NaN;\n if (Number.isFinite(value) && value >= 0) return value;\n console.warn(`[@ai-matrx/records/entity] knob entity_data.realtime_max_org_topics did not resolve; joining at most ${DEFAULT_MAX_ORG_TOPICS} organizations.`);\n return DEFAULT_MAX_ORG_TOPICS;\n });\n return maxOrgTopics;\n }\n\n const tokenBindings = new Map<string, EntityAlias>();\n function bindingOf(alias: string): EntityAlias | null {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) return aliases[alias]!;\n if (!options.tokensAreAliases || !/^[a-z][a-z0-9_]*$/.test(alias)) return null;\n let bound = tokenBindings.get(alias);\n if (!bound) {\n bound = { kind: \"entity\", token: alias };\n tokenBindings.set(alias, bound);\n }\n return bound;\n }\n\n function noSuchAlias(alias: string) {\n return refusal(\"not_found\", `This Applet has no data source called \"${alias}\".`, \"Use one of the aliases sources() lists.\");\n }\n\n /** One read of a type's columns per port; a refusal is never kept for the next asker. */\n function shapeOf(alias: string, binding: EntityAlias): Promise<RecordsResult<EntityColumnsAnswer>> {\n let held = shapes.get(alias);\n if (!held) {\n held = client.columns({ token: binding.token, organizationId: binding.organizationId ?? null }).then((answer) => {\n if (!answer.ok) shapes.delete(alias);\n return answer;\n });\n shapes.set(alias, held);\n }\n return held;\n }\n\n /** Ask for one row; every id asked for the alias before the tick ends goes in the same `entity_get`. */\n function getCoalesced(alias: string, token: string, id: Uuid): Promise<RecordsResult<Row | null>> {\n return new Promise((resolve) => {\n let batch = gets.get(alias);\n if (!batch) {\n batch = new Map();\n gets.set(alias, batch);\n const asked = batch;\n queueMicrotask(() => {\n gets.delete(alias);\n void flushGets(alias, token, asked);\n });\n }\n const waiting = batch.get(id) ?? [];\n waiting.push(resolve);\n batch.set(id, waiting);\n });\n }\n\n async function flushGets(alias: string, token: string, asked: Map<Uuid, ((answer: RecordsResult<Row | null>) => void)[]>) {\n const answer: RecordsResult<EntityGetAnswer> = await client.get({ token, ids: [...asked.keys()] });\n if (answer.ok) hold(alias, answer.data.rows);\n const byId = new Map<string, EntityWireRow>(answer.ok ? answer.data.rows.map((r) => [r.id, r]) : []);\n for (const [id, waiting] of asked) {\n // A row in the trash is not a row of this port: the DataPort's lists are active rows only (a Query has no\n // archived option), so a re-read that finds one trashed answers null and the engine takes it off the list.\n // `entity_get` itself opens trashed rows by id (`_state.archived`) for screens that read the doors directly.\n const found = byId.get(id);\n const wire = found && (found[\"_state\"] as { archived?: unknown } | undefined)?.archived === true ? undefined : found;\n const result: RecordsResult<Row | null> = answer.ok ? { ok: true, data: wire ? toRow(wire) : null } : answer;\n for (const resolve of waiting) resolve(result);\n }\n }\n\n /** The one row a write door read back (with its new `version`). */\n function readBack(alias: string, answer: RecordsResult<EntityWriteAnswer>, what: string): RecordsResult<Row> {\n if (!answer.ok) return answer;\n hold(alias, answer.data.rows);\n const wire = answer.data.rows[0];\n if (!wire) {\n return refusal(\n \"not_found\",\n `${what} was saved, but you cannot open it now, so it is not shown here.`,\n \"The row is in the store; who may open it decides whether it appears in this list.\",\n );\n }\n return { ok: true, data: toRow(wire) };\n }\n\n function done(answer: RecordsResult<EntityWriteAnswer>): RecordsResult<void> {\n return answer.ok ? { ok: true, data: undefined } : answer;\n }\n\n return {\n async sources() {\n const out: DataSource[] = [];\n for (const [alias, binding] of Object.entries(aliases)) {\n const shape = await shapeOf(alias, binding);\n if (!shape.ok) return shape;\n out.push({\n alias,\n label: binding.label ?? shape.data.label ?? alias,\n kind: \"entity\",\n canCreate: Boolean(shape.data.can_create),\n canUpdate: Boolean(shape.data.can_update),\n });\n }\n return { ok: true, data: out };\n },\n\n async describe(alias) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n const shape = await shapeOf(alias, binding);\n if (!shape.ok) return shape;\n return {\n ok: true,\n data: {\n token: binding.token,\n label: binding.label ?? shape.data.label ?? binding.token,\n canCreate: Boolean(shape.data.can_create),\n canUpdate: Boolean(shape.data.can_update),\n },\n };\n },\n\n async columns(alias) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n const shape = await shapeOf(alias, binding);\n return shape.ok ? { ok: true, data: toColumns(shape.data.columns) satisfies Column[] } : shape;\n },\n\n async list(alias, q: Query = {}, cursor) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n // A custom field's key is only known from the columns; ask for them only when the query names a column.\n let customKeys: ReadonlySet<string> = new Set();\n if ((q.where && q.where.length > 0) || (q.sort && q.sort.length > 0)) {\n const shape = await shapeOf(alias, binding);\n if (!shape.ok) return shape;\n customKeys = new Set(shape.data.columns.filter((c) => c.origin === \"custom\").map((c) => c.key));\n }\n const wire = toWire(q, customKeys);\n // A SOURCE DECLARED IN ONE ORGANIZATION reads that organization only (an Applet's own source scope,\n // CONTRACTS v2.11): the alias's organization replaces any per-query org filter — it is the source's\n // definition, not the person's list filter. Without one, the query's filter (or none) stands.\n if (binding.organizationId) wire.scope = { ...wire.scope, organization_id: binding.organizationId };\n const answer = await client.list({ token: binding.token, ...wire, after: cursor ?? null });\n if (!answer.ok) return answer;\n const { data } = answer;\n if (data.sort_ignored.length > 0) {\n // SAID OUT LOUD: the door keeps one sort key today; the rest were dropped, not silently reordered.\n console.warn(`[@ai-matrx/records/entity] \"${alias}\" sorts by one column for now; ignored: ${data.sort_ignored.join(\", \")}.`);\n }\n hold(alias, data.rows);\n const page: Page = {\n rows: data.rows.map(toRow),\n // A count that stopped at the store's cap is a floor, not a count: unknown beats a wrong number.\n total: data.total === null || data.total === undefined || data.total_is_capped ? null : data.total,\n cursor: data.has_more ? data.next_after : null,\n };\n return { ok: true, data: page };\n },\n\n async get(alias, id: Uuid) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n return getCoalesced(alias, binding.token, id);\n },\n\n async create(alias, values: Values) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n // A source declared in one organization saves there; otherwise the host's active organization.\n const organizationId = binding.organizationId ?? activeOrganization();\n if (!organizationId) {\n // MX002, said before anything is sent: a new row's organization is the person's choice, never ours.\n return refusal(\n \"organization_required\",\n \"Choose the organization this new record belongs to.\",\n \"Pick an organization, then add the row again. Nothing was saved.\",\n );\n }\n const answer = await client.insert({ token: binding.token, organizationId, rows: [toWireValues(values)], opId: ledger.mint() });\n return readBack(alias, answer, \"The new row\");\n },\n\n async update(alias, id: Uuid, patch: Values, baseVersion: number) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n const answer = await client.update({ token: binding.token, id, baseVersion, patch: toWireValues(patch), opId: ledger.mint() });\n return readBack(alias, answer, \"The change\");\n },\n\n async archive(alias, id: Uuid) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n return done(await client.archive({ token: binding.token, ids: [id], opId: ledger.mint() }));\n },\n\n async restore(alias, id: Uuid) {\n const binding = bindingOf(alias);\n if (!binding) return noSuchAlias(alias);\n if (!isUuidShape(id)) return refusal(\"invalid_argument\", `\"${String(id)}\" is not a row id.`);\n return done(await client.unarchive({ token: binding.token, ids: [id], opId: ledger.mint() }));\n },\n\n subscribe(event: DataPortEventName, listener: (event: RowsEvent) => void) {\n const alias = event.startsWith(\"rows:\") ? event.slice(5) : null;\n const binding = alias ? bindingOf(alias) : null;\n if (!alias || !binding) {\n throw new Error(`DataPort.subscribe: \"${event}\" is not an event this Applet's port carries. Use rows:<alias>.`);\n }\n const realtime = options.realtime;\n if (!realtime) {\n // NOT LIVE, SAID OUT LOUD: a host that bound no realtime layer goes stale, and the console says why.\n if (!warnedNotLive) {\n warnedNotLive = true;\n console.warn(\"[@ai-matrx/records/entity] This host bound no realtime layer, so other people's changes appear on the next read.\");\n }\n return () => {};\n }\n\n let stopped = false;\n let joined: string[] = [];\n let stopLive: (() => void) | null = null;\n const sink = { rows: (ids: string[] | null) => listener({ ids: ids === null ? null : [...ids] }) };\n\n const plan = async () => {\n const organizationIds = binding.organizationId\n ? [binding.organizationId]\n : orderOrganizationTopics({\n active: activeOrganization(),\n held: heldCounts(alias),\n members: await membershipsOnce(),\n max: await maxOrgTopicsOnce(),\n });\n if (stopped) return;\n if (organizationIds.length === joined.length && organizationIds.every((org, i) => org === joined[i])) return;\n // Join the new set before leaving the old, so a topic in both never closes and reopens.\n const previous = stopLive;\n joined = organizationIds;\n stopLive = realtime.subscribe({ token: binding.token, organizationIds }, sink);\n previous?.();\n };\n const replan = () => void plan();\n const set = replans.get(alias) ?? new Set<() => void>();\n replans.set(alias, set);\n set.add(replan);\n replan();\n\n return () => {\n stopped = true;\n set.delete(replan);\n stopLive?.();\n stopLive = null;\n };\n },\n };\n}\n\n/**\n * THE PORT A SERVER ASKS THROUGH, AND THE PAGE READS THROUGH WHILE IT HYDRATES (lane SEED-ENTITY).\n * One construction for both, so the doors' arguments are the same on either side: a token is its own\n * alias, nothing is bound to an organization, and nothing is live. `dataSource` is the person's own\n * (server), a recording one, or one that answers from a page seed.\n */\nexport function createSeedPort(dataSource: unknown): EntityDataPort {\n return createEntityDataPort({ client: createEntityClient({ dataSource }), aliases: {}, tokensAreAliases: true, activeOrganizationId: () => null });\n}\n","// src/core/errors.ts — @ai-matrx/records/entity\n//\n// THE ERROR MAP (PHASE-B-APPLETS §4). The entity doors raise their own `MX0xx` class; this turns it\n// into the `RecordsError` every other door of the records package answers, carrying THE STORE'S\n// SENTENCE VERBATIM (message and hint are never rewritten here). Anything that is not an `MX` code\n// (a timeout, a dropped connection, a revoked schema) goes through records' own `mapPgError`.\n\nimport { mapPgError } from \"../../core/pgError\";\nimport type { PgError, RecordsError, RecordsErrorCode } from \"../../results\";\n\n/**\n * Every MX code a read door raises, and the engine code a screen branches on. A code the doors learn\n * later and this map lacks comes back `internal` with `unmapped: true` (never silently \"handled\").\n */\nexport const ENTITY_REFUSALS: Readonly<Record<string, RecordsErrorCode>> = {\n /** conflict_version: somebody else's write won. */\n MX001: \"stale_write\",\n /** organization_required: the call needs an organization and carried none. */\n MX002: \"organization_required\",\n /** forbidden. */\n MX003: \"door\",\n /** not_found (also: not visible to this person). */\n MX004: \"not_found\",\n /** validation_refused (detail.reason required / bad_value / ambiguous_word / constraint; `not_supported` is read apart below). */\n MX005: \"invalid_argument\",\n /** system_column: a write named a column the store owns. */\n MX008: \"invalid_argument\",\n /** unknown_identifier: a column that is not there or not usable here. */\n MX012: \"invalid_argument\",\n /** cursor_invalid: the page cursor belongs to another list; the engine restarts the page. */\n MX013: \"invalid_argument\",\n /** view_not_offered. */\n MX015: \"invalid_argument\",\n /** invalid_argument: a parameter the door refuses by name. */\n MX016: \"invalid_argument\",\n};\n\nexport function mapEntityError(error: PgError, where: string): RecordsError {\n const mapped = mapPgError(error, where);\n const state = mapped.sqlstate;\n if (state && /^MX\\d{3}$/.test(state)) {\n const code = ENTITY_REFUSALS[state];\n if (code) {\n // MX005 that says the store does not offer this yet is a different question for a screen than a bad value.\n const reason = (mapped.detail as { reason?: unknown } | undefined)?.reason;\n const known: RecordsError = { ...mapped, code: state === \"MX005\" && reason === \"not_supported\" ? \"not_supported\" : code };\n delete known.unmapped;\n delete known.diagnostic;\n return known;\n }\n }\n return mapped;\n}\n\n/** A refusal this package itself raises (an alias nobody declared, a write not offered yet). */\nexport function refusal(code: RecordsErrorCode, message: string, hint?: string): { ok: false; error: RecordsError } {\n return { ok: false, error: { code, message, ...(hint ? { hint } : {}) } };\n}\n","// src/core/client.ts — @ai-matrx/records/entity\n//\n// THE THIN TYPED CLIENT over the live INVOKER doors in `platform`: reads (`entity_list_scoped`,\n// `entity_get`, `entity_columns`) and, since 0.3, writes (`entity_insert`, `entity_update`,\n// `entity_archive`, `entity_unarchive`). Every call answers a `RecordsResult` and\n// never throws; every refusal is the store's own sentence (see `errors.ts`). The caller's seat is the\n// one on the supabase client handed in — nothing here widens or narrows what the store lets her see.\n\nimport { asRecordsDataSource } from \"../../core/supabase\";\nimport type { RecordsDataSource } from \"../../ports\";\nimport type { RecordsResult } from \"../../results\";\nimport type { Uuid } from \"../../record\";\nimport { mapEntityError } from \"./errors\";\nimport type { EntityColumnsAnswer, EntityGetAnswer, EntityListAnswer, EntityWireQuery, EntityWriteAnswer } from \"./types\";\n\n/**\n * THE ECHO HEADER (U6). The entity doors take no `_op_id` argument: the writer's op id rides the request\n * as this header, PostgREST hands it to `request.headers`, and `platform._entity_org_notice` puts it on\n * the notice as `op_id`, so the browser that wrote drops its own echo (`@ai-matrx/records` `isOwnOp`).\n */\nexport const OP_ID_HEADER = \"x-matrx-op-id\";\n\n/** What a write takes beyond its arguments: the op id minted for it (`mintOpId`). */\nexport interface EntityWriteOptions {\n opId?: string;\n}\n\n/** The schema every entity door lives in. */\nexport const ENTITY_DOOR_SCHEMA = \"platform\";\n\nexport interface CreateEntityClientOptions {\n /** A supabase-js v2 client for the signed-in person, or anything with `rpc(fn, args, {schema})`. */\n dataSource?: unknown;\n /** Same thing, spelled the way the plan names it. Give one of the two. */\n supabase?: unknown;\n}\n\nexport interface EntityListRequest extends EntityWireQuery {\n token: string;\n /** Keyset cursor from the previous answer's `next_after`. */\n after?: string | null;\n /** Ask the door to skip the count. Default: counted. */\n withTotal?: boolean;\n archived?: \"active\" | \"archived\" | \"all\";\n}\n\nexport interface EntityClient {\n list(request: EntityListRequest): Promise<RecordsResult<EntityListAnswer>>;\n get(request: { token: string; ids: readonly Uuid[] }): Promise<RecordsResult<EntityGetAnswer>>;\n /** `organizationId` null reads the custom fields of every organization the person belongs to. */\n columns(request: { token: string; organizationId?: Uuid | null }): Promise<RecordsResult<EntityColumnsAnswer>>;\n /** One `entity_data` knob as `platform.knob_resolve` answers it for an organization (live updates read three). */\n knob(request: { key: string; organizationId?: Uuid | null }): Promise<RecordsResult<unknown>>;\n /** `platform.entity_insert`: rows into the organization the host names (never guessed). */\n insert(request: { token: string; organizationId: Uuid; rows: readonly Record<string, unknown>[] } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n /** `platform.entity_update`: one row, refused as stale (`MX001`) unless `baseVersion` is still current. */\n update(request: { token: string; id: Uuid; baseVersion: number; patch: Record<string, unknown> } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n /** `platform.entity_archive` (on these types, the trash). */\n archive(request: { token: string; ids: readonly Uuid[] } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n /** `platform.entity_unarchive`. */\n unarchive(request: { token: string; ids: readonly Uuid[] } & EntityWriteOptions): Promise<RecordsResult<EntityWriteAnswer>>;\n /** The organizations the person belongs to, as row security counts them (`iam.my_orgs()`: archived ones closed). */\n memberOrganizations(): Promise<RecordsResult<Uuid[]>>;\n}\n\nexport function createEntityClient(options: CreateEntityClientOptions): EntityClient {\n const source: RecordsDataSource = asRecordsDataSource(options.dataSource ?? options.supabase);\n\n let warnedHeaderless = false;\n\n /**\n * A per-call header rides the request builder supabase-js hands back (`PostgrestBuilder.setHeader`, set\n * before the builder is awaited). `@ai-matrx/records`' adapter returns that builder unwrapped, so the\n * header reaches PostgREST on this one call only — never on the client every other caller shares.\n * A data seam whose answer has no `setHeader` (a host's own adapter, a test double) cannot carry it:\n * the write still lands, the writer re-reads its own echo once, and the console says why.\n */\n function withHeaders(pending: PromiseLike<unknown>, headers: Record<string, string> | undefined): void {\n if (!headers) return;\n const builder = pending as { setHeader?: (name: string, value: string) => unknown };\n if (typeof builder.setHeader === \"function\") {\n for (const [name, value] of Object.entries(headers)) builder.setHeader(name, value);\n return;\n }\n if (!warnedHeaderless) {\n warnedHeaderless = true;\n console.warn(\n `[@ai-matrx/records/entity] This data source cannot carry a per-call header (${Object.keys(headers).join(\", \")}), so this browser re-reads the notice of its own writes once.`,\n );\n }\n }\n\n async function call<T>(\n fn: string,\n args: Record<string, unknown>,\n schema: string = ENTITY_DOOR_SCHEMA,\n headers?: Record<string, string>,\n ): Promise<RecordsResult<T>> {\n try {\n const pending = source.rpc(fn, args, { schema });\n withHeaders(pending, headers);\n const answer = await pending;\n if (answer.error) return { ok: false, error: mapEntityError(answer.error, `${schema}.${fn}`) };\n return { ok: true, data: answer.data as T };\n } catch (thrown) {\n // supabase-js answers failures; a throw here is a transport that never reached the store.\n return {\n ok: false,\n error: mapEntityError({ code: \"\", message: thrown instanceof Error ? thrown.message : String(thrown) }, `${schema}.${fn}`),\n };\n }\n }\n\n return {\n list(request) {\n const args: Record<string, unknown> = {\n p_entity_type: request.token,\n p_scope: request.scope ?? null,\n p_filter: request.filter ?? {},\n p_search: request.search ?? null,\n p_sort: request.sort ?? null,\n p_archived: request.archived ?? \"active\",\n p_page_size: request.pageSize ?? null,\n p_after: request.after ?? null,\n p_with_total: request.withTotal ?? true,\n };\n return call<EntityListAnswer>(\"entity_list_scoped\", args);\n },\n get(request) {\n return call<EntityGetAnswer>(\"entity_get\", { p_entity_type: request.token, p_ids: [...request.ids] });\n },\n columns(request) {\n return call<EntityColumnsAnswer>(\"entity_columns\", { p_organization_id: request.organizationId ?? null, p_token: request.token });\n },\n insert(request) {\n return call<EntityWriteAnswer>(\n \"entity_insert\",\n { p_entity_type: request.token, p_organization_id: request.organizationId, p_rows: request.rows.map((r) => ({ ...r })) },\n ENTITY_DOOR_SCHEMA,\n opHeader(request.opId),\n );\n },\n update(request) {\n return call<EntityWriteAnswer>(\n \"entity_update\",\n { p_entity_type: request.token, p_id: request.id, p_base_version: request.baseVersion, p_patch: request.patch },\n ENTITY_DOOR_SCHEMA,\n opHeader(request.opId),\n );\n },\n archive(request) {\n return call<EntityWriteAnswer>(\"entity_archive\", { p_entity_type: request.token, p_ids: [...request.ids] }, ENTITY_DOOR_SCHEMA, opHeader(request.opId));\n },\n unarchive(request) {\n return call<EntityWriteAnswer>(\"entity_unarchive\", { p_entity_type: request.token, p_ids: [...request.ids] }, ENTITY_DOOR_SCHEMA, opHeader(request.opId));\n },\n knob(request) {\n return call<unknown>(\"knob_resolve\", { p_feature: \"entity_data\", p_key: request.key, p_organization_id: request.organizationId ?? null });\n },\n async memberOrganizations() {\n const answer = await call<unknown>(\"my_orgs\", {}, \"iam\");\n if (!answer.ok) return answer;\n const rows = Array.isArray(answer.data) ? answer.data : [];\n // A SETOF uuid comes back as bare strings; a row shape (`{my_orgs}`) is read the same way.\n const ids = rows\n .map((row) => (typeof row === \"string\" ? row : row && typeof row === \"object\" ? Object.values(row as Record<string, unknown>)[0] : null))\n .filter((id): id is string => typeof id === \"string\");\n return { ok: true, data: ids };\n },\n };\n}\n\nfunction opHeader(opId: string | undefined): Record<string, string> | undefined {\n return opId ? { [OP_ID_HEADER]: opId } : undefined;\n}\n","// src/core/realtime.ts — @ai-matrx/records/entity\n//\n// LIVE NOTICES FOR PLATFORM LISTS (PHASE-B-APPLETS R4 / U6).\n//\n// The database announces every statement on the five Table-API tables (party, crm_deal, project, task,\n// hr_employee) with ONE broadcast per organization it touched, on the PRIVATE topic\n// `mx:entity-org:<organization>:<token>`, event `entity_bump`, payload\n// `{id, entity_type, organization_id, op, op_id, ids | null, at}` — ids, never values. It is written by\n// `platform.entity_org_notice_stmt` and admitted by `platform.entity_org_topic_admits` through the one RLS\n// policy on `realtime.messages`: a signed-in member of that organization (her own memberships, never the\n// admin route) whose role may read the table. The subscriber re-reads the ids through the read door, so\n// row security decides what she sees at read time.\n//\n// This file joins those topics through `@ai-matrx/realtime` — the ONE realtime layer, never a hand-written\n// `.channel(` — so the socket, `setAuth` before a private join, backoff, dedupe and wake backfill are the\n// manager's.\n//\n// · ONE CHANNEL PER (organization, token), HOWEVER MANY READERS — opened by the first, closed by the last.\n// · BURSTS COALESCED per reader: the first notice starts a `batchMs` timer, later ones join it, and\n// `maxWaitMs` caps how long a steady stream can hold a re-read back (knobs entity_data.realtime_batch_ms\n// / realtime_max_wait_ms).\n// · `ids: null` PASSES THROUGH — above knob entity_data.realtime_max_ids the database stops naming ids.\n// · ECHO DROPPED — a write that carried header `x-matrx-op-id` comes back with that `op_id`; a notice whose\n// op id this client minted (`@ai-matrx/records` `isOwnOp`) is our own write and is dropped.\n// · NO REPLAY ON A WAKE OR RECONNECT — the answer is `ids: null` (read again).\n\nimport {\n defineChannelNamespace,\n subscribeToRealtimeManager,\n type ChannelSpec,\n type RealtimeManager,\n} from \"@ai-matrx/realtime\";\nimport { isOwnOp } from \"../../ops\";\n\nimport type { EntityClient } from \"./client\";\n\n/** The topic is a CONTRACT WITH THE DATABASE (a trigger writes it, an RLS policy parses it): built once, here. */\nexport const entityOrgChannel = defineChannelNamespace({\n namespace: \"entity-org\",\n foreignTopic: \"mx:entity-org\",\n parts: [\"organizationId\", \"token\"],\n description:\n \"One organization's changes to one platform type (contacts, deals, projects, tasks, employees). Carries NOTICES written by platform.entity_org_notice_stmt — which ids moved, never a value. Admitted by the one RLS policy on realtime.messages to members of that organization.\",\n});\n\n/** The broadcast event the database sends on an organization topic. */\nexport const ENTITY_NOTICE_EVENT = \"entity_bump\";\n\n/** Starting values of the knobs the runtime coalesces with (entity_data.realtime_batch_ms / _max_wait_ms). */\nexport const DEFAULT_BATCH_MS = 150;\nexport const DEFAULT_MAX_WAIT_MS = 1000;\n/** Starting value of knob entity_data.realtime_max_org_topics. */\nexport const DEFAULT_MAX_ORG_TOPICS = 20;\n\nexport interface EntityNotice {\n id?: string;\n entity_type?: string;\n organization_id?: string;\n op?: \"created\" | \"updated\" | \"deleted\";\n /** The client operation that caused it (header `x-matrx-op-id`), or null for any other writer. */\n op_id?: string | null;\n /** `null` MEANS \"more changed than the database lists: re-read\". */\n ids?: string[] | null;\n at?: string;\n}\n\n/** A redelivered notice is the same notice: the database mints one id per send. */\nexport function entityNoticeKey(notice: EntityNotice): string | undefined {\n return notice.id ?? (notice.at ? `${notice.organization_id ?? \"\"}:${notice.entity_type ?? \"\"}:${notice.at}` : undefined);\n}\n\nexport function entityOrgTopic(organizationId: string, token: string): string {\n return entityOrgChannel.topic({ organizationId, token });\n}\n\n/** The channel spec for one (organization, token): private, echo-guarded, deduped, backfilled. */\nexport function entityOrgChannelSpec(\n organizationId: string,\n token: string,\n onNotice: (notice: EntityNotice) => void,\n onBackfill: () => void,\n): ChannelSpec {\n return {\n topic: entityOrgTopic(organizationId, token),\n // Database Broadcast is authorized by RLS on realtime.messages; the manager awaits setAuth() first.\n private: true,\n // The sender is Postgres: no Matrx envelope. Our own write is known by the op id it carried.\n wire: { mode: \"raw\", isOwnMessage: (payload) => isOwnOp((payload as EntityNotice | null)?.op_id) },\n eventKey: (_source, payload) => entityNoticeKey((payload ?? {}) as EntityNotice),\n broadcast: [\n {\n event: ENTITY_NOTICE_EVENT,\n onMessage: (message) => {\n const notice = (message.data ?? {}) as EntityNotice;\n if (isOwnOp(notice.op_id)) return; // belt and braces: the manager's test ran first\n onNotice(notice);\n },\n },\n ],\n // Realtime has no replay: a channel back from a gap re-reads.\n onBackfill: () => onBackfill(),\n };\n}\n\n/**\n * Which organization topics to join, in order, until `max`: the active organization, the alias's `org`\n * filter, then the organizations of held rows by number of held rows (descending; organization id\n * ascending on ties), then the person's remaining memberships by id. Only memberships are kept when they\n * are known — any other topic is refused by the database anyway. Deterministic for the same input.\n */\nexport function orderOrganizationTopics(input: {\n active?: string | null;\n filter?: string | null;\n held?: ReadonlyMap<string, number>;\n members?: readonly string[] | null;\n max: number;\n}): string[] {\n const members = input.members ? new Set(input.members) : null;\n const out: string[] = [];\n const push = (org: string | null | undefined) => {\n if (!org || out.includes(org)) return;\n if (members && !members.has(org)) return;\n out.push(org);\n };\n push(input.active);\n push(input.filter);\n const held = [...(input.held ?? new Map<string, number>()).entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n for (const [org] of held) push(org);\n for (const org of [...(input.members ?? [])].sort()) push(org);\n return out.slice(0, Math.max(0, input.max));\n}\n\nexport interface EntityNoticeSink {\n /** `ids` to re-read, or `null` to re-read everything this reader shows. */\n rows(ids: string[] | null): void;\n}\n\nexport interface EntityRealtime {\n /** Hear `token` across `organizationIds`; the sink gets one coalesced call per burst. Returns the stop. */\n subscribe(target: { token: string; organizationIds: readonly string[] }, sink: EntityNoticeSink): () => void;\n}\n\nexport interface CreateEntityRealtimeOptions {\n /** The host's realtime manager. Left out, the AMBIENT manager the app mounted — never a socket of our own. */\n manager?: RealtimeManager;\n /** Knob entity_data.realtime_batch_ms (starting value 150). */\n batchMs?: number;\n /** Knob entity_data.realtime_max_wait_ms (starting value 1000). */\n maxWaitMs?: number;\n}\n\ninterface OrgListener {\n notice(notice: EntityNotice): void;\n backfill(): void;\n}\n\ninterface OrgChannel {\n listeners: Set<OrgListener>;\n stop: (() => void) | null;\n}\n\n/** The live-notice layer for platform lists, bound to a realtime manager. One per host is enough. */\nexport function createEntityRealtime(options: CreateEntityRealtimeOptions = {}): EntityRealtime {\n const batchMs = options.batchMs ?? DEFAULT_BATCH_MS;\n const maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;\n const channels = new Map<string, OrgChannel>();\n\n const open = (organizationId: string, token: string): OrgChannel => {\n const channel: OrgChannel = { listeners: new Set(), stop: null };\n const spec = entityOrgChannelSpec(\n organizationId,\n token,\n (notice) => {\n for (const listener of channel.listeners) listener.notice(notice);\n },\n () => {\n for (const listener of channel.listeners) listener.backfill();\n },\n );\n if (options.manager) {\n const handle = options.manager.open(spec);\n channel.stop = () => handle.close();\n } else {\n channel.stop = subscribeToRealtimeManager(() => spec);\n }\n return channel;\n };\n\n return {\n subscribe({ token, organizationIds }, sink) {\n let timer: ReturnType<typeof setTimeout> | null = null;\n let firstAt = 0;\n let pending = new Set<string>();\n let wholeList = false;\n\n const flush = () => {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n const ids = [...pending];\n const all = wholeList;\n pending = new Set();\n wholeList = false;\n // THE IDS ARE USED AS IDS. `null` costs a whole re-read; three ids re-read three rows.\n if (all) sink.rows(null);\n else if (ids.length > 0) sink.rows(ids);\n };\n const nudge = () => {\n const now = Date.now();\n if (timer === null) firstAt = now;\n else clearTimeout(timer);\n // Wait `batchMs` after the latest notice, never past `maxWaitMs` after the first one.\n const wait = Math.max(0, Math.min(batchMs, firstAt + maxWaitMs - now));\n timer = setTimeout(flush, wait);\n };\n\n const listener: OrgListener = {\n notice(notice) {\n if (notice.entity_type && notice.entity_type !== token) return;\n if (notice.ids == null) wholeList = true;\n else for (const id of notice.ids) pending.add(id);\n nudge();\n },\n backfill() {\n wholeList = true;\n flush();\n },\n };\n\n const keys = [...new Set(organizationIds)].map((org) => {\n const key = entityOrgTopic(org, token);\n const channel = channels.get(key) ?? open(org, token);\n channels.set(key, channel);\n channel.listeners.add(listener);\n return key;\n });\n\n return () => {\n if (timer !== null) clearTimeout(timer);\n for (const key of keys) {\n const channel = channels.get(key);\n if (!channel) continue;\n channel.listeners.delete(listener);\n if (channel.listeners.size > 0) continue;\n // The last reader of this (organization, token) left: its one subscription goes with it.\n channel.stop?.();\n channels.delete(key);\n }\n };\n },\n };\n}\n\n/** The three live-update knobs as the store answers them for an organization (starting values when unset). */\nexport async function readEntityRealtimeKnobs(\n client: Pick<EntityClient, \"knob\">,\n organizationId?: string | null,\n): Promise<{ batchMs: number; maxWaitMs: number; maxOrgTopics: number }> {\n const read = async (key: string, fallback: number) => {\n const answer = await client.knob({ key, organizationId: organizationId ?? null });\n const value = answer.ok ? Number(answer.data) : Number.NaN;\n if (!Number.isFinite(value)) {\n // SAID OUT LOUD: the starting value stands in for a knob the store did not answer.\n console.warn(`[@ai-matrx/records/entity] knob entity_data.${key} did not resolve; using its starting value ${fallback}.`);\n return fallback;\n }\n return value;\n };\n const [batchMs, maxWaitMs, maxOrgTopics] = await Promise.all([\n read(\"realtime_batch_ms\", DEFAULT_BATCH_MS),\n read(\"realtime_max_wait_ms\", DEFAULT_MAX_WAIT_MS),\n read(\"realtime_max_org_topics\", DEFAULT_MAX_ORG_TOPICS),\n ]);\n return { batchMs, maxWaitMs, maxOrgTopics };\n}\n","// src/core/wire.ts — @ai-matrx/records/entity\n//\n// `toWire`: the Applets `Query` (§4) → the door's arguments (scope, filter, sort). Pure.\n//\n// What the doors do not offer yet is NOT filtered, reordered or emulated here: the clause is sent as\n// asked and the door refuses it BY NAME (`\"contains\" filters are not offered yet.`), so the day the\n// door learns it the port already speaks it, and until then the person reads the store's sentence.\n// A browser-side filter would silently drop everything the browser was not shown.\n\nimport type { Query, WhereClause } from \"../../data\";\nimport type { EntityWirePredicate, EntityWireQuery, EntityWireSort } from \"./types\";\n\n/** The runtime's underscore names for the three identity columns the doors call `id`, `version`, `organization_id`. */\nconst IDENTITY: Readonly<Record<string, string>> = {\n _id: \"id\",\n _version: \"version\",\n _organization_id: \"organization_id\",\n};\n\nexport const CUSTOM_PREFIX = \"_custom.\";\n\n/**\n * Applets column key → the door's identifier. A custom field is `_custom.<key>` (the key as\n * `columns()` answered it — the same plain key for every viewer; `<key>@<organization_id>` is accepted, never produced).\n */\nexport function wireColumn(column: string, customKeys: ReadonlySet<string>): string {\n const identity = IDENTITY[column];\n if (identity) return identity;\n if (column.startsWith(CUSTOM_PREFIX)) return column;\n return customKeys.has(column) ? `${CUSTOM_PREFIX}${column}` : column;\n}\n\nfunction predicate(clause: WhereClause, customKeys: ReadonlySet<string>): EntityWirePredicate {\n const column = wireColumn(clause.column, customKeys);\n const v = clause.value;\n switch (clause.op) {\n case \"eq\":\n // The store reads \"equals nothing\" as empty (the table port's rule, so both kinds of source agree).\n return v === null || v === undefined ? { column, op: \"empty\" } : { column, op: \"eq\", value: v };\n case \"neq\":\n return v === null || v === undefined ? { column, op: \"empty\", negated: true } : { column, op: \"neq\", value: v };\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n return { column, op: clause.op, value: v };\n case \"in\":\n return { column, op: \"in\", values: Array.isArray(v) ? v : [] };\n case \"empty\":\n return v === false ? { column, op: \"empty\", negated: true } : { column, op: \"empty\" };\n case \"contains\":\n return { column, op: \"contains\", value: v };\n default:\n // An op this version does not know is still SENT, so the door names it, instead of vanishing here.\n return { column, op: String((clause as WhereClause).op), value: v };\n }\n}\n\nexport function toWire(query: Query | undefined, customKeys: ReadonlySet<string> = new Set()): EntityWireQuery {\n const q = query ?? {};\n const out: EntityWireQuery = {};\n const scope: NonNullable<EntityWireQuery[\"scope\"]> = {};\n if (q.lane) scope.kind = q.lane; // absent = the type's own landing lane, decided by the door\n if (q.org && q.org !== \"all\") scope.organization_id = q.org; // a filter, never a lock\n if (scope.kind || scope.organization_id) out.scope = scope;\n if (q.where && q.where.length > 0) out.filter = { all: q.where.map((c) => predicate(c, customKeys)) };\n const search = q.search?.trim();\n if (search) out.search = search;\n if (q.sort && q.sort.length > 0) {\n out.sort = q.sort.map<EntityWireSort>((s) => ({\n column: wireColumn(s.column, customKeys),\n dir: s.direction === \"desc\" ? \"desc\" : \"asc\",\n nulls: \"last\",\n }));\n }\n if (typeof q.pageSize === \"number\" && Number.isFinite(q.pageSize)) out.pageSize = Math.max(1, Math.floor(q.pageSize));\n return out;\n}\n","// src/port/rows.ts — @ai-matrx/records/entity\n//\n// ROW AND COLUMN SHAPING (Applets CONTRACTS §0): the door's wire row → `Row`, its columns → `Column`.\n// Pure; every case is pinned against recorded door answers (`__fixtures__`).\n\nimport type { Column, EntityRef, Row } from \"../../data\";\nimport type { EntityColumnWire, EntityWireRow } from \"../core/types\";\n\n/** The door's identity columns become the runtime's own underscore keys on a Row; they are never plain columns. */\nconst IDENTITY_COLUMNS = new Set([\"id\", \"version\", \"organization_id\"]);\n/** The compiler's own presentation markers; not data. */\nconst PRESENTATION_KEYS = new Set([\"_state\", \"_k\"]);\n\nfunction isRefList(value: unknown): value is { token: string; id: string; label?: unknown }[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((item) => item !== null && typeof item === \"object\" && typeof (item as { token?: unknown }).token === \"string\" && typeof (item as { id?: unknown }).id === \"string\")\n );\n}\n\n/** Every link reads as `EntityRef[]` — `{token, id, label}`, the label null when the store had no words for it. */\nexport function toRefs(value: unknown): EntityRef[] {\n if (!isRefList(value)) return [];\n return value.map<EntityRef>((item) => ({ token: item.token, id: item.id, label: typeof item.label === \"string\" ? item.label : null }));\n}\n\nexport function toRow(wire: EntityWireRow): Row {\n const row: Row = {\n _id: wire.id,\n _version: wire.version,\n _organization_id: wire.organization_id,\n _custom: wire._custom && typeof wire._custom === \"object\" ? { ...wire._custom } : {},\n };\n for (const [key, value] of Object.entries(wire)) {\n if (IDENTITY_COLUMNS.has(key) || PRESENTATION_KEYS.has(key) || key === \"_custom\") continue;\n row[key] = isRefList(value) ? toRefs(value) : value === undefined ? null : value;\n }\n return row;\n}\n\nexport function toColumn(wire: EntityColumnWire): Column {\n const column: Column = {\n key: wire.key,\n label: wire.label || wire.key,\n type: wire.type,\n origin: wire.origin === \"custom\" ? \"custom\" : \"platform\",\n required: Boolean(wire.required),\n readOnly: Boolean(wire.readOnly),\n };\n if (wire.choices && wire.choices.length > 0) column.choices = [...wire.choices];\n if (wire.linksTo && wire.linksTo.length > 0) column.linksTo = [...wire.linksTo];\n return column;\n}\n\n/** The columns a person sees: the door's own list minus the identity columns a Row carries as `_id` / `_version` / `_organization_id`. */\nexport function toColumns(wire: readonly EntityColumnWire[]): Column[] {\n return wire.filter((c) => !IDENTITY_COLUMNS.has(c.key)).map(toColumn);\n}\n","// src/versions/rowVersion.ts — @ai-matrx/records/versions · pure (server-safe)\nimport type { ReadRow } from \"@ai-matrx/records\";\n\n/** The version a row carries itself, when the host's read gave it one. */\nexport function ownVersion(row: ReadRow): number | null {\n const v = (row as ReadRow & { version?: unknown }).version;\n return typeof v === \"number\" ? v : null;\n}\n","// src/views/keys.ts — @ai-matrx/records/views (headless; moved from records-ui viewKeys.ts, step 10 2026-10-08)\n// · lane S1-PRIME VIEW-KEYS (UI-CHAMPIONS-PLAN rev 2)\n//\n// EVERY PER-VIEW SETTING IS A DECLARED KEY OF THE ONE SAVED VIEW.\n//\n// A saved view is one row of `platform.saved_view` (lane S0). What it may hold is decided in ONE\n// place: `custom.view_keys()`, the registry `custom.view_declare` judges every save against. This\n// file is that registry's client half and the ONE accessor every layout reads a view through:\n//\n// - `VIEW_KEYS` mirrors `custom.view_keys()` row for row (path, shape, the layouts that read it,\n// who may write it). The live walk compares the two through REST, as test@test.com, so a key\n// added on one side and not the other fails a walk, never a person.\n// - `viewSettings(definition)` is THE reader: a stored definition in, every declared key out,\n// typed. `viewFromRow` (views.ts) goes through it, so the Grid, the board, the calendar,\n// and the gallery all see a view the same way.\n// - `viewSettingsFor(view, layout)` hands a layout only the keys it reads; a layout that does\n// not use a key never sees it (the calendar is never told about swimlanes).\n// - `viewSettingsPatch(patch)` is THE writer's shape: only the keys a press changed, a cleared\n// key as null (the door removes it). `saveViewPatch` sends it through `custom.view_declare`.\n//\n// Fields are named by KEY (a Field's key is immutable; every reader draws rows by key). The door\n// accepts an id and stores the key, so an agent may send either.\n\nimport type { RecordFilter, RuleExpression } from \"@ai-matrx/records\";\n\n/** A view's look as the store keeps it: one JSON object under `definition.presentation`. */\nexport type ViewPresentationDocument = Record<string, unknown>;\n\n/**\n * HOW A VIEW'S LOOK IS READ AND WRITTEN — a PORT. The store keeps the look as one JSON object; what it\n * means (colors, formats, frozen columns) belongs to the screens that draw it, so the screens hand their\n * codec in (`@ai-matrx/records-ui` binds its grid presentation). Left out, the look stays the plain\n * document the store keeps — a headless host reads and writes it untouched.\n */\nexport interface ViewPresentationCodec<P> {\n parse(raw: unknown): P;\n isEmpty(presentation: P): boolean;\n /** The look as the JSON object the store keeps. */\n toDocument(presentation: P): Record<string, unknown>;\n}\n\n/** The look as the plain JSON document the store keeps (no screen's meaning applied). */\nexport const plainPresentation: ViewPresentationCodec<ViewPresentationDocument> = {\n parse: (raw) => (raw && typeof raw === \"object\" && !Array.isArray(raw) ? { ...(raw as Record<string, unknown>) } : {}),\n isEmpty: (presentation) => Object.keys(presentation).length === 0,\n toDocument: (presentation) => ({ ...presentation }),\n};\n\nfunction plainCodec<P>(): ViewPresentationCodec<P> {\n return plainPresentation as unknown as ViewPresentationCodec<P>;\n}\n\n/** Every surface a saved view is drawn by. */\nexport type ViewKeyLayout = \"grid\" | \"kanban\" | \"calendar\" | \"gallery\" | \"timeline\" | \"list\";\n\n/**\n * 🚩 THE ONE SWITCH FOR THE TIMELINE'S STORE KEYS (lane VIEWS-AND-FIELDS, sublane TL).\n *\n * `vk_a_calendar_keeps_where_a_record_ends_and_a_timeline_is_a_view.sql` (sublane VK) teaches\n * `custom.view_keys()` the layout `timeline`, the keys `start_field` and `end_field` (calendar +\n * timeline), and `group_field` for the timeline. Until that migration is on production this stays\n * `false`, and:\n * · `timeline` is not a layout the store keeps (`STORE_KEPT_LAYOUTS`), so it is drawn for the visit;\n * · `start_field` / `end_field` are held for the visit, never sent (`viewSettingsPatch`), and the\n * Start also rides `date_field`, which the store already keeps;\n * · the timeline's toolbar says \"Kept for this visit only\".\n * Flipped to `true`, VIEW_KEYS below mirrors the migrated registry row for row (the live walk\n * compares them) and every one of those is kept on the view.\n */\nexport const STORE_KEEPS_TIMELINE = true;\n\n/** Who may write a key: anyone who may save the view, an input the door rewrites, or the server only. */\nexport type ViewKeyWriter = \"caller\" | \"input\" | \"server\";\n\nexport interface ViewKeyDeclaration {\n /** Where it lives in `platform.saved_view.definition` (dotted under `presentation`). */\n path: string;\n /** What the store's guard checks (`custom._view_key_value`). */\n shape: string;\n /** The layouts that read it. */\n layouts: readonly ViewKeyLayout[];\n writer: ViewKeyWriter;\n}\n\nconst ALL: readonly ViewKeyLayout[] = [\"grid\", \"kanban\", \"calendar\", \"gallery\", ...(STORE_KEEPS_TIMELINE ? ([\"timeline\"] as const) : []), \"list\"];\n/** The layouts whose cards draw the fields a view leaves shown (`presentation.hiddenFields`). */\nconst HIDES: readonly ViewKeyLayout[] = [\"grid\", \"gallery\", \"kanban\", \"calendar\", ...(STORE_KEEPS_TIMELINE ? ([\"timeline\"] as const) : []), \"list\"];\nconst GRIDS: readonly ViewKeyLayout[] = [\"grid\"];\n\n/**\n * THE REGISTRY, as `custom.view_keys()` declares it (uichamp_s1_a_view_keeps_every_setting_it_is_given.sql).\n * Order and content are compared with the store by the live walk.\n */\nexport const VIEW_KEYS: readonly ViewKeyDeclaration[] = [\n { path: \"layout\", shape: \"kind\", layouts: ALL, writer: \"caller\" },\n { path: \"filters\", shape: \"filter\", layouts: ALL, writer: \"caller\" },\n { path: \"where\", shape: \"rule\", layouts: ALL, writer: \"caller\" },\n { path: \"group_field\", shape: \"field\", layouts: [\"kanban\", ...(STORE_KEEPS_TIMELINE ? ([\"timeline\"] as const) : [])], writer: \"caller\" },\n { path: \"swimlane_field\", shape: \"field:lane\", layouts: [\"kanban\"], writer: \"caller\" },\n { path: \"collapsed_columns\", shape: \"values\", layouts: [\"kanban\"], writer: \"caller\" },\n { path: \"measure\", shape: \"field:number\", layouts: [\"kanban\"], writer: \"caller\" },\n { path: \"date_field\", shape: \"field:date\", layouts: [\"calendar\"], writer: \"caller\" },\n ...(STORE_KEEPS_TIMELINE\n ? ([\n { path: \"start_field\", shape: \"field:date\", layouts: [\"timeline\"], writer: \"caller\" },\n { path: \"end_field\", shape: \"field:date\", layouts: [\"calendar\", \"timeline\"], writer: \"caller\" },\n ] as const)\n : []),\n { path: \"image_field\", shape: \"field\", layouts: [\"gallery\"], writer: \"caller\" },\n { path: \"sorts\", shape: \"sorts\", layouts: ALL, writer: \"caller\" },\n { path: \"rule_id\", shape: \"uuid\", layouts: ALL, writer: \"caller\" },\n { path: \"is_default\", shape: \"boolean\", layouts: ALL, writer: \"caller\" },\n { path: \"presentation\", shape: \"presentation\", layouts: ALL, writer: \"caller\" },\n { path: \"presentation.style\", shape: \"style\", layouts: ALL, writer: \"caller\" },\n { path: \"presentation.formats\", shape: \"object\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.frozen\", shape: \"fields\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.grouping\", shape: \"grouping\", layouts: [\"grid\", \"gallery\", \"list\"], writer: \"caller\" },\n { path: \"presentation.widths\", shape: \"widths\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.rowHeight\", shape: \"row_height\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.hiddenFields\", shape: \"fields\", layouts: HIDES, writer: \"caller\" },\n { path: \"presentation.cardHidden\", shape: \"fields\", layouts: [\"kanban\", \"calendar\", ...(STORE_KEEPS_TIMELINE ? ([\"timeline\"] as const) : []), \"list\", \"gallery\"], writer: \"caller\" },\n { path: \"presentation.columnOrder\", shape: \"fields\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.gallerySize\", shape: \"gallery_size\", layouts: [\"gallery\"], writer: \"caller\" },\n { path: \"presentation.wrap\", shape: \"boolean\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.wrapColumns\", shape: \"fields\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.fit\", shape: \"fit\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.freezeFirst\", shape: \"boolean\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.footer\", shape: \"footer\", layouts: GRIDS, writer: \"caller\" },\n { path: \"presentation.summaries\", shape: \"summaries\", layouts: GRIDS, writer: \"caller\" },\n { path: \"grid\", shape: \"grid\", layouts: GRIDS, writer: \"caller\" },\n { path: \"hidden_fields\", shape: \"input\", layouts: HIDES, writer: \"input\" },\n { path: \"table_id\", shape: \"server\", layouts: ALL, writer: \"server\" },\n { path: \"order\", shape: \"server\", layouts: GRIDS, writer: \"server\" },\n { path: \"moved_from\", shape: \"server\", layouts: ALL, writer: \"server\" },\n];\n\n/**\n * THE LAYOUTS THE STORE KEEPS ON A VIEW. `custom.view_keys()` judges a view's `layout` against its\n * own list (grid, kanban, calendar, gallery) and refuses any other word by name. A layout this\n * package draws before the store keeps it — the timeline, 2026-10-02 — is never sent as a view's or a\n * look's layout (`viewSettingsPatch`, `viewDocument`): it is drawn for this visit and says so. When the\n * store's registry admits it, add it here and nothing else changes.\n */\nexport const STORE_KEPT_LAYOUTS: readonly string[] = [\"grid\", \"kanban\", \"calendar\", \"gallery\", ...(STORE_KEEPS_TIMELINE ? [\"timeline\"] : []), \"list\"];\n\n/** Whether the store keeps this layout on a saved view. */\nexport function storeKeepsLayout(layout: string): boolean {\n return STORE_KEPT_LAYOUTS.includes(layout);\n}\n\n/** The keys one layout reads, by path. */\nexport function viewKeysFor(layout: ViewKeyLayout): string[] {\n return VIEW_KEYS.filter((k) => k.layouts.includes(layout)).map((k) => k.path);\n}\n\n/** One sort clause: a Field key and a direction. */\nexport interface ViewSortKey {\n field: string;\n direction: \"asc\" | \"desc\";\n}\n\n/**\n * EVERY DECLARED KEY OF A VIEW, TYPED. Absent keys are `null` / empty, never guessed.\n * `presentation` is the parsed look (colour field, pinned fields, row height, grouping with its\n * sub-groups and shut sections, hidden fields, gallery size, summaries).\n */\nexport interface ViewSettings<P = ViewPresentationDocument> {\n layout: \"grid\" | \"kanban\" | \"calendar\" | \"gallery\" | \"timeline\" | \"list\";\n filters: RecordFilter | null;\n where: RuleExpression | null;\n groupField: string | null;\n swimlaneField: string | null;\n collapsedColumns: string[];\n measure: string | null;\n dateField: string | null;\n /** Timeline: where a record's bar starts (`start_field`). */\n startField: string | null;\n /** Calendar and timeline: where a record ends (`end_field`). */\n endField: string | null;\n imageField: string | null;\n sorts: ViewSortKey[];\n ruleId: string | null;\n isDefault: boolean;\n presentation: P;\n movedFrom: Record<string, unknown> | null;\n}\n\n// The layouts a stored view reads back as; one the store does not keep yet reads as a grid. A\n// saved timeline read back as \"grid\" was the reload that lost it (FDT, 2026-10-03).\nconst KINDS: readonly string[] = STORE_KEPT_LAYOUTS;\n\n/** THE READER. A stored `definition` (and the row's flat `filters`) in, every declared key out. */\nexport function viewSettings<P = ViewPresentationDocument>(\n definition: Record<string, unknown> | null | undefined,\n rowFilters?: RecordFilter | null,\n codec: ViewPresentationCodec<P> = plainCodec<P>(),\n): ViewSettings<P> {\n const data = definition ?? {};\n const text = (key: string): string | null => {\n const v = data[key];\n return typeof v === \"string\" && v !== \"\" ? v : null;\n };\n const layout = String(data[\"layout\"] ?? \"grid\");\n const flat = rowFilters ?? (isObject(data[\"filters\"]) ? (data[\"filters\"] as RecordFilter) : null);\n const moved = data[\"moved_from\"];\n return {\n layout: (KINDS as readonly string[]).includes(layout) ? (layout as ViewSettings<P>[\"layout\"]) : \"grid\",\n filters: flat && Object.keys(flat).length > 0 ? flat : null,\n where: isRule(data[\"where\"]) ? (data[\"where\"] as RuleExpression) : null,\n groupField: text(\"group_field\"),\n swimlaneField: text(\"swimlane_field\"),\n collapsedColumns: Array.isArray(data[\"collapsed_columns\"])\n ? (data[\"collapsed_columns\"] as unknown[]).filter((v) => [\"string\", \"number\", \"boolean\"].includes(typeof v)).map(String)\n : [],\n measure: text(\"measure\"),\n dateField: text(\"date_field\"),\n startField: text(\"start_field\"),\n endField: text(\"end_field\"),\n imageField: text(\"image_field\"),\n sorts: parseSorts(data[\"sorts\"]),\n ruleId: text(\"rule_id\"),\n isDefault: data[\"is_default\"] === true || data[\"is_default\"] === \"true\",\n presentation: codec.parse(data[\"presentation\"]),\n movedFrom: isObject(moved) ? (moved as Record<string, unknown>) : null,\n };\n}\n\n/** The settings as the spec names them — what `viewSettingsPatch` takes. */\nexport type ViewSettingsPatch<P = ViewPresentationDocument> = Partial<Omit<ViewSettings<P>, \"movedFrom\" | \"layout\">> & {\n /** Any layout the package draws; one the store does not keep is not sent. */\n layout?: string;\n};\n\n/**\n * THE KEYS ONE LAYOUT READS, and nothing else. A layout that does not use a key never sees it:\n * a calendar is not told the board's swimlanes, a board is not told the grid's pinned fields.\n */\nexport function viewSettingsFor<P extends object = ViewPresentationDocument>(settings: ViewSettings<P>, layout: ViewKeyLayout): Partial<ViewSettings<P>> {\n const reads = new Set(viewKeysFor(layout));\n const out: Partial<ViewSettings<P>> = { layout: settings.layout };\n const take = <K extends keyof ViewSettings<P>>(key: K, path: string) => {\n if (reads.has(path)) out[key] = settings[key];\n };\n take(\"filters\", \"filters\");\n take(\"where\", \"where\");\n take(\"groupField\", \"group_field\");\n take(\"swimlaneField\", \"swimlane_field\");\n take(\"collapsedColumns\", \"collapsed_columns\");\n take(\"measure\", \"measure\");\n take(\"dateField\", \"date_field\");\n take(\"startField\", \"start_field\");\n take(\"endField\", \"end_field\");\n take(\"imageField\", \"image_field\");\n take(\"sorts\", \"sorts\");\n take(\"ruleId\", \"rule_id\");\n take(\"isDefault\", \"is_default\");\n const p = settings.presentation;\n const look = {} as P;\n for (const [key, value] of Object.entries(p)) {\n if (reads.has(`presentation.${key}`)) (look as Record<string, unknown>)[key] = value;\n }\n out.presentation = look;\n return out;\n}\n\n/**\n * THE WRITER'S SHAPE. Only the keys a press changed; a cleared Field is `null` (the door removes\n * it); lists are sent whole. `presentation` is sent whole because the door judges it as one key.\n */\nexport function viewSettingsPatch<P = ViewPresentationDocument>(\n patch: ViewSettingsPatch<P>,\n codec: ViewPresentationCodec<P> = plainCodec<P>(),\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const field = (key: keyof ViewSettingsPatch<P>, path: string) => {\n if (patch[key] !== undefined) out[path] = (patch[key] as string | null) || null;\n };\n // A layout the store does not keep yet is held for this visit, never sent (`STORE_KEPT_LAYOUTS`).\n if (patch.layout !== undefined && storeKeepsLayout(patch.layout)) out[\"layout\"] = patch.layout;\n field(\"groupField\", \"group_field\");\n field(\"swimlaneField\", \"swimlane_field\");\n field(\"measure\", \"measure\");\n field(\"dateField\", \"date_field\");\n // Held for the visit until the store keeps them (`STORE_KEEPS_TIMELINE`).\n if (STORE_KEEPS_TIMELINE) {\n field(\"startField\", \"start_field\");\n field(\"endField\", \"end_field\");\n }\n field(\"imageField\", \"image_field\");\n field(\"ruleId\", \"rule_id\");\n if (patch.collapsedColumns !== undefined) out[\"collapsed_columns\"] = patch.collapsedColumns ?? [];\n if (patch.sorts !== undefined) out[\"sorts\"] = patch.sorts ?? [];\n if (patch.where !== undefined) out[\"where\"] = patch.where ?? null;\n if (patch.isDefault !== undefined) out[\"is_default\"] = patch.isDefault === true;\n if (patch.presentation !== undefined) {\n out[\"presentation\"] =\n !patch.presentation || codec.isEmpty(patch.presentation) ? null : codec.toDocument(patch.presentation);\n }\n return out;\n}\n\nfunction isObject(raw: unknown): boolean {\n return Boolean(raw) && typeof raw === \"object\" && !Array.isArray(raw);\n}\n\nfunction isRule(raw: unknown): boolean {\n if (!isObject(raw)) return false;\n const node = raw as { op?: unknown; args?: unknown };\n return typeof node.op === \"string\" && Array.isArray(node.args);\n}\n\nfunction parseSorts(raw: unknown): ViewSortKey[] {\n let list: unknown = raw;\n if (typeof raw === \"string\") {\n try {\n list = raw.trim() === \"\" ? [] : JSON.parse(raw);\n } catch {\n return [];\n }\n }\n if (!Array.isArray(list)) return [];\n return list\n .filter((s): s is { field: string; direction?: string } => isObject(s) && typeof (s as { field?: unknown }).field === \"string\")\n .map((s) => ({ field: s.field, direction: s.direction === \"desc\" ? \"desc\" : \"asc\" }));\n}\n","// src/views/views.ts — @ai-matrx/records/views (headless; moved from records-ui views.ts, step 10 2026-10-08)\n// · SCR-6, SCR-7, SCR-N-6. The look (`presentation`) is a codec port (keys.ts); records-ui binds its grid look.\n//\n// A SAVED VIEW IS ONE ROW OF THE ONE SAVED-VIEW STORE, `platform.saved_view`\n// (chair ruling 2026-09-23, lane S0 ONE-SAVED-VIEW), read through `custom.views`\n// and written through `custom.view_declare` — the same door the digests, the\n// notify rules, the agent's boards, the grid's choices (G1/G7), the hand-set\n// order (G13) and the mover use. It owns its layout and REFERENCES its\n// membership rule.\n//\n// 🚨 THERE WERE TWO STORES (UI-CHAMPIONS-PLAN-ATTACK hole 1). Until S0 this bar\n// kept each view as a record of a package-owned `records_ui_view` Table in every\n// organization, beside `platform.saved_view`: a view the mover carried in never\n// reached the bar, a view saved in the bar was invisible to every subscription,\n// and a grid choice G1 kept had no screen that read it. The repair migration\n// `oneview_every_view_bar_view_moves_into_the_one_store.sql` moved every one of\n// those records into `platform.saved_view` UNDER THE SAME ID and archived the\n// Tables; nothing in this package reads or writes them any more.\n//\n// The split matters. A view does not carry a filter predicate of its own that a\n// screen re-implements in JavaScript: it names a Rule, and the STORE answers\n// who is in it (`custom.rule_members`). So the same view means the same thing\n// to a grid, to an export, to an agent and to the server. What the view owns\n// itself is presentation — which of the four layouts, which Field the kanban\n// columns come from, which Field the calendar reads, which Field the gallery\n// shows — because that is not data, it is how this person wants to look at it.\n//\n// The whole view is also a plain declarative object (`SavedViewSpec`), which is\n// what makes \"an agent writes the view in 45 seconds\" true: one `view_declare`\n// of one definition, and the person only tweaks.\n\nimport {\n STORE_KEEPS_TIMELINE,\n plainPresentation,\n storeKeepsLayout,\n viewSettings,\n viewSettingsPatch,\n type ViewPresentationCodec,\n type ViewPresentationDocument,\n} from \"./keys\";\nimport type { RecordsClient } from \"../core/client\";\nimport type { RecordFilter, RuleExpression, SavedViewRow, Uuid } from \"../core/index\";\nimport type { RecordsResult } from \"../results\";\n\nfunction plainCodec<P>(): ViewPresentationCodec<P> {\n return plainPresentation as unknown as ViewPresentationCodec<P>;\n}\n\n/** The ways one saved view can be looked at (SCR-6; the timeline, lane VIEWS-AND-FIELDS TL). */\nexport const VIEW_LAYOUTS = [\"grid\", \"kanban\", \"calendar\", \"gallery\", \"timeline\", \"list\"] as const;\nexport type ViewLayout = (typeof VIEW_LAYOUTS)[number];\n\nexport const LAYOUT_LABEL: Record<ViewLayout, string> = {\n grid: \"Grid\",\n kanban: \"Kanban\",\n calendar: \"Calendar\",\n gallery: \"Gallery\",\n timeline: \"Timeline\",\n list: \"List\",\n};\n\n\n/**\n * ─────────────────────────────────────────────────────────────────────────────\n * WHAT EACH LAYOUT NEEDS FROM THE TABLE, AND HOW THE SCREEN SUPPLIES IT\n * (lane DATA-V2-VIEWS-1, Arman 2026-09-28).\n *\n * THE DEFECT. A plain table opened as a Kanban said \"A kanban board needs a Field to make its\n * columns from … Add column, then Select — and it appears here.\" It told the person what to do\n * instead of doing it, and on an AI platform it offered no AI. The ruling: ONE primitive, used by\n * every view (`ViewNeeds`) — the empty state says in one plain sentence what is missing and what\n * pressing will do, offers \"Make it work\" (the column is declared through the store's\n * `custom.field_declare`, its key minted by the store, its name and choices editable before the\n * press) and \"Ask AI\" (the agent does it through the same door, held for the person's approval by\n * the organization's \"Agent changes to this organization's data\" setting).\n *\n * THE CENSUS — every layout this package draws, and what it reads:\n * · grid nothing.\n * · kanban a CHOICE column (its options become the board's columns). Blocking.\n * · calendar a DATE column (it places each record on a day). Blocking.\n * · gallery a FILE column for the card's picture. NOT blocking: the cards draw without one,\n * so the offer sits above them instead of in place of them.\n * · timeline a DATE column each bar starts on (the calendar's `dateField`). Blocking.\n * `PAGE_VIEWS`' two extra values (dashboards, archived) read\n * nothing a table can lack. This package ships no map layout; the day it does,\n * `Record<ViewLayout, …>` below refuses to compile until the new layout names what it needs.\n */\nexport type ViewNeedKind = \"choice\" | \"date\" | \"file\";\n\nexport interface ViewNeed {\n /** What the layout reads, as a kind a column declares (`offerableFields`). */\n kind: ViewNeedKind;\n /** The view key the made column is written onto, so the layout opens drawn by it. */\n viewKey: \"groupField\" | \"dateField\" | \"imageField\";\n /** True when the layout cannot draw at all without it (kanban, calendar). */\n blocking: boolean;\n /** The column the press makes, before the person edits it: its name, the store's word, its choices. */\n starter: { label: string; type: \"select\" | \"datetime\" | \"attachment\"; options?: readonly string[] };\n /** The table HAS columns this layout can use and none is chosen: the sentence over the picker. */\n pick: string;\n /** One plain sentence: what the table is missing (all a person who may not change it is told). */\n missing: string;\n /** One plain sentence: what pressing Make it work will do, with the column's name. */\n does: (label: string) => string;\n /** The sentence an agent is asked with — the same act, said in words. */\n ask: (label: string, options: readonly string[]) => string;\n}\n\n/** A list of words as a person says it: \"To do, In progress and Done\". */\nexport function wordsList(words: readonly string[]): string {\n const clean = words.map((w) => w.trim()).filter((w) => w !== \"\");\n if (clean.length <= 1) return clean.join(\"\");\n return `${clean.slice(0, -1).join(\", \")} and ${clean[clean.length - 1]}`;\n}\n\nexport const VIEW_NEEDS: Record<ViewLayout, ViewNeed | null> = {\n grid: null,\n // A list reads nothing a table can lack: rows, titled, grouped only when the person chooses.\n list: null,\n kanban: {\n kind: \"choice\",\n viewKey: \"groupField\",\n blocking: true,\n starter: { label: \"Status\", type: \"select\", options: [\"To do\", \"In progress\", \"Done\"] },\n pick: \"Pick the choice column the board's columns come from.\",\n missing: \"This table has no choice column to make the board's columns from.\",\n does: (label) => `Make it work adds a ${label} column with the choices below and groups the board by it.`,\n ask: (label, options) =>\n `Add a choice column called ${label} to this table${options.length > 0 ? ` with the choices ${wordsList(options)}` : \"\"}, then group the Kanban board by it.`,\n },\n calendar: {\n kind: \"date\",\n viewKey: \"dateField\",\n blocking: true,\n starter: { label: \"Date\", type: \"datetime\" },\n pick: \"Pick the date column the calendar places records by.\",\n missing: \"This table has no date column to place records on.\",\n does: (label) => `Make it work adds a ${label} column and lays the calendar out by it.`,\n ask: (label) => `Add a date column called ${label} to this table, then lay the Calendar out by it.`,\n },\n gallery: {\n kind: \"file\",\n viewKey: \"imageField\",\n blocking: false,\n starter: { label: \"Photo\", type: \"attachment\" },\n pick: \"Pick the file column each card shows as its picture.\",\n missing: \"The cards have no picture because this table has no file column.\",\n does: (label) => `Make it work adds a ${label} column and shows it on each card.`,\n ask: (label) => `Add a file column called ${label} to this table, then show it as the picture on each Gallery card.`,\n },\n timeline: {\n kind: \"date\",\n viewKey: \"dateField\",\n blocking: true,\n starter: { label: \"Start\", type: \"datetime\" },\n pick: \"Pick the date column each bar starts on.\",\n missing: \"This table has no date column to place records on.\",\n does: (label) => `Make it work adds a ${label} column and lays the timeline out by it.`,\n ask: (label) => `Add a date column called ${label} to this table, then lay the Timeline out by it.`,\n },\n};\n\n/**\n * A NAME NO COLUMN OF THIS TABLE ALREADY HAS: the starter's own, else \"Status 2\", \"Status 3\"…\n * A table that already holds a text column called Status must not be refused the board.\n */\nexport function freeColumnName(wanted: string, taken: readonly string[]): string {\n const held = new Set(taken.map((t) => t.trim().toLowerCase()));\n const base = wanted.trim() === \"\" ? \"Column\" : wanted.trim();\n if (!held.has(base.toLowerCase())) return base;\n for (let n = 2; n < 100; n += 1) {\n const next = `${base} ${n}`;\n if (!held.has(next.toLowerCase())) return next;\n }\n return base;\n}\n\n/** One sort clause. The Field's key and a direction; nothing else is a sort. */\nexport interface ViewSort {\n field: string;\n direction: \"asc\" | \"desc\";\n}\n\n/** How a saved view is ordered: by hand, by its sort, or it never said (the same as sorted). */\nexport type ViewOrder = \"manual\" | \"sorted\" | null;\n\n/** The order word a stored definition carries. Only the two words the store writes are read. */\nexport function viewOrderOf(definition: Record<string, unknown> | null | undefined): ViewOrder {\n const raw = definition?.[\"order\"];\n return raw === \"manual\" ? \"manual\" : raw === \"sorted\" ? \"sorted\" : null;\n}\n\n/**\n * THE DECLARATIVE SPEC. An agent writes this whole object; a person tweaks it.\n * Every builder component in this package takes one of these as a prop.\n */\nexport interface SavedViewSpec<P = ViewPresentationDocument> {\n name: string;\n /** The Table this view looks at. */\n subject: Uuid;\n layout: ViewLayout;\n /** Kanban: the Field whose value becomes a column. */\n groupField?: string | null;\n /**\n * Kanban: a number Field to TOTAL under each column heading. It lives on the VIEW for\n * the same reason the colours do — two people read one board two ways and neither\n * reading is a fact about the records.\n */\n measure?: string | null;\n /**\n * Kanban: the Field whose values cut the board into SWIMLANES across the columns — a\n * dispatcher's board by Status, one lane per Technician (S1-PRIME VIEW-KEYS). Never the\n * column Field itself; the store refuses that.\n */\n swimlaneField?: string | null;\n /** Kanban: the columns this view keeps shut to a strip, by the column's stored value. */\n collapsedColumns?: string[];\n /** Calendar: the Field that places a record in the month. */\n dateField?: string | null;\n /** Timeline: the Field a record's bar starts on (`start_field`). */\n startField?: string | null;\n /** Calendar and timeline: the Field a record ends on (`end_field`). */\n endField?: string | null;\n /** Gallery: the Field shown large on the card. */\n imageField?: string | null;\n sorts?: ViewSort[];\n /**\n * HOW THE VIEW IS ORDERED (ORDER-FIX): `\"manual\"` — the positions a person set by hand ARE the\n * view's sort, and it carries no `sorts`; `\"sorted\"` or null — by `sorts`. READ ONLY: the store\n * writes \"manual\" only when the rows are placed (`custom.view_record_order_set`) and turns it\n * off itself when a sort is saved, so no patch ever sends it (`viewSettingsPatch` does not).\n */\n order?: ViewOrder;\n /**\n * The membership Rule. The STORE decides who is in this view; this is a\n * reference to its Rule record, never a predicate this package evaluates.\n */\n ruleId?: Uuid | null;\n /**\n * THE FLAT FILTER a digest or a notify rule wrote the view with — the one shape\n * `custom.record_filter_sql` compiles, by Field KEY. A view saved in the bar has\n * none; a view saved by `DigestScheduler` (\"where Status is Open\") does, and the\n * grid and the board show exactly the records it names.\n */\n filters?: RecordFilter;\n /**\n * S2-PRIME — THE VIEW'S OWN QUESTION, as the condition builder writes it: the store's Rule\n * shape `{op, args}`, ALL / ANY / NOT groups nested to any depth, Fields by id. Kept in the\n * definition as `where` and asked of the store unchanged — the grid's list door, the board's\n * headings and the dashboard's numbers compile it into the one WHERE clause\n * (`custom.record_filter_sql`). Never stored under `filters`: that key is the flat map the\n * digests and the notifier read, and they would refuse it by name.\n */\n where?: RuleExpression | null;\n isDefault?: boolean;\n /**\n * HOW THIS VIEW LOOKS — its colors, its per-column formats and its frozen\n * column (`presentation.ts`).\n *\n * It lives on the VIEW and not on the Fields because two people read one\n * table two ways and neither reading is a fact about the records; it lives on\n * a RECORD, not a new column, because that is what makes it something an\n * agent writes with the same `records` tool as everything else.\n */\n presentation?: P;\n}\n\n/**\n * A saved view as it comes back out of the store, with its row's own id.\n *\n * It carries no version: `custom.view_declare` MERGES one key at a time, so two\n * tabs pressing two different controls on one view both stand, and one control\n * pressed in both keeps the latest — how Airtable and Notion keep a view change.\n */\nexport interface SavedView<P = ViewPresentationDocument> extends SavedViewSpec<P> {\n id: Uuid;\n /** Where the view came from when it was moved in (the mover, the S0 repair), else null. */\n movedFrom: Record<string, unknown> | null;\n}\n\n/** THE TABLE'S DEFAULT VIEW: the first view that says it is. */\nexport function defaultViewOf<V extends Pick<SavedView, \"isDefault\">>(views: readonly V[]): V | undefined {\n return views.find((v) => v.isDefault);\n}\n\n/**\n * WHICH FIELD EACH LAYOUT CAN BE DRAWN FROM, decided from the FIELD'S OWN\n * DECLARATION and never from the values it happens to hold.\n *\n * A kanban makes columns from a choice: the Field whose value is one of a\n * closed set (FLD-5 / FLD-6 — a pick-list is a Table, and a select stores the\n * id of one of its records). Grouping by a free-text Field produces one column\n * per record, which is not a board. A calendar places a record in time, so it\n * needs a Field that holds a date.\n *\n * These two answers are here, beside the layouts, because the picker on the\n * screen and any agent writing a view spec must agree about what is offerable.\n */\nexport const LAYOUT_FIELD_KIND: Record<ViewLayout, ViewNeedKind | null> = {\n grid: null,\n kanban: \"choice\",\n calendar: \"date\",\n gallery: \"file\",\n timeline: \"date\",\n list: null,\n};\n\n/**\n * ─────────────────────────────────────────────────────────────────────────────\n * WHICH VIEW A LINK NAMES — the address bar as a first-class control.\n *\n * 🚨 THE DEFECT THIS CLOSES (lane FRONT-DOOR, 2026-09-21; VERIFIER-8 HIGH-2).\n * `/data/<table>?view=kanban` returned 200 and rendered THE GRID. The\n * switcher was there, the four buttons worked, and the parameter was read by\n * nobody — so a person who bookmarked a board, or sent one to a colleague, got\n * a grid, and nothing on the screen said the view had been dropped. A link that\n * does not land is the inbox-link defect (`activeRecordId`) and the dashboard\n * defect (`activeDashboardId`) for the third time, so this is the same shape of\n * fix: the URL names it, the page opens on it, and the URL FOLLOWS the person\n * when they pick another.\n *\n * The dashboards are a fifth value and not a special case: to the person, \"the\n * dashboard\" is one of the ways to look at this table, and a link to it has to\n * work like a link to the board.\n */\n/**\n * 🚨 `archived` IS THE SIXTH VALUE, AND IT IS NOT A SPECIAL CASE EITHER (lane\n * FIX-10A-ARCHIVE, 2026-09-22; VERIFIER-10 F4).\n *\n * Archiving a record used to be a ONE-WAY DOOR: the grid's row action soft-\n * deletes correctly — `deleted_at` set, version bumped, nothing removed — and\n * then no screen anywhere in the platform could bring it back. The store's\n * `custom.record_restore` was there the whole time and did exactly the right\n * thing; nothing reached it, because every read door answers live rows only.\n *\n * So the archive is a WAY OF LOOKING AT THIS TABLE, like the board and the\n * dashboards, reached by the same row of buttons and named by the same\n * `?view=` parameter — never a Trash area of the app somebody has to know\n * exists, and never a per-table screen. Every Table inherits it the moment it\n * is in this list.\n */\nexport const PAGE_VIEWS = [...VIEW_LAYOUTS, \"dashboards\", \"archived\"] as const;\nexport type PageView = (typeof PAGE_VIEWS)[number];\n\nexport const PAGE_VIEW_LABEL: Record<PageView, string> = {\n ...LAYOUT_LABEL,\n dashboards: \"Dashboards\",\n archived: \"Archived\",\n};\n\n/**\n * THE WORDS A LINK MAY USE. The canonical token first; the rest are what a\n * person or an agent actually types, because a link that dies on \"board\" when\n * the button says \"Kanban\" is the same dead link with better spelling.\n */\nconst PAGE_VIEW_SPELLINGS: Record<string, PageView> = {\n grid: \"grid\",\n table: \"grid\",\n rows: \"grid\",\n list: \"list\",\n kanban: \"kanban\",\n board: \"kanban\",\n pipeline: \"kanban\",\n calendar: \"calendar\",\n month: \"calendar\",\n schedule: \"calendar\",\n gallery: \"gallery\",\n cards: \"gallery\",\n timeline: \"timeline\",\n gantt: \"timeline\",\n dashboards: \"dashboards\",\n dashboard: \"dashboards\",\n charts: \"dashboards\",\n archived: \"archived\",\n archive: \"archived\",\n // The grid's row action says \"Delete\" and the store soft-deletes, so the word\n // a person types is as likely to be the one the button used as the one this\n // view is called. Both land in the same place; neither dies.\n deleted: \"archived\",\n trash: \"archived\",\n removed: \"archived\",\n};\n\n/**\n * What a `?view=` value means, or `null` when it means nothing here.\n *\n * `null` is NOT \"show the grid\": the caller is expected to say that the link\n * named something this table has no view for, because silently substituting a\n * different view is exactly the defect above wearing a parser.\n */\nexport function pageViewFromParam(raw: string | null | undefined): PageView | null {\n if (typeof raw !== \"string\") return null;\n const token = raw.trim().toLowerCase();\n if (token === \"\") return null;\n return PAGE_VIEW_SPELLINGS[token] ?? null;\n}\n\n/** The sentence a link that named a view nobody has says. Never silent. */\nexport function unknownViewLine(raw: string): string {\n return (\n `The link asked for a view called “${raw}”, which this table has no view for, so you are looking at ` +\n `${PAGE_VIEW_LABEL.grid}. The views this table has are ` +\n `${PAGE_VIEWS.map((v) => PAGE_VIEW_LABEL[v]).join(\", \")} — pick one above and the address follows it.`\n );\n}\n\n/**\n * THE SPEC AS THE ONE DEFINITION `platform.saved_view` HOLDS — the keys\n * `custom.view_declare` documents, by Field KEY. `subject` is not in it: the door\n * takes the Table as its own argument and writes `table_id` itself.\n */\nexport function viewDocument<P = ViewPresentationDocument>(spec: SavedViewSpec<P>, codec: ViewPresentationCodec<P> = plainCodec<P>()): Record<string, unknown> {\n const out: Record<string, unknown> = {\n // A layout the store does not keep yet is not sent: the view is saved as a grid (`STORE_KEPT_LAYOUTS`).\n layout: storeKeepsLayout(spec.layout) ? spec.layout : \"grid\",\n sorts: spec.sorts ?? [],\n is_default: spec.isDefault === true,\n };\n if (spec.groupField) out[\"group_field\"] = spec.groupField;\n if (spec.swimlaneField) out[\"swimlane_field\"] = spec.swimlaneField;\n if (spec.collapsedColumns && spec.collapsedColumns.length > 0) out[\"collapsed_columns\"] = spec.collapsedColumns;\n if (spec.measure) out[\"measure\"] = spec.measure;\n if (spec.dateField) out[\"date_field\"] = spec.dateField;\n if (STORE_KEEPS_TIMELINE && spec.startField) out[\"start_field\"] = spec.startField;\n if (STORE_KEEPS_TIMELINE && spec.endField) out[\"end_field\"] = spec.endField;\n if (spec.imageField) out[\"image_field\"] = spec.imageField;\n if (spec.ruleId) out[\"rule_id\"] = spec.ruleId;\n if (spec.where) out[\"where\"] = spec.where;\n if (spec.presentation && !codec.isEmpty(spec.presentation)) {\n out[\"presentation\"] = codec.toDocument(spec.presentation);\n }\n return out;\n}\n\n/**\n * One row of `custom.views` back into the spec a screen and an agent both read — THROUGH THE ONE\n * ACCESSOR (`viewSettings`, viewKeys.ts), so every layout sees every declared key the same way.\n */\nexport function viewFromRow<P = ViewPresentationDocument>(row: SavedViewRow, codec: ViewPresentationCodec<P> = plainCodec<P>()): SavedView<P> {\n const data = (row.definition ?? {}) as Record<string, unknown>;\n const k = viewSettings(data, row.filters && Object.keys(row.filters).length > 0 ? row.filters : null, codec);\n const tableFromDefinition = typeof data[\"table_id\"] === \"string\" && data[\"table_id\"] !== \"\" ? (data[\"table_id\"] as string) : null;\n return {\n id: row.view_id,\n name: row.name || \"Untitled view\",\n subject: (row.table_id ?? tableFromDefinition ?? \"\") as Uuid,\n layout: k.layout,\n groupField: k.groupField,\n swimlaneField: k.swimlaneField,\n collapsedColumns: k.collapsedColumns,\n measure: k.measure,\n dateField: k.dateField,\n startField: k.startField,\n endField: k.endField,\n imageField: k.imageField,\n sorts: k.sorts,\n order: viewOrderOf(data),\n ruleId: k.ruleId,\n ...(k.filters ? { filters: k.filters } : {}),\n where: k.where,\n // The older table's own default view, carried in by the mover, IS this table's default —\n // the mover wrote the row's column, which `custom.views` does not return. Read as anything\n // else, the page would seed a second \"All records\" beside it and open on that.\n isDefault: k.isDefault || k.movedFrom?.[\"kind\"] === \"default_view\",\n presentation: k.presentation,\n movedFrom: k.movedFrom,\n };\n}\n\n/**\n * SAVE ONE NEW VIEW of a Table — the bar's \"New view\" and an agent's seed spec.\n * One `view_declare` with no `view_id`; the answer is the new view's id.\n */\nexport async function declareView<P = ViewPresentationDocument>(\n client: Pick<RecordsClient, \"viewDeclare\">,\n spec: SavedViewSpec<P>,\n codec: ViewPresentationCodec<P> = plainCodec<P>(),\n): Promise<RecordsResult<Uuid>> {\n return client.viewDeclare({\n table_id: spec.subject,\n spec: {\n name: spec.name,\n ...(spec.filters ? { filters: spec.filters } : {}),\n definition: viewDocument(spec, codec),\n },\n });\n}\n\n/**\n * WRITE A CHANGE ONTO A SAVED VIEW, AND KEEP IT.\n *\n * `custom.view_declare` with the view's id MERGES: only the keys in `patch` are\n * written, a key cleared to null is removed, and everything the patch did not\n * name — the grid's own choices, a hand-set order, where the view was moved from,\n * a colour set in another tab — stays exactly as it was (S0, 2026-09-23: the door\n * used to rebuild the whole definition from what one press sent).\n *\n * There is no version to be stale against (VERIFIER-15 M4 is closed by the shape,\n * not by a retry): a saved view is a person's own arrangement of a table, and\n * their latest press on a control is the one that stands. A refusal — the view\n * was removed, or belongs to a table this person cannot open — is handed back for\n * the page to say through the one notice.\n */\nexport async function saveViewPatch<P = ViewPresentationDocument>(\n client: Pick<RecordsClient, \"viewDeclare\">,\n tableId: Uuid,\n viewId: Uuid,\n patch: Partial<SavedViewSpec<P>>,\n codec: ViewPresentationCodec<P> = plainCodec<P>(),\n): Promise<RecordsResult<Uuid>> {\n const definition = viewPatchDocument(patch, codec);\n const renamed = patch.name !== undefined && patch.name.trim() !== \"\";\n const refiltered = patch.filters !== undefined;\n return client.viewDeclare({\n table_id: tableId,\n spec: {\n view_id: viewId,\n ...(renamed ? { name: patch.name!.trim() } : {}),\n ...(refiltered ? { filters: patch.filters ?? null } : {}),\n definition,\n },\n });\n}\n\n/**\n * A PARTIAL change to a saved view, as the definition keys the door merges. Only\n * the keys the caller actually changed are sent; a Field cleared (a board with no\n * \"Group by\") is sent as `null`, which the door removes.\n */\nexport function viewPatchDocument<P = ViewPresentationDocument>(\n patch: Partial<SavedViewSpec<P>>,\n codec: ViewPresentationCodec<P> = plainCodec<P>(),\n): Record<string, unknown> {\n const { name: _name, subject: _subject, filters: _filters, ...keys } = patch;\n return viewSettingsPatch(keys, codec);\n}\n\n/**\n * A LOOK AT A TABLE NEVER CHANGES HOW IT OPENS (lane VIEW-SWITCH-NOT-DESIGNATION, VERIFIER-21).\n *\n * On production the owner pressed Kanban, then Calendar, and the office member's table opened in\n * the Calendar: every layout press was saved onto the DEFAULT view, which is how the table opens\n * for everyone. The table's default view's `layout` and `isDefault` are its DESIGNATION, changed\n * only by an editor's deliberate \"Make this the default\" (`designateView`); the store refuses them\n * through `view_declare` by name. So a press on the default view carries every other key it\n * changed — a board's grouping, a calendar's date, a colour — and never those two.\n */\nexport function viewPatchFor<S extends { layout?: unknown; isDefault?: boolean }>(\n view: { isDefault?: boolean },\n patch: Partial<S>,\n): Partial<S> {\n if (!view.isDefault) return patch;\n const { layout: _layout, isDefault: _isDefault, ...kept } = patch;\n return kept as Partial<S>;\n}\n\n/** The one words for the explicit designation, with the layout it would make the default. */\nexport function makeDefaultLabel(layoutLabel: string): string {\n return `Make ${layoutLabel} the default`;\n}\n\n/**\n * MAKE THIS THE DEFAULT — the ONE designation door (`custom.view_designate`, editor on the table).\n * `layout` is the layout this table should open in for everyone: one of the layouts the store keeps. The view\n * becomes the table's only default.\n */\nexport async function designateView(\n client: Pick<RecordsClient, \"viewDesignate\">,\n tableId: Uuid,\n viewId: Uuid,\n layout: string | null,\n): Promise<RecordsResult<Uuid>> {\n return client.viewDesignate({ table_id: tableId, view_id: viewId, layout });\n}\n","// src/views/look.ts — @ai-matrx/records/views · A PERSON'S OWN LOOK AT A SHARED VIEW, HEADLESS\n//\n// (Moved from records-ui `viewLook.ts`, step 10, 2026-10-08.) How a person looks at a shared view (its grouping,\n// date field, sort, filter, presentation, layout) is HER look: the store keeps one per (person, view) through\n// `custom.view_look_set` / `view_look_read`, never written onto the view row. The view changes only when she\n// saves to it. This file is the look's shape: the keys a look may hold, how it reads back, how it lays over the\n// view, and what \"Save to view\" sends. The presentation half reads through the same codec port as the view.\n\nimport type { RecordsClient } from \"../core/client\";\nimport type { Uuid } from \"../core/index\";\nimport type { RecordsResult } from \"../results\";\nimport { plainPresentation, viewSettings, viewSettingsPatch, type ViewPresentationCodec, type ViewPresentationDocument } from \"./keys\";\nimport { VIEW_LAYOUTS, viewPatchFor, type SavedView, type SavedViewSpec, type ViewLayout } from \"./views\";\n\nconst plain = <P>() => plainPresentation as unknown as ViewPresentationCodec<P>;\n\n/**\n * WHAT A LOOK MAY HOLD — how a person looks, never what the view is: not its name, not whether it is the default,\n * not its Rule, not the flat filters the digests read, not the order the store writes.\n */\nexport type ViewLook<P = ViewPresentationDocument> = Partial<\n Pick<\n SavedViewSpec<P>,\n | \"layout\"\n | \"groupField\"\n | \"swimlaneField\"\n | \"collapsedColumns\"\n | \"measure\"\n | \"dateField\"\n | \"startField\"\n | \"endField\"\n | \"imageField\"\n | \"sorts\"\n | \"where\"\n | \"presentation\"\n >\n>;\n\nconst LOOK_KEYS = [\n \"layout\",\n \"groupField\",\n \"swimlaneField\",\n \"collapsedColumns\",\n \"measure\",\n \"dateField\",\n \"startField\",\n \"endField\",\n \"imageField\",\n \"sorts\",\n \"where\",\n \"presentation\",\n] as const satisfies ReadonlyArray<keyof ViewLook>;\n\n/** Only the look's own keys of a press — a name, a default, a Rule or an order is never a look. */\nexport function lookPart<P = ViewPresentationDocument>(patch: Partial<SavedViewSpec<P>>): ViewLook<P> {\n const out: ViewLook<P> = {};\n for (const key of LOOK_KEYS) {\n if (patch[key] !== undefined) (out as Record<string, unknown>)[key] = patch[key];\n }\n return out;\n}\n\n/** The look as the definition keys the store keeps (`view_look_set`); a cleared key is null. */\nexport function lookDocument<P = ViewPresentationDocument>(look: ViewLook<P>, codec: ViewPresentationCodec<P> = plain<P>()): Record<string, unknown> {\n return viewSettingsPatch<P>(look, codec);\n}\n\n/** A kept look back into the spec's words. Only the keys it holds; a null key is \"none, for me\". */\nexport function lookFromDocument<P = ViewPresentationDocument>(\n doc: Record<string, unknown> | null | undefined,\n codec: ViewPresentationCodec<P> = plain<P>(),\n): ViewLook<P> {\n const data = doc ?? {};\n const read = viewSettings<P>(data, undefined, codec);\n const out: ViewLook<P> = {};\n const has = (key: string) => Object.prototype.hasOwnProperty.call(data, key);\n if (has(\"layout\") && (VIEW_LAYOUTS as readonly string[]).includes(String(data[\"layout\"]))) {\n out.layout = data[\"layout\"] as ViewLayout;\n }\n if (has(\"group_field\")) out.groupField = read.groupField;\n if (has(\"swimlane_field\")) out.swimlaneField = read.swimlaneField;\n if (has(\"collapsed_columns\")) out.collapsedColumns = read.collapsedColumns;\n if (has(\"measure\")) out.measure = read.measure;\n if (has(\"date_field\")) out.dateField = read.dateField;\n if (has(\"start_field\")) out.startField = read.startField;\n if (has(\"end_field\")) out.endField = read.endField;\n if (has(\"image_field\")) out.imageField = read.imageField;\n if (has(\"sorts\")) out.sorts = read.sorts;\n if (has(\"where\")) out.where = read.where;\n if (has(\"presentation\")) out.presentation = codec.parse(data[\"presentation\"]);\n return out;\n}\n\n/** THE VIEW AS THIS PERSON SEES IT: the saved view, with her look laid over it. */\nexport function applyLook<P = ViewPresentationDocument>(view: SavedView<P>, look: ViewLook<P> | null | undefined): SavedView<P> {\n if (!look) return view;\n return { ...view, ...look } as SavedView<P>;\n}\n\n/** Whether the look shows anything the view does not — which is when \"Save to view\" means something. */\nexport function lookDiffers<P = ViewPresentationDocument>(view: SavedView<P>, look: ViewLook<P> | null | undefined): boolean {\n if (!look) return false;\n const shown = applyLook(view, look);\n return LOOK_KEYS.some((key) => look[key] !== undefined && JSON.stringify(shown[key] ?? null) !== JSON.stringify(view[key] ?? null));\n}\n\n/**\n * WHAT \"SAVE TO VIEW\" SENDS, and what stays the person's own afterwards. The default view's layout is the table's\n * designation (`viewPatchFor`): it is never saved here, so a look's layout on the default view stays her look.\n */\nexport function saveToViewPlan<P = ViewPresentationDocument>(\n view: SavedView<P>,\n look: ViewLook<P>,\n): { patch: Partial<SavedViewSpec<P>>; left: ViewLook<P> | null } {\n const patch = viewPatchFor(view, look) as Partial<SavedViewSpec<P>>;\n const left: ViewLook<P> = {};\n if (look.layout !== undefined && patch.layout === undefined && look.layout !== view.layout) left.layout = look.layout;\n return { patch, left: Object.keys(left).length > 0 ? left : null };\n}\n\n/** The caller's own looks at every view of a table, by view id. */\nexport async function readLooks<P = ViewPresentationDocument>(\n client: Pick<RecordsClient, \"viewLookRead\">,\n tableId: Uuid,\n codec: ViewPresentationCodec<P> = plain<P>(),\n): Promise<RecordsResult<Record<string, ViewLook<P>>>> {\n const answered = await client.viewLookRead({ table_id: tableId });\n if (!answered.ok) return answered;\n const out: Record<string, ViewLook<P>> = {};\n for (const [viewId, row] of Object.entries(answered.data ?? {})) {\n out[viewId] = lookFromDocument(row?.look ?? null, codec);\n }\n return { ok: true, data: out };\n}\n\n/** Keep the whole look (null: \"Reset to view\"). The shared view is never written. */\nexport async function keepLook<P = ViewPresentationDocument>(\n client: Pick<RecordsClient, \"viewLookSet\">,\n tableId: Uuid,\n viewId: Uuid,\n look: ViewLook<P> | null,\n codec: ViewPresentationCodec<P> = plain<P>(),\n): Promise<RecordsResult<Record<string, unknown> | null>> {\n const doc = look ? lookDocument(look, codec) : null;\n return client.viewLookSet({ table_id: tableId, view_id: viewId, look: doc && Object.keys(doc).length > 0 ? doc : null });\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;;;ACoFO,SAAS,aAAa,QAA2C;AACtE,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,EAAG,QAAO;AAC3E,QAAM,OAAO;AACb,SAAO,OAAO,KAAK,OAAO,YAAY,MAAM,QAAQ,KAAK,IAAI;AAC/D;AAmIO,SAAS,gBAAgB,QAAgD;AAC9E,MAAI,CAAC,OAAQ,QAAO;AAGpB,MAAI,aAAa,MAAM,EAAG,QAAO,KAAK,UAAU,MAAM;AACtD,QAAM,OAAO,OAAO,KAAK,MAAM,EAAE,KAAK;AACtC,MAAI,KAAK,WAAW,EAAG,QAAO;AAC9B,QAAM,QAAQ,KAAK,IAAI,CAAC,QAAQ;AAC9B,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,YAAM,SAAS;AACf,aAAO,GAAG,KAAK,UAAU,GAAG,CAAC,YAAY,KAAK,UAAU,OAAO,QAAQ,IAAI,CAAC,SAAS,KAAK,UAAU,OAAO,MAAM,IAAI,CAAC;AAAA,IACxH;AACA,WAAO,GAAG,KAAK,UAAU,GAAG,CAAC,IAAI,KAAK,UAAU,SAAS,IAAI,CAAC;AAAA,EAChE,CAAC;AACD,SAAO,IAAI,MAAM,KAAK,GAAG,CAAC;AAC5B;AAQO,SAAS,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O,CAAC,EAAE;AAC7G;AAMA,eAAsB,mBACpB,OACsB;AACtB,QAAM,YAAY,oBAAoB,oBAAoB,MAAM,UAAU,CAAC;AAC3E,QAAM,OAAO,eAAe,UAAU,MAAM;AAC5C,MAAI;AACF,UAAM,QAAQ,IAAI,CAAC,KAAK,SAAS,MAAM,KAAK,GAAG,KAAK,KAAK,MAAM,OAAO,iBAAiB,MAAM,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;AAAA,EAChH,QAAQ;AAAA,EAER;AACA,SAAO,UAAU,KAAK;AACxB;AAGA,eAAsB,aACpB,OAIsB;AACtB,QAAM,EAAE,WAAW,OAAO,IAAI,eAAe,KAAK;AAClD,MAAI;AACF,UAAM,OAAO,SAAS,EAAE,QAAQ,MAAM,QAAuB,UAAU,oBAAoB,MAAM,YAAY,CAAC,CAAC,EAAE,CAAC;AAAA,EACpH,QAAQ;AAAA,EAER;AACA,SAAO,UAAU,KAAK;AACxB;AAMA,eAAsB,YAAY,OAAoF;AACpH,QAAM,EAAE,WAAW,OAAO,IAAI,eAAe,KAAK;AAClD,QAAM,QAAQ,MAAM,QAAQ,MAAM,IAAI,IAAI,MAAM,OAAO,CAAC,MAAM,IAAI;AAClE,QAAM,QAAQ,IAAI,MAAM,IAAI,CAAC,SAAS,OAAO,gBAAgB,EAAE,UAAU,MAAM,SAAS,GAAG,KAAK,CAAC,EAAE,MAAM,MAAM,IAAI,CAAC,CAAC;AACrH,SAAO,UAAU,KAAK;AACxB;AAMO,SAAS,mBAAsB,OAAiC;AACrE,SAAO;AAAA,IACL,sBAAsB,CACpB,QACA,SACA,UAAmD,CAAC,MACjD,qBAAwB,QAAQ,SAAS,EAAE,GAAG,SAAS,MAAM,CAAC;AAAA,IACnE,kBAAkB,CAAC,UAAoE,iBAAoB,EAAE,GAAG,OAAO,MAAM,CAAC;AAAA,EAChI;AACF;","names":["registry","import_uuid","import_global_slot","import_uuid","predicate","flight","refusal","rows","siblings","import_uuid","import_uuid","held","sink","plainCodec","plainCodec"]}
|